diff --git a/.github/workflows/windows.yaml b/.github/workflows/windows.yaml index 1214a751..77e7006e 100644 --- a/.github/workflows/windows.yaml +++ b/.github/workflows/windows.yaml @@ -68,7 +68,7 @@ jobs: args: "--locked --release" - run: | cargo install cargo-wix - cargo wix --no-build -p komorebi-windows --nocapture -I .\wix\main.wxs --target ${{ matrix.platform.target }} + cargo wix --no-build -p komorebi --nocapture -I .\wix\main.wxs --target ${{ matrix.platform.target }} - uses: actions/upload-artifact@v7 with: name: komorebi-${{ matrix.platform.target }}-${{ github.sha }} diff --git a/Cargo.lock b/Cargo.lock index 7efffda4..b3b7ce90 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3383,6 +3383,17 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" +[[package]] +name = "komorebi" +version = "0.1.42" +dependencies = [ + "color-eyre", + "komorebi-linux", + "komorebi-macos", + "komorebi-windows", + "serde_json_lenient", +] + [[package]] name = "komorebi-backend" version = "0.1.42" diff --git a/Cargo.toml b/Cargo.toml index f48d405d..6288f854 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "komorebi-layouts", "komorebi-scrolling", "komorebic", + "komorebi-daemon", "komorebic-no-console", "crates/komorebic-core", "komorebi-bar", @@ -48,6 +49,7 @@ default-members = [ "komorebi-layouts", "komorebi-scrolling", "komorebic", + "komorebi-daemon", "komorebic-no-console", "crates/komorebic-core", "komorebi-bar", diff --git a/crates/komorebi-core/src/workspace.rs b/crates/komorebi-core/src/workspace.rs index 22fa1ad1..a91a2eaa 100644 --- a/crates/komorebi-core/src/workspace.rs +++ b/crates/komorebi-core/src/workspace.rs @@ -40,6 +40,44 @@ use std::fmt::Display; use std::fmt::Formatter; use std::num::NonZeroUsize; +/// What [`WorkspacePlatform::begin_update`] answers. +pub enum Flow { + /// Do not update the workspace now. + Skip, + /// Update it, holding the guard (if any) until the update is done. + Run(Option>), +} + +/// What [`WorkspacePlatform::end_update`] answers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Pass { + /// The windows are placed. + Done, + /// Lay the workspace out and place the windows once more. + Again, +} + +/// What the hooks of an update know about the pass that is running. +#[derive(Clone, Copy, Debug)] +pub struct Placement { + /// The work area less the monitor's and the workspace's offsets and padding. + pub adjusted_work_area: Rect, + /// The work area of the monitor. + pub work_area: Rect, + /// The padding around a container. + pub container_padding: i32, + /// The offset of the border from the window. + pub border_offset: i32, + /// The width of the border. + pub border_width: i32, + /// Whether the workspace has the scrolling layout. + pub is_scrolling: bool, + /// Whether the workspace has no resize adjustments. + pub resize_dimensions_is_empty: bool, + /// Whether a window is maximized on this workspace. + pub managed_maximized_window: bool, +} + /// What names a window of the platform `P`: the id the shared code compares. pub type PlatformWindowId

= <

::Window as ContainerWindow>::Id; @@ -135,6 +173,84 @@ pub trait WorkspacePlatform: Sized + Clone + std::fmt::Debug + PartialEq + 'stat fn before_hide_containers(_workspace: &mut Workspace) -> Option>> { None } + + // ---- the hooks of `update_shared`, in the order it calls them ----------------------------- + + /// Called first: the platform may skip the update (`Flow::Skip`) or run it holding a guard + /// that is dropped when the update ends (Windows: the animation batch). KDE prunes duplicate + /// windows here. Not called by a platform that has its own update. + fn begin_update(_workspace: &mut Workspace) -> eyre::Result { + Ok(Flow::Run(None)) + } + + /// Called after the empty containers are dropped, with the index that had the focus before. + /// KDE keeps the focus on a container that exists; Windows leaves it where it is. + fn containers_pruned(_workspace: &mut Workspace, _focused_before: usize) {} + + /// Puts the monocle window on the work area it is given. + fn place_monocle(_window: &mut Self::Window, _rect: &Rect) -> eyre::Result<()> { + Err(eyre::eyre!("this platform has no shared update")) + } + + /// Lays the maximized window out: the platform's own maximize. + fn maximize_in_layout(_window: &mut Self::Window) -> eyre::Result<()> { + Err(eyre::eyre!("this platform has no shared update")) + } + + /// Whether the scrolling layout should learn the widths the windows really have before it is + /// laid out (Windows: animations on and no live resize; KDE: the last placement has settled). + fn adopt_widths_before_layout(_workspace: &Workspace) -> bool { + false + } + + /// Has the scrolling layout learn the widths the windows really have; true if one changed. + fn adopt_actual_widths( + _workspace: &mut Workspace, + _around_window: i32, + _viewport_width: i32, + ) -> bool { + false + } + + /// The tile of every container of a scrolling workspace and whether each rests hidden past an + /// edge with another monitor next to it. + fn scrolling_layouts( + _workspace: &mut Workspace, + _adjusted_work_area: &Rect, + _container_padding: i32, + ) -> (Vec, Vec) { + (vec![], vec![]) + } + + /// Adjusts the tile of one container before its windows are placed: the room a border takes, + /// and whatever else the platform needs (the clamp to the work area, the stackbar). + fn adjust_layout( + _container: &mut Container, + _layout: &mut Rect, + _placement: &Placement, + ) { + } + + /// Puts the windows of a container on its (adjusted) tile, or hides them when `hidden`. + fn place_container( + _container: &mut Container, + _layout: &Rect, + _hidden: bool, + _placement: &Placement, + ) -> eyre::Result<()> { + Err(eyre::eyre!("this platform has no shared update")) + } + + /// Called after every placement pass; `Pass::Again` runs one more (the Windows scrolling layout + /// does once, when a window refused the width it was given). + fn end_update( + _workspace: &mut Workspace, + _pass: usize, + _around_window: i32, + _viewport_width: i32, + ) -> eyre::Result { + Ok(Pass::Done) + } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] @@ -1512,6 +1628,228 @@ impl Workspace

