reach out directly to pop shell gbus for window list

This commit is contained in:
Ashley Wulber 2021-12-22 12:32:46 -05:00
parent 6be5b84b24
commit c2dd25a09d
6 changed files with 58 additions and 34 deletions

View file

@ -27,6 +27,7 @@ async-io = "1.6.0"
# zbus # zbus
zbus = "2.0.0-beta.7" zbus = "2.0.0-beta.7"
zvariant = "2.10.0" zvariant = "2.10.0"
zvariant_derive = "2.10.0"
futures-util = "0.3.19" futures-util = "0.3.19"
[dependencies.gtk4] [dependencies.gtk4]

View file

@ -1,16 +1,12 @@
use crate::BoxedSearchResults; use crate::utils::BoxedWindowList;
use gdk4::ContentProvider; use gdk4::ContentProvider;
use gdk4::Display; use gdk4::Display;
use gio::DesktopAppInfo; use gio::DesktopAppInfo;
use gio::Icon; use gio::Icon;
use gio::ListStore; use gio::ListStore;
use gtk4 as gtk; use gtk4 as gtk;
use gtk4::Align;
use gtk4::Box;
use gtk4::DragSource; use gtk4::DragSource;
use gtk4::IconTheme; use gtk4::IconTheme;
use gtk4::Label;
use gtk4::Orientation;
mod imp; mod imp;
use gtk::glib; use gtk::glib;
@ -123,7 +119,7 @@ impl DockItem {
println!("initializing dock item failed..."); println!("initializing dock item failed...");
} }
if let Ok(active_value) = app_info.property("active") { if let Ok(active_value) = app_info.property("active") {
if let Ok(active) = active_value.get::<BoxedSearchResults>() { if let Ok(active) = active_value.get::<BoxedWindowList>() {
self_.dots.set_text(""); self_.dots.set_text("");
for _ in active.0 { for _ in active.0 {
self_ self_

View file

@ -1,4 +1,4 @@
use crate::utils::BoxedSearchResults; use crate::utils::BoxedWindowList;
use gio::DesktopAppInfo; use gio::DesktopAppInfo;
use glib::{ParamFlags, ParamSpec, Value}; use glib::{ParamFlags, ParamSpec, Value};
use gtk4::glib; use gtk4::glib;
@ -12,7 +12,7 @@ use std::cell::RefCell;
#[derive(Default)] #[derive(Default)]
pub struct DockObject { pub struct DockObject {
appinfo: RefCell<Option<DesktopAppInfo>>, appinfo: RefCell<Option<DesktopAppInfo>>,
active: RefCell<BoxedSearchResults>, active: RefCell<BoxedWindowList>,
saved: Cell<bool>, saved: Cell<bool>,
} }
@ -47,7 +47,7 @@ impl ObjectImpl for DockObject {
"active", "active",
// Short description // Short description
"active", "active",
BoxedSearchResults::static_type(), BoxedWindowList::static_type(),
// The property can be read and written to // The property can be read and written to
ParamFlags::READWRITE, ParamFlags::READWRITE,
), ),
@ -72,7 +72,7 @@ impl ObjectImpl for DockObject {
self.appinfo.replace(appinfo); self.appinfo.replace(appinfo);
} }
"active" => { "active" => {
let active = value.get().expect("Value needs to be BoxedSearchResults"); let active = value.get().expect("Value needs to be BoxedWindowList");
self.active.replace(active); self.active.replace(active);
} }
"saved" => { "saved" => {

View file

@ -1,6 +1,6 @@
mod imp; mod imp;
use crate::utils::BoxedSearchResults; use crate::utils::BoxedWindowList;
use gdk4::glib::Object; use gdk4::glib::Object;
use gio::DesktopAppInfo; use gio::DesktopAppInfo;
use gtk4::glib; use gtk4::glib;
@ -16,7 +16,7 @@ impl DockObject {
.expect("Failed to create `DockObject`.") .expect("Failed to create `DockObject`.")
} }
pub fn from_search_results(results: BoxedSearchResults) -> Self { pub fn from_search_results(results: BoxedWindowList) -> Self {
let appinfo = if let Some(first) = results.0.iter().next() { let appinfo = if let Some(first) = results.0.iter().next() {
xdg::BaseDirectories::new() xdg::BaseDirectories::new()
.expect("could not access XDG Base directory") .expect("could not access XDG Base directory")

View file

@ -4,7 +4,7 @@ mod dock_object;
mod utils; mod utils;
mod window; mod window;
use crate::utils::BoxedSearchResults; use crate::utils::BoxedWindowList;
use async_io::Timer; use async_io::Timer;
use futures::StreamExt; use futures::StreamExt;
use gdk4::Display; use gdk4::Display;
@ -17,13 +17,15 @@ use gtk4 as gtk;
use gtk4::CssProvider; use gtk4::CssProvider;
use gtk4::StyleContext; use gtk4::StyleContext;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use pop_launcher::SearchResult;
use pop_launcher_service::IpcClient; use pop_launcher_service::IpcClient;
use postage::mpsc::Sender; use postage::mpsc::Sender;
use postage::prelude::*; use postage::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::time::Duration; use std::time::Duration;
use x11rb::rust_connection::RustConnection; use x11rb::rust_connection::RustConnection;
use zbus::Connection;
use zvariant_derive::Type;
use self::dock_object::DockObject; use self::dock_object::DockObject;
use self::window::Window; use self::window::Window;
@ -34,11 +36,20 @@ static X11_CONN: OnceCell<RustConnection> = OnceCell::new();
pub enum Event { pub enum Event {
Response(pop_launcher::Response), Response(pop_launcher::Response),
WindowList(Vec<Item>),
RefreshFromCache, RefreshFromCache,
Search(String), Search(String),
Activate(u32), Activate(u32),
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone, PartialEq, Eq)]
pub struct Item {
entity: (u32, u32),
name: String,
description: String,
desktop_entry: String,
}
fn spawn_launcher(tx: Sender<Event>) -> IpcClient { fn spawn_launcher(tx: Sender<Event>) -> IpcClient {
let (launcher, responses) = let (launcher, responses) =
pop_launcher_service::IpcClient::new().expect("failed to connect to launcher service"); pop_launcher_service::IpcClient::new().expect("failed to connect to launcher service");
@ -51,12 +62,25 @@ fn spawn_launcher(tx: Sender<Event>) -> IpcClient {
} }
}); });
// TODO listen for signal indicating change from dock service...
let mut sender = tx.clone(); let mut sender = tx.clone();
glib::MainContext::default().spawn_local(async move { glib::MainContext::default().spawn_local(async move {
loop { loop {
let _ = sender.send(Event::Search(String::new())).await; let connection = Connection::session().await.unwrap();
Timer::after(Duration::from_secs(1)).await; let m = connection
.call_method(
Some("com.System76.PopShell"),
"/com/System76/PopShell",
Some("com.System76.PopShell"),
"WindowList",
&(),
)
.await;
if let Ok(m) = m {
if let Ok(reply) = m.body::<Vec<Item>>() {
let _ = sender.send(Event::WindowList(reply)).await;
}
Timer::after(Duration::from_secs(1)).await;
}
} }
}); });
@ -86,7 +110,7 @@ fn load_css() {
} }
fn main() { fn main() {
assert!(utils::BoxedSearchResults::static_type().is_valid()); assert!(utils::BoxedWindowList::static_type().is_valid());
let app = gtk::Application::builder() let app = gtk::Application::builder()
.application_id("com.cosmic.Launcher") .application_id("com.cosmic.Launcher")
.build(); .build();
@ -116,7 +140,7 @@ fn main() {
let window = Window::new(app); let window = Window::new(app);
window.show(); window.show();
let cached_results: Vec<SearchResult> = vec![]; let cached_results: Vec<Item> = vec![];
glib::MainContext::default().spawn_local(async move { glib::MainContext::default().spawn_local(async move {
futures::pin_mut!(cached_results); futures::pin_mut!(cached_results);
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
@ -130,18 +154,17 @@ fn main() {
Event::RefreshFromCache => { Event::RefreshFromCache => {
//TODO refresh the model from cached_results (required after DnD for example) //TODO refresh the model from cached_results (required after DnD for example)
} }
Event::Response(event) => { Event::WindowList(mut results) => {
// TODO investigate why polled results are out of date after launching a new window // sort to make comparison with cache easier
if let pop_launcher::Response::Update(mut results) = event {
// sort to make comparison with cache easier
let mut cached_results = cached_results.as_mut(); let mut cached_results = cached_results.as_mut();
results.sort_by(|a, b| a.name.cmp(&b.name)); results.sort_by(|a, b| a.name.cmp(&b.name));
dbg!(&results);
dbg!(&cached_results); // dbg!(&results);
// check if cache equals the new polled results // dbg!(&cached_results);
// // check if cache equals the new polled results
// skip if equal // skip if equal
if cached_results.len() == results.len() && results.iter().zip(cached_results.iter()).fold(0, |acc, z: (&SearchResult, &SearchResult)| { if cached_results.len() == results.len() && results.iter().zip(cached_results.iter()).fold(0, |acc, z: (&Item, &Item)| {
let (a, b) = z; let (a, b) = z;
if a.name == b.name {acc + 1} else {acc} if a.name == b.name {acc + 1} else {acc}
}) == cached_results.len() { }) == cached_results.len() {
@ -150,15 +173,15 @@ fn main() {
println!("updating active apps"); println!("updating active apps");
// build active app stacks for each app // build active app stacks for each app
let stack_active = results.iter().fold(BTreeMap::new(), |mut acc: BTreeMap<String, BoxedSearchResults>, elem| { let stack_active = results.iter().fold(BTreeMap::new(), |mut acc: BTreeMap<String, BoxedWindowList>, elem| {
if let Some(v) = acc.get_mut(&elem.description) { if let Some(v) = acc.get_mut(&elem.description) {
v.0.push(elem.clone()); v.0.push(elem.clone());
} else { } else {
acc.insert(elem.description.clone(), BoxedSearchResults(vec![elem.clone()])); acc.insert(elem.description.clone(), BoxedWindowList(vec![elem.clone()]));
} }
acc acc
}); });
let mut stack_active: Vec<BoxedSearchResults> = stack_active.into_values().collect(); let mut stack_active: Vec<BoxedWindowList> = stack_active.into_values().collect();
// update active app stacks for saved apps into the saved app model // update active app stacks for saved apps into the saved app model
// then put the rest in the active app model (which doesn't include saved apps) // then put the rest in the active app model (which doesn't include saved apps)
@ -188,8 +211,10 @@ fn main() {
.collect(); .collect();
active_app_model.splice(0, model_len, &new_results[..]); active_app_model.splice(0, model_len, &new_results[..]);
cached_results.splice(.., results); cached_results.splice(.., results);
} }
else if let pop_launcher::Response::DesktopEntry { Event::Response(event) => {
// TODO investigate why polled results are out of date after launching a new window
if let pop_launcher::Response::DesktopEntry {
path, path,
gpu_preference: _gpu_preference, // TODO use GPU preference when launching app gpu_preference: _gpu_preference, // TODO use GPU preference when launching app
} = event } = event

View file

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