Skip to content

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

wip

Lars Bergerdffc37de6b68
diff --git a/Cargo.toml b/Cargo.toml
index ea8bcb08..7f116ec6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,11 +1,6 @@
[workspace]
resolver = "2"
-members = [
- "packages/ipc-client",
- "packages/ipc-server",
- "packages/watcher",
- "packages/wm",
-]
+members = ["packages/*"]
[workspace.dependencies]
anyhow = "1"
diff --git a/packages/ipc-client/src/ipc_message.rs b/packages/ipc-client/src/ipc_message.rs
new file mode 100644
index 00000000..6841e599
--- /dev/null
+++ b/packages/ipc-client/src/ipc_message.rs
@@ -0,0 +1,9 @@
+pub enum IpcMessage {
+ QueryMonitors,
+ QueryWorkspaces,
+ QueryWindows,
+ QueryFocusedContainer,
+ QueryBindingMode,
+ InvokeCommand,
+ SubscribeEvent,
+}
diff --git a/packages/ipc-client/src/lib.rs b/packages/ipc-client/src/lib.rs
index a361c02f..f167d6de 100644
--- a/packages/ipc-client/src/lib.rs
+++ b/packages/ipc-client/src/lib.rs
@@ -2,6 +2,20 @@ use std::env::ArgsOs;
use anyhow::Result;
-pub fn send_raw(_message: ArgsOs) -> Result<()> {
- Ok(())
+pub const DEFAULT_IPC_ADDR: &'static str = "127.0.0.1:6123";
+
+pub struct IpcClient {}
+
+impl IpcClient {
+ pub fn new() -> Self {
+ Self {}
+ }
+
+ pub async fn connect() -> Result<()> {
+ todo!()
+ }
+
+ pub async fn send_raw(_message: ArgsOs) -> Result<()> {
+ todo!()
+ }
}
diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.toml
index f127d276..5c7317be 100644
--- a/packages/wm/Cargo.toml
+++ b/packages/wm/Cargo.toml
@@ -14,6 +14,7 @@ watcher = { path = "../watcher" }
anyhow = { workspace = true }
clap = { version = "4", features = ["derive"] }
futures-util = "0.3"
+home = "0.5"
uuid = { version = "1", features = ["v4"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
diff --git a/packages/wm/src/cli.rs b/packages/wm/src/cli.rs
index 1988a0c8..b079e2ac 100644
--- a/packages/wm/src/cli.rs
+++ b/packages/wm/src/cli.rs
@@ -16,7 +16,7 @@ pub enum CliCommand {
Start {
/// Custom path to user config file.
#[clap(short, long)]
- config: String,
+ config_path: Option<String>,
},
/// Query the window manager's state.
diff --git a/packages/wm/src/common/direction.rs b/packages/wm/src/common/direction.rs
new file mode 100644
index 00000000..1dfa9906
--- /dev/null
+++ b/packages/wm/src/common/direction.rs
@@ -0,0 +1,37 @@
+pub enum Direction {
+ Left,
+ Right,
+ Up,
+ Down,
+}
+
+impl Direction {
+ /// Get the inverse of a given direction.
+ ///
+ /// Example:
+ /// ```
+ /// Direction::Left.inverse() // Direction::Right
+ /// ```
+ pub fn inverse(&self) -> Direction {
+ match self {
+ Direction::Left => Direction::Right,
+ Direction::Right => Direction::Left,
+ Direction::Up => Direction::Down,
+ Direction::Down => Direction::Up,
+ }
+ }
+
+ /// Get the tiling direction that is needed when moving or switching
+ /// focus in given direction.
+ ///
+ /// Example:
+ /// ```
+ /// Direction::Left.to_tiling_direction() // TilingDirection::Horizontal
+ /// ```
+ pub fn to_tiling_direction(&self) -> TilingDirection {
+ match self {
+ Direction::Left | Direction::Right => TilingDirection.Horizontal,
+ Direction::Up | Direction::Down => TilingDirection.Vertical,
+ }
+ }
+}
diff --git a/packages/wm/src/common/mod.rs b/packages/wm/src/common/mod.rs
index 7e8b1e7d..93fc0224 100644
--- a/packages/wm/src/common/mod.rs
+++ b/packages/wm/src/common/mod.rs
@@ -1,9 +1,13 @@
+mod direction;
mod focus_mode;
mod platform;
mod rect_delta;
+mod tiling_direction;
mod units;
+pub use direction::*;
pub use focus_mode::*;
pub use platform::*;
pub use rect_delta::*;
+pub use tiling_direction::*;
pub use units::*;
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index db6bb608..82491fe0 100644
--- a/packages/wm/src/common/platform/event_listener.rs
+++ b/packages/wm/src/common/platform/event_listener.rs
@@ -1,336 +1,41 @@
-// use std::{
-// cell::OnceCell, fmt::Debug, hash::Hash, io, mem::MaybeUninit,
-// num::NonZeroU32, ops::Range, ptr, ptr::NonNull,
-// };
-
-// use winapi::{
-// shared::{
-// minwindef::{DWORD, FALSE},
-// windef::{HWINEVENTHOOK, HWINEVENTHOOK__, HWND, HWND__},
-// },
-// um::{
-// winnt::LONG,
-// winuser::{GetWindowThreadProcessId, SetWinEventHook, UnhookWinEvent},
-// },
-// };
-
-// use crate::{
-// message_loop::run_dummy_message_loop, raw_event, RawWindowHandle,
-// WindowEvent,
-// };
-
-// /// A raw handle to a hook created using [`SetWinEventHook`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook).
-// pub type RawHookHandle = HWINEVENTHOOK;
-
-// /// A non null handle to a hook created using [`SetWinEventHook`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook).
-// pub type HookHandle = NonNull<HWINEVENTHOOK__>;
-
-// /// A raw handle to a window.
-// pub type RawWindowHandle = HWND;
-
-// /// A non null handle to a window.
-// pub type WindowHandle = NonNull<HWND__>;
-
-// /// A raw window event received by a [`WindowEventHook`](crate::WindowEventHook).
-// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-// pub struct RawWindowEvent {
-// /// Handle to the shared event hook function.
-// pub hook_handle: HWINEVENTHOOK,
-// /// Specifies the event that occurred
-// pub event_id: DWORD,
-// /// Handle to the window that generates the event, or `NULL` if no window is associated with the event.
-// /// For example, the mouse pointer is not associated with a window.
-// pub window_handle: HWND,
-// /// Identifies the object associated with the event.
-// pub object_id: LONG,
-// /// Identifies whether the event was triggered by an object or a child element of the object.
-// /// If this value is [`CHILDID_SELF`], the event was triggered by the object; otherwise, this value is the child ID of the element that triggered the event.
-// pub child_id: LONG,
-// /// Identifies the thread that generated the event.
-// pub thread_id: DWORD,
-// /// Specifies the time since system startup, in milliseconds, that the event was generated.
-// pub timestamp: DWORD,
-// }
-
-// thread_local! {
-// static HOOK_EVENT_TX: OnceCell<(tokio::sync::mpsc::UnboundedSender<WindowEvent>, EventPredicate)> = OnceCell::new();
-// }
-
-// extern "system" fn win_event_hook_callback(
-// hook: HWINEVENTHOOK,
-// event: DWORD,
-// h_wnd: HWND,
-// id_object: LONG,
-// id_child: LONG,
-// event_thread: DWORD,
-// event_time: DWORD,
-// ) {
-// HOOK_EVENT_TX.with(|event_tx| {
-// if let Some((event_tx, predicate)) = event_tx.get() {
-// let event = WindowEvent::from_raw(RawWindowEvent {
-// hook_handle: hook,
-// event_id: event,
-// window_handle: h_wnd,
-// object_id: id_object,
-// child_id: id_child,
-// thread_id: event_thread,
-// timestamp: event_time,
-// });
-// if predicate(&event) {
-// let _ = event_tx.send(event);
-// }
-// }
-// });
-// }
-
-// #[derive(Debug)]
-// /// A hook with a message loop that listens for window events.
-// pub struct WindowEventHook {
-// abort_tx: tokio::sync::oneshot::Sender<()>,
-// event_thread: async_thread::JoinHandle<Result<(), std::io::Error>>,
-// }
-
-// impl WindowEventHook {
-// /// Creates a new [`WindowEventHook`] that listens to the events matching the given filter.
-// /// An [`WindowEvent`] is sent to the given `event_tx` whenever an event matching the filter is received.
-// /// A dedicated event loop thread is created to be able to receive events.
-// pub async fn hook(
-// filter: EventFilter,
-// event_tx: tokio::sync::mpsc::UnboundedSender<WindowEvent>,
-// ) -> Result<Self, io::Error> {
-// let (handle_tx, handle_rx) = tokio::sync::oneshot::channel();
-// let (abort_tx, abort_rx) = tokio::sync::oneshot::channel();
-
-// let event_thread = async_thread::Builder::new()
-// .name("WindowEventHook EventLoop".to_string())
-// .spawn(move || {
-// let mut flags = HookFlags::OUT_OF_CONTEXT;
-// if filter.skip_own_process {
-// flags |= HookFlags::SKIP_OWN_PROCESS;
-// }
-// if filter.skip_own_thread {
-// flags |= HookFlags::SKIP_OWN_THREAD;
-// }
-
-// let hook = unsafe {
-// SetWinEventHook(
-// filter.events.0 as _,
-// filter.events.1 as _,
-// ptr::null_mut(),
-// Some(win_event_hook_callback),
-// filter.process_id,
-// filter.thread_id,
-// flags.bits(),
-// )
-// };
-
-// let hook_result = if !hook.is_null() {
-// HOOK_EVENT_TX.with(|tx| {
-// tx.set((event_tx, filter.predicate.get()))
-// .map_err(|_| ())
-// .unwrap();
-// });
-// Ok(())
-// } else {
-// Err(io::Error::last_os_error())
-// };
-
-// handle_tx.send(hook_result).unwrap();
-
-// run_dummy_message_loop(abort_rx).unwrap();
-
-// let unhook_result = unsafe { UnhookWinEvent(hook) };
-// if unhook_result == FALSE {
-// Err(io::Error::last_os_error())
-// } else {
-// Ok(())
-// }
-// })
-// .unwrap();
-
-// handle_rx.await.unwrap().map(|_| Self {
-// abort_tx,
-// event_thread,
-// })
-// }
-
-// /// Unhook this hook and stop the event loop.
-// pub async fn unhook(self) -> Result<(), io::Error> {
-// self.abort_tx.send(()).unwrap();
-// self.event_thread.join().await.unwrap()
-// }
-// }
-
-// /// A filter for window events.
-// pub type EventPredicate = fn(&WindowEvent) -> bool;
-
-// #[derive(Clone, Copy)]
-// struct EventPredicateHolder(Option<EventPredicate>);
-
-// impl EventPredicateHolder {
-// fn new() -> Self {
-// Self(None)
-// }
-// fn set(&mut self, predicate: EventPredicate) {
-// self.0 = Some(predicate);
-// }
-// fn get(&self) -> EventPredicate {
-// self.0.unwrap_or(|_| true)
-// }
-// }
-
-// impl Debug for EventPredicateHolder {
-// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-// write!(f, "{:?}", self.0.as_ref().map(|_| "some predicate"))
-// }
-// }
-
-// #[derive(Debug, Clone, Copy)]
-// /// A filter for window events to be received.
-// pub struct EventFilter {
-// events: (i32, i32), // Range<i32> is not Copy
-// skip_own_thread: bool,
-// skip_own_process: bool,
-// thread_id: u32,
-// process_id: u32,
-// predicate: EventPredicateHolder,
-// }
-
-// impl Default for EventFilter {
-// fn default() -> Self {
-// Self {
-// events: (raw_event::MIN, raw_event::MAX),
-// skip_own_thread: true,
-// skip_own_process: false,
-// thread_id: 0,
-// process_id: 0,
-// predicate: EventPredicateHolder::new(),
-// }
-// }
-// }
-
-// impl EventFilter {
-// /// Set the event that should be received by the hook.
-// #[must_use]
-// pub fn event(self, event: i32) -> Self {
-// self.events(Range {
-// start: event,
-// end: event,
-// })
-// }
-
-// /// Set the range of events that should be received by the hook.
-// #[must_use]
-// pub fn events(mut self, events: Range<i32>) -> Self {
-// self.events = (events.start, events.end);
-// self
-// }
-
-// /// If true, the event will be skipped if it is generated by the current process.
-// #[must_use]
-// pub fn skip_own_process(mut self, value: bool) -> Self {
-// self.skip_own_process = value;
-// self
-// }
-
-// /// If true, the event will be skipped if it is generated by the event loop thread.
-// #[must_use]
-// pub fn skip_own_thread(mut self, value: bool) -> Self {
-// self.skip_own_thread = value;
-// self
-// }
-
-// /// Only include events from the process with the given id.
-// #[must_use]
-// pub fn process(mut self, id: NonZeroU32) -> Self {
-// self.process_id = id.get();
-// self
-// }
-
-// /// Only include events from the thread with the given id.
-// #[must_use]
-// pub fn thread(mut self, id: NonZeroU32) -> Self {
-// self.thread_id = id.get();
-// self
-// }
-
-// /// Only include events from the thread and process of the given window.
-// #[must_use]
-// pub fn window(self, window: RawWindowHandle) -> Self {
-// let window_info = WindowThreadProcess::from_handle(window);
-// self.thread(window_info.thread).process(window_info.process)
-// }
-
-// /// Include events from all processes.
-// /// To receive events from the current process `skip_own_process` must be set to false.
-// #[must_use]
-// pub fn all_processes(mut self) -> Self {
-// self.process_id = 0;
-// self
-// }
-
-// /// Include events from all threads.
-// /// To receive events from the event loop thread `skip_own_thread` must be set to false.
-// #[must_use]
-// pub fn all_threads(mut self) -> Self {
-// self.thread_id = 0;
-// self
-// }
-
-// /// Set the predicate that determines whether an event should be accepted.
-// #[must_use]
-// pub fn predicate(mut self, predicate: EventPredicate) -> EventFilter {
-// self.predicate.set(predicate);
-// self
-// }
-// }
-
-// struct WindowThreadProcess {
-// process: NonZeroU32,
-// thread: NonZeroU32,
-// }
-
-// impl WindowThreadProcess {
-// fn new(process: NonZeroU32, thread: NonZeroU32) -> Self {
-// Self { process, thread }
-// }
-
-// fn from_handle(window: RawWindowHandle) -> Self {
-// let mut process_id = MaybeUninit::uninit();
-// let thread_id =
-// unsafe { GetWindowThreadProcessId(window, process_id.as_mut_ptr()) };
-// let process_id = unsafe { process_id.assume_init() };
-// Self::new(
-// NonZeroU32::new(process_id).unwrap(),
-// NonZeroU32::new(thread_id).unwrap(),
-// )
-// }
-// }
-
-// // bitflags::bitflags! {
-// // struct HookFlags: u32 {
-// // /// The callback function is not mapped into the address space of the process that generates the event.
-// // /// Because the hook function is called across process boundaries, the system must queue events.
-// // /// Although this method is asynchronous, events are guaranteed to be in sequential order.
-// // const OUT_OF_CONTEXT = 0x0000;
-
-// // /// Prevents this instance of the hook from receiving the events that are generated by the thread that is registering this hook.
-// // const SKIP_OWN_THREAD = 0x0001;
-
-// // /// Prevents this instance of the hook from receiving the events that are generated by threads in this process.
-// // /// This flag does not prevent threads from generating events.
-// // const SKIP_OWN_PROCESS = 0x0002;
-
-// // /// The DLL that contains the callback function is mapped into the address space of the process that generates the event.
-// // /// With this flag, the system sends event notifications to the callback function as they occur.
-// // /// The hook function must be in a DLL when this flag is specified.
-// // /// This flag has no effect when both the calling process and the generating process are not 32-bit or 64-bit processes, or when the generating process is a console application.
-// // const IN_CONTEXT = 0x0004;
-// // }
-// // }
-
-// // impl Default for HookFlags {
-// // fn default() -> Self {
-// // Self::OUT_OF_CONTEXT
-// // }
-// // }
+use anyhow::Result;
+
+pub enum PlatformEvent {
+ DisplaySettingsChanged,
+ MouseMove,
+ WindowDestroyed,
+ WindowFocused,
+ WindowHidden,
+ WindowLocationChanged,
+ WindowMinimizeEnded,
+ WindowMinimized,
+ WindowMovedOrResized,
+ WindowShown,
+ WindowTitleChanged,
+}
+
+pub struct EventListener {
+ event_tx: Sender<WindowEvent>,
+ pub event_rx: Receiver<WindowEvent>,
+ hook: WindowEventHook,
+}
+
+impl EventListener {
+ pub fn new() -> Self {
+ let (event_tx, mut event_rx) = mpsc::unbounded_channel();
+ Self { event_tx, event_rx }
+ }
+
+ pub async fn start(&mut self) -> Self {
+ self.hook =
+ WindowEventHook::hook(EventFilter::default(), self.event_tx).await?;
+
+ self
+ }
+}
+
+impl Drop for EventListener {
+ fn drop(&mut self) {
+ self.hook.unhook().unwrap();
+ }
+}
diff --git a/packages/wm/src/common/rect_delta.rs b/packages/wm/src/common/rect_delta.rs
index 4e25c737..aba3a3d5 100644
--- a/packages/wm/src/common/rect_delta.rs
+++ b/packages/wm/src/common/rect_delta.rs
@@ -1,19 +1,24 @@
pub struct RectDelta {
- /// The diff in x-coordinates of the upper-left corner of the rectangle.
- left: i32,
+ /// The delta in x-coordinates on the left of the rectangle.
+ left: LengthValue,
- /// The diff in y-coordinates of the upper-left corner of the rectangle.
- top: i32,
+ /// The delta in y-coordinates on the top of the rectangle.
+ top: LengthValue,
- /// The diff in x-coordinates of the lower-right corner of the rectangle.
- right: i32,
+ /// The delta in x-coordinates on the right of the rectangle.
+ right: LengthValue,
- /// The diff in y-coordinates of the lower-right corner of the rectangle.
- bottom: i32,
+ /// The delta in y-coordinates on the bottom of the rectangle.
+ bottom: LengthValue,
}
impl RectDelta {
- pub fn new(left: i32, top: i32, right: i32, bottom: i32) -> Self {
+ pub fn new(
+ left: LengthValue,
+ top: LengthValue,
+ right: LengthValue,
+ bottom: LengthValue,
+ ) -> Self {
Self {
left,
top,
@@ -21,4 +26,44 @@ impl RectDelta {
bottom,
}
}
+
+ pub fn from_str(unparsed: &str) -> Result<Self> {
+ let parts: Vec<_> = unparsed.split_whitespace();
+
+ match parts.len() {
+ 1 => {
+ let value = parse_length_value(&parts[0])?;
+ Ok(Self::new(
+ value.clone(),
+ value.clone(),
+ value.clone(),
+ value,
+ ))
+ }
+ 2 => {
+ let top_bottom = parse_length_value(&parts[0])?;
+ let left_right = parse_length_value(&parts[1])?;
+ Ok(Self::new(
+ left_right.clone(),
+ top_bottom.clone(),
+ left_right,
+ top_bottom,
+ ))
+ }
+ 3 => {
+ let top = parse_length_value(&parts[0])?;
+ let left_right = parse_length_value(&parts[1])?;
+ let bottom = parse_length_value(&parts[2])?;
+ Ok(Self::new(left_right.clone(), top, left_right, bottom))
+ }
+ 4 => {
+ let top = parse_length_value(&parts[0])?;
+ let right = parse_length_value(&parts[1])?;
+ let bottom = parse_length_value(&parts[2])?;
+ let left = parse_length_value(&parts[3])?;
+ Ok(Self::new(left, top, right, bottom))
+ }
+ _ => Err("Invalid shorthand.".into()),
+ }
+ }
}
diff --git a/packages/wm/src/common/tiling_direction.rs b/packages/wm/src/common/tiling_direction.rs
new file mode 100644
index 00000000..166ea1b1
--- /dev/null
+++ b/packages/wm/src/common/tiling_direction.rs
@@ -0,0 +1,19 @@
+pub enum TilingDirection {
+ Vertical,
+ Horizontal,
+}
+
+impl TilingDirection {
+ /// Get the inverse of a given tiling direction.
+ ///
+ /// Example:
+ /// ```
+ /// TilingDirection::Horizontal.inverse() // TilingDirection::Vertical
+ /// ```
+ pub fn inverse(&self) -> TilingDirection {
+ match self {
+ TilingDirection::Horizontal => TilingDirection::Vertical,
+ TilingDirection::Vertical => TilingDirection::Horizontal,
+ }
+ }
+}
diff --git a/packages/wm/src/common/units.rs b/packages/wm/src/common/units.rs
index fca9b652..bc193102 100644
--- a/packages/wm/src/common/units.rs
+++ b/packages/wm/src/common/units.rs
@@ -1,27 +1,37 @@
-use regex::Regex;
use std::str::FromStr;
-pub enum Unit {
+use regex::Regex;
+
+pub struct LengthValue {
+ pub amount: f32,
+ pub unit: LengthUnit,
+}
+
+pub enum LengthUnit {
Pixel,
Percentage,
- None,
}
-/// Parses a string containing a number followed by a unit (`px`, `%`).
-///
-/// Returns a tuple where the first element is a float, and the second
-/// element is the unit as an enum value.
-pub fn extract_units(amount_with_units: &str) -> (f32, Unit) {
- let units_regex = Regex::new(r"(\d+)(%|ppt|px)?").unwrap();
+impl LengthValue {
+ /// Parses a string containing a number followed by a unit (`px`, `%`).
+ ///
+ /// Example:
+ /// ```
+ /// LengthValue::from_str("100px") // { amount: 100.0, unit: LengthUnit::Pixel }
+ /// ```
+ fn from_str(unparsed: &str) -> Result<LengthValue> {
+ let units_regex = Regex::new(r"(\d+)(%|ppt|px)?")?;
- let captures = units_regex.captures(amount_with_units).unwrap();
- let amount = f32::from_str(&captures[1]).unwrap_or(0.0);
+ let captures = units_regex.captures(unparsed)?;
+ let amount = f32::from_str(&captures[1])?;
- let unit = match captures.get(2).map_or("", |m| m.as_str()) {
- "px" => Unit::Pixel,
- "%" => Unit::Percentage,
- _ => Unit::None,
- };
+ let unit_str = captures.get(2).map_or("", |m| m.as_str());
+ let unit = match unit_str {
+ "px" | "" => Unit::Pixel,
+ "%" => Unit::Percentage,
+ _ => bail!("Not a valid unit '{}'.", unit_str),
+ };
- (amount, unit)
+ Ok(LengthValue { amount, unit })
+ }
}
diff --git a/packages/wm/src/containers/container.rs b/packages/wm/src/containers/container.rs
index b6be873b..e4bad040 100644
--- a/packages/wm/src/containers/container.rs
+++ b/packages/wm/src/containers/container.rs
@@ -4,6 +4,7 @@ use uuid::Uuid;
use super::container_type::ContainerType;
+#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct InnerContainer {
id: Uuid,
parent: Option<Arc<dyn Container>>,
@@ -44,15 +45,22 @@ pub trait Container {
/// Derived container type (eg. `ContainerType::Monitor`).
fn r#type(&self) -> ContainerType;
+ /// Height of the container. Implementation varies by container type.
fn height(&self) -> u32;
+
+ /// Width of the container. Implementation varies by container type.
fn width(&self) -> u32;
+
+ /// X-coordinate of the container. Implementation varies by container type.
fn x(&self) -> u32;
+
+ /// Y-coordinate of the container. Implementation varies by container type.
fn y(&self) -> u32;
/// A unique identifier for the container.
fn inner(&self) -> InnerContainer;
- /// A unique identifier for the container.
+ /// Unique identifier for the container.
fn id(&self) -> Uuid {
self.inner().id
}
diff --git a/packages/wm/src/containers/container_type.rs b/packages/wm/src/containers/container_type.rs
index c300b6cf..e37696bd 100644
--- a/packages/wm/src/containers/container_type.rs
+++ b/packages/wm/src/containers/container_type.rs
@@ -7,9 +7,5 @@ pub enum ContainerType {
Monitor,
Workspace,
SplitContainer,
- FloatingWindow,
- TilingWindow,
- MinimizedWindow,
- MaximizedWindow,
- FullscreenWindow,
+ Window,
}
diff --git a/packages/wm/src/ipc_server.rs b/packages/wm/src/ipc_server.rs
index b6fb87da..dcdcae3f 100644
--- a/packages/wm/src/ipc_server.rs
+++ b/packages/wm/src/ipc_server.rs
@@ -1,4 +1,5 @@
use anyhow::Result;
+use ipc_client::DEFAULT_IPC_ADDR;
use futures_util::{SinkExt, StreamExt};
use tokio::{net::TcpListener, sync::mpsc::UnboundedSender};
use tokio_tungstenite::accept_async;
@@ -12,20 +13,21 @@ pub enum IpcMessage {
pub struct IpcServer {
message_tx: UnboundedSender<IpcMessage>,
+ message_rx: UnboundedReceiver<IpcMessage>,
}
-const DEFAULT_PORT: u32 = 6123;
-
impl IpcServer {
pub fn new(message_tx: UnboundedSender<IpcMessage>) -> Self {
- Self { message_tx }
+ let (message_tx, mut message_rx) = mpsc::unbounded_channel::<i32>();
+ Self { message_tx, message_rx }
}
pub async fn start(&self) -> Result<()> {
- let server = TcpListener::bind("127.0.0.1:6123").await?;
+ 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.");
while let Some(msg) = ws_stream.next().await {
let msg = msg?;
diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rs
index 1bd9cc52..79359769 100644
--- a/packages/wm/src/main.rs
+++ b/packages/wm/src/main.rs
@@ -14,9 +14,12 @@ mod ipc_server;
mod common;
mod containers;
mod monitors;
-// mod user_config;
+mod user_config;
// mod windows;
+mod wm;
mod wm_state;
+mod wm_command;
+mod wm_event;
mod workspaces;
#[tokio::main]
@@ -24,53 +27,36 @@ async fn main() {
let cli = Cli::parse();
match cli.command {
- CliCommand::Start { config } => {
- let workspace = Workspace::new(
- "name".into(),
- "display_name".into(),
- true,
- RectDelta::new(1, 2, 3, 4),
- );
+ CliCommand::Start { config_path } => {
+ let _ = start_wm(config_path).await;
}
_ => {
let args = std::env::args_os();
- ipc_client::send_raw(args).unwrap()
+ ipc_client::new().send_raw(args).unwrap()
}
}
}
-async fn start_wm() {
- let (event_tx, mut event_rx) = mpsc::unbounded_channel();
-
- // TODO
- let (ipc_tx, mut ipc_rx) = mpsc::unbounded_channel::<i32>();
-
- let hook = WindowEventHook::hook(EventFilter::default(), event_tx)
- .await
- .unwrap();
-
- let ipc_server = IpcServer::new(ipc_tx);
-
- tokio::spawn(async move {
- let wm_state = WmState::new();
-
- // Wait and print events
- while let Some(event) = event_rx.recv().await {
- println!("{:#?}", event);
- wm_state.focus_mode();
- }
- });
-
- let mut foo = None;
- let mut bar = None;
+async fn start_wm(config_path: Option<&str>) {
+ let user_config = UserConfig::read(config_path).await;
+ let event_listener = platform::EventListener::new().start().await;
+ let ipc_server = IpcServer::new().start().await;
+ let wm = WindowManager::new(user_config).start().await;
loop {
tokio::select! {
- f = event_rx.recv() => foo = f,
- b = ipc_rx.recv() => bar = b,
+ Some(event) = event_listener.event_rx.recv() => {
+ info!("Received platform event: {}", event);
+ wm.process_event(event).await
+ },
+ Some(wm_event) = wm.event_rx.recv() => {
+ info!("Received WM event: {}", wm_event);
+ ipc_server.process_event(wm_event).await
+ },
+ Some(ipc_message) = ipc_server.message_rx.recv() => {
+ info!("Received IPC message: {}", ipc_message);
+ ipc_server.process_message(ipc_message, wm.state).await
+ },
}
}
-
- // Unhook the hook
- hook.unhook().await.unwrap();
}
diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rs
new file mode 100644
index 00000000..d5090143
--- /dev/null
+++ b/packages/wm/src/user_config.rs
@@ -0,0 +1,103 @@
+#[derive(Debug, Deserialize)]
+pub struct GapsConfig {
+ /// Gap between adjacent windows.
+ #[serde(deserialize_with = "to_length_value")]
+ pub inner_gap: LengthValue,
+
+ /// Gap between windows and the screen edge.
+ #[serde(deserialize_with = "to_rect_delta")]
+ pub outer_gap: RectDelta,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct FocusBorder {
+ /// Whether the default transparent border be used.
+ pub enabled: bool,
+
+ /// Border color of the window.
+ pub color: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct FocusBordersConfig {
+ /// Border of the focused window.
+ pub active: FocusBorder,
+
+ /// Border of non-focused windows.
+ pub inactive: FocusBorder,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BindingModeConfig {
+ /// Name of the binding mode.
+ pub name: String,
+
+ /// Keybindings that will be active when the binding mode is active.
+ pub keybindings: Vec<KeybindingConfig>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct UserConfig {
+ pub binding_modes: Vec<BindingModeConfig>,
+ pub focus_borders: FocusBordersConfig,
+ pub gaps: GapsConfig,
+ pub general: GeneralConfig,
+ pub keybindings: Vec<KeybindingConfig>,
+ pub window_rules: Vec<WindowRuleConfig>,
+ pub workspaces: Vec<WorkspaceConfig>,
+}
+
+const SAMPLE_CONFIG: &str = include_str!("resources/sample-config.yaml");
+
+impl UserConfig {
+ pub async fn read(config_path: Option<&str>) -> Self {
+ let default_config_path = home::home_dir().context("Unable to get home directory.")?.resolve(".glzr/glazewm/config.yaml");
+
+
+ let config_path = match config_path {
+ Some(val) => PathBuf::from(val),
+ None => default_config_path,
+ };
+
+ // Create new config file from sample if it doesn't exist.
+ if !config_path.exists() {
+ fs::create_dir_all(&config_path).with_context(|| {
+ format!("Unable to create directory {}.", &config_path.display())
+ })?;
+
+ fs::write(&config_path, SAMPLE_CONFIG).with_context(|| {
+ format!("Unable to write to {}.", config_path.display())
+ })?;
+
+ let config_str = fs::read_to_string(&config_path).context("Unable to read config file.");
+ }
+
+ UserConfig {
+ gaps: GapsConfig::new(),
+ focus_borders: FocusBordersConfig::new(),
+ general: GeneralConfig::new(),
+ bar: BarConfig::new(),
+ bars: Vec::new(),
+ workspaces: Vec::new(),
+ window_rules: Vec::new(),
+ keybindings: Vec::new(),
+ binding_modes: Vec::new(),
+ }
+ }
+}
+
+fn to_length_value<'de, D>(deserializer: D) -> Result<LengthValue, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ let str = String::deserialize(deserializer)?;
+ LengthValue::from_str(&str).map_err(serde::de::Error::custom)
+}
+
+fn to_rect_delta<'de, D>(deserializer: D) -> Result<RectDelta, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ let str = String::deserialize(deserializer)?;
+ RectDelta::from_str(&str).map_err(serde::de::Error::custom)
+}
diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rs
new file mode 100644
index 00000000..79eda87d
--- /dev/null
+++ b/packages/wm/src/wm.rs
@@ -0,0 +1,19 @@
+pub struct WindowManager {
+ state: WmState,
+}
+
+impl WindowManager {
+ pub fn new() -> Self {
+ Self {
+ state: WmState::new(),
+ }
+ }
+
+ pub fn init(&mut self) {
+ todo!()
+ }
+
+ pub fn process_event(event: WindowEvent) {
+ todo!()
+ }
+}
diff --git a/packages/wm/src/wm_command.rs b/packages/wm/src/wm_command.rs
new file mode 100644
index 00000000..440c9d1c
--- /dev/null
+++ b/packages/wm/src/wm_command.rs
@@ -0,0 +1,71 @@
+pub enum WmCommand {
+ CloseWindow(dyn Container),
+ ExitWm,
+ Focus(dyn Container, Direction),
+ FocusWorkspace(dyn Container, String),
+ IgnoreWindow(dyn Container),
+ MoveWindow(dyn Container, Direction),
+ MoveWorkspace(dyn Container, Direction),
+ Noop,
+ ReloadConfig,
+ SetTilingDirection(dyn Container, TilingDirection),
+ ToggleTilingDirection(dyn Container),
+}
+
+impl WmCommand {
+ pub fn from_str(
+ unparsed: &str,
+ subject_container: dyn Container,
+ ) -> Result<Command> {
+ let parts: Vec<&str> = unparsed.split_whitespace().collect();
+
+ let command = match parts.as_slice() {
+ ["close_window"] => WmCommand::CloseWindow(subject_container),
+ ["exit_wm"] => WmCommand::ExitWm,
+ ["focus", "left"] => {
+ WmCommand::Focus(subject_container, Direction::Left)
+ }
+ ["focus", "right"] => {
+ WmCommand::Focus(subject_container, Direction::Right)
+ }
+ ["focus", "up"] => {
+ WmCommand::Focus(subject_container, Direction::Up)
+ }
+ ["focus", "down"] => {
+ WmCommand::Focus(subject_container, Direction::Down)
+ }
+ ["focus_workspace", name] => {
+ WmCommand::FocusWorkspace(subject_container, Direction::Down)
+ }
+ ["move_window", "left"] => {
+ WmCommand::MoveWindow(subject_container, Direction::Left)
+ }
+ ["move_window", "right"] => {
+ WmCommand::MoveWindow(subject_container, Direction::Right)
+ }
+ ["move_window", "up"] => {
+ WmCommand::MoveWindow(subject_container, Direction::Up)
+ }
+ ["move_window", "down"] => {
+ WmCommand::MoveWindow(subject_container, Direction::Down)
+ }
+ ["move_workspace", "left"] => {
+ WmCommand::MoveWorkspace(subject_container, Direction::Left)
+ }
+ ["move_workspace", "right"] => {
+ WmCommand::MoveWorkspace(subject_container, Direction::Right)
+ }
+ ["move_workspace", "up"] => {
+ WmCommand::MoveWorkspace(subject_container, Direction::Up)
+ }
+ ["move_workspace", "down"] => {
+ WmCommand::MoveWorkspace(subject_container, Direction::Down)
+ }
+ ["noop"] => WmCommand::Noop,
+ ["reload_config"] => WmCommand::ReloadConfig,
+ _ => Err("Not a known command."),
+ };
+
+ Ok(command)
+ }
+}
diff --git a/packages/wm/src/wm_event.rs b/packages/wm/src/wm_event.rs
new file mode 100644
index 00000000..c2988ac1
--- /dev/null
+++ b/packages/wm/src/wm_event.rs
@@ -0,0 +1,46 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Deserialize, Clone, Serialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum WmEvent {
+ BindingModeChanged {
+ new_binding_mode: String,
+ },
+ FocusChanged {
+ focused_container: &dyn Container,
+ },
+ FocusedContainerMoved {
+ focused_container: &dyn Container,
+ },
+ MonitorAdded {
+ added_monitor: &dyn Container,
+ },
+ MonitorRemoved {
+ removed_id: Guid,
+ removed_device_name: String,
+ },
+ NativeFocusSynced {
+ focused_container: &dyn Container,
+ },
+ TilingDirectionChanged {
+ new_tiling_direction: TilingDirection,
+ },
+ UserConfigReloaded,
+ WindowManaged {
+ managed_window: &dyn Container,
+ },
+ WindowUnmanaged {
+ unmanaged_id: Guid,
+ unmanaged_handle: WindowHandle,
+ },
+ WorkspaceActivated {
+ activated_workspace: &dyn Container,
+ },
+ WorkspaceDeactivated {
+ deactivated_id: Guid,
+ deactivated_name: String,
+ },
+ WorkingAreaResized {
+ affected_monitor: &dyn Container,
+ },
+}
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index 18e55d84..4a6f0da3 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -20,7 +20,7 @@ pub struct WmState {
has_pending_focus_sync: bool,
/// Name of the currently active binding mode (if one is active).
- active_binding_mode: String,
+ active_binding_mode: Option<String>,
}
impl WmState {
@@ -29,7 +29,7 @@ impl WmState {
root_container: RootContainer::new(),
containers_to_redraw: Vec::new(),
has_pending_focus_sync: false,
- active_binding_mode: String::new(),
+ active_binding_mode: None,
}
}
diff --git a/resources/icon.ico b/resources/icon.ico
new file mode 100644
index 00000000..e6db364e
Binary files /dev/null and b/resources/icon.ico differ
diff --git a/resources/sample-config.yaml b/resources/sample-config.yaml
new file mode 100644
index 00000000..f537afaf
--- /dev/null
+++ b/resources/sample-config.yaml
@@ -0,0 +1,258 @@
+general:
+ # Whether to automatically focus windows underneath the cursor.
+ focus_follows_cursor: false
+
+ # Whether to jump the cursor between windows focused by the WM.
+ cursor_follows_focus: false
+
+ # Whether to switch back and forth between the previously focused workspace
+ # when focusing the current workspace.
+ toggle_workspace_on_refocus: true
+
+ # Whether to show floating windows as always on top.
+ show_floating_on_top: false
+
+ # Amount to move floating windows by (eg. when using `alt+<hjkl>` on a floating window)
+ floating_window_move_amount: "5%"
+
+ # Whether to center new floating windows.
+ center_new_floating_windows: true
+
+ # *Strongly* recommended to set to 'false'. Whether to globally enable/disable
+ # window transition animations (on minimize, close, etc). Set to 'unchanged'
+ # to make no setting changes.
+ window_animations: "unchanged"
+
+gaps:
+ # Gap between adjacent windows.
+ inner_gap: "20px"
+
+ # Gap between windows and the screen edge.
+ outer_gap: "20px"
+
+# Highlight active/inactive windows with a colored border.
+# ** Exclusive to Windows 11 due to API limitations.
+focus_borders:
+ active:
+ enabled: true
+ color: "#0000ff"
+
+ inactive:
+ enabled: false
+ color: "#ff0000"
+
+bar:
+ height: "30px"
+ position: "top"
+ opacity: 1.0
+ background: "#20242cc4"
+ foreground: "#ffffff"
+ font_family: "Segoe UI"
+ font_size: "13px"
+ padding: "4px 6px"
+ offset_x: "0"
+ offset_y: "0"
+ border_radius: "0"
+ components_left:
+ - type: "workspaces"
+ focused_workspace_background: "#ffffff33"
+ displayed_workspace_background: "#00000033"
+ default_workspace_background: "transparent"
+ components_center:
+ - type: "window title"
+ components_right:
+ - type: "system tray"
+ - type: "tiling direction"
+ label_horizontal: "⮂"
+ label_vertical: "⮁"
+ background: "#ffffff33"
+ margin: "0 4px"
+ padding: "0 8px"
+ - type: "binding mode"
+ background: "#ffffff33"
+ margin: "0 4px 0 0"
+ padding: "0 8px"
+ - type: "clock"
+ # Documentation on formatting date/time string:
+ # https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
+ time_formatting: "hh:mm tt ddd MMM d"
+
+workspaces:
+ - name: "1"
+ - name: "2"
+ - name: "3"
+ - name: "4"
+ - name: "5"
+ - name: "6"
+ - name: "7"
+ - name: "8"
+ - name: "9"
+
+window_rules:
+ # Task Manager requires admin privileges to manage and should be ignored unless running
+ # the WM as admin.
+ - command: "ignore"
+ match_process_name: "/Taskmgr|ScreenClippingHost/"
+
+ # Launches system dialogs as floating by default (eg. File Explorer save/open dialog).
+ - command: "set floating"
+ match_class_name: "#32770"
+
+ # Do not manage picture-in-picture windows for browsers. Note that the default is for
+ # English; change `match_title` to the window's title if you use another language.
+ - command: "ignore"
+ match_title: "[Pp]icture.in.[Pp]icture"
+ match_class_name: "Chrome_WidgetWin_1|MozillaDialogClass"
+
+ # Some applications (eg. Steam) have borders that extend past the normal border size.
+ - command: "resize borders 0px -7px -7px -7px"
+ match_process_name: "steam"
+
+binding_modes:
+ - name: "resize"
+ keybindings:
+ # Resize focused window by a percentage or pixel amount.
+ - command: "resize width -2%"
+ bindings: ["H", "Left"]
+ - command: "resize width +2%"
+ bindings: ["L", "Right"]
+ - command: "resize height +2%"
+ bindings: ["K", "Up"]
+ - command: "resize height -2%"
+ bindings: ["J", "Down"]
+ # Press enter/escape to return to default keybindings.
+ - command: "binding mode none"
+ bindings: ["Escape", "Enter"]
+
+keybindings:
+ # Shift focus in a given direction.
+ - command: "focus left"
+ bindings: ["Alt+H", "Alt+Left"]
+ - command: "focus right"
+ bindings: ["Alt+L", "Alt+Right"]
+ - command: "focus up"
+ bindings: ["Alt+K", "Alt+Up"]
+ - command: "focus down"
+ bindings: ["Alt+J", "Alt+Down"]
+
+ # Move focused window in a given direction.
+ - command: "move left"
+ bindings: ["Alt+Shift+H", "Alt+Shift+Left"]
+ - command: "move right"
+ bindings: ["Alt+Shift+L", "Alt+Shift+Right"]
+ - command: "move up"
+ bindings: ["Alt+Shift+K", "Alt+Shift+Up"]
+ - command: "move down"
+ bindings: ["Alt+Shift+J", "Alt+Shift+Down"]
+
+ # Resize focused window by a percentage or pixel amount.
+ - command: "resize width -2%"
+ binding: "Alt+U"
+ - command: "resize width +2%"
+ binding: "Alt+P"
+ - command: "resize height +2%"
+ binding: "Alt+O"
+ - command: "resize height -2%"
+ binding: "Alt+I"
+
+ # As an alternative to the resize keybindings above, resize mode enables resizing via
+ # HJKL or arrow keys. The binding mode is defined above with the name "resize".
+ - command: "binding mode resize"
+ binding: "Alt+R"
+
+ # Change tiling direction. This determines where new tiling windows will be inserted.
+ - command: "tiling direction toggle"
+ binding: "Alt+V"
+
+ # Change focus between floating / tiling windows.
+ - command: "focus mode toggle"
+ binding: "Alt+Space"
+
+ # Change the focused window to be floating / tiling.
+ - command: "toggle floating"
+ binding: "Alt+Shift+Space"
+
+ # Change the focused window to be maximized / unmaximized.
+ - command: "toggle maximized"
+ binding: "Alt+X"
+
+ # Minimize focused window.
+ - command: "set minimized"
+ binding: "Alt+M"
+
+ # Close focused window.
+ - command: "close"
+ binding: "Alt+Shift+Q"
+
+ # Kill GlazeWM process safely.
+ - command: "exit wm"
+ binding: "Alt+Shift+E"
+
+ # Re-evaluate configuration file.
+ - command: "reload config"
+ binding: "Alt+Shift+R"
+
+ # Launch CMD terminal (alternatively `exec wt` or `exec %ProgramFiles%/Git/git-bash.exe`
+ # to start Windows Terminal and Git Bash respectively.
+ - command: "exec cmd"
+ binding: "Alt+Enter"
+
+ # Focus the workspace that last had focus.
+ - command: "focus workspace recent"
+ binding: "Alt+Y"
+
+ # Focus the next/previous workspace defined in `workspaces` config.
+ - command: "focus workspace next"
+ binding: "Alt+T"
+ - command: "focus workspace prev"
+ binding: "Alt+Shift+T"
+
+ # Change focus to a workspace defined in `workspaces` config.
+ - command: "focus workspace 1"
+ binding: "Alt+1"
+ - command: "focus workspace 2"
+ binding: "Alt+2"
+ - command: "focus workspace 3"
+ binding: "Alt+3"
+ - command: "focus workspace 4"
+ binding: "Alt+4"
+ - command: "focus workspace 5"
+ binding: "Alt+5"
+ - command: "focus workspace 6"
+ binding: "Alt+6"
+ - command: "focus workspace 7"
+ binding: "Alt+7"
+ - command: "focus workspace 8"
+ binding: "Alt+8"
+ - command: "focus workspace 9"
+ binding: "Alt+9"
+
+ # Move focused workspace to a monitor in a given direction.
+ - command: "move workspace left"
+ binding: "Alt+A"
+ - command: "move workspace right"
+ binding: "Alt+F"
+ - command: "move workspace up"
+ binding: "Alt+D"
+ - command: "move workspace down"
+ binding: "Alt+S"
+
+ # Move focused window to a workspace defined in `workspaces` config.
+ - commands: ["move to workspace 1", "focus workspace 1"]
+ binding: "Alt+Shift+1"
+ - commands: ["move to workspace 2", "focus workspace 2"]
+ binding: "Alt+Shift+2"
+ - commands: ["move to workspace 3", "focus workspace 3"]
+ binding: "Alt+Shift+3"
+ - commands: ["move to workspace 4", "focus workspace 4"]
+ binding: "Alt+Shift+4"
+ - commands: ["move to workspace 5", "focus workspace 5"]
+ binding: "Alt+Shift+5"
+ - commands: ["move to workspace 6", "focus workspace 6"]
+ binding: "Alt+Shift+6"
+ - commands: ["move to workspace 7", "focus workspace 7"]
+ binding: "Alt+Shift+7"
+ - commands: ["move to workspace 8", "focus workspace 8"]
+ binding: "Alt+Shift+8"
+ - commands: ["move to workspace 9", "focus workspace 9"]
+ bindings: ["Alt+Shift+9"]