{ Ok(()) } + + /// Lays the windows of the workspace out: asks the layout for a tile per container in the + /// work area (less the paddings, the offsets and the room a border takes) and has the platform + /// put the windows on their tiles. What is the platform's (animations, title bars, stackbars, + /// the clamp to the work area, the scrolling layout's extra pass) is in the hooks of + /// [`WorkspacePlatform`] that `update_shared` calls, in the order of its documentation. + /// + /// Not named `update`, so that a daemon keeps its own `update` (it calls this one). + pub fn update_shared(&mut self) -> eyre::Result<()> { + // the platform may skip the update, and may hold a guard that lives until it is done + let _guard = match P::begin_update(self)? { + Flow::Skip => return Ok(()), + Flow::Run(guard) => guard, + }; + + // make sure we are never holding on to empty containers + let focused_container_idx = self.focused_container_idx(); + self.containers_mut() + .retain(|c| c.is_preselect() || !c.windows().is_empty()); + P::containers_pruned(self, focused_container_idx); + + let container_padding = self + .container_padding + .or(self.globals.container_padding) + .unwrap_or_default(); + let workspace_padding = self + .workspace_padding + .or(self.globals.workspace_padding) + .unwrap_or_default(); + let border_width = self.globals.border_width; + let border_offset = self.globals.border_offset; + let work_area = self.globals.work_area; + let mut rules_work_area_offset = None; + + if !self.work_area_offset_rules.is_empty() { + let count = if self.monocle_container.is_some() { + 1 + } else { + self.containers().len() + }; + + for (threshold, work_area_offset_rule) in &self.work_area_offset_rules { + if count >= *threshold { + rules_work_area_offset = Some(*work_area_offset_rule); + } + } + }; + + let work_area_offset = rules_work_area_offset + .or(self.work_area_offset) + .or(self.globals.work_area_offset); + let window_based_work_area_offset = self.globals.window_based_work_area_offset; + let window_based_work_area_offset_limit = self.globals.window_based_work_area_offset_limit; + + let mut adjusted_work_area = work_area_offset.map_or_else( + || work_area, + |offset| { + let mut with_offset = work_area; + with_offset.left += offset.left; + with_offset.top += offset.top; + with_offset.right -= offset.right; + with_offset.bottom -= offset.bottom; + + with_offset + }, + ); + + if (self.containers().len() <= window_based_work_area_offset_limit as usize + || self.monocle_container.is_some() && window_based_work_area_offset_limit > 0) + && self.apply_window_based_work_area_offset + { + adjusted_work_area = window_based_work_area_offset.map_or_else( + || adjusted_work_area, + |offset| { + let mut with_offset = adjusted_work_area; + with_offset.left += offset.left; + with_offset.top += offset.top; + with_offset.right -= offset.right; + with_offset.bottom -= offset.bottom; + + with_offset + }, + ); + } + + adjusted_work_area.add_padding(workspace_padding); + + self.enforce_resize_constraints(); + + if !self.layout_rules.is_empty() { + let mut updated_layout = None; + + for (threshold, layout) in &self.layout_rules { + if self.containers().len() >= *threshold { + updated_layout = Option::from(layout.clone()); + } + } + + if let Some(updated_layout) = updated_layout { + self.layout = updated_layout; + } + } + + if let Some(window_container_behaviour_rules) = &self.window_container_behaviour_rules { + let mut updated_behaviour = None; + for (threshold, behaviour) in window_container_behaviour_rules { + if self.containers().len() >= *threshold { + updated_behaviour = Option::from(*behaviour); + } + } + + self.window_container_behaviour = updated_behaviour; + } + + let managed_maximized_window = self.maximized_window.is_some(); + + if self.tile { + if let Some(container) = &mut self.monocle_container { + if let Some(window) = container.focused_window_mut() { + adjusted_work_area.add_padding(container_padding); + adjusted_work_area.add_padding(border_offset); + adjusted_work_area.add_padding(border_width); + P::place_monocle(window, &adjusted_work_area)?; + }; + } else if let Some(window) = &mut self.maximized_window { + P::maximize_in_layout(window)?; + } else if !self.containers().is_empty() { + let is_scrolling = self.is_scrolling(); + let around_window = container_padding + border_offset + border_width; + + // windows that were not what they were told to be since the last layout + if is_scrolling && P::adopt_widths_before_layout(self) { + P::adopt_actual_widths(self, around_window, adjusted_work_area.right); + } + + let mut pass = 0; + loop { + let effective_layout_options = self.effective_layout_options(); + + tracing::debug!( + "Workspace '{}' update() - effective_layout_options: {:?} (base: {:?}, rules: {})", + self.name.as_deref().unwrap_or("unnamed"), + effective_layout_options, + self.layout_options, + self.layout_options_rules.len(), + ); + + // the containers that rest where another monitor is seen from, which are hidden + let mut hidden = vec![]; + let mut layouts = if is_scrolling { + let (layouts, hide) = + P::scrolling_layouts(self, &adjusted_work_area, container_padding); + hidden = hide; + layouts + } else { + self.layout.as_boxed_arrangement().calculate( + &adjusted_work_area, + NonZeroUsize::new(self.containers().len()).ok_or_eyre( + "there must be at least one container to calculate a workspace layout", + )?, + Some(container_padding), + self.layout_flip, + &self.resize_dimensions, + self.focused_container_idx(), + effective_layout_options, + &self.latest_layout, + ) + }; + + let placement = Placement { + adjusted_work_area, + work_area, + container_padding, + border_offset, + border_width, + is_scrolling, + resize_dimensions_is_empty: self.resize_dimensions.is_empty(), + managed_maximized_window, + }; + + for (i, container) in self.containers_mut().iter_mut().enumerate() { + if let Some(layout) = layouts.get_mut(i) { + P::adjust_layout(container, layout, &placement); + P::place_container( + container, + layout, + hidden.get(i).copied().unwrap_or_default(), + &placement, + )?; + } + } + + self.latest_layout = layouts; + + match P::end_update(self, pass, around_window, adjusted_work_area.right)? { + Pass::Again => { + pass += 1; + continue; + } + Pass::Done => break, + } + } + } + } + + // Always make sure that the length of the resize dimensions vec is the same as the + // number of layouts / containers. This should never actually truncate as the remove_window + // function takes care of cleaning up resize dimensions when destroying empty containers + let container_count = self.containers().len(); + + // since monocle is a toggle, we never want to truncate the resize dimensions since it will + // almost always be toggled off and the container will be reintegrated into layout + // + // without this check, if there are exactly two containers, when one is toggled to monocle + // the resize dimensions will be truncated to len == 1, and when it is reintegrated, if it + // had a resize adjustment before, that will have been lost + if self.monocle_container.is_none() { + self.resize_dimensions.resize(container_count, None); + } + + Ok(()) + } } #[cfg(test)] @@ -1521,6 +1859,14 @@ mod tests { #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] struct W(u32); + thread_local! { + static LOG: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn log() -> Vec { + LOG.with(|log| std::mem::take(&mut *log.borrow_mut())) + } + thread_local! { static HIDDEN: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } @@ -1638,6 +1984,41 @@ mod tests { } fn note_scrolling_departure(_: &Workspace, _: usize) {} + + fn begin_update(_: &mut Workspace) -> eyre::Result { + LOG.with(|log| log.borrow_mut().push("begin".to_string())); + Ok(Flow::Run(None)) + } + + fn containers_pruned(_: &mut Workspace, focused_before: usize) { + LOG.with(|log| log.borrow_mut().push(format!("pruned {focused_before}"))); + } + + fn adjust_layout(_: &mut Container, layout: &mut Rect, _: &Placement) { + layout.add_padding(1); + } + + fn place_container( + container: &mut Container, + layout: &Rect, + hidden: bool, + _: &Placement, + ) -> eyre::Result<()> { + LOG.with(|log| { + log.borrow_mut().push(format!( + "place {} {} {}", + container.windows()[0].0, + layout.left, + hidden + )) + }); + Ok(()) + } + + fn end_update(_: &mut Workspace, pass: usize, _: i32, _: i32) -> eyre::Result { + LOG.with(|log| log.borrow_mut().push(format!("end {pass}"))); + Ok(if pass == 0 { Pass::Again } else { Pass::Done }) + } } fn workspace_of(ids: &[u32]) -> Workspace { @@ -1685,6 +2066,29 @@ mod tests { assert!(!keys.contains(&"scrolling")); } + #[test] + fn the_shared_update_calls_the_hooks_in_order_and_runs_again_when_asked() { + let mut workspace = workspace_of(&[1, 2]); + workspace.globals.work_area = Rect { + left: 0, + top: 0, + right: 1000, + bottom: 800, + }; + log(); + + workspace.update_shared().unwrap(); + + let log = log(); + assert_eq!(log[0], "begin"); + assert_eq!(log[1], "pruned 1"); + assert_eq!(log.iter().filter(|l| l.starts_with("place ")).count(), 4); + assert_eq!(log[4], "end 0"); + assert_eq!(log[7], "end 1"); + assert_eq!(workspace.latest_layout.len(), 2); + assert_eq!(workspace.resize_dimensions.len(), 2); + } + #[test] fn promoting_a_container_puts_it_first_and_focuses_it() { let mut workspace = workspace_of(&[1, 2, 3]); diff --git a/crates/komorebi-transport/src/listener.rs b/crates/komorebi-transport/src/listener.rs index 1bcef46a..cb17b1a2 100644 --- a/crates/komorebi-transport/src/listener.rs +++ b/crates/komorebi-transport/src/listener.rs @@ -86,6 +86,12 @@ pub trait ConnectionPolicy: Clone + Send + Sync + 'static { fn on_accept(&self, _stream: &S) {} fn on_message(&self, _message: &SocketMessage, _stream: &S) {} + + /// Who holds the window manager lock now, for the warning when it could not be acquired. + /// Defaults to nothing: only a daemon that records its holders can say. + fn lock_holder(&self) -> Option { + None + } } /// The policy that does nothing at either point @@ -190,7 +196,11 @@ where None => { tracing::warn!( target: LOG_TARGET, - "could not acquire window manager lock, not processing message: {message}" + "could not acquire window manager lock, not processing message: {message}{}", + policy + .lock_holder() + .map(|holder| format!(" (held by {holder})")) + .unwrap_or_default() ); } Some(ended) => { diff --git a/crates/komorebi-transport/src/subscribers.rs b/crates/komorebi-transport/src/subscribers.rs index 6d131c5b..8ee004c1 100644 --- a/crates/komorebi-transport/src/subscribers.rs +++ b/crates/komorebi-transport/src/subscribers.rs @@ -43,7 +43,23 @@ pub fn notify_sockets( match connect(path) { Ok(mut stream) => { tracing::debug!(target: LOG_TARGET, "pushed notification to subscriber: {socket}"); - stream.write_all(notification.as_bytes())?; + match stream.write_all(notification.as_bytes()) { + Ok(()) => {} + // a subscriber that does not read (the stream has a write timeout) + // is skipped, so that it cannot hold up the one that is pushing + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock + ) => + { + tracing::warn!( + target: LOG_TARGET, + "subscriber {socket} did not take the notification in time: {error}" + ); + } + Err(error) => return Err(error), + } } Err(_) => { stale_sockets.push(socket.clone()); @@ -132,4 +148,41 @@ mod tests { assert!(live.accept().is_ok()); let _ = std::fs::remove_dir_all(&dir); } + + /// A stream whose write times out, as one with a write timeout does when nobody reads it + struct Stuck; + + impl Write for Stuck { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::ErrorKind::TimedOut.into()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn a_subscriber_that_times_out_is_skipped_and_stays_subscribed() { + let dir = dir("timeout"); + let mut sockets = HashMap::from([ + ("a.sock".to_string(), dir.join("a.sock")), + ("b.sock".to_string(), dir.join("b.sock")), + ]); + let pushed = std::cell::Cell::new(0); + + let result = notify_sockets("{}", &mut sockets, &HashMap::new(), false, &dir, |_| { + pushed.set(pushed.get() + 1); + Ok(Stuck) + }); + + assert!(result.is_ok()); + assert_eq!( + pushed.get(), + 2, + "the subscribers after the stuck one are tried" + ); + assert_eq!(sockets.len(), 2, "a slow subscriber is not removed"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/deny.toml b/deny.toml index e9675ed5..61f56194 100644 --- a/deny.toml +++ b/deny.toml @@ -42,6 +42,11 @@ allow = [ ] confidence-threshold = 0.8 +[[licenses.clarify]] +crate = "komorebi" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "komorebi-windows" expression = "LicenseRef-Komorebi-2.0" diff --git a/docs/dev/core-model.md b/docs/dev/core-model.md index 085b332f..4e150a99 100644 --- a/docs/dev/core-model.md +++ b/docs/dev/core-model.md @@ -1108,3 +1108,197 @@ The decision of section 14 was made (D-coord-7) and the three macOS layers moved Nothing here has run on macOS. The Mini's `cargo test` is the oracle for the 53 workspace functions that were replaced by the shared text. + +## 16. `update_shared` landed (wip-u-core2), and what macOS keeps + +`Workspace::update_shared` is in `komorebi-core` with the hooks of section 12 (`begin_update` returning +`Flow`, `containers_pruned`, `place_monocle`, `maximize_in_layout`, `adopt_widths_before_layout`, +`adopt_actual_widths`, `scrolling_layouts` (which folds the `monitor_rects` and `other_monitors` of the +proposal into one hook, so each daemon keeps its own scrolling glue), `adjust_layout`, +`place_container`, `end_update` returning `Pass`). It is named `update_shared` and not `update` so +that a daemon's own `update` keeps working: the KDE and Windows `WorkspaceExt::update` are now +`self.update_shared()`, and macOS's is untouched. Every hook has a default so that `MacosPlatform` +compiles unchanged; the defaults of the ones a daemon must provide return an error. Where the +implementation departs from section 12: `adjust_layout` and `place_container` take the container +and the tile, not its index; the guard of `begin_update` is a boxed `dyn Any` (no associated type, so +macOS needs nothing); the KDE closure around the placement is gone (it had nothing between it and +its `?`); the Windows title-bar tables are read once per container instead of once per pass. + +**What macOS keeps (kfm's `update`, not touched):** its `update` is another shape, not the same text +with other hooks. It wraps the placement in SkyLight's `SLSDisableUpdate`/`SLSReenableUpdate` (a +`begin_update` guard could carry that); it has no maximized-window branch (the shared skeleton would +call `maximize_in_layout` for a workspace whose `maximized_window` is set, which on macOS would +change which branch runs); a scrolling workspace is placed by a separate `arrange_scrolling` that +sets the rectangles itself and returns, not by the shared per-container loop; it computes the layouts +with its own `calculate_layouts` and clamps with a free `clamp_to_work_area` in every case; it has no +stackbar and no second pass. Adopting `update_shared` on macOS means three decisions for its owner +(the maximized branch, folding `arrange_scrolling` into `scrolling_layouts` plus `place_container`, +and whether the clamp stays unconditional); none is needed to finish the Windows and KDE steps. + +## 17. Classification of `window_manager.rs`, `process_command.rs` and `process_event.rs` + +Method as in sections 7 and 14: `window_manager.rs` is cut into functions and compared function by +function across the three daemons (comments and blank lines dropped, indentation stripped; "changed" +counts the `<`/`>` lines of `diff`); `process_command.rs` and `process_event.rs` are one big `match` +each, so they are compared arm by arm (the arm of `SocketMessage::X` or `WindowManagerEvent::Y`). +Measured at the tip of `wip-u-core2` (KDE = `komorebi-linux`, Windows = `komorebi-windows`, macOS = +`komorebi-macos`). Classes: **identical**, **drift** (a few changed lines: an id type, a name, an +ordering), **same behaviour** (different text that does the same, found by reading the diff), +**real** (a platform difference, a hook is needed), **one-sided** (one daemon only). + +### `process_command.rs` (the router): 198 / 163 / 156 arms (Windows / KDE / macOS) + +| | arms | +|---|---| +| in all three, identical text | 110 | +| in all three, text differs | 45 | +| only in Windows (not-supported replies for macOS/KDE-only messages, `Notification`, `initial_state`) | 35 | +| in Windows and KDE only (`FocusFollowsMouse`, transparency, `ReloadHotkeys`, `ToggleMaximize`) | 7 | +| macOS and Windows only (`PanGesture`) | 1 | +| KDE only (`HotkeysState`) | 1 | + +Of the 45 that differ: 20 are macOS still carrying the body inline where Windows and KDE call the named +method of section 5 (`CloseWorkspace`, `CycleFocusWorkspace`, `EagerFocus`, `IgnoreRule`, +`LayoutRatios`, `Query`, `ReplaceConfiguration`, `ResizeWindowAxis`, `SessionFloatRule`, +`ToggleWorkspaceLayer`, the two named-workspace rules, `ToggleWorkspaceWindowContainerBehaviour`, +`BorderColour`, `MoveContainerToLastWorkspace`, `CycleFocusEmptyWorkspace`, `DebugWindow`, +`ManageRule`, `AddSubscriberPipe`): drift of shape, same behaviour once macOS calls the methods (kfm's +conversion, step 9's precondition). The other 25 are KDE against Windows, in these clusters: + +- **same behaviour, written differently** (a method on one side, inline on the other, or `unwrap_or_else` + against `match`): `FocusLastWorkspace` (Windows `focus_last_workspace()`, KDE inline), `FocusWorkspaceNumbers`, + `Close`, `Minimize`, `State`, `SessionFloatRules`, `StaticConfigSchema`, + `ApplicationSpecificConfigurationSchema`, `VisibleWindows` (the key of the map: Windows' device id, + KDE's monitor id), `TogglePause` and `Retile` (modulo the border lines below). +- **real**: `Border`, `BorderOffset`, `BorderWidth`, `ReloadStaticConfiguration`, `Retile`, + `RetileWithResizeDimensions` (Windows' border implementations and `force_update_borders`); + `StackAll`, `UnstackAll`, `StackWindow`, `UnstackWindow`, `CycleStack`, `CycleStackIndex`, + `FocusStackWindow` (KDE switches animations off around them, Windows does not); + `ResizeWindowEdge` (the Windows `live_resize::InPlace` guard); `FocusWorkspaceNumber` (Windows first + focuses the monitor under the pointer when its workspace is empty). + +Order for the router: (1) macOS converges its arms onto the named methods (nothing shared is needed); +(2) the 110 identical arms plus the 20 that become identical are one exhaustive `match` in the crate +with each arm one call into `WindowManager`; (3) the remaining arms become `RouterPlatform` hooks +with a default of "not supported" (`before_command`, `after_command`, the border arms, the animation +guard around stacking, the live-resize guard, the pointer-monitor preamble). The 36 Windows-only and +KDE-only arms are the "not supported" list of section 5 and need no hook. + +### `process_event.rs`: 11 / 15 / 10 arms + +The event vocabularies are platform's own: only `Destroy`, `Show` and `Minimize` exist on all three, +and their bodies differ (Windows 10/145/22 lines, KDE 44/112/8, macOS 44/168/4 for +`Destroy`/`Show`/`Minimize`; changed lines against each other 48-153). KDE and macOS share six more +(`MoveStart`, `MoveEnd`, `ResizeStart`, `ResizeEnd`, `ResizeStep`, `Restore`) with drift of 4-58 lines; +Windows has eight of its own (`FocusChange`, `Hide`, `Maximize`, `Unmaximize`, `MouseCapture`, +`MoveResizeStart`, `MoveResizeEnd`, `window`), KDE five (`FullscreenChange`, `MaximizeChange`, +`OutputChange`, `TitleUpdate`, `WorkspaceChange`, `WorkspaceMove`), macOS one (`Unmanage`). So +`process_event` is not shareable by converge: it is the "thin events" step of the plan (each platform +translates its events into a small shared vocabulary, `Added`, `Removed`, `Focused`, `Moved`, +`Resized`, `Minimized`, `Restored`, `Unmanaged`, and the shared handler runs the arms that are the +same). It comes last, after `WindowManager`. + +### `window_manager.rs`: 134 non-test functions in the union + +| | functions | +|---|---| +| in all three, identical | 39 | +| in all three, differ | 48 (19 drift of 1-4 lines; 20 of 5-20; 10 of more than 20 against the Windows one) | +| Windows only | 13: `apply_state` (131), `update_known_hwnds`, `raise_window_at_cursor_pos`, `workspace_transition_plan`, the custom-layout setters, `configure_watcher`/`watch_configuration`/`reload_configuration`, `focus_container_at_edge`, `focus_workspace_towards`, `remove_all_accents` | +| KDE only | 4: `adopt_maximize_change`, `adopt_workspace_change`, `sync_workspace_desktops`, `reap_invalid_windows` | +| macOS only | 16: the live resize family (`live_resize_*`, `apply_mouse_resize`, `resize_by_drag`, `edges_moved`), `entering_borders`, `workspace_transition`, `drag_origin`, `set_messaging_timeouts` | +| Windows and KDE only | 4: `maximize_window`, `unmaximize_window`, `toggle_maximize`, `monitor_idx_from_window` | +| KDE and macOS only | 2: `extract_minimized_window`, `update_known_window_ids` | + +The big differences (more than 20 changed lines Windows against KDE) are `focus_floating_window_in_direction` +(105), `focus_container_in_direction` (69), `resize_window` (58, macOS 52), `update_focused_workspace` (57; +KDE and macOS are identical), `enforce_workspace_rules` (43), `restore_all_windows` (40), +`transfer_window` (36), `move_container_to_monitor` (30), `new` (25) and `monitor_idx_from_window` (23). +Twenty functions are identical in KDE and macOS and differ only in Windows (`retile_all`, +`change_workspace_layout_default`, `move_container_in_direction`, `promote_container_swap`, +`toggle_monocle`, `float_window`, `focus_monitor`, `unstack_all`, ...): the Windows copy still has its +older form, the KDE and macOS one is the one to share. 61 of the 91 functions that exist in Windows and +KDE differ by at most 4 lines (42 not at all), so most of the layer is convergence of Windows onto the +KDE/macOS text, which kfw can do function by function the way it did the container and workspace. + +Order for `WindowManager` (the next layers of step 9): (1) Windows converges the 20 KDE=macOS-identical +functions and the 19 drift functions (mechanical, tests/e2e per cluster); (2) the struct moves as +`WindowManager

` with `P::State` for the platform fields of section 2 (Windows: `known_hwnds`, +`virtual_desktop_id`, `has_pending_raise_op`; KDE: `opacity_applied`, `minimized_windows`, +`live_resize`; macOS: the live resize and drag state) and the 39 + converged identical functions; +(3) the real differences become hooks, in this order: `monitor_idx_from_window`, +`transfer_window`/`move_container_to_monitor` (the move across a monitor boundary), +`restore_all_windows`, `enforce_workspace_rules`, `focus_*_in_direction` (floating windows), +`resize_window` (live resize, shared by KDE-macOS first), `update_focused_workspace`; (4) the +platform-only functions stay in each daemon's `WindowManagerExt` (the Windows custom layouts and +watcher, the KDE desktop sync, the macOS live resize); (5) the router; (6) `process_event` with the +thin events. + +## 18. Converging `window_manager.rs` and the router: what is cosmetic, what is real, and why `WindowManager

` waits + +Measured at the tip of `wip-u-core3` (core2 plus one Windows revision), the same function comparison +as section 17. In KDE's 2621 non-test function lines (stripped) of `window_manager.rs`: + +| | lines | share | +|---|---|---| +| in functions identical with the Windows copy | 689 | 26% | +| in functions that differ by at most 4 lines from the Windows copy | 961 | 37% | +| in functions that are KDE-only, or differ by more | 1660 | 63% | + +The threshold for creating `WindowManager

