diff --git a/Cargo.lock b/Cargo.lock index fb13da7c..bc92e850 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3548,6 +3548,17 @@ dependencies = [ name = "komorebi-scrolling" version = "0.1.42" +[[package]] +name = "komorebi-settings" +version = "0.1.42" +dependencies = [ + "komorebi-config", + "komorebi-layouts", + "komorebi-protocol", + "komorebi-themes", + "parking_lot", +] + [[package]] name = "komorebi-shortcuts" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 32f95367..fec65f2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ members = [ "crates/komorebi-backend", "crates/komorebi-collections", "crates/komorebi-config", + "crates/komorebi-settings", "komorebi-layouts", "komorebi-scrolling", "komorebic", diff --git a/crates/komorebi-settings/Cargo.toml b/crates/komorebi-settings/Cargo.toml new file mode 100644 index 00000000..b807819d --- /dev/null +++ b/crates/komorebi-settings/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "komorebi-settings" +version = "0.1.42" +edition = "2024" +description = "The settings every komorebi daemon reads while it runs: one immutable snapshot, replaced as a whole, instead of process-wide statics" + +[dependencies] +komorebi-config = { path = "../komorebi-config", default-features = false } +komorebi-layouts = { path = "../../komorebi-layouts" } +komorebi-protocol = { path = "../komorebi-protocol", default-features = false } +komorebi-themes = { path = "../../komorebi-themes", default-features = false } + +parking_lot = "0.12" diff --git a/crates/komorebi-settings/src/handle.rs b/crates/komorebi-settings/src/handle.rs new file mode 100644 index 00000000..c3ab7666 --- /dev/null +++ b/crates/komorebi-settings/src/handle.rs @@ -0,0 +1,267 @@ +use std::sync::Arc; + +use parking_lot::Mutex; +use parking_lot::RwLock; + +use crate::Settings; + +/// The current [`Settings`] of a daemon. +/// +/// Reading costs one uncontended read lock and an `Arc` clone; the lock is held for the clone +/// only, never while the caller uses the snapshot. The representation (an `RwLock>`) is +/// private: it can become an `ArcSwap` later without touching a caller. +pub struct Handle

{ + current: RwLock>>, + // Serialises writers. Readers never take it. + writers: Mutex<()>, +} + +impl

Handle

{ + pub fn new(settings: Settings

) -> Self { + Self { + current: RwLock::new(Arc::new(settings)), + writers: Mutex::new(()), + } + } + + /// The settings as they are now. Take it once per unit of work (one border render, one + /// layout pass, one rule check) and use it for all of it. + pub fn snapshot(&self) -> Arc> { + Arc::clone(&self.current.read()) + } + + /// Publish a whole new value. Readers that already hold a snapshot keep the old one. + pub fn replace(&self, settings: Settings

) { + let _writer = self.writers.lock(); + *self.current.write() = Arc::new(settings); + } +} + +impl Handle

{ + /// Copy the current value, let `edit` change the copy and publish it once. + /// + /// Writers are serialised for the whole call, so an `update` never overwrites a change made by + /// another `update` that ran at the same time. If `edit` panics nothing is published. + pub fn update(&self, edit: impl FnOnce(&mut Settings

) -> R) -> R { + let _writer = self.writers.lock(); + let mut copy = (**self.current.read()).clone(); + let result = edit(&mut copy); + *self.current.write() = Arc::new(copy); + result + } +} + +impl Handle

{ + /// Set one field now and put its previous value back when the guard is dropped. + /// + /// The previous value is restored only if the field still holds the value this call set. If a + /// reload or a command changed the field meanwhile, that change wins. (The statics did the + /// opposite: the saved value overwrote whatever had been written in between.) + pub fn scoped( + &self, + field: fn(&mut Settings

) -> &mut T, + value: T, + ) -> Scoped<'_, P, T> + where + T: Clone + PartialEq, + { + let previous = self.update(|settings| std::mem::replace(field(settings), value.clone())); + + Scoped { + handle: self, + field, + set: value, + previous: Some(previous), + } + } +} + +/// The guard returned by [`Handle::scoped`]. +#[must_use = "the previous value is put back when the guard is dropped"] +pub struct Scoped<'a, P: Clone + 'static, T: Clone + PartialEq> { + handle: &'a Handle

