Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: create `CommonContainer` trait; progress on win event hooking

Lars Berger5319d39dcc50
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 1ae96274..2e535f1d 100755
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -2,25 +2,17 @@
"version": "0.2.0",
"configurations": [
{
- // Use IntelliSense to find out which attributes exist for C# debugging
- // Use hover for the description of the existing attributes
- // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
- "name": ".NET Core Launch (console)",
- "type": "coreclr",
+ "name": "Launch",
+ "type": "cppvsdbg",
"request": "launch",
- "preLaunchTask": "build",
- // If you have changed target frameworks, make sure to update the program path.
- "program": "${workspaceFolder}/GlazeWM.App/bin/Debug/net7-windows10.0.17763.0/GlazeWM.exe",
- "args": [],
- "cwd": "${workspaceFolder}/GlazeWM.App",
- // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
- "console": "internalConsole",
- "stopAtEntry": false
- },
- {
- "name": ".NET Core Attach",
- "type": "coreclr",
- "request": "attach"
+ "program": "${workspaceRoot}/target/debug/wm.exe",
+ "preLaunchTask": "rust: cargo build",
+ "args": ["start"],
+ "stopAtEntry": false,
+ "cwd": "${workspaceRoot}",
+ "environment": [],
+ "console": "integratedTerminal"
+ // "externalConsole": true
}
]
}
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index 0079abd4..b2d4f29c 100755
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -2,74 +2,11 @@
"version": "2.0.0",
"tasks": [
{
- "label": "build",
- "command": "dotnet",
- "type": "process",
- "args": [
- "build",
- "${workspaceFolder}/GlazeWM.App/GlazeWM.App.csproj",
- "/property:GenerateFullPaths=true",
- "/consoleloggerparameters:NoSummary"
- ],
- "problemMatcher": "$msCompile"
- },
- {
- "label": "publish (x64)",
- "command": "dotnet",
- "type": "process",
- "args": [
- "publish",
- "${workspaceFolder}/GlazeWM.App/GlazeWM.App.csproj",
- "--configuration=Release",
- "--runtime=win-x64",
- "--self-contained",
- "-p:PublishSingleFile=true",
- "-p:IncludeAllContentForSelfExtract=true",
- "/property:GenerateFullPaths=true",
- "/consoleloggerparameters:NoSummary"
- ],
- "problemMatcher": "$msCompile"
- },
- {
- "label": "publish (x86)",
- "command": "dotnet",
- "type": "process",
- "args": [
- "publish",
- "${workspaceFolder}/GlazeWM.App/GlazeWM.App.csproj",
- "--configuration=Release",
- "--runtime=win-x86",
- "--self-contained",
- "-p:PublishSingleFile=true",
- "-p:IncludeAllContentForSelfExtract=true",
- "/property:GenerateFullPaths=true",
- "/consoleloggerparameters:NoSummary"
- ],
- "problemMatcher": "$msCompile"
- },
- {
- "label": "watch",
- "command": "dotnet",
- "type": "process",
- "args": [
- "watch",
- "run",
- "--project",
- "${workspaceFolder}/GlazeWM.App/GlazeWM.App.csproj"
- ],
- "problemMatcher": "$msCompile"
- },
- {
- "label": "publish",
- "command": "dotnet",
- "type": "process",
- "args": [
- "publish",
- "${workspaceFolder}/GlazeWM.App/GlazeWM.App.csproj",
- "/property:GenerateFullPaths=true",
- "/consoleloggerparameters:NoSummary"
- ],
- "problemMatcher": "$msCompile"
+ "type": "cargo",
+ "command": "build",
+ "problemMatcher": ["$rustc"],
+ "group": "build",
+ "label": "rust: cargo build"
}
]
}
diff --git a/Cargo.lock b/Cargo.lock
index bdc2a164..4f2c2391 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -465,6 +465,15 @@ version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
+[[package]]
+name = "matchers"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"
+dependencies = [
+ "regex-automata 0.1.10",
+]
+
[[package]]
name = "memchr"
version = "2.7.1"
@@ -670,8 +679,17 @@ checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15"
dependencies = [
"aho-corasick",
"memchr",
- "regex-automata",
- "regex-syntax",
+ "regex-automata 0.4.5",
+ "regex-syntax 0.8.2",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"
+dependencies = [
+ "regex-syntax 0.6.29",
]
[[package]]
@@ -682,9 +700,15 @@ checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd"
dependencies = [
"aho-corasick",
"memchr",
- "regex-syntax",
+ "regex-syntax 0.8.2",
]
+[[package]]
+name = "regex-syntax"
+version = "0.6.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
+
[[package]]
name = "regex-syntax"
version = "0.8.2"
@@ -960,10 +984,14 @@ version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b"
dependencies = [
+ "matchers",
"nu-ansi-term",
+ "once_cell",
+ "regex",
"sharded-slab",
"smallvec",
"thread_local",
+ "tracing",
"tracing-core",
"tracing-log",
]
diff --git a/Cargo.toml b/Cargo.toml
index 7f116ec6..9d9261c3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
resolver = "2"
members = ["packages/*"]
+default-members = ["packages/wm"]
[workspace.dependencies]
anyhow = "1"
diff --git a/packages/cli/src/main.rs b/packages/cli/src/main.rs
index ba5557e5..28677848 100644
--- a/packages/cli/src/main.rs
+++ b/packages/cli/src/main.rs
@@ -1,29 +1,29 @@
-#[derive(Parser, Debug)]
-#[clap(author, version, about, long_about = None, arg_required_else_help = true)]
-pub struct Cli {
- #[command(subcommand)]
- pub message: WmMessage,
-}
+// #[derive(Parser, Debug)]
+// #[clap(author, version, about, long_about = None, arg_required_else_help = true)]
+// pub struct Cli {
+// #[command(subcommand)]
+// pub message: WmMessage,
+// }
#[tokio::main]
async fn main() {
- let cli = Cli::parse();
+ // let cli = Cli::parse();
- match cli.message {
- WmMessage::Start { config_path } => {
- let wm_path = env::var_os("CARGO_BIN_FILE_WM")
- .context("Failed to resolve path to the WM process.")?;
+ // match cli.message {
+ // WmMessage::Start { config_path } => {
+ // let wm_path = env::var_os("CARGO_BIN_FILE_WM")
+ // .context("Failed to resolve path to the WM process.")?;
- Command::new(wm_path)
- }
- _ => {
- let args = std::env::args_os();
- IpcClient::connect()
- .await
- .unwrap()
- .send_raw(args)
- .await
- .unwrap()
- }
- }
+ // Command::new(wm_path)
+ // }
+ // _ => {
+ // let args = std::env::args_os();
+ // IpcClient::connect()
+ // .await
+ // .unwrap()
+ // .send_raw(args)
+ // .await
+ // .unwrap()
+ // }
+ // }
}
diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.toml
index 624b1615..19458af8 100644
--- a/packages/wm/Cargo.toml
+++ b/packages/wm/Cargo.toml
@@ -23,6 +23,6 @@ regex = { workspace = true }
tokio = { workspace = true }
tokio-tungstenite = "0.21"
tracing = "0.1"
-tracing-subscriber = "0.3"
+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
windows = { workspace = true }
wineventhook = "0.9"
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index 154e0c42..d1ef1374 100644
--- a/packages/wm/src/common/platform/event_listener.rs
+++ b/packages/wm/src/common/platform/event_listener.rs
@@ -7,27 +7,30 @@ use tokio::sync::{
};
use wineventhook::{EventFilter, WindowEvent, WindowEventHook};
-use crate::user_config::UserConfig;
+use crate::user_config::{KeybindingConfig, UserConfig};
+
+use super::{EventWindow, NativeWindow};
pub enum PlatformEvent {
DisplaySettingsChanged,
+ KeybindingTriggered(KeybindingConfig),
MouseMove,
- WindowDestroyed,
- WindowFocused,
- WindowHidden,
- WindowLocationChanged,
- WindowMinimizeEnded,
- WindowMinimized,
- WindowMovedOrResized,
- WindowShown,
- WindowTitleChanged,
+ WindowDestroyed(NativeWindow),
+ WindowFocused(NativeWindow),
+ WindowHidden(NativeWindow),
+ WindowLocationChanged(NativeWindow),
+ WindowMinimized(NativeWindow),
+ WindowMinimizeEnded(NativeWindow),
+ WindowMovedOrResized(NativeWindow),
+ WindowShown(NativeWindow),
+ WindowTitleChanged(NativeWindow),
}
pub struct EventListener {
config: Arc<Mutex<UserConfig>>,
config_changes_rx: UnboundedReceiver<UserConfig>,
pub event_rx: UnboundedReceiver<WindowEvent>,
- hook: WindowEventHook,
+ event_window: EventWindow,
}
impl EventListener {
@@ -38,14 +41,13 @@ impl EventListener {
) -> Result<Self> {
let (event_tx, event_rx) = mpsc::unbounded_channel();
- let hook =
- WindowEventHook::hook(EventFilter::default(), event_tx).await?;
+ let event_window = EventWindow::new();
Ok(Self {
config,
config_changes_rx,
event_rx,
- hook,
+ event_window,
})
}
}
diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rs
new file mode 100644
index 00000000..2635dd60
--- /dev/null
+++ b/packages/wm/src/common/platform/event_window.rs
@@ -0,0 +1,121 @@
+use std::{cell::OnceCell, thread};
+
+use anyhow::{bail, Result};
+use tokio::sync::mpsc::UnboundedSender;
+use tracing::{error, warn};
+use windows::Win32::{
+ Foundation::HWND,
+ UI::{
+ Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK},
+ WindowsAndMessaging::{
+ DispatchMessageW, GetMessageW, TranslateMessage,
+ EVENT_OBJECT_CLOAKED, EVENT_OBJECT_DESTROY, EVENT_OBJECT_FOCUS,
+ EVENT_OBJECT_HIDE, EVENT_OBJECT_LOCATIONCHANGE,
+ EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_SHOW, EVENT_SYSTEM_FOREGROUND,
+ EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART,
+ EVENT_SYSTEM_MOVESIZEEND, MSG, OBJID_WINDOW, WINEVENT_OUTOFCONTEXT,
+ WINEVENT_SKIPOWNPROCESS,
+ },
+ },
+};
+
+use super::{NativeWindow, PlatformEvent};
+
+thread_local! {
+ static HOOK_EVENT_TX: OnceCell<UnboundedSender<PlatformEvent>> = OnceCell::new();
+}
+
+extern "system" fn event_hook_proc(
+ hook: HWINEVENTHOOK,
+ event: u32,
+ hwnd: HWND,
+ id_object: i32,
+ id_child: i32,
+ event_thread: u32,
+ event_time: u32,
+) {
+ HOOK_EVENT_TX.with(|event_tx| {
+ if let Some(event_tx) = event_tx.get() {
+ let is_window_event =
+ id_object == OBJID_WINDOW.0 && id_child == 0 && hwnd != HWND(0);
+
+ // Check whether the event is associated with a window object instead
+ // of a UI control.
+ if !is_window_event {
+ return;
+ }
+
+ let window = NativeWindow::new(hwnd);
+
+ let platform_event = match event {
+ EVENT_OBJECT_DESTROY => PlatformEvent::WindowDestroyed(window),
+ EVENT_SYSTEM_FOREGROUND => PlatformEvent::WindowFocused(window),
+ EVENT_OBJECT_HIDE | EVENT_OBJECT_CLOAKED => {
+ PlatformEvent::WindowHidden(window)
+ }
+ EVENT_OBJECT_LOCATIONCHANGE => {
+ PlatformEvent::WindowLocationChanged(window)
+ }
+ EVENT_SYSTEM_MINIMIZESTART => {
+ PlatformEvent::WindowMinimized(window)
+ }
+ EVENT_SYSTEM_MINIMIZEEND => {
+ PlatformEvent::WindowMinimizeEnded(window)
+ }
+ EVENT_SYSTEM_MOVESIZEEND => {
+ PlatformEvent::WindowMovedOrResized(window)
+ }
+ EVENT_OBJECT_SHOW => PlatformEvent::WindowShown(window),
+ EVENT_OBJECT_NAMECHANGE => {
+ PlatformEvent::WindowTitleChanged(window)
+ }
+ _ => return,
+ };
+
+ if let Err(err) = event_tx.send(platform_event) {
+ warn!("Failed to send platform event '{}'", err);
+ }
+ }
+ });
+}
+
+pub struct EventWindow;
+
+impl EventWindow {
+ pub fn new() -> Self {
+ let event_window_thread = thread::spawn(|| unsafe {
+ let event_hook = SetWinEventHook(
+ EVENT_SYSTEM_FOREGROUND,
+ EVENT_OBJECT_DESTROY,
+ None,
+ Some(event_hook_proc),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ );
+
+ if event_hook.is_invalid() {
+ bail!("`SetWinEventHook` failed.");
+ }
+
+ let mut msg = MSG::default();
+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ let true = UnhookWinEvent(event_hook).as_bool() else {
+ bail!("`UnhookWinEvent` failed.");
+ };
+
+ Ok(())
+ });
+
+ match event_window_thread.join() {
+ Err(err) => error!("join th: {:?}", err),
+ _ => (),
+ }
+
+ Self
+ }
+}
diff --git a/packages/wm/src/common/platform/mod.rs b/packages/wm/src/common/platform/mod.rs
index cde0c0bb..e5275a2f 100644
--- a/packages/wm/src/common/platform/mod.rs
+++ b/packages/wm/src/common/platform/mod.rs
@@ -1,9 +1,11 @@
mod event_listener;
+mod event_window;
mod native_monitor;
mod native_window;
mod platform;
pub use event_listener::*;
+pub use event_window::*;
pub use native_monitor::*;
pub use native_window::*;
pub use platform::*;
diff --git a/packages/wm/src/containers/common_container.rs b/packages/wm/src/containers/common_container.rs
new file mode 100644
index 00000000..5379e4a8
--- /dev/null
+++ b/packages/wm/src/containers/common_container.rs
@@ -0,0 +1,33 @@
+use std::cell::{Ref, RefMut};
+
+use super::ContainerRef;
+
+// TODO: Consider renaming to `TilingContainer`.
+pub trait CommonContainer {
+ fn borrow_parent(&self) -> Ref<'_, Option<ContainerRef>>;
+ fn borrow_parent_mut(&self) -> RefMut<'_, Option<ContainerRef>>;
+ fn borrow_children(&self) -> Ref<'_, Vec<ContainerRef>>;
+ fn borrow_children_mut(&self) -> RefMut<'_, Vec<ContainerRef>>;
+
+ /// Return a reference to the parent node, unless this node is the root
+ /// of the tree.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the node is currently mutability borrowed.
+ fn parent(&self) -> Option<ContainerRef> {
+ self.borrow_parent().clone()
+ }
+
+ fn insert_child(&self, target_index: usize, child: ContainerRef) {
+ self
+ .borrow_children_mut()
+ .insert(target_index, child.clone());
+
+ *child.common().borrow_parent_mut() = Some(child.clone());
+ }
+
+ fn grandparent(&self) -> Option<ContainerRef> {
+ self.parent()?.common().parent()
+ }
+}
diff --git a/packages/wm/src/containers/container.rs b/packages/wm/src/containers/container.rs
deleted file mode 100644
index ce6ef386..00000000
--- a/packages/wm/src/containers/container.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use core::fmt;
-use std::{
- cell::{Ref, RefCell, RefMut},
- collections::VecDeque,
- rc::{Rc, Weak},
-};
-
-use uuid::Uuid;
-
-// use super::{ContainerType, SplitContainer};
-
-#[derive(Clone)]
-pub struct RootContainerRef(Rc<RefCell<RootContainer>>);
-
-#[derive(Debug)]
-pub struct RootContainer {
- pub parent: Option<ContainerRef>,
- pub children: Vec<ContainerRef>,
- pub val: i32,
-}
-
-/// A reference to a `Container`.
-///
-/// Internally, this uses reference counting for lifetime tracking and
-/// `std::cell::RefCell` for interior mutability.
-///
-/// **Note:** Cloning a `ContainerRef` only increments a reference count.
-#[derive(Clone, Debug)]
-pub enum ContainerRef {
- RootContainer(RootContainerRef),
- // Monitor(MonitorRef),
- // Workspace(WorkspaceRef),
- // SplitContainer(SplitContainerRef),
- // Window(WindowRef),
-}
-
-pub trait CommonContainer {
- /// Return a reference to the parent node, unless this node is the root
- /// of the tree.
- ///
- /// # Panics
- ///
- /// Panics if the node is currently mutability borrowed.
- fn parent(&self) -> Option<ContainerRef>;
- fn set_parent(&self, parent: ContainerRef);
- fn grandparent(&self) -> Option<ContainerRef>;
-
- fn insert_child(&self, child: ContainerRef);
-}
-
-impl RootContainerRef {
- pub fn new(val: i32) -> Self {
- let root = RootContainer {
- parent: None,
- children: Vec::new(),
- val,
- };
-
- Self(Rc::new(RefCell::new(root)))
- }
-
- pub fn set_val(&self, val: i32) {
- self.0.borrow_mut().val = val
- }
-}
-
-impl CommonContainer for RootContainerRef {
- fn grandparent(&self) -> Option<ContainerRef> {
- self.parent()?.common().parent()
- }
-
- fn parent(&self) -> Option<ContainerRef> {
- self.0.borrow().parent.clone()
- }
-
- fn insert_child(&self, child: ContainerRef) {
- self.0.borrow_mut().children.push(child.clone());
- child
- .common()
- .set_parent(ContainerRef::RootContainer(self.clone()))
- }
-
- fn set_parent(&self, parent: ContainerRef) {
- self.0.borrow_mut().parent = Some(parent)
- }
-}
-
-impl ContainerRef {
- fn common(&self) -> &dyn CommonContainer {
- match self {
- ContainerRef::RootContainer(c) => c,
- }
- }
-}
-
-impl fmt::Debug for RootContainerRef {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- fmt::Debug::fmt(&self.0.borrow().val, f)
- }
-}
diff --git a/packages/wm/src/containers/container_ref.rs b/packages/wm/src/containers/container_ref.rs
new file mode 100644
index 00000000..0c450c3b
--- /dev/null
+++ b/packages/wm/src/containers/container_ref.rs
@@ -0,0 +1,33 @@
+use crate::{
+ monitors::MonitorRef, windows::WindowRef, workspaces::WorkspaceRef,
+};
+
+use super::{CommonContainer, RootContainerRef, SplitContainerRef};
+
+/// A reference to a `Container`.
+///
+/// Internally, this uses reference counting for lifetime tracking and
+/// `std::cell::RefCell` for interior mutability.
+///
+/// **Note:** Cloning a `ContainerRef` only increments a reference count.
+#[derive(Clone, Debug)]
+pub enum ContainerRef {
+ RootContainer(RootContainerRef),
+ Monitor(MonitorRef),
+ Workspace(WorkspaceRef),
+ SplitContainer(SplitContainerRef),
+ Window(WindowRef),
+}
+
+impl ContainerRef {
+ pub fn common(&self) -> &dyn CommonContainer {
+ match self {
+ ContainerRef::RootContainer(c) => c,
+ ContainerRef::Monitor(c) => c,
+ // ContainerRef::Workspace(c) => c,
+ // ContainerRef::SplitContainer(c) => c,
+ // ContainerRef::Window(c) => c,
+ _ => todo!(),
+ }
+ }
+}
diff --git a/packages/wm/src/containers/mod.rs b/packages/wm/src/containers/mod.rs
index c3e2e023..a72cf07e 100644
--- a/packages/wm/src/containers/mod.rs
+++ b/packages/wm/src/containers/mod.rs
@@ -1,9 +1,11 @@
-mod container;
+mod common_container;
+mod container_ref;
mod container_type;
mod root_container;
mod split_container;
-pub use container::*;
+pub use common_container::*;
+pub use container_ref::*;
pub use container_type::*;
pub use root_container::*;
pub use split_container::*;
diff --git a/packages/wm/src/containers/root_container.rs b/packages/wm/src/containers/root_container.rs
index 099656fa..46333c8e 100644
--- a/packages/wm/src/containers/root_container.rs
+++ b/packages/wm/src/containers/root_container.rs
@@ -1,22 +1,44 @@
-use super::{ContainerType, InnerContainer};
+use std::{
+ cell::{Ref, RefCell, RefMut},
+ rc::Rc,
+};
+
+use super::{CommonContainer, ContainerRef};
+
+#[derive(Clone, Debug)]
+pub struct RootContainerRef(Rc<RefCell<RootContainer>>);
#[derive(Debug)]
pub struct RootContainer {
- pub inner: InnerContainer,
- width: u32,
- height: u32,
- x: u32,
- y: u32,
+ pub parent: Option<ContainerRef>,
+ pub children: Vec<ContainerRef>,
}
-impl RootContainer {
+impl RootContainerRef {
pub fn new() -> Self {
- Self {
- inner: InnerContainer::new(ContainerType::RootContainer),
- width: 0,
- height: 0,
- x: 0,
- y: 0,
- }
+ let root = RootContainer {
+ parent: None,
+ children: Vec::new(),
+ };
+
+ Self(Rc::new(RefCell::new(root)))
+ }
+}
+
+impl CommonContainer for RootContainerRef {
+ fn borrow_parent(&self) -> Ref<'_, Option<ContainerRef>> {
+ Ref::map(self.0.borrow(), |c| &c.parent)
+ }
+
+ fn borrow_parent_mut(&self) -> RefMut<'_, Option<ContainerRef>> {
+ RefMut::map(self.0.borrow_mut(), |c| &mut c.parent)
+ }
+
+ fn borrow_children(&self) -> Ref<'_, Vec<ContainerRef>> {
+ Ref::map(self.0.borrow(), |c| &c.children)
+ }
+
+ fn borrow_children_mut(&self) -> RefMut<'_, Vec<ContainerRef>> {
+ RefMut::map(self.0.borrow_mut(), |c| &mut c.children)
}
}
diff --git a/packages/wm/src/containers/split_container.rs b/packages/wm/src/containers/split_container.rs
index 0b06b6f0..1f0cd839 100644
--- a/packages/wm/src/containers/split_container.rs
+++ b/packages/wm/src/containers/split_container.rs
@@ -1,24 +1,17 @@
-use crate::containers::ContainerType;
+use std::{cell::RefCell, rc::Rc};
-use super::InnerContainer;
+use crate::common::TilingDirection;
+
+#[derive(Clone, Debug)]
+pub struct SplitContainerRef(Rc<RefCell<SplitContainer>>);
#[derive(Debug)]
pub struct SplitContainer {
- pub inner: InnerContainer,
- width: u32,
- height: u32,
- x: u32,
- y: u32,
+ tiling_direction: TilingDirection,
}
impl SplitContainer {
- pub fn new() -> Self {
- Self {
- inner: InnerContainer::new(ContainerType::SplitContainer),
- width: 0,
- height: 0,
- x: 0,
- y: 0,
- }
+ pub fn new(tiling_direction: TilingDirection) -> Self {
+ Self { tiling_direction }
}
}
diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rs
index 8dbe5d1c..eddd4640 100644
--- a/packages/wm/src/ipc_server.rs
+++ b/packages/wm/src/ipc_server.rs
@@ -9,6 +9,7 @@ use tokio::{
mpsc::{self, UnboundedReceiver, UnboundedSender},
Mutex,
},
+ task,
};
use tokio_tungstenite::accept_async;
use tracing::info;
@@ -37,17 +38,19 @@ impl IpcServer {
let server = TcpListener::bind(DEFAULT_IPC_ADDR).await?;
- while let Ok((stream, _)) = server.accept().await {
- let mut ws_stream = accept_async(stream).await?;
- info!("Received new IPC connection.");
+ task::spawn(async move {
+ while let Ok((stream, _)) = server.accept().await {
+ let mut ws_stream = accept_async(stream).await.unwrap();
+ info!("Received new IPC connection.");
- while let Some(msg) = ws_stream.next().await {
- let msg = msg?;
- if msg.is_text() || msg.is_binary() {
- ws_stream.send(msg).await?;
+ while let Some(msg) = ws_stream.next().await {
+ let msg = msg.unwrap();
+ if msg.is_text() || msg.is_binary() {
+ ws_stream.send(msg).await.unwrap();
+ }
}
}
- }
+ });
Ok(Self {
message_rx,
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index 6f384c40..9c5f3d49 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -10,11 +10,15 @@ use tokio::{
process::Command,
sync::{mpsc, Mutex},
};
-use tracing::info;
+use tracing::{info, level_filters::LevelFilter};
+use tracing_subscriber::EnvFilter;
use user_config::UserConfig;
use wm::WindowManager;
-use crate::cli::{Cli, CliCommand};
+use crate::{
+ cli::{Cli, CliCommand},
+ containers::{CommonContainer, ContainerRef, RootContainerRef},
+};
mod cli;
mod common;
@@ -31,23 +35,18 @@ mod workspaces;
#[tokio::main]
async fn main() {
- let cli = Cli::parse();
-
- match cli.command {
- CliCommand::Start { config_path } => {
- if let Err(err) = start_wm(config_path).await {
- eprintln!("Error starting WM: {}", err);
- }
- }
- _ => {
- let args = std::env::args_os();
- IpcClient::connect()
- .await
- .unwrap()
- .send_raw(args)
- .await
- .unwrap()
- }
+ // TODO: Take log level and config path from `start` command arguments.
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ EnvFilter::from_env("LOG_LEVEL")
+ .add_directive(LevelFilter::INFO.into()),
+ )
+ .init();
+
+ let config_path = None;
+
+ if let Err(err) = start_wm(config_path).await {
+ eprintln!("Failed to start GlazeWM: {}", err);
}
}
@@ -57,17 +56,17 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {
let (config_changes_tx, config_changes_rx) =
mpsc::unbounded_channel::<UserConfig>();
- // Start listening for platform events.
- let mut event_listener =
- Platform::new_event_listener(config.clone(), config_changes_rx)
- .await?;
-
let mut ipc_server = IpcServer::start().await?;
// Start watcher process for restoring hidden windows on crash.
start_watcher_process()?;
- let mut wm = WindowManager::start(config, config_changes_tx).await?;
+ let mut wm =
+ WindowManager::start(config.clone(), config_changes_tx).await?;
+
+ // Start listening for platform events.
+ let mut event_listener =
+ Platform::new_event_listener(config, config_changes_rx).await?;
loop {
let wm_state = wm.state.clone();
@@ -79,22 +78,19 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {
wm_state.lock().await.add_monitor();
wm_state.lock().await.add_monitor();
- let root = RootContainerRef::new(1);
- let leaf = RootContainerRef::new(2);
- root.insert_child(ContainerRef::RootContainer(leaf.clone()));
+ let root = RootContainerRef::new();
+ let leaf = RootContainerRef::new();
+ root.insert_child(0, ContainerRef::RootContainer(leaf.clone()));
- let leaf_deep = RootContainerRef::new(3);
- leaf.insert_child(ContainerRef::RootContainer(leaf_deep.clone()));
+ let leaf_deep = RootContainerRef::new();
+ leaf.insert_child(0, ContainerRef::RootContainer(leaf_deep.clone()));
- match leaf_deep.grandparent().unwrap() {
- ContainerRef::RootContainer(val) => val.set_val(999),
- }
- println!("aaaa {:?}", root);
- println!("aaaa {:?}", leaf);
- println!("aaaa {:?}", leaf_deep);
- println!("aaaa {:?}", leaf_deep.grandparent());
+ // println!("aaaa {:?}", root);
+ // println!("aaaa {:?}", leaf);
+ // println!("aaaa {:?}", leaf_deep);
+ // println!("aaaa {:?}", leaf_deep.grandparent());
- wm.process_event(event).await
+ // wm.process_event(event).await
},
Some(wm_event) = wm.event_rx.recv() => {
info!("Received WM event: {:?}", wm_event);
@@ -112,9 +108,16 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {
}
}
+/// Launch watcher binary. This is a separate process that is responsible
+/// for restoring hidden windows in case the main WM process crashes.
+///
+/// This assumes the watcher binary exists in the same directory as the WM
+/// binary.
fn start_watcher_process() -> Result<Command> {
- let watcher_path = env::var_os("CARGO_BIN_FILE_WATCHER")
- .context("Failed to resolve path to the watcher process.")?;
+ let watcher_path = env::current_exe()?
+ .parent()
+ .context("Failed to resolve path to the watcher process.")?
+ .join("watcher");
Ok(Command::new(watcher_path))
}
diff --git a/packages/wm/src/monitors/monitor.rs b/packages/wm/src/monitors/monitor.rs
index fec6531c..b86700a0 100644
--- a/packages/wm/src/monitors/monitor.rs
+++ b/packages/wm/src/monitors/monitor.rs
@@ -1,11 +1,20 @@
+use std::{
+ cell::{Ref, RefCell, RefMut},
+ rc::Rc,
+};
+
use crate::{
common::platform::NativeMonitor,
- containers::{ContainerType, InnerContainer},
+ containers::{CommonContainer, ContainerRef},
};
+#[derive(Clone, Debug)]
+pub struct MonitorRef(Rc<RefCell<Monitor>>);
+
#[derive(Debug)]
pub struct Monitor {
- pub inner: InnerContainer,
+ pub parent: Option<ContainerRef>,
+ pub children: Vec<ContainerRef>,
pub device_name: String,
pub width: u32,
pub height: u32,
@@ -13,15 +22,36 @@ pub struct Monitor {
pub y: u32,
}
-impl Monitor {
+impl MonitorRef {
pub fn new(native_monitor: NativeMonitor) -> Self {
- Self {
- inner: InnerContainer::new(ContainerType::Monitor),
+ let monitor = Monitor {
+ parent: None,
+ children: Vec::new(),
device_name: native_monitor.device_name,
width: native_monitor.width,
height: native_monitor.height,
x: native_monitor.x,
y: native_monitor.y,
- }
+ };
+
+ Self(Rc::new(RefCell::new(monitor)))
+ }
+}
+
+impl CommonContainer for MonitorRef {
+ fn borrow_parent(&self) -> Ref<'_, Option<ContainerRef>> {
+ Ref::map(self.0.borrow(), |c| &c.parent)
+ }
+
+ fn borrow_parent_mut(&self) -> RefMut<'_, Option<ContainerRef>> {
+ RefMut::map(self.0.borrow_mut(), |c| &mut c.parent)
+ }
+
+ fn borrow_children(&self) -> Ref<'_, Vec<ContainerRef>> {
+ Ref::map(self.0.borrow(), |c| &c.children)
+ }
+
+ fn borrow_children_mut(&self) -> RefMut<'_, Vec<ContainerRef>> {
+ RefMut::map(self.0.borrow_mut(), |c| &mut c.children)
}
}
diff --git a/packages/wm/src/windows/window.rs b/packages/wm/src/windows/window.rs
index 1badffb1..4f112078 100644
--- a/packages/wm/src/windows/window.rs
+++ b/packages/wm/src/windows/window.rs
@@ -1,8 +1,11 @@
-use crate::containers::{ContainerType, InnerContainer};
+use std::{cell::RefCell, rc::Rc};
+#[derive(Clone, Debug)]
+pub struct WindowRef(Rc<RefCell<Window>>);
+
+// TODO: Consider renaming to `TilingWindow` and splitting out `NonTilingWindow`.
#[derive(Debug)]
pub struct Window {
- pub inner: InnerContainer,
width: u32,
height: u32,
x: u32,
@@ -12,7 +15,6 @@ pub struct Window {
impl Window {
pub fn new() -> Self {
Self {
- inner: InnerContainer::new(ContainerType::Window),
width: 0,
height: 0,
x: 0,
diff --git a/packages/wm/src/wm_event.rs b/packages/wm/src/wm_event.rs
index 84967d5d..b97094e3 100644
--- a/packages/wm/src/wm_event.rs
+++ b/packages/wm/src/wm_event.rs
@@ -2,7 +2,7 @@ use uuid::Uuid;
use crate::{
common::{platform::WindowHandle, TilingDirection},
- containers::Container,
+ containers::ContainerRef,
};
#[derive(Debug)]
@@ -12,17 +12,17 @@ pub struct BindingModeChangedEvent {
#[derive(Debug)]
pub struct FocusChangedEvent {
- pub focused_container: Container,
+ pub focused_container: ContainerRef,
}
#[derive(Debug)]
pub struct FocusedContainerMovedEvent {
- pub focused_container: Container,
+ pub focused_container: ContainerRef,
}
#[derive(Debug)]
pub struct MonitorAddedEvent {
- pub added_monitor: Container,
+ pub added_monitor: ContainerRef,
}
#[derive(Debug)]
@@ -33,7 +33,7 @@ pub struct MonitorRemovedEvent {
#[derive(Debug)]
pub struct NativeFocusSyncedEvent {
- pub focused_container: Container,
+ pub focused_container: ContainerRef,
}
#[derive(Debug)]
@@ -43,7 +43,7 @@ pub struct TilingDirectionChangedEvent {
#[derive(Debug)]
pub struct WindowManagedEvent {
- pub managed_window: Container,
+ pub managed_window: ContainerRef,
}
#[derive(Debug)]
@@ -54,7 +54,7 @@ pub struct WindowUnmanagedEvent {
#[derive(Debug)]
pub struct WorkspaceActivatedEvent {
- pub activated_workspace: Container,
+ pub activated_workspace: ContainerRef,
}
#[derive(Debug)]
@@ -65,7 +65,7 @@ pub struct WorkspaceDeactivatedEvent {
#[derive(Debug)]
pub struct WorkingAreaResizedEvent {
- pub affected_monitor: Container,
+ pub affected_monitor: ContainerRef,
}
#[derive(Debug)]
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index 18a65d16..371a7876 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -12,8 +12,11 @@ use uuid::Uuid;
use crate::{
common::{platform::NativeMonitor, FocusMode},
- containers::{Container, ContainerType, RootContainer},
- monitors::Monitor,
+ containers::{
+ CommonContainer, ContainerRef, ContainerType, RootContainer,
+ RootContainerRef,
+ },
+ monitors::{Monitor, MonitorRef},
user_config::{BindingModeConfig, UserConfig},
wm_event::WmEvent,
};
@@ -21,10 +24,10 @@ use crate::{
pub struct WmState {
/// Root node of the container tree. Monitors are the children of the
/// root node, followed by workspaces, then split containers/windows.
- root_container: RootContainer,
+ root_container: RootContainerRef,
/// Containers (and their descendants) that have a pending redraw.
- containers_to_redraw: Vec<Weak<Container>>,
+ containers_to_redraw: Vec<Weak<ContainerRef>>,
/// Whether native focus needs to be reassigned to the WM's focused
/// container.
@@ -48,7 +51,7 @@ impl WmState {
event_tx: UnboundedSender<WmEvent>,
) -> Self {
Self {
- root_container: RootContainer::new(),
+ root_container: RootContainerRef::new(),
containers_to_redraw: Vec::new(),
has_pending_focus_sync: false,
binding_modes: Vec::new(),
@@ -60,14 +63,11 @@ impl WmState {
pub fn add_monitor(&mut self) {
let monitor =
- Monitor::new(NativeMonitor::new(String::from("aaa"), 0, 0, 0, 0));
+ MonitorRef::new(NativeMonitor::new(String::from("aaa"), 0, 0, 0, 0));
self
.root_container
- .inner
- .children
- .borrow_mut()
- .push_front(Rc::new(RefCell::new(Container::Monitor(monitor))));
+ .insert_child(0, ContainerRef::Monitor(monitor))
}
pub fn emit_event(&self, event: WmEvent) -> Result<()> {
diff --git a/packages/wm/src/workspaces/workspace.rs b/packages/wm/src/workspaces/workspace.rs
index ef44afa8..eb1443b2 100644
--- a/packages/wm/src/workspaces/workspace.rs
+++ b/packages/wm/src/workspaces/workspace.rs
@@ -1,11 +1,12 @@
-use crate::{
- common::RectDelta,
- containers::{ContainerType, InnerContainer},
-};
+use std::{cell::RefCell, rc::Rc};
+
+use crate::common::RectDelta;
+
+#[derive(Clone, Debug)]
+pub struct WorkspaceRef(Rc<RefCell<Workspace>>);
#[derive(Debug)]
pub struct Workspace {
- pub inner: InnerContainer,
name: String,
display_name: String,
keep_alive: bool,
@@ -20,7 +21,6 @@ impl Workspace {
outer_gaps: RectDelta,
) -> Self {
Self {
- inner: InnerContainer::new(ContainerType::Workspace),
name,
display_name,
keep_alive,