` (more than 60% shared) is not met and cannot be met by +converging cosmetics: of the 19 functions that differ by 1 to 4 lines, almost all differ in +behaviour. What the converge revision took (Windows to KDE's text): `eyre::bail!` in full, the +`Lockable` form of `toggle_lock`, two log lines (one with a typo), and the `SessionFloatRules` and +`State` arms. The rest of the near-identical functions, one by one: + +| function(s) | the difference | kind | +|---|---|---| +| `toggle_monocle`, `stack_all`, `remove_window_from_container`, `move_container_to_workspace`, `promote_container_to_front`, `move_container_in_cycle_direction` (and 12 more of the 20-line group) | Windows calls `handle_unmanaged_window_behaviour()` at the top of 18 individual functions; KDE and macOS call it once in the router for every message | real (when it refuses: a command about an unmanaged focus is refused per function on Windows, for every message on KDE/macOS) | +| `monocle_on`, `monocle_off` | Windows also hides / restores the floating windows | real | +| `cycle_monocle` | Windows destroys the borders | real | +| `set_workspace_name` | Windows records the name in the monitor's extra `workspace_names` | real (a Windows field) | +| `cycle_layout`, `promote_focus_to_front`, `promote_container_swap`, `change_workspace_layout_default` | the Windows `Layout::Custom` arms (`promote_focus_to_front` falls back to the first column, the others fail without a primary column) | real: hook `primary_container_idx` exists, but the fallback of `promote_focus_to_front` differs | +| `apply_wallpaper_for_monitor_workspace`, `retile_all` | the monitor id is an `isize` handle on Windows, a `u32` on KDE; `retile_all` also destroys the borders on KDE | type (`PlatformMonitorId` would remove the first) and real | +| `add_window_handle_to_move_based_on_workspace_rule`, `stack_all` | `hwnd: isize` against `window_id: u32` | type: `PlatformWindowId` | +| `clear_workspace_layout_rules`, `maximize_window`, `focus_monitor`, `toggle_lock` | log text, `bail!`, `Lockable` | cosmetic: done | +| `float_window` and the `focus_*` family | KDE reads `mouse_follows_focus` into a local (borrow); same behaviour | cosmetic, left (the local is KDE's borrow fix) | + +Larger real differences, from section 17's list: `focus_workspace` (Windows plans a slide transition, +KDE asks the compositor; `focus_workspace_towards`, `workspace_transition_plan`), `init`, `stop` (the +Windows state file, animations, focus-follows-mouse), `manage_focused_window` and +`unmanage_focused_window` (an event against a notification), `monitor_idx_from_current_pos` (Windows +refreshes a monitor from the system), `move_container_in_direction` (a DPI check across monitors), +`move_floating_window_in_direction` (border offsets), `focus_floating_window_in_direction` (105 lines), +`resize_window` (58; macOS 52 against KDE 0), `restore_all_windows`, `enforce_workspace_rules`. + +**The router, KDE against Windows.** The 25 differing arms: two made identical (`SessionFloatRules`, +`State`); the rest are real and stay: `Close` and `Minimize` (Windows ignores a failed backend call +with `let _ =`, KDE propagates it), `StaticConfigSchema` and `ApplicationSpecificConfigurationSchema` +(Windows prints `schema_for!`, KDE and macOS the platform view of `komorebi-config`; the Windows +output would change), `VisibleWindows` (the JSON key: Windows' device id, KDE's monitor id), +`Border*`, `Retile*`, `ReloadStaticConfiguration`, `TogglePause` (borders and `force_update_borders`), +`StackAll`/`UnstackAll`/`StackWindow`/`UnstackWindow`/`CycleStack*`/`FocusStackWindow` (KDE switches +animations off around them), `ResizeWindowEdge` (the live-resize guard), and `FocusWorkspaceNumber`, +`FocusWorkspaceNumbers`, `FocusLastWorkspace` (Windows first focuses the monitor under the pointer when +its workspace is empty; the identical arms `CycleFocusWorkspace`, `CloseWorkspace` and +`MoveContainerToLastWorkspace` do it on KDE too, so for these three it is probably an omission on KDE: +decision for the owner). + +**Blocker list for `WindowManager

`:** +1. the `handle_unmanaged_window_behaviour` placement (router on KDE/macOS, per function on Windows): + one `before_command` hook cannot give both; either Windows moves to the router (a behaviour change in + which commands are refused) or the shared functions call a hook that is a no-op on KDE and macOS; +2. borders: the Windows border calls inside shared functions (`cycle_monocle`, `retile_all`, + `Border*`) need a `BorderPlatform` hook with a no-op default; +3. the workspace transition (`focus_workspace`) needs the plan/execute split as a hook; +4. the platform fields of the struct (section 2) and `init`/`stop`/`new`; +5. `PlatformMonitorId` next to `PlatformWindowId` (the `isize`/`u32` handles in 12 functions); +6. the Windows custom layouts (the `primary_container_idx` hook covers most arms); +7. macOS's 16 own functions (the live resize family, `entering_borders`, `workspace_transition`) would + stay in a `WindowManagerExt`, which means the text KDE and macOS share (20 functions identical + between them, 6 of the router's arms) is the base, not the Windows text. + +Recommended next step: shared text first between KDE and macOS (kfm and kfde), where 20 window manager +functions and most router arms are already identical, then Windows converges onto it function by +function against the blocker list above; creating `WindowManager