, + field: fn(&mut Settings

) -> &mut T, + set: T, + previous: Option, +} + +impl Drop for Scoped<'_, P, T> { + fn drop(&mut self) { + if let Some(previous) = self.previous.take() { + let field = self.field; + let set = &self.set; + self.handle.update(|settings| { + let slot = field(settings); + if slot == set { + *slot = previous; + } + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::shared::PlatformDefaults; + + #[derive(Clone, Debug, PartialEq, Default)] + struct Platform { + hiding: u8, + flag: bool, + } + + fn handle() -> Handle { + Handle::new(Settings::new( + crate::Shared::defaults_for(PlatformDefaults::KDE), + Platform::default(), + )) + } + + #[test] + fn a_snapshot_does_not_change_when_the_handle_does() { + let handle = handle(); + let before = handle.snapshot(); + + handle.update(|s| s.shared.border.width = 99); + + assert_eq!(before.shared.border.width, 10); + assert_eq!(handle.snapshot().shared.border.width, 99); + } + + #[test] + fn replace_publishes_the_whole_value() { + let handle = handle(); + let mut next = (*handle.snapshot()).clone(); + next.platform.hiding = 3; + next.shared.border.enabled = false; + + handle.replace(next); + + let now = handle.snapshot(); + assert_eq!(now.platform.hiding, 3); + assert!(!now.shared.border.enabled); + } + + #[test] + fn a_panicking_edit_publishes_nothing() { + let handle = handle(); + + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + handle.update(|s| { + s.shared.border.width = 77; + panic!("edit failed"); + }); + })); + + assert!(result.is_err()); + assert_eq!(handle.snapshot().shared.border.width, 10); + // and the writer lock is free again + handle.update(|s| s.shared.border.width = 5); + assert_eq!(handle.snapshot().shared.border.width, 5); + } + + #[test] + fn concurrent_updates_lose_nothing() { + let handle = Arc::new(handle()); + let threads: Vec<_> = (0..8) + .map(|_| { + let handle = Arc::clone(&handle); + std::thread::spawn(move || { + for _ in 0..500 { + handle.update(|s| s.shared.border.width += 1); + } + }) + }) + .collect(); + for thread in threads { + thread.join().unwrap(); + } + + assert_eq!(handle.snapshot().shared.border.width, 10 + 8 * 500); + } + + #[test] + fn readers_never_see_half_an_update() { + // The writer keeps width and offset equal; a torn read would show them different. + let handle = Arc::new(handle()); + handle.update(|s| { + s.shared.border.width = 0; + s.shared.border.offset = 0; + }); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + + let writer = { + let (handle, stop) = (Arc::clone(&handle), Arc::clone(&stop)); + std::thread::spawn(move || { + let mut n = 0; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + n += 1; + handle.update(|s| { + s.shared.border.width = n; + s.shared.border.offset = n; + }); + } + }) + }; + + for _ in 0..50_000 { + let seen = handle.snapshot(); + assert_eq!(seen.shared.border.width, seen.shared.border.offset); + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + writer.join().unwrap(); + } + + #[test] + fn scoped_puts_the_value_back() { + let handle = handle(); + + { + let _guard = handle.scoped(|s| &mut s.platform.hiding, 9); + assert_eq!(handle.snapshot().platform.hiding, 9); + } + + assert_eq!(handle.snapshot().platform.hiding, 0); + } + + #[test] + fn scoped_leaves_a_change_made_meanwhile() { + let handle = handle(); + + { + let _guard = handle.scoped(|s| &mut s.platform.hiding, 9); + // a reload writes the field while the override is held + handle.update(|s| s.platform.hiding = 4); + } + + assert_eq!(handle.snapshot().platform.hiding, 4); + } + + #[test] + fn scoped_touches_only_its_own_field() { + let handle = handle(); + + { + let _guard = handle.scoped(|s| &mut s.platform.flag, true); + handle.update(|s| s.shared.border.width = 31); + } + + let now = handle.snapshot(); + assert!(!now.platform.flag); + assert_eq!(now.shared.border.width, 31); + } + + #[test] + fn nested_scopes_unwind_in_order() { + let handle = handle(); + + let outer = handle.scoped(|s| &mut s.platform.hiding, 1); + let inner = handle.scoped(|s| &mut s.platform.hiding, 2); + assert_eq!(handle.snapshot().platform.hiding, 2); + drop(inner); + assert_eq!(handle.snapshot().platform.hiding, 1); + drop(outer); + assert_eq!(handle.snapshot().platform.hiding, 0); + } +} diff --git a/crates/komorebi-settings/src/lib.rs b/crates/komorebi-settings/src/lib.rs new file mode 100644 index 00000000..c7c0854e --- /dev/null +++ b/crates/komorebi-settings/src/lib.rs @@ -0,0 +1,41 @@ +//! The settings a daemon reads while it runs. +//! +//! Today each daemon keeps them in dozens of process-wide statics that `apply_globals` and the +//! `SocketMessage` handlers write one at a time while the border, animator and reaper threads +//! read them (see `docs/dev/settings.md`). This crate holds the replacement and nothing else: no +//! daemon uses it yet. +//! +//! * [`Settings`] is a value: a [`Shared`] part that is the same struct on every platform and a +//! platform part `P` that each daemon defines for its own subsystems. +//! * [`Handle`] holds the current value. A reader takes a [`Handle::snapshot`] once per unit of +//! work and sees one consistent configuration for all of it. A writer uses [`Handle::update`], +//! which serialises writers, so two writers never lose each other's change, and publishes the +//! result once. +//! * [`Handle::scoped`] replaces the "store a value, do work, store the old value back" pattern +//! without clobbering a change made in between. +#![warn(clippy::all)] +#![allow(clippy::missing_errors_doc, clippy::use_self, clippy::doc_markdown)] + +mod handle; +pub mod shared; + +pub use handle::Handle; +pub use handle::Scoped; +pub use shared::Shared; + +/// Every setting of one running daemon. +/// +/// `P` is the platform part: a plain type the daemon defines (the Windows stackbar and hiding +/// behaviour, the macOS tabbed-application list, ...). Shared code never looks inside it, so it is +/// a type parameter and not a trait; it needs to be `Clone` so that an update can copy the value. +#[derive(Clone, Debug, PartialEq)] +pub struct Settings

