feat: generated workspaces protocol and various improvements

This commit is contained in:
Ashley Wulber 2022-06-08 23:51:33 -04:00
parent bfa8fa58ff
commit 02e240b6bb
No known key found for this signature in database
GPG key ID: BCD0B777C3F6E2FD
19 changed files with 480 additions and 110 deletions

View file

@ -1,22 +1,28 @@
// SPDX-License-Identifier: MPL-2.0-only
use gtk4::{gdk::Display, gio::{self, ApplicationFlags}, glib, prelude::*, CssProvider, StyleContext};
use gtk4::{
gdk::Display,
gio::{self, ApplicationFlags},
glib,
prelude::*,
CssProvider, StyleContext,
};
use once_cell::sync::OnceCell;
use window::CosmicWorkspacesWindow;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
use utils::{Event, BoxedWorkspaceList};
use utils::{Activate, Workspace};
use window::CosmicWorkspacesWindow;
mod localize;
mod utils;
mod wayland;
mod window;
mod workspace_button;
mod workspace_list;
mod wayland;
mod localize;
mod utils;
mod workspace_object;
const ID: &str = "com.system76.CosmicAppletWorkspaces";
static TX: OnceCell<mpsc::Sender<Event>> = OnceCell::new();
static TX: OnceCell<mpsc::Sender<Activate>> = OnceCell::new();
pub fn localize() {
let localizer = crate::localize::localizer();
@ -29,7 +35,7 @@ pub fn localize() {
fn load_css() {
let provider = CssProvider::new();
provider.load_from_resource("/com.system76.CosmicAppletWorkspaces/style.css");
provider.load_from_resource("/com/System76/CosmicAppletWorkspaces/style.css");
StyleContext::add_provider_for_display(
&Display::default().unwrap(),
@ -50,24 +56,16 @@ fn main() {
app.connect_activate(|app| {
load_css();
let (tx, mut rx) = mpsc::channel(100);
let (tx, mut rx) = mpsc::channel::<Vec<Workspace>>(100);
let window = CosmicWorkspacesWindow::new(app, tx.clone());
let wayland_tx = wayland::spawn_workspaces(tx.clone());
let window = CosmicWorkspacesWindow::new(app);
let workspace_list = Arc::new(Mutex::new(Vec::<BoxedWorkspaceList>::new()));
TX.set(tx.clone()).unwrap();
TX.set(wayland_tx).unwrap();
let _ = glib::MainContext::default().spawn_local(async move {
while let Some(event) = rx.recv().await {
match event {
Event::Activate(_) => {
// TODO activate the selected workspace
}
Event::WorkspaceList => {
// TODO update the model with the new workspace list
}
}
while let Some(workspace_list) = rx.recv().await {
// TODO update the model with the new workspace list
}
});
window.show();

View file

@ -5,26 +5,13 @@ use std::path::PathBuf;
use gtk4::glib;
use std::future::Future;
#[derive(Debug)]
pub enum Event {
WorkspaceList,
Activate(u32),
}
pub type Activate = u32;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Workspace {
pub(crate) id: u32,
pub(crate) active: bool,
}
#[derive(Clone, Debug, Default, glib::Boxed)]
#[boxed_type(name = "BoxedWorkspace")]
pub struct BoxedWorkspace(pub Option<Workspace>);
#[derive(Clone, Debug, Default, glib::Boxed)]
#[boxed_type(name = "BoxedWorkspaceList")]
pub struct BoxedWorkspaceList(pub Vec<Workspace>);
pub fn data_path() -> PathBuf {
let mut path = glib::user_data_dir();
path.push(crate::ID);

View file

@ -0,0 +1,52 @@
use crate::utils::{Activate, Workspace};
use std::{
num::ParseIntError,
os::unix::prelude::RawFd,
sync::{Arc, Mutex},
};
use tokio::sync::mpsc;
use wayland_client::{protocol::wl_registry, Display, GlobalManager};
mod generated {
// The generated code tends to trigger a lot of warnings
// so we isolate it into a very permissive module
#![allow(dead_code, non_camel_case_types, unused_unsafe, unused_variables)]
#![allow(non_upper_case_globals, non_snake_case, unused_imports)]
pub mod client {
// These imports are used by the generated code
pub(crate) use wayland_commons::map::{Object, ObjectMetadata};
pub(crate) use wayland_commons::smallvec;
pub(crate) use wayland_commons::wire::{Argument, ArgumentType, Message, MessageDesc};
pub(crate) use wayland_commons::{Interface, MessageGroup};
pub(crate) use wayland_client::protocol::wl_output;
pub(crate) use wayland_client::sys;
pub(crate) use wayland_client::{AnonymousObject, Main, Proxy, ProxyMap};
include!(concat!(env!("OUT_DIR"), "/ext_workspace.rs"));
}
}
pub fn spawn_workspaces(tx: mpsc::Sender<Vec<Workspace>>) -> mpsc::Sender<Activate> {
let (workspaces_tx, mut workspaces_rx) = mpsc::channel(100);
if let Ok(display) = std::env::var("HOST_WAYLAND_DISPLAY")
.map_err(anyhow::Error::msg)
.and_then(|fd| Display::connect_to_name(fd).map_err(anyhow::Error::msg))
{
std::thread::spawn(move || {
let mut event_queue = display.create_event_queue();
let attached_display = display.attach(event_queue.token());
let globals = GlobalManager::new(&attached_display);
dbg!(event_queue.sync_roundtrip(&mut (), |_, _, _| unreachable!()));
println!("Globals: ");
for (name, interface, version) in globals.list() {
println!("{}: {} (version {})", name, interface, version);
}
});
} else {
eprintln!("ENV variable HOST_WAYLAND_SOCKET is missing. Exiting...");
std::process::exit(1);
}
workspaces_tx
}

View file

@ -1,8 +1,8 @@
// SPDX-License-Identifier: MPL-2.0-only
use crate::workspace_list::WorkspaceList;
use gtk4::{glib, subclass::prelude::*};
use once_cell::sync::OnceCell;
use crate::{workspace_list::WorkspaceList};
// Object holding the state
#[derive(Default)]

View file

@ -1,6 +1,6 @@
// SPDX-License-Identifier: MPL-2.0-only
use crate::{fl, utils::Event, workspace_list::WorkspaceList};
use crate::{fl, utils::Activate, workspace_list::WorkspaceList};
use cascade::cascade;
use cosmic_panel_config::config::CosmicPanelConfig;
use gtk4::{
@ -21,7 +21,7 @@ glib::wrapper! {
}
impl CosmicWorkspacesWindow {
pub fn new(app: &gtk4::Application, tx: mpsc::Sender<Event>) -> Self {
pub fn new(app: &gtk4::Application) -> Self {
let self_: Self = Object::new(&[("application", app)])
.expect("Failed to create `CosmicWorkspacesWindow`.");
let imp = imp::CosmicWorkspacesWindow::from_instance(&self_);
@ -37,7 +37,7 @@ impl CosmicWorkspacesWindow {
};
let config = CosmicPanelConfig::load_from_env().unwrap_or_default();
let app_list = WorkspaceList::new(tx, config);
let app_list = WorkspaceList::new(config);
self_.set_child(Some(&app_list));
imp.inner.set(app_list).unwrap();

View file

@ -1,13 +1,12 @@
use std::{rc::Rc, cell::RefCell};
use gtk4::{ToggleButton, glib, subclass::prelude::*};
use tokio::sync::mpsc;
use crate::Activate;
use gtk4::{glib, subclass::prelude::*, ToggleButton};
use once_cell::sync::OnceCell;
use crate::Event;
use std::{cell::RefCell, rc::Rc};
use tokio::sync::mpsc;
// Object holding the state
#[derive(Default)]
pub struct WorkspaceButton {
pub tx: Rc<OnceCell<mpsc::Sender<Event>>>,
pub button: Rc<RefCell<ToggleButton>>,
}
@ -26,4 +25,4 @@ impl ObjectImpl for WorkspaceButton {}
impl WidgetImpl for WorkspaceButton {}
// Trait shared by all buttons
impl BoxImpl for WorkspaceButton {}
impl BoxImpl for WorkspaceButton {}

View file

@ -1,9 +1,8 @@
mod imp;
use crate::{workspace_object::WorkspaceObject, Activate, TX};
use glib::Object;
use gtk4::{glib, prelude::*, subclass::prelude::*, ToggleButton};
use tokio::sync::mpsc;
use crate::{Event, workspace_object::WorkspaceObject};
glib::wrapper! {
pub struct WorkspaceButton(ObjectSubclass<imp::WorkspaceButton>)
@ -12,16 +11,15 @@ glib::wrapper! {
}
impl WorkspaceButton {
pub fn new(tx: mpsc::Sender<Event>) -> Self {
pub fn new() -> Self {
let self_ = Object::new(&[]).expect("Failed to create `WorkspaceButton`.");
let imp = imp::WorkspaceButton::from_instance(&self_);
imp.tx.set(tx).unwrap();
let tb = ToggleButton::with_label("");
self_.append(&tb);
imp.button.replace(tb);
self_
}
@ -34,9 +32,9 @@ impl WorkspaceButton {
let new_button = ToggleButton::with_label(&format!("{}", id));
new_button.set_active(obj.active());
self.append(&new_button);
new_button.connect_clicked(glib::clone!(@weak imp.tx as tx => move |_| {
let _ = tx.get().unwrap().send(Event::Activate(id));
}));
new_button.connect_clicked(move |_| {
let _ = TX.get().unwrap().send(id);
});
imp.button.replace(new_button);
}

View file

@ -1,20 +1,19 @@
// SPDX-License-Identifier: MPL-2.0-only
use cosmic_panel_config::config::{CosmicPanelConfig};
use cosmic_panel_config::config::CosmicPanelConfig;
use gtk4::subclass::prelude::*;
use gtk4::{gio, glib};
use gtk4::{Box, ListView};
use tokio::sync::mpsc;
use once_cell::sync::OnceCell;
use tokio::sync::mpsc;
use crate::utils::Event;
use crate::utils::Activate;
#[derive(Debug, Default)]
pub struct WorkspaceList {
pub list_view: OnceCell<ListView>,
pub model: OnceCell<gio::ListStore>,
pub tx: OnceCell<mpsc::Sender<Event>>,
pub config: OnceCell<CosmicPanelConfig>
pub config: OnceCell<CosmicPanelConfig>,
}
#[glib::object_subclass]

View file

@ -1,14 +1,14 @@
// SPDX-License-Identifier: MPL-2.0-only
use crate::utils::{Event, BoxedWorkspace};
use crate::utils::Activate;
use crate::workspace_button::WorkspaceButton;
use crate::workspace_object::WorkspaceObject;
use cascade::cascade;
use cosmic_panel_config::config::{CosmicPanelConfig};
use gtk4::{glib, gio, prelude::*, subclass::prelude::*};
use cosmic_panel_config::config::CosmicPanelConfig;
use gtk4::ListView;
use gtk4::Orientation;
use gtk4::SignalListItemFactory;
use gtk4::{gio, glib, prelude::*, subclass::prelude::*};
use tokio::sync::mpsc::Sender;
mod imp;
@ -20,10 +20,9 @@ glib::wrapper! {
}
impl WorkspaceList {
pub fn new(tx: Sender<Event>, config: CosmicPanelConfig) -> Self {
pub fn new(config: CosmicPanelConfig) -> Self {
let self_: WorkspaceList = glib::Object::new(&[]).expect("Failed to create WorkspaceList");
let imp = imp::WorkspaceList::from_instance(&self_);
imp.tx.set(tx).unwrap();
imp.config.set(config).unwrap();
self_.layout();
//dnd behavior is different for each type, as well as the data in the model
@ -51,7 +50,7 @@ impl WorkspaceList {
fn setup_model(&self) {
let imp = imp::WorkspaceList::from_instance(self);
let model = gio::ListStore::new(BoxedWorkspace::static_type());
let model = gio::ListStore::new(WorkspaceObject::static_type());
let selection_model = gtk4::NoSelection::new(Some(&model));
@ -65,28 +64,24 @@ impl WorkspaceList {
let imp = imp::WorkspaceList::from_instance(self);
let factory = SignalListItemFactory::new();
let model = imp.model.get().expect("Failed to get saved app model.");
let tx = imp.tx.get().unwrap().clone();
let icon_size = imp.config.get().unwrap().get_applet_icon_size();
factory.connect_setup(
glib::clone!(@weak model => move |_, list_item| {
let workspace_button = WorkspaceButton::new(tx.clone());
list_item.set_child(Some(&workspace_button));
}),
);
factory.connect_setup(glib::clone!(@weak model => move |_, list_item| {
let workspace_button = WorkspaceButton::new();
list_item.set_child(Some(&workspace_button));
}));
factory.connect_bind(|_, list_item| {
let workspace_object = list_item
.item()
.expect("The item has to exist.")
.downcast::<WorkspaceObject>()
.expect("The item has to be a `DockObject`");
let workspace_button = list_item
.child()
.expect("The list item child needs to exist.")
.downcast::<WorkspaceButton>()
.expect("The list item type needs to be `DockItem`");
workspace_button.set_workspace_object(&workspace_object);
},
);
let workspace_object = list_item
.item()
.expect("The item has to exist.")
.downcast::<WorkspaceObject>()
.expect("The item has to be a `DockObject`");
let workspace_button = list_item
.child()
.expect("The list item child needs to exist.")
.downcast::<WorkspaceButton>()
.expect("The list item type needs to be `DockItem`");
workspace_button.set_workspace_object(&workspace_object);
});
// Set the factory of the list view
imp.list_view.get().unwrap().set_factory(Some(&factory));
}

View file

@ -53,7 +53,6 @@ impl ObjectImpl for WorkspaceObject {
false,
ParamFlags::READWRITE,
),
]
});
PROPERTIES.as_ref()

View file

@ -19,11 +19,11 @@ impl WorkspaceObject {
pub fn id(&self) -> u32 {
imp::WorkspaceObject::from_instance(&self).id.get()
}
}
pub fn active(&self) -> bool {
imp::WorkspaceObject::from_instance(&self).active.get()
}
}
}
#[derive(Clone, Debug, Default, glib::Boxed)]