` before blockers 1 to 3 are decided +would move less than half of the file. diff --git a/docs/dev/unified-binaries.md b/docs/dev/unified-binaries.md index a26f2fd5..ca4d26a9 100644 --- a/docs/dev/unified-binaries.md +++ b/docs/dev/unified-binaries.md @@ -323,3 +323,45 @@ The macOS checks that matter by revision: `refactor(komorebic): move the macOS CLI ...` (komorebic, quickstart, start, stop), `refactor(client): one komorebi-client ...` (the client tests in `komorebi-client/src/macos.rs`), and `refactor(bar): one komorebi-bar package ...` (the bar opens, `--schema`). Everything in `docs/dev/macos-handcheck.md` still applies. + +## Step 8 done: one `komorebi` + +`komorebi-daemon/` is the package `komorebi` (binary `komorebi`): a `main` that calls +`komorebi_windows::daemon::run()`, `komorebi_linux::daemon::run()` or `komorebi_macos::daemon::run()` by +`cfg_select!` on the target OS, through target-gated dependencies on the three libraries. The old `main.rs` +files are `daemon.rs` of those libraries (`komorebi::` became `crate::`), and the libraries have no binary: +`-p komorebi-windows`, `-p komorebi-linux` and `-p komorebi-macos` still build, as libraries; the binary is +`-p komorebi` on every platform. The features `deadlock_detection` and `schemars` are forwarded. +The KDE tests that run the binary moved to `komorebi-daemon/tests/linux_*.rs`. + +So `cargo build -p komorebi`, `-p komorebic`, `-p komorebi-bar` and `cargo run -p komorebi-bar -- --schema` build and +run the right program on Windows, KDE Plasma and macOS. What is left for the cutover (nothing here deletes it yet): + +- the shim packages `komorebic-linux`, `komorebic-macos`, `komorebi-client-linux`, `komorebi-client-macos`, + `komorebi-bar-macos` (each a `#[path]` include of the unified module) and their directories under + `komorebi-for-kde/` and `komorebi-for-mac/`; +- the per-platform `version` packages (`version-linux`, `version-macos`) once one `version` crate serves + all three; +- the three flakes becoming one, the repository layout (`komorebi-for-kde/`, `komorebi-for-mac/` trees move + under the platform crates' final directories), one `deny.toml`, the workspace-wide version number + (0.1.42 / 0.1.0 / 0.1.1), and the comments and docs that name the old paths; +- the libraries `komorebi-windows`, `komorebi-linux`, `komorebi-macos` stay: they are the daemons. + +Owed by the coordinator for this step (none was built): the heavy builds listed above, now also +`nix build -L .#packages.x86_64-linux.komorebi .#packages.x86_64-linux.kfde-komorebi`; the Windows e2e +(BEHAVIOUR: the Windows executable is linked from the library's `daemon::run`); the KDE VM `fast` suites. + +### Mac Mini commands for the new package + +``` +cargo build --locked -p komorebi -p komorebic -p komorebi-bar +target/debug/komorebi --version # prints komorebi 0.1.0 (the macOS version crate) +target/debug/komorebi --help | head -3 +cargo clippy --locked -p komorebi -p komorebi-macos -p komorebic -p komorebi-client -p komorebi-bar -p komorebi-bar-core --all-targets -- -D warnings +cargo test --locked -p komorebi-macos -p komorebic -p komorebi-client -p komorebi-bar-core -p komorebi-bar +cargo build --locked --features deadlock_detection -p komorebi # the feature is forwarded +``` + +`komorebi` is now a package name on every platform: `-p komorebi` builds the macOS daemon on a Mac. The libraries +build with `cargo build -p komorebi-macos` but have no binary. The daemon itself (start, tile, `komorebic state`) is +the hand check in `docs/dev/macos-handcheck.md`. diff --git a/flake.nix b/flake.nix index c2ba9fee..d390194c 100644 --- a/flake.nix +++ b/flake.nix @@ -224,7 +224,7 @@ # the other platforms' crates are added as stubs below !(pkgs.lib.hasInfix "/komorebi-for-kde" path || pkgs.lib.hasInfix "/komorebi-for-mac" path) # the Linux and macOS files of komorebic are not read when building for Windows - && !(builtins.match ".*/komorebi(c/(src/(linux|macos)|tests/(linux|macos)_)|-client/(src/(linux|macos)\\.rs|tests/(linux|macos)_)|-bar/src/macos)[^/]*.*" path != null) + && !(builtins.match ".*/komorebi(c/(src/(linux|macos)|tests/(linux|macos)_)|-client/(src/(linux|macos)\\.rs|tests/(linux|macos)_)|-bar/src/macos|-daemon/tests/(linux|macos)_)[^/]*.*" path != null) && ( (craneLib.filterCargoSources path type) || (pkgs.lib.hasInfix "/docs/" path) diff --git a/justfile b/justfile index 3296b7dd..8353731e 100644 --- a/justfile +++ b/justfile @@ -86,7 +86,7 @@ jsonschema: cargo run --package komorebic -- application-specific-configuration-schema > schema.asc.json cargo run --package komorebi-bar -- --schema > schema.bar.json -version := `cargo metadata --format-version 1 --no-deps | jq -r '.packages[] | select(.name == "komorebi-windows") | .version'` +version := `cargo metadata --format-version 1 --no-deps | jq -r '.packages[] | select(.name == "komorebi") | .version'` schemapub: rm -Force komorebi-schema diff --git a/komorebi-daemon/Cargo.toml b/komorebi-daemon/Cargo.toml new file mode 100644 index 00000000..af3e0063 --- /dev/null +++ b/komorebi-daemon/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "komorebi" +version = "0.1.42" +description = "A tiling window manager for Windows, KDE Plasma and macOS" +repository = "https://github.com/LGUG2Z/komorebi" +edition = "2024" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +# The daemon of each platform is a library (`komorebi-windows`, `komorebi-linux`, `komorebi-macos`) with a +# `daemon::run` that is the old main; this package is the one `komorebi` binary and calls the one of the +# target OS. A dependency key has one path, so each library has a key of its own. + +[dependencies] +color-eyre = { workspace = true } + +[target.'cfg(windows)'.dependencies] +komorebi-windows = { package = "komorebi-windows", path = "../komorebi", default-features = false } + +[target.'cfg(target_os = "linux")'.dependencies] +komorebi-linux = { package = "komorebi-linux", path = "../komorebi-for-kde/komorebi", default-features = false } + +[target.'cfg(target_os = "macos")'.dependencies] +komorebi-macos = { package = "komorebi-macos", path = "../komorebi-for-mac/komorebi", default-features = false } + +[features] +default = ["schemars"] +deadlock_detection = ["komorebi-windows/deadlock_detection", "komorebi-linux/deadlock_detection", "komorebi-macos/deadlock_detection"] +schemars = ["komorebi-windows/schemars", "komorebi-linux/schemars", "komorebi-macos/schemars"] + +[target.'cfg(target_os = "linux")'.dev-dependencies] +serde_json = { workspace = true } diff --git a/komorebi-daemon/src/main.rs b/komorebi-daemon/src/main.rs new file mode 100644 index 00000000..e79d9c7a --- /dev/null +++ b/komorebi-daemon/src/main.rs @@ -0,0 +1,10 @@ +//! `komorebi`, the tiling window manager daemon, for Windows, KDE Plasma and macOS: the daemon of the target +//! OS is a library of its own and this binary runs it. + +fn main() -> color_eyre::eyre::Result<()> { + cfg_select! { + target_os = "windows" => komorebi_windows::daemon::run(), + target_os = "linux" => komorebi_linux::daemon::run(), + target_os = "macos" => komorebi_macos::daemon::run(), + } +} diff --git a/komorebi-for-kde/komorebi/tests/hot_reload.rs b/komorebi-daemon/tests/linux_hot_reload.rs similarity index 99% rename from komorebi-for-kde/komorebi/tests/hot_reload.rs rename to komorebi-daemon/tests/linux_hot_reload.rs index b2a3310f..2cdad023 100644 --- a/komorebi-for-kde/komorebi/tests/hot_reload.rs +++ b/komorebi-daemon/tests/linux_hot_reload.rs @@ -1,3 +1,4 @@ +#![cfg(target_os = "linux")] //! The daemon and its `komorebi.json`: `komorebi --fake-backend` finds the file in the config home //! or is given it with `--config`, is configured by it, and applies it again when the file changes. //! diff --git a/komorebi-for-kde/komorebi/tests/no_kwin.rs b/komorebi-daemon/tests/linux_no_kwin.rs similarity index 99% rename from komorebi-for-kde/komorebi/tests/no_kwin.rs rename to komorebi-daemon/tests/linux_no_kwin.rs index 417c68a3..b3ade6f0 100644 --- a/komorebi-for-kde/komorebi/tests/no_kwin.rs +++ b/komorebi-daemon/tests/linux_no_kwin.rs @@ -1,3 +1,4 @@ +#![cfg(target_os = "linux")] //! `komorebi` connects to KWin unless it is told to run against the in-memory desktop, says //! what went wrong when it cannot, and then leaves the socket of a komorebi that is running //! alone. diff --git a/komorebi-for-kde/komorebi/tests/socket.rs b/komorebi-daemon/tests/linux_socket.rs similarity index 99% rename from komorebi-for-kde/komorebi/tests/socket.rs rename to komorebi-daemon/tests/linux_socket.rs index 42f4c6d5..9cd834f8 100644 --- a/komorebi-for-kde/komorebi/tests/socket.rs +++ b/komorebi-daemon/tests/linux_socket.rs @@ -1,3 +1,4 @@ +#![cfg(target_os = "linux")] //! The daemon over its socket: `komorebi --fake-backend` answers on `komorebi.sock` in its //! runtime directory, and stops when it is sent `Stop`. diff --git a/komorebi-daemon/tests/linux_version.rs b/komorebi-daemon/tests/linux_version.rs new file mode 100644 index 00000000..fd627c96 --- /dev/null +++ b/komorebi-daemon/tests/linux_version.rs @@ -0,0 +1,27 @@ +#![cfg(target_os = "linux")] +//! `komorebi --version` reports the workspace version. + +use std::process::Command; + +#[test] +fn reports_the_package_version() { + let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) + .arg("--version") + .output() + .expect("komorebi runs"); + + assert!(output.status.success()); + + let stdout = String::from_utf8(output.stdout).expect("utf-8 output"); + // the version the KDE daemon reports is that of the KDE `version` crate (the workspace version of + // komorebi for KDE), not of this package, which is shared with the other platforms + let manifest = include_str!("../../komorebi-for-kde/version/Cargo.toml"); + let version = manifest + .lines() + .find_map(|line| line.strip_prefix("version = \"")) + .and_then(|rest| rest.strip_suffix('"')) + .expect("the version crate has a version"); + let expected = format!("komorebi {version}"); + + assert_eq!(stdout.lines().next(), Some(expected.as_str())); +} diff --git a/komorebi-for-kde/deny.toml b/komorebi-for-kde/deny.toml index 4439b6a0..eab867dd 100644 --- a/komorebi-for-kde/deny.toml +++ b/komorebi-for-kde/deny.toml @@ -38,6 +38,11 @@ allow = [ ] confidence-threshold = 0.8 +[[licenses.clarify]] +crate = "komorebi" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "komorebi-linux" expression = "LicenseRef-Komorebi-2.0" diff --git a/komorebi-for-kde/flake.nix b/komorebi-for-kde/flake.nix index f60290e3..ea310c93 100644 --- a/komorebi-for-kde/flake.nix +++ b/komorebi-for-kde/flake.nix @@ -97,8 +97,19 @@ "komorebi-client/tests" ] || pkgs.lib.hasPrefix "komorebi-client/tests/linux_" relative; + + # the one komorebi binary package: its manifest, main.rs and tests + komorebiDaemon = + builtins.elem relative [ + "komorebi-daemon" + "komorebi-daemon/Cargo.toml" + "komorebi-daemon/src" + "komorebi-daemon/src/main.rs" + "komorebi-daemon/tests" + ] + || pkgs.lib.hasPrefix "komorebi-daemon/tests/linux_" relative; in - ((rootCrate || rootCrateParent || komorebic || komorebiClient) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree) + ((rootCrate || rootCrateParent || komorebic || komorebiClient || komorebiDaemon) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree) && # the VM tests (their library, scripts and the states they keep) are not built, so # editing one does not change the source the daemon is built from @@ -131,9 +142,10 @@ pkgs.lib.hasPrefix "${platformDir}/" member || member == "komorebic" || member == "komorebi-client" + || member == "komorebi-daemon" || builtins.any (crate: member == crate || pkgs.lib.hasPrefix "${crate}/" member) rootCrates; }; - packages = "-p komorebi-linux -p komorebic -p komorebi-client -p komorebi-hotkeys"; + packages = "-p komorebi -p komorebi-linux -p komorebic -p komorebi-client -p komorebi-hotkeys"; workspaceArgs = { pname = "komorebi-workspace"; version = (builtins.fromTOML (builtins.readFile ./komorebi/Cargo.toml)).package.version; diff --git a/komorebi-for-kde/komorebi/Cargo.toml b/komorebi-for-kde/komorebi/Cargo.toml index 747623b3..1d8d0bb1 100644 --- a/komorebi-for-kde/komorebi/Cargo.toml +++ b/komorebi-for-kde/komorebi/Cargo.toml @@ -61,7 +61,3 @@ schemars = ["dep:schemars", "komorebi-collections/schemars", "komorebi-core/sche [lib] name = "komorebi" - -[[bin]] -name = "komorebi" -path = "src/main.rs" diff --git a/komorebi-for-kde/komorebi/src/main.rs b/komorebi-for-kde/komorebi/src/daemon.rs similarity index 91% rename from komorebi-for-kde/komorebi/src/main.rs rename to komorebi-for-kde/komorebi/src/daemon.rs index d20b4692..5d896b06 100644 --- a/komorebi-for-kde/komorebi/src/main.rs +++ b/komorebi-for-kde/komorebi/src/daemon.rs @@ -3,15 +3,15 @@ //! The daemon owns the layout of every window and asks the compositor, through a backend, to //! put each one where the layout says. //! -//! The backend is KWin's ([`komorebi::kwin`]): the daemon connects to the session bus, loads its +//! The backend is KWin's ([`crate::kwin`]): the daemon connects to the session bus, loads its //! script into KWin and waits for the script to report the desktop. `--fake-backend` replaces it //! with an in-memory desktop with one monitor and no windows, for development and testing. //! //! The daemon starts from `komorebi.json`: the file `--config` names, or else the one in -//! [`struct@HOME_DIR`] when there is one ([`komorebi::static_config`]), which it reloads whenever +//! [`struct@HOME_DIR`] when there is one ([`crate::static_config`]), which it reloads whenever //! it changes. Without a file it runs on its defaults. It loads the monitors and the windows //! that are open, gives each monitor the configuration the file has for it, asks for the borders -//! it draws ([`komorebi::border_manager`]), tiles the windows, listens for messages on +//! it draws ([`crate::border_manager`]), tiles the windows, listens for messages on //! `komorebi.sock` in [`struct@DATA_DIR`], handles the events the backend reports and the changes //! of the monitors on threads of their own, and runs until it is stopped, with `SIGINT`, //! `SIGTERM` or a `Stop` message. @@ -19,7 +19,7 @@ //! With a key binding file (`--keybindings`, or the first of `skhdrc`, `whkdrc` and `sxhkdrc` in //! [`struct@HOME_DIR`]), the daemon also runs the engine of [`komorebi_hotkeys`]: it registers the //! keys of the bindings that are not static shortcuts with KWin's global shortcut daemon and runs -//! their commands ([`komorebi::kwin::hotkeys::load`]). A file that cannot be read is logged, and +//! their commands ([`crate::kwin::hotkeys::load`]). A file that cannot be read is logged, and //! the window manager runs without keys. The bindings it takes are the engine's part of the file's //! plan in `--keybindings-mode`, the mode `komorebic hotkeys compile --mode` wrote the static //! shortcuts in. `--chord-timeout` is how long the next key of a chord chain is waited for, and @@ -36,21 +36,21 @@ use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; -use komorebi::DATA_DIR; -use komorebi::HOME_DIR; -use komorebi::LOG_DIR; -use komorebi::backend; -use komorebi::backend::fake::FakeBackend; -use komorebi::border_manager; -use komorebi::core::pathext::replace_env_in_path; -use komorebi::kwin::hotkeys::Keybindings; -use komorebi::monitor_reconciliator; -use komorebi::process_command::listen_for_commands; -use komorebi::process_event::listen_for_events; -use komorebi::static_config::StaticConfig; -use komorebi::static_config::StaticConfigExt; -use komorebi::window_manager::WindowManager; -use komorebi::window_manager_event_listener; +use crate::DATA_DIR; +use crate::HOME_DIR; +use crate::LOG_DIR; +use crate::backend; +use crate::backend::fake::FakeBackend; +use crate::border_manager; +use crate::core::pathext::replace_env_in_path; +use crate::kwin::hotkeys::Keybindings; +use crate::monitor_reconciliator; +use crate::process_command::listen_for_commands; +use crate::process_event::listen_for_events; +use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; +use crate::window_manager::WindowManager; +use crate::window_manager_event_listener; use komorebi_hotkeys::Format; use komorebi_hotkeys::engine::EngineOptions; use komorebi_hotkeys::plan::PlanMode; @@ -269,7 +269,7 @@ fn app_alias(value: &str) -> Result<(String, Vec), String> { Ok((name.trim().to_string(), aliases)) } -fn main() -> eyre::Result<()> { +pub fn run() -> eyre::Result<()> { let opts: Opts = Opts::parse(); let (_guard, _color_guard) = setup(opts.log_level.clone())?; @@ -282,7 +282,7 @@ fn main() -> eyre::Result<()> { backend::set_backend(Arc::new(FakeBackend::with_one_monitor())); } else { tracing::info!("connecting to KWin"); - backend::set_backend(komorebi::kwin::connect()?); + backend::set_backend(crate::kwin::connect()?); } #[cfg(feature = "deadlock_detection")] @@ -339,7 +339,7 @@ fn main() -> eyre::Result<()> { { let mut wm = wm.lock(); border_manager::update_colours(&wm); - komorebi::transparency_manager::apply(&mut wm); + crate::transparency_manager::apply(&mut wm); } monitor_reconciliator::listen_for_notifications(wm.clone())?; @@ -365,7 +365,7 @@ fn main() -> eyre::Result<()> { app_aliases, }, }; - if let Err(error) = komorebi::kwin::hotkeys::load(keybindings) { + if let Err(error) = crate::kwin::hotkeys::load(keybindings) { tracing::error!("the key bindings are not active: {error}"); } } @@ -383,11 +383,11 @@ fn main() -> eyre::Result<()> { { let mut wm = wm.lock(); wm.restore_all_windows(false)?; - komorebi::transparency_manager::restore(&mut wm); + crate::transparency_manager::restore(&mut wm); } backend::backend().shutdown(); - let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock(); + let sockets = crate::SUBSCRIPTION_SOCKETS.lock(); for path in (*sockets).values() { if let Ok(stream) = UnixStream::connect(path) { stream.shutdown(Shutdown::Both)?; diff --git a/komorebi-for-kde/komorebi/src/lib.rs b/komorebi-for-kde/komorebi/src/lib.rs index 20064658..e9c2c80d 100644 --- a/komorebi-for-kde/komorebi/src/lib.rs +++ b/komorebi-for-kde/komorebi/src/lib.rs @@ -64,6 +64,7 @@ extern crate komorebi_collections; pub use komorebi_collections::ring; +pub mod daemon; pub mod animation; pub mod backend; pub mod border_manager; diff --git a/komorebi-for-kde/komorebi/src/workspace.rs b/komorebi-for-kde/komorebi/src/workspace.rs index b63c8c29..228fabd1 100644 --- a/komorebi-for-kde/komorebi/src/workspace.rs +++ b/komorebi-for-kde/komorebi/src/workspace.rs @@ -36,7 +36,6 @@ pub use komorebi_core::WorkspaceGlobals; use komorebi_themes::KomorebiTheme; use komorebi_themes::KomorebiThemeCustom; use std::collections::HashMap; -use std::num::NonZeroUsize; use komorebi_core::CachedLayoutDefault; pub use komorebi_core::WorkspaceLayer; @@ -145,6 +144,191 @@ impl komorebi_core::WorkspacePlatform for KdePlatform { resize_dimensions } + + fn begin_update(workspace: &mut Workspace) -> eyre::Result { + workspace.prune_duplicate_windows()?; + Ok(komorebi_core::Flow::Run(None)) + } + + fn containers_pruned(workspace: &mut Workspace, focused_before: usize) { + // make sure we are never focused on a no longer existent final empty container + if focused_before >= workspace.containers().len() { + workspace.focus_container(focused_before.saturating_sub(1)); + } + } + + fn place_monocle(window: &mut Window, rect: &Rect) -> eyre::Result<()> { + Ok(window.set_position(rect)?) + } + + fn maximize_in_layout(window: &mut Window) -> eyre::Result<()> { + // the compositor's own maximize, which is the work area and not the padded one + Ok(window.maximize()?) + } + + fn adopt_widths_before_layout(workspace: &Workspace) -> bool { + // a window that would not get as narrow as its column was learned of once the windows have + // had time to draw at the sizes that they were sent, and not while one is being dragged, + // whose neighbours are on their way + workspace + .state + .scrolling_placed + .as_ref() + .is_some_and(crate::scrolling::Placed::has_settled) + && !crate::window::live_resize_in_progress() + } + + fn adopt_actual_widths( + workspace: &mut Workspace, + around_window: i32, + viewport_width: i32, + ) -> bool { + workspace.adopt_actual_widths(around_window, viewport_width) + } + + fn scrolling_layouts( + workspace: &mut Workspace, + adjusted_work_area: &Rect, + container_padding: i32, + ) -> (Vec, Vec) { + let mut hidden = vec![]; + let monitors: Vec = backend() + .monitors() + .map(|monitors| monitors.iter().map(|monitor| monitor.size).collect()) + .unwrap_or_default(); + let others = crate::scrolling::other_monitors(&workspace.globals.work_area, &monitors); + + let layouts = workspace + .layout_scrolling(adjusted_work_area, container_padding) + .into_iter() + .map(|placement| { + let (rect, hide) = crate::scrolling::rest( + placement.rect, + placement.visibility, + adjusted_work_area, + &others, + ); + hidden.push(hide); + rect + }) + .collect(); + + (layouts, hidden) + } + + fn adjust_layout( + _container: &mut Container, + layout: &mut Rect, + placement: &komorebi_core::Placement, + ) { + let adjusted_work_area = placement.adjusted_work_area; + + // The scrolling layout is a strip that is meant to run past the edges of + // the work area, and says itself where each window rests when it is out + // of view (KWin does not constrain where a window is put). Everything + // else is clamped to the work area so it cannot bleed onto an adjacent + // monitor. + if !placement.is_scrolling { + // horizontal + if layout.left < adjusted_work_area.left { + layout.right -= adjusted_work_area.left - layout.left; + layout.left = adjusted_work_area.left; + } + let max_right_edge = adjusted_work_area.left + adjusted_work_area.right; + let current_right_edge = layout.left + layout.right; + if current_right_edge > max_right_edge { + layout.right = max_right_edge - layout.left; + } + + // vertical + if layout.top < adjusted_work_area.top { + layout.bottom -= adjusted_work_area.top - layout.top; + layout.top = adjusted_work_area.top; + } + let max_bottom_edge = adjusted_work_area.top + adjusted_work_area.bottom; + let current_bottom_edge = layout.top + layout.bottom; + if current_bottom_edge > max_bottom_edge { + layout.bottom = max_bottom_edge - layout.top; + } + } + + layout.add_padding(placement.border_offset); + layout.add_padding(placement.border_width); + } + + fn place_container( + container: &mut Container, + layout: &Rect, + hidden: bool, + placement: &komorebi_core::Placement, + ) -> eyre::Result<()> { + if hidden { + // it is seen on another monitor wherever it rests here + for window in container.windows() { + window.hide(); + } + return Ok(()); + } + + // a window that was hidden for resting past an edge with another + // monitor next to it is shown before it is put where the strip says + let front = container.focused_window().map(|window| window.id); + let restore = placement.is_scrolling + && front.is_some_and(|front| { + crate::scrolling::should_restore_when_placed( + front, + Some(front), + &HIDDEN_WINDOWS.lock(), + ) + }); + if restore && let Some(window) = container.focused_window() { + window.restore(); + } + + for window in container.windows_mut() { + let current_rect = window.rect().unwrap_or_default(); + let current_percentage = placement + .work_area + .percentage_within_horizontal_bounds(¤t_rect); + let proposed_percentage = placement + .work_area + .percentage_within_horizontal_bounds(layout); + + // the strip puts a window where it goes, however far + let percentage_override = !placement.is_scrolling + && proposed_percentage == 0.0 + && current_percentage > 0.1 + && current_percentage < 100.0 + && placement.resize_dimensions_is_empty; + + if percentage_override { + window.center(&placement.work_area, false)?; + } else if let Err(error) = window.set_position(layout) { + tracing::warn!("failed to set window position: {error}") + } + } + + Ok(()) + } + + fn end_update( + workspace: &mut Workspace, + _pass: usize, + _around_window: i32, + _viewport_width: i32, + ) -> eyre::Result { + if workspace.is_scrolling() { + workspace.state.scrolling_placed = Some(crate::scrolling::Placed::new( + workspace + .containers() + .iter() + .zip(workspace.latest_layout.iter()) + .map(|(container, layout)| (container.id.clone(), layout.right)), + )); + } + + Ok(komorebi_core::Pass::Done) + } } /// `komorebi_layouts::Rect::percentage_within_horizontal_bounds`, which that crate compiles only @@ -819,307 +1003,7 @@ impl WorkspaceExt for Workspace { } fn update(&mut self) -> eyre::Result<()> { - // make sure we are never holding on to empty containers - self.prune_duplicate_windows()?; - let focused_container_idx = self.focused_container_idx(); - self.containers_mut() - .retain(|c| c.is_preselect() || !c.windows().is_empty()); - - // make sure we are never focused on a no longer existent final empty container - if focused_container_idx >= self.containers().len() { - self.focus_container(focused_container_idx.saturating_sub(1)); - } - - let container_padding = self - .container_padding - .or(self.globals.container_padding) - .unwrap_or_default(); - let workspace_padding = self - .workspace_padding - .or(self.globals.workspace_padding) - .unwrap_or_default(); - let border_width = self.globals.border_width; - let border_offset = self.globals.border_offset; - let work_area = self.globals.work_area; - let mut rules_work_area_offset = None; - - if !self.work_area_offset_rules.is_empty() { - let count = if self.monocle_container.is_some() { - 1 - } else { - self.containers().len() - }; - - for (threshold, work_area_offset_rule) in &self.work_area_offset_rules { - if count >= *threshold { - rules_work_area_offset = Some(*work_area_offset_rule); - } - } - }; - - let work_area_offset = rules_work_area_offset - .or(self.work_area_offset) - .or(self.globals.work_area_offset); - let window_based_work_area_offset = self.globals.window_based_work_area_offset; - let window_based_work_area_offset_limit = self.globals.window_based_work_area_offset_limit; - - let mut adjusted_work_area = work_area_offset.map_or_else( - || work_area, - |offset| { - let mut with_offset = work_area; - with_offset.left += offset.left; - with_offset.top += offset.top; - with_offset.right -= offset.right; - with_offset.bottom -= offset.bottom; - - with_offset - }, - ); - - if (self.containers().len() <= window_based_work_area_offset_limit as usize - || self.monocle_container.is_some() && window_based_work_area_offset_limit > 0) - && self.apply_window_based_work_area_offset - { - adjusted_work_area = window_based_work_area_offset.map_or_else( - || adjusted_work_area, - |offset| { - let mut with_offset = adjusted_work_area; - with_offset.left += offset.left; - with_offset.top += offset.top; - with_offset.right -= offset.right; - with_offset.bottom -= offset.bottom; - - with_offset - }, - ); - } - - adjusted_work_area.add_padding(workspace_padding); - - self.enforce_resize_constraints(); - - if !self.layout_rules.is_empty() { - let mut updated_layout = None; - - for (threshold, layout) in &self.layout_rules { - if self.containers().len() >= *threshold { - updated_layout = Option::from(layout.clone()); - } - } - - if let Some(updated_layout) = updated_layout { - self.layout = updated_layout; - } - } - - if let Some(window_container_behaviour_rules) = &self.window_container_behaviour_rules { - let mut updated_behaviour = None; - for (threshold, behaviour) in window_container_behaviour_rules { - if self.containers().len() >= *threshold { - updated_behaviour = Option::from(*behaviour); - } - } - - self.window_container_behaviour = updated_behaviour; - } - - if self.tile { - // the backend batches the commands this produces and sends them together - let result = (|| -> eyre::Result<()> { - if let Some(container) = self.monocle_container.as_mut() { - if let Some(window) = container.focused_window_mut() { - adjusted_work_area.add_padding(container_padding); - adjusted_work_area.add_padding(border_offset); - adjusted_work_area.add_padding(border_width); - window.set_position(&adjusted_work_area)?; - }; - } else if let Some(window) = self.maximized_window { - // the compositor's own maximize, which is the work area and not the padded one - window.maximize()?; - } else if !self.containers().is_empty() { - let is_scrolling = self.is_scrolling(); - let around_window = container_padding + border_offset + border_width; - - // a window that would not get as narrow as its column was learned of once the - // windows have had time to draw at the sizes that they were sent, and not - // while one is being dragged, whose neighbours are on their way - if is_scrolling - && self - .state - .scrolling_placed - .as_ref() - .is_some_and(crate::scrolling::Placed::has_settled) - && !crate::window::live_resize_in_progress() - { - self.adopt_actual_widths(around_window, adjusted_work_area.right); - } - - let effective_layout_options = self.effective_layout_options(); - - tracing::debug!( - "Workspace '{}' update() - effective_layout_options: {:?} (base: {:?}, rules: {})", - self.name.as_deref().unwrap_or("unnamed"), - effective_layout_options, - self.layout_options, - self.layout_options_rules.len(), - ); - // the containers that rest where another monitor is seen from, which are hidden - let mut hidden = vec![]; - let mut layouts = if is_scrolling { - let monitors: Vec = backend() - .monitors() - .map(|monitors| monitors.iter().map(|monitor| monitor.size).collect()) - .unwrap_or_default(); - let others = - crate::scrolling::other_monitors(&self.globals.work_area, &monitors); - - self.layout_scrolling(&adjusted_work_area, container_padding) - .into_iter() - .map(|placement| { - let (rect, hide) = crate::scrolling::rest( - placement.rect, - placement.visibility, - &adjusted_work_area, - &others, - ); - hidden.push(hide); - rect - }) - .collect() - } else { - self.layout.as_boxed_arrangement().calculate( - &adjusted_work_area, - NonZeroUsize::new(self.containers().len()).ok_or_eyre( - "there must be at least one container to calculate a workspace layout", - )?, - Some(container_padding), - self.layout_flip, - &self.resize_dimensions, - self.focused_container_idx(), - effective_layout_options, - &self.latest_layout, - ) - }; - - let resize_dimensions_is_empty = self.resize_dimensions.is_empty(); - - let containers = self.containers_mut(); - - for (i, container) in containers.iter_mut().enumerate() { - if let Some(layout) = layouts.get_mut(i) { - // The scrolling layout is a strip that is meant to run past the edges of - // the work area, and says itself where each window rests when it is out - // of view (KWin does not constrain where a window is put). Everything - // else is clamped to the work area so it cannot bleed onto an adjacent - // monitor. - if !is_scrolling { - // horizontal - if layout.left < adjusted_work_area.left { - layout.right -= adjusted_work_area.left - layout.left; - layout.left = adjusted_work_area.left; - } - let max_right_edge = - adjusted_work_area.left + adjusted_work_area.right; - let current_right_edge = layout.left + layout.right; - if current_right_edge > max_right_edge { - layout.right = max_right_edge - layout.left; - } - - // vertical - if layout.top < adjusted_work_area.top { - layout.bottom -= adjusted_work_area.top - layout.top; - layout.top = adjusted_work_area.top; - } - let max_bottom_edge = - adjusted_work_area.top + adjusted_work_area.bottom; - let current_bottom_edge = layout.top + layout.bottom; - if current_bottom_edge > max_bottom_edge { - layout.bottom = max_bottom_edge - layout.top; - } - } - - layout.add_padding(border_offset); - layout.add_padding(border_width); - - if hidden.get(i).copied().unwrap_or_default() { - // it is seen on another monitor wherever it rests here - for window in container.windows() { - window.hide(); - } - continue; - } - - // a window that was hidden for resting past an edge with another - // monitor next to it is shown before it is put where the strip says - let front = container.focused_window().map(|window| window.id); - let restore = is_scrolling - && front.is_some_and(|front| { - crate::scrolling::should_restore_when_placed( - front, - Some(front), - &HIDDEN_WINDOWS.lock(), - ) - }); - if restore && let Some(window) = container.focused_window() { - window.restore(); - } - - for window in container.windows_mut() { - let current_rect = window.rect().unwrap_or_default(); - let current_percentage = - work_area.percentage_within_horizontal_bounds(¤t_rect); - let proposed_percentage = - work_area.percentage_within_horizontal_bounds(layout); - - // the strip puts a window where it goes, however far - let percentage_override = !is_scrolling - && proposed_percentage == 0.0 - && current_percentage > 0.1 - && current_percentage < 100.0 - && resize_dimensions_is_empty; - - if percentage_override { - window.center(&work_area, false)?; - } else if let Err(error) = window.set_position(layout) { - tracing::warn!("failed to set window position: {error}") - } - } - } - } - - self.latest_layout = layouts; - - if is_scrolling { - self.state.scrolling_placed = Some(crate::scrolling::Placed::new( - self.containers() - .iter() - .zip(self.latest_layout.iter()) - .map(|(container, layout)| (container.id.clone(), layout.right)), - )); - } - } - Ok(()) - })(); - - result?; - } - - // Always make sure that the length of the resize dimensions vec is the same as the - // number of layouts / containers. This should never actually truncate as the remove_window - // function takes care of cleaning up resize dimensions when destroying empty containers - let container_count = self.containers().len(); - - // since monocle is a toggle, we never want to truncate the resize dimensions since it will - // almost always be toggled off and the container will be reintegrated into layout - // - // without this check, if there are exactly two containers, when one is toggled to monocle - // the resize dimensions will be truncated to len == 1, and when it is reintegrated, if it - // had a resize adjustment before, that will have been lost - if self.monocle_container.is_none() { - self.resize_dimensions.resize(container_count, None); - } - - Ok(()) + self.update_shared() } fn visible_window_details(&self) -> Vec { diff --git a/komorebi-for-kde/komorebi/tests/version.rs b/komorebi-for-kde/komorebi/tests/version.rs deleted file mode 100644 index e5d7e05e..00000000 --- a/komorebi-for-kde/komorebi/tests/version.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! `komorebi --version` reports the workspace version. - -use std::process::Command; - -#[test] -fn reports_the_package_version() { - let output = Command::new(env!("CARGO_BIN_EXE_komorebi")) - .arg("--version") - .output() - .expect("komorebi runs"); - - assert!(output.status.success()); - - let stdout = String::from_utf8(output.stdout).expect("utf-8 output"); - let expected = format!("komorebi {}", env!("CARGO_PKG_VERSION")); - - assert_eq!(stdout.lines().next(), Some(expected.as_str())); -} diff --git a/komorebi-for-mac/deny.toml b/komorebi-for-mac/deny.toml index 8377debc..ff68c08a 100644 --- a/komorebi-for-mac/deny.toml +++ b/komorebi-for-mac/deny.toml @@ -43,6 +43,11 @@ allow = [ ] confidence-threshold = 0.8 +[[licenses.clarify]] +crate = "komorebi" +expression = "LicenseRef-Komorebi-2.0" +license-files = [] + [[licenses.clarify]] crate = "komorebi-macos" expression = "LicenseRef-Komorebi-2.0" diff --git a/komorebi-for-mac/flake.nix b/komorebi-for-mac/flake.nix index 92054bcc..7dbe4ab2 100644 --- a/komorebi-for-mac/flake.nix +++ b/komorebi-for-mac/flake.nix @@ -93,8 +93,18 @@ "komorebi-bar/src/main.rs" ] || pkgs.lib.hasPrefix "komorebi-bar/src/macos" relative; + + # the one komorebi binary package: its manifest, main.rs and tests + komorebiDaemon = + builtins.elem relative [ + "komorebi-daemon" + "komorebi-daemon/Cargo.toml" + "komorebi-daemon/src" + "komorebi-daemon/src/main.rs" + "komorebi-daemon/tests" + ]; in - ((rootCrate || komorebic || komorebiClient || komorebiBar) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree) + ((rootCrate || komorebic || komorebiClient || komorebiBar || komorebiDaemon) && !(pkgs.lib.hasSuffix "/Cargo.lock" path) || relative == "Cargo.toml" || relative == "Cargo.lock" || inTree) && ( (craneLib.filterCargoSources path type) || (pkgs.lib.hasInfix "/docs/" path) @@ -113,10 +123,11 @@ pkgs.lib.hasPrefix "${platformDir}/" member || member == "komorebic" || member == "komorebi-client" + || member == "komorebi-daemon" || member == "komorebi-bar" || builtins.any (crate: member == crate || pkgs.lib.hasPrefix "${crate}/" member) rootCrates; }; - packages = "-p komorebi-macos -p komorebic -p komorebi-client -p komorebi-bar"; + packages = "-p komorebi -p komorebi-macos -p komorebic -p komorebi-client -p komorebi-bar"; workspaceArgs = { pname = "komorebi-workspace"; inherit version; diff --git a/komorebi-for-mac/komorebi/Cargo.toml b/komorebi-for-mac/komorebi/Cargo.toml index 0e984dc8..bfb1ca57 100644 --- a/komorebi-for-mac/komorebi/Cargo.toml +++ b/komorebi-for-mac/komorebi/Cargo.toml @@ -138,7 +138,3 @@ schemars = ["dep:schemars", "komorebi-collections/schemars", "komorebi-core/sche [lib] name = "komorebi" - -[[bin]] -name = "komorebi" -path = "src/main.rs" diff --git a/komorebi-for-mac/komorebi/src/main.rs b/komorebi-for-mac/komorebi/src/daemon.rs similarity index 92% rename from komorebi-for-mac/komorebi/src/main.rs rename to komorebi-for-mac/komorebi/src/daemon.rs index 5b5ad65c..fc1505b5 100644 --- a/komorebi-for-mac/komorebi/src/main.rs +++ b/komorebi-for-mac/komorebi/src/daemon.rs @@ -4,26 +4,26 @@ use clap::Parser; use clap::ValueEnum; use color_eyre::eyre; use color_eyre::eyre::OptionExt; -use komorebi::CoreFoundationRunLoop; -use komorebi::DATA_DIR; -use komorebi::HOME_DIR; -use komorebi::border_manager; -use komorebi::core::pathext::replace_env_in_path; -use komorebi::display_reconfiguration_listener::DisplayReconfigurationListener; -use komorebi::input_event_listener; -use komorebi::input_event_listener::InputEventListener; -use komorebi::monitor_reconciliator; -use komorebi::notification_center_listener::NotificationCenterListener; -use komorebi::process_command::listen_for_commands; -use komorebi::process_event::listen_for_events; -use komorebi::reaper; -use komorebi::settle; -use komorebi::static_config::StaticConfig; -use komorebi::static_config::StaticConfigExt; -use komorebi::theme_manager; -use komorebi::window_manager::WindowManager; -use komorebi::window_manager_event_listener; -use komorebi::workspace_reconciliator; +use crate::CoreFoundationRunLoop; +use crate::DATA_DIR; +use crate::HOME_DIR; +use crate::border_manager; +use crate::core::pathext::replace_env_in_path; +use crate::display_reconfiguration_listener::DisplayReconfigurationListener; +use crate::input_event_listener; +use crate::input_event_listener::InputEventListener; +use crate::monitor_reconciliator; +use crate::notification_center_listener::NotificationCenterListener; +use crate::process_command::listen_for_commands; +use crate::process_event::listen_for_events; +use crate::reaper; +use crate::settle; +use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; +use crate::theme_manager; +use crate::window_manager::WindowManager; +use crate::window_manager_event_listener; +use crate::workspace_reconciliator; use objc2::MainThreadMarker; use objc2::rc::autoreleasepool; use objc2_app_kit::NSApplication; @@ -200,7 +200,7 @@ struct Opts { log_level: LogLevel, } -fn main() -> eyre::Result<()> { +pub fn run() -> eyre::Result<()> { let opts: Opts = Opts::parse(); let (_guard, _color_guard) = setup(opts.log_level)?; @@ -350,11 +350,11 @@ fn main() -> eyre::Result<()> { } // nothing may move a window once they have all been put back where they were found - komorebi::animation::animator::shutdown(); + crate::animation::animator::shutdown(); wm.lock().restore_all_windows(false)?; - let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock(); + let sockets = crate::SUBSCRIPTION_SOCKETS.lock(); for path in (*sockets).values() { if let Ok(stream) = UnixStream::connect(path) { stream.shutdown(Shutdown::Both)?; diff --git a/komorebi-for-mac/komorebi/src/lib.rs b/komorebi-for-mac/komorebi/src/lib.rs index d69b65ea..df046e82 100644 --- a/komorebi-for-mac/komorebi/src/lib.rs +++ b/komorebi-for-mac/komorebi/src/lib.rs @@ -43,6 +43,7 @@ extern crate komorebi_collections; pub use komorebi_collections::ring; +pub mod daemon; pub mod accessibility; pub mod animation; pub mod app_kit_notification_constants; diff --git a/komorebi/Cargo.toml b/komorebi/Cargo.toml index d2bde6ff..0db869c1 100644 --- a/komorebi/Cargo.toml +++ b/komorebi/Cargo.toml @@ -83,7 +83,3 @@ schemars = [ [lib] name = "komorebi" - -[[bin]] -name = "komorebi" -path = "src/main.rs" diff --git a/komorebi/src/border_manager/mod.rs b/komorebi/src/border_manager/mod.rs index b50abe3e..e06a3a6b 100644 --- a/komorebi/src/border_manager/mod.rs +++ b/komorebi/src/border_manager/mod.rs @@ -375,8 +375,11 @@ fn watch_steps() { && warned != Some(since) { tracing::warn!( - "border manager: stuck for {} ms in `{name}`", - since.elapsed().as_millis() + "border manager: stuck for {} ms in `{name}`{}", + since.elapsed().as_millis(), + crate::lock_holder::describe() + .map(|holder| format!(" (window manager lock held by {holder})")) + .unwrap_or_default() ); warned = Some(since); } @@ -419,6 +422,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result let _waiting = Waiting; // Check the wm state every time we receive a notification let state = wm.lock(); + let _held = crate::lock_holder::held("border manager"); let is_paused = state.is_paused; let focused_monitor_idx = state.focused_monitor_idx(); let focused_workspace_idx = diff --git a/komorebi/src/main.rs b/komorebi/src/daemon.rs similarity index 90% rename from komorebi/src/main.rs rename to komorebi/src/daemon.rs index 76d858ce..2cca1181 100644 --- a/komorebi/src/main.rs +++ b/komorebi/src/daemon.rs @@ -20,10 +20,10 @@ use clap::ValueEnum; use color_eyre::eyre; use color_eyre::eyre::bail; use crossbeam_utils::Backoff; -use komorebi::animation::ANIMATION_ENABLED_GLOBAL; -use komorebi::animation::ANIMATION_ENABLED_PER_ANIMATION; -use komorebi::animation::AnimationEngine; -use komorebi::replace_env_in_path; +use crate::animation::ANIMATION_ENABLED_GLOBAL; +use crate::animation::ANIMATION_ENABLED_PER_ANIMATION; +use crate::animation::AnimationEngine; +use crate::replace_env_in_path; use parking_lot::Mutex; #[cfg(feature = "deadlock_detection")] use parking_lot::deadlock; @@ -35,29 +35,29 @@ use tracing_subscriber::EnvFilter; use tracing_subscriber::layer::SubscriberExt; use uds_windows::UnixStream; -use komorebi::CUSTOM_FFM; -use komorebi::DATA_DIR; -use komorebi::HOME_DIR; -use komorebi::INITIAL_CONFIGURATION_LOADED; -use komorebi::SESSION_ID; -use komorebi::border_manager; -use komorebi::focus_manager; -use komorebi::load_configuration; -use komorebi::monitor_reconciliator; -use komorebi::process_command::listen_for_commands; -use komorebi::process_command::listen_for_commands_tcp; -use komorebi::process_event::listen_for_events; -use komorebi::process_movement::listen_for_movements; -use komorebi::reaper; -use komorebi::stackbar_manager; -use komorebi::state::State; -use komorebi::static_config::StaticConfig; -use komorebi::static_config::StaticConfigExt; -use komorebi::theme_manager; -use komorebi::transparency_manager; -use komorebi::window_manager::WindowManager; -use komorebi::windows_api::WindowsApi; -use komorebi::winevent_listener; +use crate::CUSTOM_FFM; +use crate::DATA_DIR; +use crate::HOME_DIR; +use crate::INITIAL_CONFIGURATION_LOADED; +use crate::SESSION_ID; +use crate::border_manager; +use crate::focus_manager; +use crate::load_configuration; +use crate::monitor_reconciliator; +use crate::process_command::listen_for_commands; +use crate::process_command::listen_for_commands_tcp; +use crate::process_event::listen_for_events; +use crate::process_movement::listen_for_movements; +use crate::reaper; +use crate::stackbar_manager; +use crate::state::State; +use crate::static_config::StaticConfig; +use crate::static_config::StaticConfigExt; +use crate::theme_manager; +use crate::transparency_manager; +use crate::window_manager::WindowManager; +use crate::windows_api::WindowsApi; +use crate::winevent_listener; fn setup(log_level: LogLevel) -> eyre::Result<(WorkerGuard, WorkerGuard)> { if std::env::var("RUST_LIB_BACKTRACE").is_err() { @@ -172,7 +172,7 @@ enum LogLevel { } #[derive(Parser)] -#[clap(name = "komorebi", author, about, version = komorebi::build::CLAP_LONG_VERSION)] +#[clap(name = "komorebi", author, about, version = crate::build::CLAP_LONG_VERSION)] struct Opts { /// Allow the use of komorebi's custom focus-follows-mouse implementation #[clap(short, long = "ffm")] @@ -197,7 +197,7 @@ struct Opts { #[tracing::instrument] #[allow(clippy::cognitive_complexity)] -fn main() -> eyre::Result<()> { +pub fn run() -> eyre::Result<()> { let opts: Opts = Opts::parse(); CUSTOM_FFM.store(opts.focus_follows_mouse, Ordering::SeqCst); @@ -342,7 +342,7 @@ fn main() -> eyre::Result<()> { } listen_for_events(wm.clone()); - komorebi::live_resize::listen_for_steps(wm.clone()); + crate::live_resize::listen_for_steps(wm.clone()); if CUSTOM_FFM.load(Ordering::SeqCst) { listen_for_movements(wm.clone()); @@ -373,7 +373,7 @@ fn main() -> eyre::Result<()> { WindowsApi::disable_focus_follows_mouse()?; } - let sockets = komorebi::SUBSCRIPTION_SOCKETS.lock(); + let sockets = crate::SUBSCRIPTION_SOCKETS.lock(); for path in (*sockets).values() { if let Ok(stream) = UnixStream::connect(path) { stream.shutdown(Shutdown::Both)?; diff --git a/komorebi/src/lib.rs b/komorebi/src/lib.rs index 24dc4f33..981483a3 100644 --- a/komorebi/src/lib.rs +++ b/komorebi/src/lib.rs @@ -3,6 +3,7 @@ #[macro_use] extern crate komorebi_collections; +pub mod daemon; pub mod animation; pub mod border_manager; pub mod cloaked; @@ -14,6 +15,7 @@ pub mod focus_manager; pub mod live_resize; pub use komorebi_collections::Lockable; pub use komorebi_collections::lockable_sequence; +pub mod lock_holder; pub mod monitor; pub mod monitor_reconciliator; pub mod pan; @@ -388,7 +390,13 @@ pub fn notify_subscribers( &options, state_has_been_modified || is_override_event, &DATA_DIR, - |path| UnixStream::connect(path), + |path| { + let stream = UnixStream::connect(path)?; + // a subscriber that does not read must not hold up the writer, which has the + // window manager locked + stream.set_write_timeout(Some(std::time::Duration::from_secs(1)))?; + Ok(stream) + }, )?; let mut stale_pipes = vec![]; diff --git a/komorebi/src/lock_holder.rs b/komorebi/src/lock_holder.rs new file mode 100644 index 00000000..c43b66ee --- /dev/null +++ b/komorebi/src/lock_holder.rs @@ -0,0 +1,108 @@ +//! Who holds the window manager lock, and for how long. +//! +//! The window manager is one `Arc>` that every thread locks. When a hold +//! runs long, the other threads can only say that they are waiting ("could not acquire", "stuck +//! for"), not for whom. A place that locks it calls [`held`] right after it has the guard and +//! keeps the returned [`Held`] next to the guard: the holder is recorded in a slot of its own +//! (a mutex that is only ever held for the time of a copy, never while anything else is done), +//! a hold that lasts longer than [`SLOW`] is logged when it ends, and [`describe`] tells the +//! waiters who it is. + +use parking_lot::Mutex; +use std::borrow::Cow; +use std::thread::Thread; +use std::time::Duration; +use std::time::Instant; + +/// A hold longer than this is logged when it ends +pub const SLOW: Duration = Duration::from_millis(200); + +struct Holder { + what: Cow<'static, str>, + thread: Thread, + since: Instant, +} + +static HOLDER: Mutex> = Mutex::new(None); + +/// Records the calling thread as the holder of the window manager lock, until it is dropped +#[must_use = "the hold ends when this is dropped: keep it next to the lock guard"] +pub struct Held { + what: Cow<'static, str>, + thread: Thread, + since: Instant, +} + +/// Says who has just locked the window manager: `what` is the call site or the command +pub fn held(what: impl Into>) -> Held { + let what = what.into(); + let thread = std::thread::current(); + let since = Instant::now(); + + *HOLDER.lock() = Some(Holder { + what: what.clone(), + thread: thread.clone(), + since, + }); + + Held { + what, + thread, + since, + } +} + +impl Drop for Held { + fn drop(&mut self) { + let elapsed = self.since.elapsed(); + + // only clear the slot if it is still this hold's (another thread may have locked and + // recorded itself in the instant between this guard's release and this drop) + { + let mut slot = HOLDER.lock(); + if slot + .as_ref() + .is_some_and(|holder| holder.since == self.since) + { + *slot = None; + } + } + + if elapsed >= SLOW { + tracing::warn!( + "window manager lock held by {} (thread {}) for {} ms", + self.what, + self.thread.name().unwrap_or("unnamed"), + elapsed.as_millis() + ); + } + } +} + +/// Who holds the lock now and for how long so far, for the warnings of the threads that wait +pub fn describe() -> Option { + HOLDER.lock().as_ref().map(|holder| { + format!( + "{} (thread {}) for {} ms so far", + holder.what, + holder.thread.name().unwrap_or("unnamed"), + holder.since.elapsed().as_millis() + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_holder_is_described_while_held_and_not_after() { + let hold = held("a test"); + let described = describe().expect("a holder is recorded"); + assert!(described.starts_with("a test (thread "), "{described}"); + drop(hold); + + // another test may hold at the same time: only check that this one is gone + assert!(describe().is_none_or(|d| !d.starts_with("a test ("))); + } +} diff --git a/komorebi/src/monitor_reconciliator/mod.rs b/komorebi/src/monitor_reconciliator/mod.rs index f0a16e92..83c0d418 100644 --- a/komorebi/src/monitor_reconciliator/mod.rs +++ b/komorebi/src/monitor_reconciliator/mod.rs @@ -277,6 +277,7 @@ where // Keep reference to Arc for potential re-locking let wm_arc = Arc::clone(&wm); let mut wm = wm.lock(); + let _held = crate::lock_holder::held("monitor reconciliator"); let initial_state = State::from(wm.as_ref()); diff --git a/komorebi/src/process_command.rs b/komorebi/src/process_command.rs index 913fc10d..425d5728 100644 --- a/komorebi/src/process_command.rs +++ b/komorebi/src/process_command.rs @@ -20,6 +20,7 @@ use std::net::TcpStream; use std::num::NonZeroUsize; use std::str::FromStr; use std::sync::Arc; +use std::sync::atomic::AtomicI8; use std::sync::atomic::Ordering; use std::time::Duration; use uds_windows::UnixListener; @@ -85,7 +86,6 @@ use crate::notify_subscribers; use crate::stackbar_manager; use crate::stackbar_manager::STACKBAR_FONT_FAMILY; use crate::stackbar_manager::STACKBAR_FONT_SIZE; -use crate::state; use crate::state::GlobalState; use crate::state::State; use crate::static_config::StaticConfig; @@ -128,6 +128,10 @@ impl ConnectionPolicy for WindowsConnectionPolicy { } } + fn lock_holder(&self) -> Option { + crate::lock_holder::describe() + } + fn on_message(&self, message: &SocketMessage, stream: &UnixStream) { // the fingers of a gesture can be still for longer than a command is waited for, and // what they do next is told on this connection: it is closed when they have lifted @@ -137,9 +141,88 @@ impl ConnectionPolicy for WindowsConnectionPolicy { ) { let _ = stream.set_read_timeout(Some(Duration::from_secs(30))); } + + // looked for here, before the window manager is locked for the message: a process scan + // under the lock held every other thread for seconds (see `replace_configuration`) + if matches!(message, SocketMessage::ReplaceConfiguration(_)) { + BAR_RUNNING.store(i8::from(komorebi_bar_is_running()), Ordering::SeqCst); + } } } +/// Whether komorebi-bar.exe was running when a `ReplaceConfiguration` was read, for the handler +/// of that message to take: -1 when it was not looked for +static BAR_RUNNING: AtomicI8 = AtomicI8::new(-1); + +/// Stops the running komorebi-bar processes and starts them again from the configuration. Runs on +/// a thread of its own: PowerShell takes seconds, which must not be spent with the window manager +/// locked. +#[allow(clippy::ptr_arg)] // StaticConfig::read takes a &PathBuf +fn restart_bars(config: &std::path::PathBuf) -> eyre::Result<()> { + let script = r" +Stop-Process -Name:komorebi-bar -ErrorAction SilentlyContinue + "; + match powershell_script::run(script) { + Ok(_) => { + println!("{script}"); + + // start new bar(s) + let mut config = StaticConfig::read(config)?; + if let Some(display_bar_configurations) = &mut config.bar_configurations { + for config_file_path in &mut *display_bar_configurations { + let script = r#"Start-Process "komorebi-bar" '"--config" "CONFIGFILE"' -WindowStyle hidden"# + .replace("CONFIGFILE", &config_file_path.to_string_lossy()); + + match powershell_script::run(&script) { + Ok(_) => { + println!("{script}"); + } + Err(error) => { + println!("Error: {error}"); + } + } + } + } else { + let script = r" +if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) +{ + Start-Process komorebi-bar -WindowStyle hidden +} + "; + match powershell_script::run(script) { + Ok(_) => { + println!("{script}"); + } + Err(error) => { + println!("Error: {error}"); + } + } + } + } + Err(error) => { + println!("Error: {error}"); + } + } + Ok(()) +} + +/// Whether a komorebi-bar.exe process is running. Only the names of the processes are read: +/// `System::new_all` also opens the performance counters and reads the command line, the +/// environment and the owner of every process, which is the slow part. +fn komorebi_bar_is_running() -> bool { + let mut system = sysinfo::System::new(); + system.refresh_processes_specifics( + sysinfo::ProcessesToUpdate::All, + true, + sysinfo::ProcessRefreshKind::nothing(), + ); + + system + .processes_by_name("komorebi-bar.exe".as_ref()) + .next() + .is_some() +} + /// What the generic command listener needs of the window manager impl CommandTarget for WindowManager { type Listener = UnixListener; @@ -221,6 +304,8 @@ impl WindowManager { message: SocketMessage, mut reply: impl std::io::Write, ) -> eyre::Result<()> { + let _held = crate::lock_holder::held(format!("command {message}")); + let command_started = std::time::Instant::now(); if let Some(virtual_desktop_id) = &self.virtual_desktop_id && let Some(id) = current_virtual_desktop() && id != *virtual_desktop_id @@ -515,10 +600,8 @@ impl WindowManager { } SocketMessage::SessionFloatRules => { let session_floating_applications = SESSION_FLOATING_APPLICATIONS.lock(); - let rules = match serde_json::to_string_pretty(&*session_floating_applications) { - Ok(rules) => rules, - Err(error) => error.to_string(), - }; + let rules = serde_json::to_string_pretty(&*session_floating_applications) + .unwrap_or_else(|error| error.to_string()); reply.write_all(rules.as_bytes())?; } @@ -953,7 +1036,7 @@ impl WindowManager { self.set_workspace_name(monitor_idx, workspace_idx, name.to_string())?; } SocketMessage::State => { - let state = match serde_json::to_string_pretty(&state::State::from(&*self)) { + let state = match serde_json::to_string_pretty(&State::from(&*self)) { Ok(state) => state, Err(error) => error.to_string(), }; @@ -1458,7 +1541,9 @@ impl WindowManager { }; // Update list of known_hwnds and their monitor/workspace index pair + let after_command = std::time::Instant::now(); self.update_known_hwnds(); + let after_hwnds = std::time::Instant::now(); notify_subscribers( Notification { @@ -1467,6 +1552,12 @@ impl WindowManager { }, initial_state.has_been_modified(self.as_ref()), )?; + tracing::debug!( + "processed `{message}`: command {} ms, known hwnds {} ms, notify subscribers {} ms", + after_command.duration_since(command_started).as_millis(), + after_hwnds.duration_since(after_command).as_millis(), + after_hwnds.elapsed().as_millis() + ); if force_update_borders { border_manager::send_force_update(); @@ -1572,6 +1663,15 @@ impl WindowManager { pub fn replace_configuration(&mut self, config: &std::path::PathBuf) -> eyre::Result { let mut force_update_borders = false; + let mut last = std::time::Instant::now(); + let mut lap = |step: &str| { + let now = std::time::Instant::now(); + tracing::info!( + "replace-configuration: {step} took {} ms", + now.duration_since(last).as_millis() + ); + last = now; + }; // Check that this is a valid static config file first if StaticConfig::read(config).is_ok() { // Clear workspace rules; these will need to be replaced @@ -1580,6 +1680,7 @@ impl WindowManager { self.is_paused = true; // Bring all windows to the foreground self.restore_all_windows(false)?; + lap("restore all windows"); // Create a new wm from the config path let mut wm = StaticConfig::preload( @@ -1587,75 +1688,42 @@ impl WindowManager { winevent_listener::event_rx(), self.command_listener.try_clone().ok(), )?; + lap("preload"); // Initialize the new wm wm.init()?; + lap("init"); wm.restore_all_windows(true)?; + lap("restore all windows of the new wm"); // This is equivalent to StaticConfig::postload for this use case StaticConfig::reload(config, &mut wm)?; + lap("reload"); // Set self to the new wm instance *self = wm; + lap("swap"); // check if there are any bars - let mut system = sysinfo::System::new_all(); - system.refresh_processes(sysinfo::ProcessesToUpdate::All, true); - - let has_bar = system - .processes_by_name("komorebi-bar.exe".as_ref()) - .next() - .is_some(); + let has_bar = match BAR_RUNNING.swap(-1, Ordering::SeqCst) { + -1 => komorebi_bar_is_running(), + running => running == 1, + }; + lap("process scan for komorebi-bar"); // stop bar(s) if has_bar { - let script = r" -Stop-Process -Name:komorebi-bar -ErrorAction SilentlyContinue - "; - match powershell_script::run(script) { - Ok(_) => { - println!("{script}"); - - // start new bar(s) - let mut config = StaticConfig::read(config)?; - if let Some(display_bar_configurations) = &mut config.bar_configurations { - for config_file_path in &mut *display_bar_configurations { - let script = r#"Start-Process "komorebi-bar" '"--config" "CONFIGFILE"' -WindowStyle hidden"# - .replace("CONFIGFILE", &config_file_path.to_string_lossy()); - - match powershell_script::run(&script) { - Ok(_) => { - println!("{script}"); - } - Err(error) => { - println!("Error: {error}"); - } - } - } - } else { - let script = r" -if (!(Get-Process komorebi-bar -ErrorAction SilentlyContinue)) -{ - Start-Process komorebi-bar -WindowStyle hidden -} - "; - match powershell_script::run(script) { - Ok(_) => { - println!("{script}"); - } - Err(error) => { - println!("Error: {error}"); - } - } - } - } - Err(error) => { + // PowerShell takes seconds: not with the window manager locked + let config = config.clone(); + std::thread::spawn(move || { + if let Err(error) = restart_bars(&config) { println!("Error: {error}"); } - } + }); } + lap("bar restart"); force_update_borders = true; } Ok(force_update_borders) diff --git a/komorebi/src/process_event.rs b/komorebi/src/process_event.rs index 3006a1c2..43bb0ae5 100644 --- a/komorebi/src/process_event.rs +++ b/komorebi/src/process_event.rs @@ -124,6 +124,7 @@ pub fn listen_for_events(wm: Arc>) { loop { if let Ok(event) = receiver.recv() { let mut guard = wm.lock(); + let _held = crate::lock_holder::held("process_event"); match guard.process_event(event) { Ok(()) => {} Err(error) => { diff --git a/komorebi/src/reaper.rs b/komorebi/src/reaper.rs index 00077fbc..c2848733 100644 --- a/komorebi/src/reaper.rs +++ b/komorebi/src/reaper.rs @@ -78,6 +78,7 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> for notification in receiver { let orphan_hwnds = notification.0; let mut wm = wm.lock(); + let _held = crate::lock_holder::held("reaper"); let mut update_borders = false; @@ -133,14 +134,7 @@ fn handle_notifications(wm: Arc>) -> color_eyre::Result<()> } // Save to file - let hwnd_json = DATA_DIR.join("komorebi.hwnd.json"); - let file = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(hwnd_json)?; - - serde_json::to_writer_pretty(&file, &wm.known_hwnds.keys().collect::>())?; + save_known_hwnds(wm.known_hwnds.keys().copied().collect()); } Ok(()) @@ -212,3 +206,49 @@ fn find_orphans() -> color_eyre::Result<()> { } } } + +static PENDING_HWNDS: Mutex>> = Mutex::new(None); +static PENDING_HWNDS_CHANGED: parking_lot::Condvar = parking_lot::Condvar::new(); +static HWNDS_WRITER: std::sync::Once = std::sync::Once::new(); + +/// Saves the list of known handles to `komorebi.hwnd.json`, from a thread of its own: writing the +/// file with the window manager locked made every other thread wait for the disk. Only the latest +/// list is written when several arrive before the writer is done, as the file only ever says what +/// is known now. +pub fn save_known_hwnds(hwnds: Vec) { + *PENDING_HWNDS.lock() = Some(hwnds); + HWNDS_WRITER.call_once(|| { + std::thread::spawn(|| { + loop { + let hwnds = { + let mut pending = PENDING_HWNDS.lock(); + while pending.is_none() { + PENDING_HWNDS_CHANGED.wait(&mut pending); + } + pending.take().unwrap_or_default() + }; + + let hwnd_json = DATA_DIR.join("komorebi.hwnd.json"); + match OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(hwnd_json) + { + Ok(file) => { + if let Err(error) = serde_json::to_writer_pretty(&file, &hwnds) { + tracing::error!( + "Failed to save list of known_hwnds on file: {}", + error + ); + } + } + Err(error) => { + tracing::error!("Failed to save list of known_hwnds on file: {}", error); + } + } + } + }); + }); + PENDING_HWNDS_CHANGED.notify_one(); +} diff --git a/komorebi/src/stackbar_manager/mod.rs b/komorebi/src/stackbar_manager/mod.rs index edc8aa82..34318339 100644 --- a/komorebi/src/stackbar_manager/mod.rs +++ b/komorebi/src/stackbar_manager/mod.rs @@ -96,6 +96,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // Check the wm state every time we receive a notification let mut state = wm.lock(); + let _held = crate::lock_holder::held("stackbar manager"); // If stackbars are disabled if matches!(STACKBAR_MODE.load(), StackbarMode::Never) diff --git a/komorebi/src/transparency_manager.rs b/komorebi/src/transparency_manager.rs index 1194a9e8..8547b84e 100644 --- a/komorebi/src/transparency_manager.rs +++ b/komorebi/src/transparency_manager.rs @@ -85,6 +85,7 @@ pub fn handle_notifications(wm: Arc>) -> color_eyre::Result // Check the wm state every time we receive a notification let state = wm.lock(); + let _held = crate::lock_holder::held("transparency manager"); let focused_monitor_idx = state.focused_monitor_idx(); diff --git a/komorebi/src/window_manager.rs b/komorebi/src/window_manager.rs index ab53d108..51315a5d 100644 --- a/komorebi/src/window_manager.rs +++ b/komorebi/src/window_manager.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::env::temp_dir; -use std::fs::OpenOptions; use std::io::ErrorKind; use std::net::Shutdown; use std::num::NonZeroUsize; @@ -16,7 +15,6 @@ use std::sync::atomic::Ordering; use color_eyre::eyre; use color_eyre::eyre::OptionExt; -use color_eyre::eyre::bail; use crossbeam_channel::Receiver; use hotwatch::EventKind; use hotwatch::Hotwatch; @@ -58,6 +56,7 @@ use komorebi_core::ContainerWindow; use crate::CrossBoundaryBehaviour; use crate::DATA_DIR; use crate::HOME_DIR; +use crate::Lockable; use crate::NO_TITLEBAR; use crate::REGEX_IDENTIFIERS; use crate::SUBSCRIPTION_SOCKETS; @@ -1560,7 +1559,7 @@ impl WindowManager { let workspace = self.focused_workspace()?; let focused_hwnd = WindowsApi::foreground_window()?; if !workspace.contains_managed_window(focused_hwnd) { - bail!("ignoring commands while active window is not managed by komorebi"); + eyre::bail!("ignoring commands while active window is not managed by komorebi"); } } @@ -1693,7 +1692,7 @@ impl WindowManager { ) -> eyre::Result<()> { // check the target before anything is taken out of the workspace it is in if monitor_idx >= self.monitors().len() { - bail!("there is no monitor at index {monitor_idx}"); + eyre::bail!("there is no monitor at index {monitor_idx}"); } self.handle_unmanaged_window_behaviour()?; @@ -1722,7 +1721,7 @@ impl WindowManager { .ok_or_eyre("there is no workspace")?; if workspace.maximized_window.is_some() { - bail!("cannot move native maximized window to another monitor or workspace"); + eyre::bail!("cannot move native maximized window to another monitor or workspace"); } let foreground_hwnd = WindowsApi::foreground_window()?; @@ -1801,7 +1800,7 @@ impl WindowManager { } } } else { - bail!("failed to find a window to move"); + eyre::bail!("failed to find a window to move"); } if should_load_workspace { @@ -1867,7 +1866,7 @@ impl WindowManager { // check the target before the workspace is taken out of its monitor if idx >= self.monitors().len() { - bail!("there is no monitor at index {idx}"); + eyre::bail!("there is no monitor at index {idx}"); } let mouse_follows_focus = self.mouse_follows_focus; @@ -2449,7 +2448,7 @@ impl WindowManager { // removing this messes up the monitor / container / window index somewhere // and results in the wrong window getting moved across the monitor boundary if workspace.is_focused_window_monocle_or_maximized()? { - bail!("ignoring command while active window is in monocle mode or maximized"); + eyre::bail!("ignoring command while active window is in monocle mode or maximized"); } tracing::info!("moving container"); @@ -2718,7 +2717,7 @@ impl WindowManager { let workspace = self.focused_workspace_mut()?; if workspace.is_focused_window_monocle_or_maximized()? { - bail!("ignoring command while active window is in monocle mode or maximized"); + eyre::bail!("ignoring command while active window is in monocle mode or maximized"); } tracing::info!("moving container"); @@ -2753,7 +2752,7 @@ impl WindowManager { .ok_or_eyre("there must be at least one window in a container")?; if len.get() == 1 { - bail!("there is only one window in this container"); + eyre::bail!("there is only one window in this container"); } let current_idx = container.focused_window_idx(); @@ -2789,7 +2788,7 @@ impl WindowManager { .ok_or_eyre("there must be at least one window in a container")?; if len.get() == 1 { - bail!("there is only one window in this container"); + eyre::bail!("there is only one window in this container"); } let current_idx = container.focused_window_idx(); @@ -2822,11 +2821,11 @@ impl WindowManager { .ok_or_eyre("there must be at least one window in a container")?; if len.get() == 1 && idx != 0 { - bail!("there is only one window in this container"); + eyre::bail!("there is only one window in this container"); } if container.windows().get(idx).is_none() { - bail!("there is no window in this container at index {idx}"); + eyre::bail!("there is no window in this container at index {idx}"); } container.focus_window(idx); @@ -3066,7 +3065,7 @@ impl WindowManager { tracing::info!("removing window"); if self.focused_container()?.windows().len() == 1 { - bail!("a container must have at least one window"); + eyre::bail!("a container must have at least one window"); } let workspace = self.focused_workspace_mut()?; @@ -3115,7 +3114,7 @@ impl WindowManager { let workspace = self.focused_workspace_mut()?; if let Some(container) = workspace.focused_container_mut() { // Toggle the locked flag - container.locked = !container.locked; + container.set_locked(!container.locked()); } Ok(()) } @@ -3239,7 +3238,7 @@ impl WindowManager { #[tracing::instrument(skip(self))] pub fn maximize_window(&mut self) -> eyre::Result<()> { - tracing::info!("maximizing windowj"); + tracing::info!("maximizing window"); let workspace = self.focused_workspace_mut()?; workspace.new_maximized_window() @@ -3523,7 +3522,7 @@ impl WindowManager { monitor_idx: usize, workspace_idx: usize, ) -> eyre::Result<()> { - tracing::info!("setting workspace layout"); + tracing::info!("clearing workspace layout rules"); let focused_monitor_idx = self.focused_monitor_idx(); @@ -3759,7 +3758,7 @@ impl WindowManager { if self.monitors().get(idx).is_some() { self.monitors.focus(idx); } else { - bail!("this is not a valid monitor index"); + eyre::bail!("this is not a valid monitor index"); } Ok(()) @@ -4008,25 +4007,8 @@ impl WindowManager { *reaper_cache = known_hwnds.clone(); } - // Save to file - let hwnd_json = DATA_DIR.join("komorebi.hwnd.json"); - match OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(hwnd_json) - { - Ok(file) => { - if let Err(error) = - serde_json::to_writer_pretty(&file, &known_hwnds.keys().collect::>()) - { - tracing::error!("Failed to save list of known_hwnds on file: {}", error); - } - } - Err(error) => { - tracing::error!("Failed to save list of known_hwnds on file: {}", error); - } - } + // Save to file, from the writer thread of the reaper + crate::reaper::save_known_hwnds(known_hwnds.keys().copied().collect()); // Store new hwnds self.known_hwnds = known_hwnds; diff --git a/komorebi/src/workspace.rs b/komorebi/src/workspace.rs index 5b84d5d7..fb3e6599 100644 --- a/komorebi/src/workspace.rs +++ b/komorebi/src/workspace.rs @@ -2,7 +2,6 @@ use crate::scrolling::WorkspaceScrolling; use std::collections::HashMap; use std::ffi::OsStr; use std::io::Write; -use std::num::NonZeroUsize; pub use komorebi_core::WorkspaceLayer; pub use komorebi_core::WorkspaceWindowLocation; @@ -80,6 +79,163 @@ impl komorebi_core::WorkspacePlatform for WindowsPlatform { }) } + fn begin_update(_workspace: &mut Workspace) -> eyre::Result { + if !INITIAL_CONFIGURATION_LOADED.load(Ordering::SeqCst) { + return Ok(komorebi_core::Flow::Skip); + } + + // every window that moves in this pass is animated together + Ok(komorebi_core::Flow::Run(Some(Box::new( + AnimationBatch::begin(), + )))) + } + + fn place_monocle(window: &mut Window, rect: &Rect) -> eyre::Result<()> { + window.set_position(rect, true) + } + + fn maximize_in_layout(window: &mut Window) -> eyre::Result<()> { + window.maximize(); + Ok(()) + } + + fn adopt_widths_before_layout(_workspace: &Workspace) -> bool { + // neighbours of a window that is dragged are not yet the size they are being + // made while it is followed: that is not what their columns are to be + crate::scrolling::animations_enabled() && !crate::live_resize::is_stepping() + } + + fn adopt_actual_widths( + workspace: &mut Workspace, + around_window: i32, + viewport_width: i32, + ) -> bool { + workspace.adopt_actual_widths(around_window, viewport_width) + } + + fn scrolling_layouts( + workspace: &mut Workspace, + adjusted_work_area: &Rect, + container_padding: i32, + ) -> (Vec, Vec) { + let mut hidden = vec![]; + let others = crate::scrolling::other_monitors( + &workspace.globals.work_area, + &WindowsApi::monitor_rects(), + ); + + let layouts = workspace + .layout_scrolling(adjusted_work_area, container_padding) + .into_iter() + .map(|placement| { + let (rect, hide) = crate::scrolling::rest( + placement.rect, + placement.visibility, + adjusted_work_area, + &others, + ); + hidden.push(hide); + rect + }) + .collect(); + + (layouts, hidden) + } + + fn adjust_layout( + container: &mut Container, + layout: &mut Rect, + placement: &komorebi_core::Placement, + ) { + layout.add_padding(placement.border_offset); + layout.add_padding(placement.border_width); + + if stackbar_manager::should_have_stackbar(container.windows().len()) { + let tab_height = STACKBAR_TAB_HEIGHT.load(Ordering::SeqCst); + let total_height = tab_height + placement.container_padding; + + layout.top += total_height; + layout.bottom -= total_height; + } + } + + fn place_container( + container: &mut Container, + layout: &Rect, + hidden: bool, + placement: &komorebi_core::Placement, + ) -> eyre::Result<()> { + let should_remove_titlebars = REMOVE_TITLEBARS.load(Ordering::SeqCst); + let no_titlebar = NO_TITLEBAR.lock().clone(); + let regex_identifiers = REGEX_IDENTIFIERS.lock().clone(); + + for window in container.windows() { + if container + .focused_window() + .is_some_and(|w| w.hwnd == window.hwnd) + { + let should_remove_titlebar_for_window = should_act( + &window.title().unwrap_or_default(), + &window.exe().unwrap_or_default(), + &window.class().unwrap_or_default(), + &window.path().unwrap_or_default(), + &no_titlebar, + ®ex_identifiers, + ) + .is_some(); + + if should_remove_titlebars && should_remove_titlebar_for_window { + window.remove_title_bar()?; + } else if should_remove_titlebar_for_window { + window.add_title_bar()?; + } + + // If a window has been unmaximized via toggle-maximize, this block + // will make sure that it is unmaximized via restore_window + if window.is_maximized() && !placement.managed_maximized_window { + let _ = backend().unminimize(WindowId::from_hwnd(window.hwnd)); + } + } + if hidden { + // it is seen on another monitor wherever it rests here + let _ = window.hide_window(()); + } else { + if crate::scrolling::should_restore_when_placed( + window.hwnd, + container.focused_window().map(|w| w.hwnd), + &HIDDEN_HWNDS.lock(), + ) { + let _ = window.restore_window(); + } + + backend().set_rect(WindowId::from_hwnd(window.hwnd), layout)?; + } + } + + Ok(()) + } + + fn end_update( + workspace: &mut Workspace, + pass: usize, + around_window: i32, + viewport_width: i32, + ) -> eyre::Result { + // with animations off every window that changed width has been asked what it + // is by now, so a window that refused is known, and everything after it is + // placed again with room for it. Once is enough: a layout is never made to + // chase the sizes that are read back this time round. + if pass == 0 + && workspace.is_scrolling() + && !crate::scrolling::animations_enabled() + && workspace.adopt_actual_widths(around_window, viewport_width) + { + return Ok(komorebi_core::Pass::Again); + } + + Ok(komorebi_core::Pass::Done) + } + fn scrolling_idx_for_direction( workspace: &Workspace, direction: OperationDirection, @@ -115,6 +271,7 @@ use crate::core::DefaultLayout; use crate::core::Layout; use crate::core::LayoutDefaultEntry; use crate::core::OperationDirection; +use crate::core::Rect; use crate::core::WindowKind; use crate::should_act; use crate::should_act_window; @@ -478,284 +635,7 @@ impl WorkspaceExt for Workspace { } fn update(&mut self) -> eyre::Result<()> { - if !INITIAL_CONFIGURATION_LOADED.load(Ordering::SeqCst) { - return Ok(()); - } - - // every window that moves in this pass is animated together - let _animations = AnimationBatch::begin(); - - // make sure we are never holding on to empty containers - self.containers_mut() - .retain(|c| c.is_preselect() || !c.windows().is_empty()); - - let container_padding = self - .container_padding - .or(self.globals.container_padding) - .unwrap_or_default(); - let workspace_padding = self - .workspace_padding - .or(self.globals.workspace_padding) - .unwrap_or_default(); - let border_width = self.globals.border_width; - let border_offset = self.globals.border_offset; - let work_area = self.globals.work_area; - let window_based_work_area_offset = self.globals.window_based_work_area_offset; - let window_based_work_area_offset_limit = self.globals.window_based_work_area_offset_limit; - let mut rules_work_area_offset = None; - - if !self.work_area_offset_rules.is_empty() { - let count = if self.monocle_container.is_some() { - 1 - } else { - self.containers().len() - }; - - for (threshold, work_area_offset_rule) in &self.work_area_offset_rules { - if count >= *threshold { - rules_work_area_offset = Some(*work_area_offset_rule); - } - } - }; - - let work_area_offset = rules_work_area_offset - .or(self.work_area_offset) - .or(self.globals.work_area_offset); - - let mut adjusted_work_area = work_area_offset.map_or_else( - || work_area, - |offset| { - let mut with_offset = work_area; - with_offset.left += offset.left; - with_offset.top += offset.top; - with_offset.right -= offset.right; - with_offset.bottom -= offset.bottom; - - with_offset - }, - ); - if (self.containers().len() <= window_based_work_area_offset_limit as usize - || self.monocle_container.is_some() && window_based_work_area_offset_limit > 0) - && self.apply_window_based_work_area_offset - { - adjusted_work_area = window_based_work_area_offset.map_or_else( - || adjusted_work_area, - |offset| { - let mut with_offset = adjusted_work_area; - with_offset.left += offset.left; - with_offset.top += offset.top; - with_offset.right -= offset.right; - with_offset.bottom -= offset.bottom; - - with_offset - }, - ); - } - - adjusted_work_area.add_padding(workspace_padding); - - self.enforce_resize_constraints(); - - if !self.layout_rules.is_empty() { - let mut updated_layout = None; - - for (threshold, layout) in &self.layout_rules { - if self.containers().len() >= *threshold { - updated_layout = Option::from(layout.clone()); - } - } - - if let Some(updated_layout) = updated_layout { - self.layout = updated_layout; - } - } - - if let Some(window_container_behaviour_rules) = &self.window_container_behaviour_rules { - let mut updated_behaviour = None; - for (threshold, behaviour) in window_container_behaviour_rules { - if self.containers().len() >= *threshold { - updated_behaviour = Option::from(*behaviour); - } - } - - self.window_container_behaviour = updated_behaviour; - } - - let managed_maximized_window = self.maximized_window.is_some(); - - if self.tile { - if let Some(container) = &mut self.monocle_container { - if let Some(window) = container.focused_window_mut() { - adjusted_work_area.add_padding(container_padding); - adjusted_work_area.add_padding(border_offset); - adjusted_work_area.add_padding(border_width); - window.set_position(&adjusted_work_area, true)?; - }; - } else if let Some(window) = &mut self.maximized_window { - window.maximize(); - } else if !self.containers().is_empty() { - // windows that were not what they were told to be since the last layout, which - // is something that animations only show once they are done - let around_window = container_padding + border_offset + border_width; - // neighbours of a window that is dragged are not yet the size they are being - // made while it is followed: that is not what their columns are to be - if self.is_scrolling() - && crate::scrolling::animations_enabled() - && !crate::live_resize::is_stepping() - { - self.adopt_actual_widths(around_window, adjusted_work_area.right); - } - - let mut pass = 0; - loop { - let effective_layout_options = self.effective_layout_options(); - - tracing::debug!( - "Workspace '{}' update() - effective_layout_options: {:?} (base: {:?}, rules: {})", - self.name.as_deref().unwrap_or("unnamed"), - effective_layout_options, - self.layout_options, - self.layout_options_rules.len(), - ); - let mut hidden = vec![]; - let mut layouts = if self.is_scrolling() { - let others = crate::scrolling::other_monitors( - &self.globals.work_area, - &WindowsApi::monitor_rects(), - ); - - self.layout_scrolling(&adjusted_work_area, container_padding) - .into_iter() - .map(|placement| { - let (rect, hide) = crate::scrolling::rest( - placement.rect, - placement.visibility, - &adjusted_work_area, - &others, - ); - hidden.push(hide); - rect - }) - .collect() - } else { - self.layout.as_boxed_arrangement().calculate( - &adjusted_work_area, - NonZeroUsize::new(self.containers().len()).ok_or_eyre( - "there must be at least one container to calculate a workspace layout", - )?, - Some(container_padding), - self.layout_flip, - &self.resize_dimensions, - self.focused_container_idx(), - effective_layout_options, - &self.latest_layout, - ) - }; - - let should_remove_titlebars = REMOVE_TITLEBARS.load(Ordering::SeqCst); - let no_titlebar = NO_TITLEBAR.lock().clone(); - let regex_identifiers = REGEX_IDENTIFIERS.lock().clone(); - - let containers = self.containers_mut(); - - for (i, container) in containers.iter_mut().enumerate() { - let window_count = container.windows().len(); - - if let Some(layout) = layouts.get_mut(i) { - layout.add_padding(border_offset); - layout.add_padding(border_width); - - if stackbar_manager::should_have_stackbar(window_count) { - let tab_height = STACKBAR_TAB_HEIGHT.load(Ordering::SeqCst); - let total_height = tab_height + container_padding; - - layout.top += total_height; - layout.bottom -= total_height; - } - - for window in container.windows() { - if container - .focused_window() - .is_some_and(|w| w.hwnd == window.hwnd) - { - let should_remove_titlebar_for_window = should_act( - &window.title().unwrap_or_default(), - &window.exe().unwrap_or_default(), - &window.class().unwrap_or_default(), - &window.path().unwrap_or_default(), - &no_titlebar, - ®ex_identifiers, - ) - .is_some(); - - if should_remove_titlebars && should_remove_titlebar_for_window - { - window.remove_title_bar()?; - } else if should_remove_titlebar_for_window { - window.add_title_bar()?; - } - - // If a window has been unmaximized via toggle-maximize, this block - // will make sure that it is unmaximized via restore_window - if window.is_maximized() && !managed_maximized_window { - let _ = - backend().unminimize(WindowId::from_hwnd(window.hwnd)); - } - } - if hidden.get(i).copied().unwrap_or_default() { - // it is seen on another monitor wherever it rests here - let _ = window.hide_window(()); - } else { - if crate::scrolling::should_restore_when_placed( - window.hwnd, - container.focused_window().map(|w| w.hwnd), - &HIDDEN_HWNDS.lock(), - ) { - let _ = window.restore_window(); - } - - backend().set_rect(WindowId::from_hwnd(window.hwnd), layout)?; - } - } - } - } - - self.latest_layout = layouts; - - // with animations off every window that changed width has been asked what it - // is by now, so a window that refused is known, and everything after it is - // placed again with room for it. Once is enough: a layout is never made to - // chase the sizes that are read back this time round. - if pass == 0 - && self.is_scrolling() - && !crate::scrolling::animations_enabled() - && self.adopt_actual_widths(around_window, adjusted_work_area.right) - { - pass += 1; - continue; - } - - break; - } - } - } - - // Always make sure that the length of the resize dimensions vec is the same as the - // number of layouts / containers. This should never actually truncate as the remove_window - // function takes care of cleaning up resize dimensions when destroying empty containers - let container_count = self.containers().len(); - - // since monocle is a toggle, we never want to truncate the resize dimensions since it will - // almost always be toggled off and the container will be reintegrated into layout - // - // without this check, if there are exactly two containers, when one is toggled to monocle - // the resize dimensions will be truncated to len == 1, and when it is reintegrated, if it - // had a resize adjustment before, that will have been lost - if self.monocle_container.is_none() { - self.resize_dimensions.resize(container_count, None); - } - - Ok(()) + self.update_shared() } fn hwnd_from_exe(&self, exe: &str) -> Option {