{ + pub shared: Shared, + pub platform: P, +} + +impl

Settings

{ + pub fn new(shared: Shared, platform: P) -> Self { + Self { shared, platform } + } +} diff --git a/crates/komorebi-settings/src/shared.rs b/crates/komorebi-settings/src/shared.rs new file mode 100644 index 00000000..a18a62d4 --- /dev/null +++ b/crates/komorebi-settings/src/shared.rs @@ -0,0 +1,89 @@ +//! The part of the settings that is the same struct on every platform. + +use komorebi_themes::colour::Colour; +use komorebi_themes::colour::Rgb; + +/// The defaults a daemon starts with. They differ per platform today (border width 8 / 10 / 10, +/// padding 10 / 5 / 5, ...) and this step does not change any of them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlatformDefaults { + pub border_width: i32, + pub border_offset: i32, + pub border_radius: i32, +} + +impl PlatformDefaults { + /// `komorebi/src/border_manager/mod.rs`; Windows has no border radius setting (the unused + /// value is the one the other platforms use). + pub const WINDOWS: Self = Self { + border_width: 8, + border_offset: -1, + border_radius: 10, + }; + /// `komorebi-for-kde/komorebi/src/border_manager/mod.rs` + pub const KDE: Self = Self { + border_width: 10, + border_offset: 0, + border_radius: 10, + }; + /// `komorebi-for-mac/komorebi/src/border_manager/mod.rs` + pub const MACOS: Self = Self { + border_width: 10, + border_offset: 0, + border_radius: 10, + }; +} + +/// Colours are `u32` exactly as the border statics hold them (`u32::from(Colour)`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BorderColours { + pub single: u32, + pub stack: u32, + pub monocle: u32, + pub floating: u32, + pub unfocused: u32, + pub unfocused_locked: u32, +} + +/// Whether and how the borders are drawn; the colours are the same on all three platforms. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Border { + pub enabled: bool, + pub width: i32, + pub offset: i32, + /// Used by KDE and macOS; Windows keeps it but never reads it. + pub radius: i32, + pub colours: BorderColours, +} + +/// Every setting that is not tied to one platform. +#[derive(Clone, Debug, PartialEq)] +pub struct Shared { + pub border: Border, +} + +impl Shared { + /// The values the statics hold before any configuration is read. + pub fn defaults_for(defaults: PlatformDefaults) -> Self { + Self { + border: Border { + enabled: true, + width: defaults.border_width, + offset: defaults.border_offset, + radius: defaults.border_radius, + colours: BorderColours { + single: rgb(66, 165, 245), + stack: rgb(0, 165, 66), + monocle: rgb(255, 51, 153), + floating: rgb(245, 245, 165), + unfocused: rgb(128, 128, 128), + unfocused_locked: rgb(158, 8, 8), + }, + }, + } + } +} + +fn rgb(r: u32, g: u32, b: u32) -> u32 { + u32::from(Colour::Rgb(Rgb::new(r, g, b))) +}