add active list to dock object

This commit is contained in:
Ashley Wulber 2021-12-20 23:52:59 -05:00
parent 5cda4046a6
commit 6a479899ad
20 changed files with 250 additions and 601 deletions

Binary file not shown.

View file

@ -1,5 +1,6 @@
use gdk4::ContentProvider;
use gdk4::Display;
use gio::DesktopAppInfo;
use gio::Icon;
use gio::ListStore;
use gtk4 as gtk;
@ -11,6 +12,8 @@ use gtk::glib;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use crate::dock_object::DockObject;
glib::wrapper! {
pub struct DockItem(ObjectSubclass<imp::DockItem>)
@extends gtk::Widget, gtk::Box;
@ -47,70 +50,72 @@ impl DockItem {
// TODO current method seems very messy...
// refactor to emit event for removing the item?
pub fn set_app_info(
&self,
app_info: &gio::DesktopAppInfo,
i: u32,
saved_app_model: &ListStore,
) {
dbg!("setting app info");
let self_ = imp::DockItem::from_instance(self);
self_.image.set_tooltip_text(Some(&app_info.name()));
pub fn set_app_info(&self, app_info: &DockObject, i: u32, saved_app_model: &ListStore) {
if let Ok(app_info_value) = app_info.property("appinfo") {
if let Ok(Some(app_info)) = app_info_value.get::<Option<DesktopAppInfo>>() {
dbg!("setting app info");
let self_ = imp::DockItem::from_instance(self);
self_.image.set_tooltip_text(Some(&app_info.name()));
if let Some(drag_controller) = self_.drag_controller.get() {
if let Some(file) = app_info.filename() {
let provider = ContentProvider::for_value(&file.to_string_lossy().to_value());
drag_controller.set_content(Some(&provider));
}
drag_controller.connect_drag_end(move |_self, _drag, delete_data| {
dbg!("removing", delete_data);
});
//TODO investigate X11 errors when reordering dock items
drag_controller.connect_drag_cancel(
glib::clone!(@weak saved_app_model => @default-return true, move |_self, _drag, _delete_data| {
dbg!("removing {}", i);
if saved_app_model.n_items() > i {
saved_app_model.remove(i);
if let Some(drag_controller) = self_.drag_controller.get() {
if let Some(file) = app_info.filename() {
let provider =
ContentProvider::for_value(&file.to_string_lossy().to_value());
drag_controller.set_content(Some(&provider));
}
true
}),
);
drag_controller.connect_drag_end(
glib::clone!(@weak saved_app_model => move |_self, _drag, delete_data| {
dbg!("removing {}", i);
if delete_data && saved_app_model.n_items() > i {
saved_app_model.remove(i);
}
}),
);
drag_controller.connect_drag_end(move |_self, _drag, delete_data| {
dbg!("removing", delete_data);
});
//TODO investigate rare X11 errors when reordering dock items
drag_controller.connect_drag_cancel(
glib::clone!(@weak saved_app_model => @default-return true, move |_self, _drag, _delete_data| {
dbg!("removing {}", i);
if saved_app_model.n_items() > i {
saved_app_model.remove(i);
}
true
}),
);
drag_controller.connect_drag_end(
glib::clone!(@weak saved_app_model => move |_self, _drag, delete_data| {
dbg!("removing {}", i);
if delete_data && saved_app_model.n_items() > i {
saved_app_model.remove(i);
}
}),
);
let icon = app_info
.icon()
.unwrap_or(Icon::for_string("image-missing").expect("Failed to set default icon"));
drag_controller.connect_drag_begin(glib::clone!(@weak icon, => move |_self, _drag| {
// set drag source icon if possible...
// gio Icon is not easily converted to a Paintable, but this seems to be the correct method
if let Some(default_display) = &Display::default() {
if let Some(icon_theme) = IconTheme::for_display(default_display) {
if let Some(paintable_icon) = icon_theme.lookup_by_gicon(
&icon,
64,
1,
gtk4::TextDirection::None,
gtk4::IconLookupFlags::empty(),
) {
_self.set_icon(Some(&paintable_icon), 32, 32);
}
}
let icon = app_info.icon().unwrap_or(
Icon::for_string("image-missing").expect("Failed to set default icon"),
);
drag_controller.connect_drag_begin(
glib::clone!(@weak icon, => move |_self, _drag| {
// set drag source icon if possible...
// gio Icon is not easily converted to a Paintable, but this seems to be the correct method
if let Some(default_display) = &Display::default() {
if let Some(icon_theme) = IconTheme::for_display(default_display) {
if let Some(paintable_icon) = icon_theme.lookup_by_gicon(
&icon,
64,
1,
gtk4::TextDirection::None,
gtk4::IconLookupFlags::empty(),
) {
_self.set_icon(Some(&paintable_icon), 32, 32);
}
}
}
}),
);
}
}));
let icon = app_info.icon().unwrap_or(
Icon::for_string("image-missing").expect("Failed to set default icon"),
);
self_.image.set_from_gicon(&icon);
}
}
let icon = app_info
.icon()
.unwrap_or(Icon::for_string("image-missing").expect("Failed to set default icon"));
self_.image.set_from_gicon(&icon);
}
// pub fn set_app_info(&self, app_obj: ApplicationObject) {

View file

@ -0,0 +1,79 @@
use crate::utils::BoxedSearchResults;
use gio::DesktopAppInfo;
use glib::{FromVariant, ParamFlags, ParamSpec, ToVariant, Value, Variant, VariantTy};
use gtk4::glib;
use gtk4::prelude::*;
use gtk4::subclass::prelude::*;
use once_cell::sync::Lazy;
use std::cell::RefCell;
// Object holding the state
#[derive(Default)]
pub struct DockObject {
appinfo: RefCell<Option<DesktopAppInfo>>,
active: RefCell<BoxedSearchResults>,
}
// The central trait for subclassing a GObject
#[glib::object_subclass]
impl ObjectSubclass for DockObject {
const NAME: &'static str = "DockObject";
type Type = super::DockObject;
type ParentType = glib::Object;
}
// Trait shared by all GObjects
impl ObjectImpl for DockObject {
fn properties() -> &'static [ParamSpec] {
static PROPERTIES: Lazy<Vec<ParamSpec>> = Lazy::new(|| {
vec![
ParamSpec::new_object(
// Name
"appinfo",
// Nickname
"appinfo",
// Short description
"app info",
DesktopAppInfo::static_type(),
// The property can be read and written to
ParamFlags::READWRITE,
),
ParamSpec::new_boxed(
// Name
"active",
// Nickname
"active",
// Short description
"active",
BoxedSearchResults::static_type(),
// The property can be read and written to
ParamFlags::READWRITE,
),
]
});
PROPERTIES.as_ref()
}
fn set_property(&self, _obj: &Self::Type, _id: usize, value: &Value, pspec: &ParamSpec) {
match pspec.name() {
"appinfo" => {
let appinfo = value
.get()
.expect("Value needs to be Option<DesktopAppInfo>");
self.appinfo.replace(appinfo);
}
"active" => {
let active = value.get().expect("Value needs to be BoxedSearchResults");
self.active.replace(active);
}
_ => unimplemented!(),
}
}
fn property(&self, _obj: &Self::Type, _id: usize, pspec: &ParamSpec) -> Value {
match pspec.name() {
"appinfo" => self.appinfo.borrow().to_value(),
_ => unimplemented!(),
}
}
}

View file

@ -0,0 +1,51 @@
mod imp;
use crate::utils::BoxedSearchResults;
use gdk4::glib::Object;
use gio::DesktopAppInfo;
use gtk4::glib;
use gtk4::prelude::AppInfoExt;
glib::wrapper! {
pub struct DockObject(ObjectSubclass<imp::DockObject>);
}
impl DockObject {
pub fn new(appinfo: DesktopAppInfo) -> Self {
Object::new(&[("appinfo", &Some(appinfo))]).expect("Failed to create `DockObject`.")
}
pub fn from_search_results(results: BoxedSearchResults) -> Self {
let appinfo = xdg::BaseDirectories::new()
.expect("could not access XDG Base directory")
.get_data_dirs()
.iter_mut()
.filter_map(|xdg_data_path| {
let defaults = ["Firefox Web Browser", "Files", "Terminal", "Pop!_Shop"];
xdg_data_path.push("applications");
dbg!(&xdg_data_path);
std::fs::read_dir(xdg_data_path).ok()
})
.flatten()
.filter_map(|dir_entry| {
let defaults = ["Firefox Web Browser", "Files", "Terminal", "Pop!_Shop"];
if let Ok(dir_entry) = dir_entry {
if let Some(path) = dir_entry.path().file_name() {
if let Some(path) = path.to_str() {
if let Some(app_info) = gio::DesktopAppInfo::new(path) {
if app_info.should_show()
&& defaults.contains(&app_info.name().as_str())
{
return Some(DockObject::new(app_info));
}
}
}
}
}
None
})
.next();
Object::new(&[("appinfo", &appinfo), ("active", &results)])
.expect("Failed to create `DockObject`.")
}
}

View file

@ -1,5 +1,6 @@
mod application_object;
mod dock_item;
mod dock_object;
mod utils;
mod window;
@ -70,6 +71,7 @@ fn load_css() {
}
fn main() {
assert!(utils::BoxedSearchResults::static_type().is_valid());
let app = gtk::Application::builder()
.application_id("com.cosmic.Launcher")
.build();
@ -78,7 +80,12 @@ fn main() {
setup_shortcuts(app);
load_css()
});
// TODO investigate multiple signals to connect_activate
// crashes when called twice bc of singleton
app.connect_activate(move |app| {
// Seems that over a long period of time, this might be called multiple times
// The global variables should be initialized outside this closure
let (tx, mut rx) = postage::mpsc::channel(1);
let mut launcher = spawn_launcher(tx.clone());
if TX.set(tx).is_err() {

View file

@ -1 +1,3 @@
#[derive(Clone, Debug, Default, glib::GBoxed)]
#[gboxed(type_name = "BoxedLauncherActive")]
pub struct BoxedSearchResults(pub Vec<pop_launcher::SearchResult>);

View file

@ -1,6 +1,7 @@
mod imp;
// use crate::ApplicationObject;
use crate::dock_item::DockItem;
use crate::dock_object::DockObject;
use crate::X11_CONN;
use gdk4::Rectangle;
use gdk4::Surface;
@ -49,7 +50,7 @@ impl Window {
// Get state and set model
let imp = imp::Window::from_instance(self);
let saved_app_model = gio::ListStore::new(DesktopAppInfo::static_type());
let saved_app_model = gio::ListStore::new(DockObject::static_type());
let selection_model = gtk::SingleSelection::builder()
.autoselect(false)
@ -74,8 +75,7 @@ impl Window {
if app_info.should_show()
&& defaults.contains(&app_info.name().as_str())
{
dbg!(app_info.name());
saved_app_model.append(&app_info)
saved_app_model.append(&DockObject::new(app_info));
} else {
// println!("Ignoring {}", path);
}
@ -118,17 +118,19 @@ impl Window {
println!("selected app {}", position);
// Launch the application when an item of the list is activated
if let Some(item) = model.item(position) {
let app_info = item.downcast::<gio::DesktopAppInfo>().unwrap();
let context = window.display().app_launch_context();
if let Err(err) = app_info.launch(&[], Some(&context)) {
gtk::MessageDialog::builder()
.text(&format!("Failed to start {}", app_info.name()))
.secondary_text(&err.to_string())
.message_type(gtk::MessageType::Error)
.modal(true)
.transient_for(&window)
.build()
.show();
let app_info = item.downcast::<DockObject>().expect("App model must only contain DockObject");
if let Ok(Some(app_info)) = app_info.property("appinfo").expect("DockObject must have appinfo property").get::<Option<DesktopAppInfo>>() {
let context = window.display().app_launch_context();
if let Err(err) = app_info.launch(&[], Some(&context)) {
gtk::MessageDialog::builder()
.text(&format!("Failed to start {}", app_info.name()))
.secondary_text(&err.to_string())
.message_type(gtk::MessageType::Error)
.modal(true)
.transient_for(&window)
.build()
.show();
}
}
}
}),
@ -239,10 +241,12 @@ impl Window {
let mut i: u32 = 0;
let mut index_of_existing_app: Option<u32> = None;
while let Some(item) = saved_app_model.item(i) {
if let Ok(cur_app_info) = item.downcast::<gio::DesktopAppInfo>() {
dbg!(cur_app_info.filename());
if cur_app_info.filename() == Some(Path::new(&path_str).to_path_buf()) {
index_of_existing_app = Some(i);
if let Ok(cur_app_info) = item.downcast::<DockObject>() {
if let Ok(Some(cur_app_info)) = cur_app_info.property("appinfo").expect("property appinfo missing from DockObject").get::<Option<DesktopAppInfo>>() {
dbg!(cur_app_info.filename());
if cur_app_info.filename() == Some(Path::new(&path_str).to_path_buf()) {
index_of_existing_app = Some(i);
}
}
}
i += 1;
@ -274,7 +278,7 @@ impl Window {
dbg!(index);
dbg!("dropped it!");
dbg!(drop_value.type_());
saved_app_model.insert(index, &app_info);
saved_app_model.insert(index, &DockObject::new(app_info));
}
}
}
@ -356,8 +360,8 @@ impl Window {
let application_object = list_item
.item()
.expect("The item has to exist.")
.downcast::<DesktopAppInfo>()
.expect("The item has to be a `DesktopAppInfo`");
.downcast::<DockObject>()
.expect("The item has to be a `DockObject`");
let dock_item = list_item
.child()
.expect("The list item child needs to exist.")