diff --git a/Cargo.lock b/Cargo.lock index 2d355ce7..00ef7c63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3387,6 +3387,13 @@ dependencies = [ "winreg", ] +[[package]] +name = "komorebi-backend" +version = "0.1.42" +dependencies = [ + "komorebi-layouts", +] + [[package]] name = "komorebi-bar" version = "0.1.42" diff --git a/Cargo.toml b/Cargo.toml index 290284f0..32f95367 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "komorebi", "komorebi-client", "komorebi-gui", + "crates/komorebi-backend", "crates/komorebi-collections", "crates/komorebi-config", "komorebi-layouts", diff --git a/crates/komorebi-backend/Cargo.toml b/crates/komorebi-backend/Cargo.toml new file mode 100644 index 00000000..071703b8 --- /dev/null +++ b/crates/komorebi-backend/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "komorebi-backend" +version = "0.1.42" +description = "What every komorebi daemon asks of its platform: the Backend trait, WindowId, plain-data window and monitor infos, and an in-memory FakeBackend" +edition = "2024" + +[dependencies] +komorebi-layouts = { path = "../../komorebi-layouts" } diff --git a/crates/komorebi-backend/src/backend.rs b/crates/komorebi-backend/src/backend.rs new file mode 100644 index 00000000..95e7d8d3 --- /dev/null +++ b/crates/komorebi-backend/src/backend.rs @@ -0,0 +1,360 @@ +use crate::error::Error; +use crate::error::Result; +use crate::id::MonitorId; +use crate::id::WindowId; +use crate::info::MonitorInfo; +use crate::info::WindowInfo; +use komorebi_layouts::Rect; + +/// An operation that only some platforms have, and so is asked about with +/// [`Backend::supports`] instead of being required of every backend. +/// +/// Calling one of these operations on a backend that does not support it returns +/// [`Error::Unsupported`], whatever the arguments. +/// +/// | capability | KDE | Windows | macOS | +/// |---|---|---|---| +/// | [`Capability::Workspaces`] | yes: the compositor's virtual desktops | no: komorebi's own workspaces, shown and hidden with `hide` and `restore` | no: same | +/// | [`Capability::Maximize`] | yes | yes | no | +/// | [`Capability::Opacity`] | yes | yes | no | +/// | [`Capability::FocusFollowsMouse`] | yes (a `kwinrc` setting) | yes (a system setting) | no | +/// +/// (`docs/dev/seam.md` section 2.1, rows 16 to 19.) +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[non_exhaustive] +pub enum Capability { + /// The five workspace methods: [`Backend::ensure_workspaces`], [`Backend::switch_workspace`], + /// [`Backend::set_window_workspace`], [`Backend::window_workspace`] and + /// [`Backend::current_workspaces`]. They exist because KDE delegates workspaces to the + /// compositor; elsewhere the shared core keeps them itself. + Workspaces, + /// [`Backend::maximize`]. + Maximize, + /// [`Backend::set_opacity`]. + Opacity, + /// [`Backend::set_focus_follows_mouse`]. + FocusFollowsMouse, +} + +impl Capability { + /// Every capability, for a test that goes through all of them. + pub const ALL: [Capability; 4] = [ + Capability::Workspaces, + Capability::Maximize, + Capability::Opacity, + Capability::FocusFollowsMouse, + ]; +} + +/// The desktop, as the window manager sees it: the one seam between shared code and a platform. +/// +/// Only operations that at least two platforms have (`docs/dev/seam.md` section 2.1) are here. +/// What only some platforms have is behind [`Backend::supports`]; what is one platform's own +/// business (borders, the look, the wallpaper, drag frames) is not in this trait at all. +/// +/// # Who implements it +/// +/// KDE (over the compositor), Windows (over `WindowsApi`), macOS (over `MacosApi` and the +/// Accessibility API) and the in-memory fake. Each method's documentation says which of +/// the three real platforms implement it; an operation that is optional says so and is listed in +/// [`Capability`]. +/// +/// # Threads (TARGET rules: no platform follows them everywhere today) +/// +/// - A backend is `Send + Sync`, and **every method may be called from any thread except a +/// platform's main thread**. Windows is stateless (only window creation and message loops are +/// thread-affine, and a backend does neither). KDE's calls come from threads that hold the +/// window manager lock and never from the bridge's async runtime. macOS already calls the +/// platform from the event, command, reaper, settle, reconciler and animator threads. +/// - **No method waits for the main thread of its own platform.** On macOS the work that must +/// run on main (`NSScreen`, border windows) is either `exec_async`, or answered from data the +/// backend already holds, such as a monitor list that the display callback refreshes. A method +/// that waits for anything (Windows `SetWindowPos` waits for the target window unless the +/// backend is asynchronous; KDE `cursor_pos` waits up to 250 ms) has to say so in its +/// documentation and be bounded. The macOS main-queue deadlock of `docs/dev/seam.md` +/// section 3.3 is the reason for the rule: a call made under the window manager lock must not +/// wait for a closure that needs the lock. +/// - A backend never calls back into the window manager while a method runs. Events travel the +/// other way, through the event channel. +/// +/// # Reads after writes +/// +/// A write (`set_rect`, `minimize`, `hide`, ...) is a **request**: it returns when the request +/// has been made, not when the platform has acted. A read straight after it (`window`, +/// `window_rect`) returns what the platform defines, and shared code may rely only on this: +/// +/// - the answer is a value the platform has reported or, if it keeps a cache, the request itself +/// until an event corrects it (KDE does the latter, `K/kwin/state.rs:594-600`); +/// - the answer need not equal the request: a client may refuse a size, and the platform's idea +/// of the frame may differ from the one `set_rect` takes (Windows reports the visible bounds +/// and `set_rect` adds the shadow offset itself, so a request and its read-back agree there, but +/// KDE and macOS report whatever the window ended up with); +/// - to learn the achieved frame, wait for the event, or call `window_rect` where the layout +/// needs the truth (a refused width, the end of a drag). +/// +/// the in-memory fake answers a read after a write at once with the request, clamped to +/// the window's minimum size and moved by its frame offset. +/// +/// # Errors +/// +/// Window commands fail with [`Error::WindowGone`] when the window is unknown or dead, and +/// otherwise only when the platform refuses ([`Error::Platform`]). Optional operations fail with +/// [`Error::Unsupported`]. No method panics because a window died. +/// +/// The compiler enforces the part of the contract that it can see: a backend has to be +/// `Send + Sync`. +/// +/// ```rust,compile_fail,E0277 +/// use komorebi_backend::{Backend, MonitorInfo, Rect, Result, WindowId, WindowInfo}; +/// use std::rc::Rc; +/// +/// struct NotShareable(Rc); +/// +/// impl Backend for NotShareable { +/// fn windows(&self) -> Vec { vec![] } +/// fn window(&self, _: WindowId) -> Option { None } +/// fn foreground_window(&self) -> Option { None } +/// fn monitors(&self) -> Result> { Ok(vec![]) } +/// fn cursor_pos(&self) -> Option<(i32, i32)> { None } +/// fn set_rect(&self, _: WindowId, _: &Rect) -> Result<()> { Ok(()) } +/// fn focus(&self, _: WindowId, _: bool) -> Result<()> { Ok(()) } +/// fn raise(&self, _: WindowId) -> Result<()> { Ok(()) } +/// fn hide(&self, _: WindowId) -> Result<()> { Ok(()) } +/// fn restore(&self, _: WindowId) -> Result<()> { Ok(()) } +/// fn minimize(&self, _: WindowId) -> Result<()> { Ok(()) } +/// fn unminimize(&self, _: WindowId) -> Result<()> { Ok(()) } +/// fn close(&self, _: WindowId) -> Result<()> { Ok(()) } +/// fn center_cursor_in(&self, _: &Rect) -> Result<()> { Ok(()) } +/// } +/// ``` +pub trait Backend: Send + Sync + 'static { + // ---- queries ------------------------------------------------------------------------------- + + /// Returns every window that is a candidate for management and alive, ordered by id. + /// + /// Implemented by KDE (its table), Windows (`enum_windows`, `load_workspace_information`) + /// and macOS (CoreGraphics list joined with Accessibility elements; the join is by title + /// today, see `docs/dev/seam.md` row 10). On Windows and macOS the daemons enumerate at + /// start-up and learn from events afterwards, so a backend may be slow here: call it rarely. + fn windows(&self) -> Vec; + + /// Returns what is known about the window, or `None` if the backend has never heard of it. + /// A destroyed window may stay queryable for a while with [`WindowInfo::alive`] false. + /// + /// Implemented by KDE (table lookup, never waits), Windows (assembled from several calls) and + /// macOS (over Accessibility, so it can fail and then answers `None`). + fn window(&self, id: WindowId) -> Option; + + /// Returns the id of the window that has the focus, if any window does. + /// + /// Implemented by KDE (table), Windows (`GetForegroundWindow`; a null handle is `None`) and + /// macOS (Accessibility system-wide, `None` whenever a step fails). + fn foreground_window(&self) -> Option; + + /// Returns every connected monitor. + /// + /// Implemented by KDE (table, logical pixels), Windows (physical pixels) and macOS (points; + /// today a live `NSScreen` query that is only legal on the main thread, so a macOS backend + /// has to serve it from a cache that the display callback refreshes: the TARGET rule above). + /// + /// # Errors + /// + /// When the platform cannot report its monitors, or reports none. + fn monitors(&self) -> Result>; + + /// Returns where the pointer is, if the platform says. + /// + /// Implemented by KDE (asks the KWin script and waits up to 250 ms, falling back to the last + /// position seen), Windows (`GetCursorPos`; a failure is `None`) and macOS (`CGEvent`). + fn cursor_pos(&self) -> Option<(i32, i32)>; + + // ---- commands ------------------------------------------------------------------------------ + + /// Moves and resizes the window to `rect`: a position and a size. + /// + /// **This is a request.** It returns when the request has been made (KDE queues it, Windows + /// and macOS issue it), says nothing about the frame the window ends up with, and may fail + /// only for an unknown or dead window ([`Error::WindowGone`]) or when the platform refuses + /// the write outright. A client may refuse the size. See the section "Reads after writes" of + /// [`Backend`] for what [`Backend::window`] and [`Backend::window_rect`] return afterwards. + /// + /// Implemented by KDE (`frameGeometry`, queued, optimistic table write), Windows + /// (`SetWindowPos`, synchronous by default, `rect` is the visible frame and the shadow offset + /// is added by the implementation) and macOS (two Accessibility writes, or the animator). + fn set_rect(&self, id: WindowId, rect: &Rect) -> Result<()>; + + /// Gives the window the focus, and, if `mouse_follows_focus`, puts the pointer in its middle. + /// + /// Implemented by KDE (activates, then waits for the window to be foreground before moving + /// the pointer), Windows and macOS (focus, then `center_cursor_in` on the window's frame when + /// asked; neither platform has this as one call). + fn focus(&self, id: WindowId, mouse_follows_focus: bool) -> Result<()>; + + /// Raises the window above the others. + /// + /// Implemented by KDE and Windows (raise without activating). macOS has no raise without + /// focus: its implementation focuses the window as well. + fn raise(&self, id: WindowId) -> Result<()>; + + /// Takes the window out of sight without closing or minimizing it: how the core keeps the + /// back of a stack, or a workspace that is not showing, out of the way. The window stays + /// alive. Hiding a hidden window leaves it as it is. + /// + /// Implemented by KDE (a park desktop nobody looks at), Windows (cloak by default) and macOS + /// (a sliver in a display corner). Whether the user can notice (macOS, Windows `Hide` and + /// `Minimize`) differs, so the core keeps its own table of what it hid + /// (`docs/dev/seam.md` finding 11). + fn hide(&self, id: WindowId) -> Result<()>; + + /// Brings a hidden window back. A window that is not hidden is left as it is. + /// + /// Implemented by KDE, Windows and macOS. + fn restore(&self, id: WindowId) -> Result<()>; + + /// Minimizes the window. Implemented by KDE, Windows and macOS. + fn minimize(&self, id: WindowId) -> Result<()>; + + /// Brings a minimized window back. Implemented by KDE, Windows (`restore_window`) and macOS. + fn unminimize(&self, id: WindowId) -> Result<()>; + + /// Asks the window to close. A request: the window may stay, and the event that it is gone + /// is what the core reacts to. Implemented by KDE, Windows (`WM_CLOSE`) and macOS (presses + /// the close button, `Ok` when there is none). + fn close(&self, id: WindowId) -> Result<()>; + + /// Puts the pointer in the middle of `rect`. + /// + /// Implemented by Windows and macOS. **KDE ignores `rect`**: KWin can only centre on the + /// active window, so on KDE the call is correct only right after focusing the window whose + /// frame `rect` is (`docs/dev/seam.md` row 14, finding 10). + /// + /// # Errors + /// + /// When the platform refuses to move the pointer. + fn center_cursor_in(&self, rect: &Rect) -> Result<()>; + + // ---- capabilities -------------------------------------------------------------------------- + + /// Returns true if and only if the backend implements the operations behind `capability`. The + /// default supports none; an operation that is not supported returns [`Error::Unsupported`]. + fn supports(&self, _capability: Capability) -> bool { + false + } + + /// Has the platform maximize the window to the work area of its monitor, or, with `maximize` + /// false, give it back the frame it had. Capability [`Capability::Maximize`]: KDE and + /// Windows. The default is [`Error::Unsupported`]. + fn maximize(&self, _id: WindowId, _maximize: bool) -> Result<()> { + Err(Error::Unsupported(Capability::Maximize)) + } + + /// Asks the platform to draw the window with this opacity, 255 being not see-through at all. + /// Capability [`Capability::Opacity`]: KDE and Windows. The default is + /// [`Error::Unsupported`]. + fn set_opacity(&self, _id: WindowId, _alpha: u8) -> Result<()> { + Err(Error::Unsupported(Capability::Opacity)) + } + + /// Asks the platform to give the focus to the window under the pointer as it moves (`true`), + /// or to go back to the policy the user had (`false`). Capability + /// [`Capability::FocusFollowsMouse`]: KDE and Windows (which also has an implementation of + /// its own that does not use this). The default is [`Error::Unsupported`]. + fn set_focus_follows_mouse(&self, _enable: bool) -> Result<()> { + Err(Error::Unsupported(Capability::FocusFollowsMouse)) + } + + /// Makes sure there are at least as many workspaces as `names`, creating the missing ones. + /// Capability [`Capability::Workspaces`]: KDE only. The default is [`Error::Unsupported`]. + fn ensure_workspaces(&self, _names: &[String]) -> Result<()> { + Err(Error::Unsupported(Capability::Workspaces)) + } + + /// Shows workspace `idx` on a monitor, leaving the other monitors as they are. Capability + /// [`Capability::Workspaces`]: KDE only. The default is [`Error::Unsupported`]. + fn switch_workspace(&self, _monitor: MonitorId, _idx: usize) -> Result<()> { + Err(Error::Unsupported(Capability::Workspaces)) + } + + /// Puts a window on workspace `idx`. Capability [`Capability::Workspaces`]: KDE only. The + /// default is [`Error::Unsupported`]. + fn set_window_workspace(&self, _id: WindowId, _idx: usize) -> Result<()> { + Err(Error::Unsupported(Capability::Workspaces)) + } + + /// Returns the workspace a window is on, `None` for a window that is on none or on every + /// workspace. Capability [`Capability::Workspaces`]: KDE only. The default is + /// [`Error::Unsupported`]. + fn window_workspace(&self, _id: WindowId) -> Result> { + Err(Error::Unsupported(Capability::Workspaces)) + } + + /// Returns the workspace each monitor shows. Capability [`Capability::Workspaces`]: KDE only. + /// The default is [`Error::Unsupported`]. + fn current_workspaces(&self) -> Result> { + Err(Error::Unsupported(Capability::Workspaces)) + } + + // ---- batches ------------------------------------------------------------------------------- + + /// Starts a batch: from here until the matching [`Backend::end_batch`], what the writes + /// change on screen should appear together. Batches nest, and a backend counts them. Use + /// [`Batch`] instead of calling this and `end_batch` by hand. + /// + /// The default does nothing. macOS implements it with SkyLight (`SLSDisableUpdate`, + /// `BatchedUpdates::begin`, which the core-adjacent code already brackets groups of window + /// operations with); KDE batches by construction (the answer to a held poll carries every + /// queued command) and Windows does not batch. + fn begin_batch(&self) {} + + /// Ends the batch started by the matching [`Backend::begin_batch`]. The default does + /// nothing. + fn end_batch(&self) {} + + // ---- provided ------------------------------------------------------------------------------ + + /// Returns true if and only if the backend has a live window with this id. + fn is_window(&self, id: WindowId) -> bool { + self.window(id).is_some_and(|w| w.alive) + } + + /// Returns the window's frame, if the backend knows the window: the `rect` of + /// [`Backend::window`], in the platform's own definition (Windows: the visible bounds + /// without the shadow; KDE: the frame geometry; macOS: the Accessibility position and size). + fn window_rect(&self, id: WindowId) -> Option { + self.window(id).map(|w| w.rect) + } + + /// Returns the id of the monitor whose bounds contain the point. A point outside every + /// monitor gives `None` on KDE and macOS, and the **nearest** monitor on Windows + /// (`MONITOR_DEFAULTTONEAREST`), so callers must not use `None` to detect "off screen". + /// The default implements the KDE and macOS answer. + fn monitor_from_point(&self, x: i32, y: i32) -> Option { + self.monitors().ok()?.into_iter().find_map(|m| { + let (l, t) = (m.size.left, m.size.top); + let (r, b) = (l + m.size.right, t + m.size.bottom); + (x >= l && x < r && y >= t && y < b).then_some(m.id) + }) + } +} + +/// A batch scope: writes made while it lives should appear together, and the batch ends when it +/// is dropped, also when the code in between panics. +/// +/// A backend that cannot batch ignores it ([`Backend::begin_batch`] does nothing by default), so +/// shared code may bracket every layout with it. +#[must_use = "the batch ends when this is dropped"] +pub struct Batch<'a, B: Backend + ?Sized>(&'a B); + +impl<'a, B: Backend + ?Sized> Batch<'a, B> { + /// Starts a batch on `backend`. + pub fn begin(backend: &'a B) -> Self { + backend.begin_batch(); + Self(backend) + } +} + +impl Drop for Batch<'_, B> { + fn drop(&mut self) { + self.0.end_batch(); + } +} diff --git a/crates/komorebi-backend/src/error.rs b/crates/komorebi-backend/src/error.rs new file mode 100644 index 00000000..3d72bb5f --- /dev/null +++ b/crates/komorebi-backend/src/error.rs @@ -0,0 +1,80 @@ +use crate::backend::Capability; +use crate::id::WindowId; +use std::fmt; + +/// What a [`crate::Backend`] call can fail with. +pub type Result = std::result::Result; + +/// Why a backend call failed. +/// +/// Every platform has its own errors (`eyre` reports on KDE, Win32 `HRESULT`s, macOS +/// `AccessibilityError`); this is what the shared code can act on. In particular it can tell +/// "the window is gone", which macOS uses as its only signal that a window has died (a failed +/// write asks the reaper whether the window still exists, `docs/dev/seam.md` finding 9), from +/// every other failure. +/// +/// # Example +/// +/// ```rust +/// use komorebi_backend::{Error, WindowId}; +/// +/// let error = Error::WindowGone(WindowId::from_u32(9)); +/// assert!(error.is_window_gone()); +/// assert_eq!(error.to_string(), "no such window: 9"); +/// ``` +#[derive(Debug)] +#[non_exhaustive] +pub enum Error { + /// The window is not known to the backend, or has been destroyed. Every window command may + /// fail with this, and (see [`crate::Backend::set_rect`]) with nothing else that the caller + /// should treat as a property of the request. + WindowGone(WindowId), + /// The platform does not have this operation: the [`Capability`] is not + /// [supported](crate::Backend::supports). + Unsupported(Capability), + /// The platform refused or failed, with its own error as the cause. + Platform(Box), +} + +impl Error { + /// Returns true if and only if this is [`Error::WindowGone`]. + pub fn is_window_gone(&self) -> bool { + matches!(self, Self::WindowGone(_)) + } + + /// Returns true if and only if this is [`Error::Unsupported`]. + pub fn is_unsupported(&self) -> bool { + matches!(self, Self::Unsupported(_)) + } + + /// A [`Error::Platform`] failure that is only a message. + pub fn platform(message: impl Into) -> Self { + Self::Platform(message.into().into()) + } + + /// A [`Error::Platform`] failure with the platform's own error as the cause. + pub fn from_platform(cause: impl std::error::Error + Send + Sync + 'static) -> Self { + Self::Platform(Box::new(cause)) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::WindowGone(id) => write!(f, "no such window: {id}"), + Self::Unsupported(capability) => { + write!(f, "{capability:?} is not supported on this platform") + } + Self::Platform(cause) => cause.fmt(f), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Platform(cause) => Some(cause.as_ref()), + _ => None, + } + } +} diff --git a/crates/komorebi-backend/src/id.rs b/crates/komorebi-backend/src/id.rs new file mode 100644 index 00000000..c11fe4ae --- /dev/null +++ b/crates/komorebi-backend/src/id.rs @@ -0,0 +1,128 @@ +use std::fmt; + +/// The name a backend gives a window, which is how every other part of komorebi refers to it. +/// +/// It is an opaque 64-bit number. What it is made from is the backend's own business, and the +/// conversions below are the only ones to use: +/// +/// - **KDE**: a counter the daemon assigns to each KWin window UUID (a `u32`): +/// [`WindowId::from_u32`], [`WindowId::to_u32`]. +/// - **macOS**: the `CGWindowID` (a `u32`), same conversions. +/// - **Windows**: the `HWND`, a pointer-sized integer (`isize`). [`WindowId::from_hwnd`] keeps +/// the bits of the handle unchanged, so it never loses one and [`WindowId::to_hwnd`] gives the +/// same `isize` back, whether or not a handle fits in 32 bits (the e2e samples in +/// `docs/dev/seam.md` section 4.1 stayed below 2^32, but that is an observation, not a +/// guarantee). +/// +/// # Example +/// +/// ```rust +/// use komorebi_backend::WindowId; +/// +/// let id = WindowId::from_u32(7); +/// assert_eq!(id.to_u32(), Some(7)); +/// assert_eq!(id.to_string(), "7"); +/// +/// // a handle with the top bit set, as a 64-bit HWND may have +/// let hwnd = -123_isize; +/// assert_eq!(WindowId::from_hwnd(hwnd).to_hwnd(), hwnd); +/// assert_eq!(WindowId::from_hwnd(hwnd).to_u32(), None); +/// ``` +#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct WindowId(pub u64); + +impl WindowId { + /// The id of a KDE or macOS window. + pub const fn from_u32(id: u32) -> Self { + Self(id as u64) + } + + /// The id as a `u32`, or `None` if it does not fit (which no KDE or macOS id can be). + pub fn to_u32(self) -> Option { + u32::try_from(self.0).ok() + } + + /// The id of a Windows window: the bits of the `HWND`, unchanged. + pub const fn from_hwnd(hwnd: isize) -> Self { + Self(hwnd as usize as u64) + } + + /// The `HWND` this id was made from by [`WindowId::from_hwnd`]. + pub const fn to_hwnd(self) -> isize { + self.0 as usize as isize + } +} + +impl From for WindowId { + fn from(id: u32) -> Self { + Self::from_u32(id) + } +} + +impl fmt::Display for WindowId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +/// The name a backend gives a monitor. +/// +/// An opaque 64-bit number, like [`WindowId`]: KDE's output id and macOS's `CGDirectDisplayID` +/// are `u32` ([`MonitorId::from_u32`]), a Windows monitor handle (`HMONITOR`, an `isize`) goes +/// through [`MonitorId::from_hmonitor`] and back through [`MonitorId::to_hmonitor`], bit for bit. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct MonitorId(pub u64); + +impl MonitorId { + /// The id of a KDE or macOS monitor. + pub const fn from_u32(id: u32) -> Self { + Self(id as u64) + } + + /// The id as a `u32`, or `None` if it does not fit. + pub fn to_u32(self) -> Option { + u32::try_from(self.0).ok() + } + + /// The id of a Windows monitor: the bits of the handle, unchanged. + pub const fn from_hmonitor(handle: isize) -> Self { + Self(handle as usize as u64) + } + + /// The handle this id was made from by [`MonitorId::from_hmonitor`]. + pub const fn to_hmonitor(self) -> isize { + self.0 as usize as isize + } +} + +impl From for MonitorId { + fn from(id: u32) -> Self { + Self::from_u32(id) + } +} + +impl fmt::Display for MonitorId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_hwnd_survives_the_round_trip_with_any_bits() { + for hwnd in [0, 1, 0x1_0000_0000, isize::MAX, isize::MIN, -1] { + assert_eq!(WindowId::from_hwnd(hwnd).to_hwnd(), hwnd); + assert_eq!(MonitorId::from_hmonitor(hwnd).to_hmonitor(), hwnd); + } + } + + #[test] + fn a_u32_id_round_trips_and_a_wide_one_does_not_fit() { + assert_eq!(WindowId::from_u32(u32::MAX).to_u32(), Some(u32::MAX)); + assert_eq!(WindowId(u64::from(u32::MAX) + 1).to_u32(), None); + assert_eq!(MonitorId::from(3).to_u32(), Some(3)); + } +} diff --git a/crates/komorebi-backend/src/info.rs b/crates/komorebi-backend/src/info.rs new file mode 100644 index 00000000..67397c22 --- /dev/null +++ b/crates/komorebi-backend/src/info.rs @@ -0,0 +1,62 @@ +use crate::id::MonitorId; +use crate::id::WindowId; +use komorebi_layouts::Rect; + +/// What a backend knows about one window: plain data, a snapshot. +/// +/// Only `id`, `pid`, `rect`, `minimized` and `alive` are available on every platform cheaply. The +/// rest is `None` where the platform has no source for it or would have to ask the application +/// (`docs/dev/seam.md` finding 6): macOS has no window class and no `fullscreen`, `maximized` or +/// `normal`, and reads each string from the application over Accessibility; Windows asks the +/// system once per field. KDE (the only platform that delivers all of them in one snapshot) +/// fills every field. +/// +/// `rect` is the frame as the platform defines it (see [`crate::Backend::window_rect`]), in the +/// shared [`Rect`] convention: `right` and `bottom` hold the width and height. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct WindowInfo { + /// The window's id. + pub id: WindowId, + /// The id of the process that owns the window. + pub pid: i32, + /// The window's frame. + pub rect: Rect, + /// Whether the window is minimized. + pub minimized: bool, + /// False once the window has been destroyed. A backend may keep a destroyed window + /// queryable for a while (KDE does), with this false. + pub alive: bool, + /// The window's title. + pub title: Option, + /// The window class: the Wayland `app_id` on KDE, the Win32 class on Windows, nothing on + /// macOS. + pub class: Option, + /// The file name of the executable. + pub exe: Option, + /// The full path of the executable. + pub path: Option, + /// Whether the window covers its monitor, panels included (KDE, Windows). + pub fullscreen: Option, + /// Whether the window is maximized (KDE, Windows). + pub maximized: Option, + /// Whether the platform considers this an ordinary application window as opposed to a dialog, + /// a splash screen, a dock and so on (KDE). + pub normal: Option, +} + +/// A connected monitor, in the pixels the platform lays windows out in (logical on KDE, physical +/// on Windows, points on macOS: `docs/dev/seam.md` section 5). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MonitorInfo { + /// The monitor's id. + pub id: MonitorId, + /// The bounds of the monitor. + pub size: Rect, + /// `size` minus the panels, docks and menu bars the platform reserves. + pub work_area: Rect, + /// The name of the output (`DP-1`), where the platform has one. + pub name: Option, + /// An identity that stays the same across a hot-plug and a restart, where the platform has + /// one. + pub serial_number_id: Option, +} diff --git a/crates/komorebi-backend/src/lib.rs b/crates/komorebi-backend/src/lib.rs new file mode 100644 index 00000000..26f33d62 --- /dev/null +++ b/crates/komorebi-backend/src/lib.rs @@ -0,0 +1,40 @@ +//! What every komorebi daemon asks of its platform. +//! +//! The window manager logic should talk to a [`Backend`], never to KWin, Win32 or the macOS +//! Accessibility API. This crate holds the vocabulary of that conversation and nothing that +//! belongs to one platform: +//! +//! - [`WindowId`] and [`MonitorId`], the names a backend gives windows and monitors; +//! - [`WindowInfo`] and [`MonitorInfo`], plain data, with an [`Option`] for everything that is +//! not available on every platform; +//! - [`Error`], which can say that "the window is gone" and that "this platform cannot do that"; +//! - the [`Backend`] trait, with only the operations that at least two platforms have +//! (`docs/dev/seam.md`, section 2.1), a [`Capability`] query for the ones only some platforms +//! have, and a [`Batch`] scope for writes that should appear together. +//! +//! The evidence for each choice, and the status of every claim (confirmed, corrected or target), +//! is in `docs/dev/seam.md`. The doc comment of each item says which platforms implement it. +//! +//! # Platform-specific operations +//! +//! Borders and their colours, the look, the wallpaper, drag origin and end frames, stackbars, +//! observers and event taps are not here: they are one platform's business and live in that +//! platform's own trait or crate (for KDE, `komorebi::backend::Backend` still has them). + +#![deny(missing_docs)] + +mod backend; +mod error; +mod id; +mod info; + +pub use backend::Backend; +pub use backend::Batch; +pub use backend::Capability; +pub use error::Error; +pub use error::Result; +pub use id::MonitorId; +pub use id::WindowId; +pub use info::MonitorInfo; +pub use info::WindowInfo; +pub use komorebi_layouts::Rect;