chore(repo): combine the review fixes, new tests and docs (candidate 5)

Candidate 5: wip-cand4 plus kfw's review fixes (wip-u-fix5: revert of the subscriber write timeout and the hwnd writer thread, BAR_RUNNING tied to the message, dead-window HIDDEN_HWNDS cleanup, core in default-members), kfm's macOS registry fixes (wip-u-kfm3), kfde's hook rename and per-pass title-bar snapshot (wip-u-core4), the komorebi-core characterization tests (wip-u-coretests) and the docs (wip-u-docs). Conflicts, if any, are resolved here.
This commit is contained in:
LGUG2Z committed 2026-11-05 15:03:26 -08:00
37 files changed
+5739 -67

No files matched your search

+7
View File
@@ -43,3 +43,10 @@ DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
```
## Developer documentation
How the repository is laid out after the consolidation of the Windows, KDE
Plasma and macOS trees is in `docs/dev/ARCHITECTURE-UNIFIED.md`; the exact
build, test, e2e and VM commands for each platform, and the known flakes, are
in `docs/dev/build-and-test.md`.
+39 -1
View File
@@ -78,7 +78,9 @@ impl<H> Registry<H> {
/// if the id was registered: the caller drops it, with no lock held.
#[must_use = "drop the replaced handle yourself: it is not dropped under the lock"]
pub fn insert(&self, id: WindowId, pid: i32, handle: H) -> Option<H> {
self.lock().insert(id, Entry { pid, handle }).map(|e| e.handle)
self.lock()
.insert(id, Entry { pid, handle })
.map(|e| e.handle)
}
/// Replaces the handle of a window that is registered, keeping its pid. Returns the old
@@ -285,6 +287,42 @@ mod tests {
assert!(registry.is_empty());
}
/// Registering must not run the drop of any handle: macOS handles do Accessibility calls when
/// they are dropped, and registration happens on the event thread under the window manager lock.
#[test]
fn registering_a_new_id_drops_nothing_and_a_replaced_handle_only_when_the_caller_drops_it() {
let registry = Arc::new(Registry::new());
let drops = Arc::new(AtomicUsize::new(0));
let probe = || {
Arc::new(Probe {
registry: registry.clone(),
drops: drops.clone(),
})
};
let replaced = registry.insert(id(1), 10, probe());
assert!(replaced.is_none());
assert_eq!(drops.load(Ordering::SeqCst), 0);
let replaced = registry.insert(id(1), 10, probe());
assert_eq!(
drops.load(Ordering::SeqCst),
0,
"the old handle is handed back, not dropped"
);
drop(replaced);
assert_eq!(drops.load(Ordering::SeqCst), 1);
// a lookup clones the Arc and drops nothing
let found = registry.get(id(1)).unwrap();
drop(found);
assert_eq!(drops.load(Ordering::SeqCst), 1);
drop(registry.remove(id(1)));
assert_eq!(drops.load(Ordering::SeqCst), 2);
}
#[test]
fn many_threads_can_register_look_up_and_remove() {
let r = Arc::new(Registry::new());
+57 -12
View File
@@ -59,7 +59,7 @@ pub enum Pass {
/// What the hooks of an update know about the pass that is running.
#[derive(Clone, Copy, Debug)]
pub struct Placement {
pub struct Placement<'a> {
/// 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.
@@ -76,6 +76,8 @@ pub struct Placement {
pub resize_dimensions_is_empty: bool,
/// Whether a window is maximized on this workspace.
pub managed_maximized_window: bool,
/// What [`WorkspacePlatform::begin_pass`] returned for this pass.
pub pass: Option<&'a dyn std::any::Any>,
}
/// What names a window of the platform `P`: the id the shared code compares.
@@ -150,9 +152,11 @@ pub trait WorkspacePlatform: Sized + Clone + std::fmt::Debug + PartialEq + 'stat
/// Tells the scrolling layout that the container at `idx` is about to leave the workspace.
fn note_scrolling_departure(workspace: &Workspace<Self>, idx: usize);
/// Called after a floating window was taken out of the workspace; KDE refocuses a floating
/// window, Windows does nothing.
fn after_floating_removed(_workspace: &mut Workspace<Self>) {}
/// Called by [`Workspace::remove_floating_window`] before the floating window is taken out of the
/// workspace, while it is still in the ring: KDE and macOS move the focus to the previous
/// floating window first (the focus index moves back by one whatever the length), Windows does
/// nothing.
fn before_floating_removed(_workspace: &mut Workspace<Self>) {}
/// The index at which [`Workspace::promote_container`] inserts the container: the primary
/// position of the layout. The default layouts have it first.
@@ -222,12 +226,20 @@ pub trait WorkspacePlatform: Sized + Clone + std::fmt::Debug + PartialEq + 'stat
(vec![], vec![])
}
/// Called once per placement pass, after the layout is computed and before the containers are
/// placed: whatever the platform needs to read once for the whole pass (Windows takes a snapshot
/// of the title-bar rules here, so that two containers of a pass see the same one). The answer
/// is handed to the hooks of the pass as [`Placement::pass`].
fn begin_pass(_workspace: &Workspace<Self>) -> Option<Box<dyn std::any::Any>> {
None
}
/// 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<Self::Window>,
_layout: &mut Rect,
_placement: &Placement,
_placement: &Placement<'_>,
) {
}
@@ -236,7 +248,7 @@ pub trait WorkspacePlatform: Sized + Clone + std::fmt::Debug + PartialEq + 'stat
_container: &mut Container<Self::Window>,
_layout: &Rect,
_hidden: bool,
_placement: &Placement,
_placement: &Placement<'_>,
) -> eyre::Result<()> {
Err(eyre::eyre!("this platform has no shared update"))
}
@@ -1161,7 +1173,7 @@ impl<P: WorkspacePlatform> Workspace<P> {
None => None,
Some(idx) => {
if self.floating_windows().get(idx).is_some() {
P::after_floating_removed(self);
P::before_floating_removed(self);
self.floating_windows_mut().remove(idx)
} else {
None
@@ -1797,6 +1809,8 @@ impl<P: WorkspacePlatform> Workspace<P> {
)
};
let pass_state = P::begin_pass(self);
let placement = Placement {
adjusted_work_area,
work_area,
@@ -1806,6 +1820,7 @@ impl<P: WorkspacePlatform> Workspace<P> {
is_scrolling,
resize_dimensions_is_empty: self.resize_dimensions.is_empty(),
managed_maximized_window,
pass: pass_state.as_deref(),
};
for (i, container) in self.containers_mut().iter_mut().enumerate() {
@@ -1985,11 +2000,23 @@ mod tests {
fn note_scrolling_departure(_: &Workspace<Self>, _: usize) {}
fn before_floating_removed(workspace: &mut Workspace<Self>) {
LOG.with(|log| {
log.borrow_mut()
.push(format!("floating {}", workspace.floating_windows().len()))
});
}
fn begin_update(_: &mut Workspace<Self>) -> eyre::Result<Flow> {
LOG.with(|log| log.borrow_mut().push("begin".to_string()));
Ok(Flow::Run(None))
}
fn begin_pass(_: &Workspace<Self>) -> Option<Box<dyn std::any::Any>> {
LOG.with(|log| log.borrow_mut().push("begin_pass".to_string()));
Some(Box::new(7u8))
}
fn containers_pruned(_: &mut Workspace<Self>, focused_before: usize) {
LOG.with(|log| log.borrow_mut().push(format!("pruned {focused_before}")));
}
@@ -2002,14 +2029,15 @@ mod tests {
container: &mut Container<W>,
layout: &Rect,
hidden: bool,
_: &Placement,
placement: &Placement,
) -> eyre::Result<()> {
LOG.with(|log| {
log.borrow_mut().push(format!(
"place {} {} {}",
"place {} {} {} {:?}",
container.windows()[0].0,
layout.left,
hidden
hidden,
placement.pass.and_then(|pass| pass.downcast_ref::<u8>())
))
});
Ok(())
@@ -2083,12 +2111,29 @@ mod tests {
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!(log[2], "begin_pass");
assert_eq!(log[3], "place 1 1 false Some(7)");
assert_eq!(log[5], "end 0");
assert_eq!(log[6], "begin_pass");
assert_eq!(log[9], "end 1");
assert_eq!(workspace.latest_layout.len(), 2);
assert_eq!(workspace.resize_dimensions.len(), 2);
}
#[test]
fn the_hook_for_a_removed_floating_window_runs_before_the_removal() {
let mut workspace = Workspace::<Plat>::default();
workspace.floating_windows_mut().push_back(W(1));
workspace.floating_windows_mut().push_back(W(2));
log();
assert_eq!(workspace.remove_floating_window(2), Some(W(2)));
// the ring still had both windows when the hook ran: the focus moves first
assert_eq!(log(), ["floating 2"]);
assert_eq!(workspace.floating_windows().len(), 1);
}
#[test]
fn promoting_a_container_puts_it_first_and_focuses_it() {
let mut workspace = workspace_of(&[1, 2, 3]);
File diff suppressed because it is too large. Load diff
+500
View File
@@ -0,0 +1,500 @@
//! A recording stub platform for the characterization tests of `komorebi-core`.
//!
//! `StubWindow` and `StubPlatform` log every window operation and every hook call, in order, as a
//! line of text, so that a test says exactly which calls a shared function makes, with which
//! arguments. What the stub answers (the focus, the pointer, whether a call fails, what
//! `end_update` asks for) is set per test with the functions at the bottom of this file.
//!
//! The log and the settings are thread-local, and every test starts with [`fresh`], so tests do
//! not see each other whatever the harness does with threads.
#![allow(dead_code)]
use color_eyre::eyre;
use komorebi_config::matching::IdWithIdentifier;
use komorebi_config::matching::MatchingRule;
use komorebi_core::Container;
use komorebi_core::ContainerWindow;
use komorebi_core::Flow;
use komorebi_core::Monitor;
use komorebi_core::MonitorPlatform;
use komorebi_core::NoExtra;
use komorebi_core::Pass;
use komorebi_core::Placement;
use komorebi_core::Workspace;
use komorebi_core::WorkspacePlatform;
use komorebi_core::WorkspaceWindow;
use komorebi_layouts::OperationDirection;
use komorebi_layouts::Rect;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
/// A window that is `Clone` but not `Copy`, as the macOS window is.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StubWindow {
pub id: u32,
}
/// The platform state the stub keeps in a workspace: the spot it hides windows at, which is how
/// macOS keeps the corner of its monitor.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StubState {
pub spot: u8,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StubPlatform;
/// What the stub answers and what it makes fail; reset by [`fresh`].
#[derive(Default)]
struct Settings {
foreground: Option<u32>,
cursor: Option<(i32, i32)>,
/// operations that fail, by the text the log would have for them (see `fails`)
failing: HashSet<String>,
/// what `begin_update` does: 0 runs, 1 skips
skip_update: bool,
/// what the successive calls of `end_update` answer; `Done` once it is empty
passes: Vec<Pass>,
adopt_widths: bool,
scrolling_insertion_idx: Option<usize>,
/// what `scrolling_layouts` hides
scrolling_hidden: Vec<bool>,
known_names: HashMap<usize, String>,
/// how much `adjust_layout` shrinks a tile
adjust: i32,
/// the id the placement rule matchers answer true for
match_id: Option<String>,
}
thread_local! {
static LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
static SETTINGS: RefCell<Settings> = RefCell::new(Settings::default());
}
/// Starts a test: empties the log and sets the stub back to its defaults (the focus is on no
/// window, nothing fails, `end_update` is done after one pass).
pub fn fresh() {
LOG.with(|log| log.borrow_mut().clear());
SETTINGS.with(|s| *s.borrow_mut() = Settings::default());
}
/// Takes the log, leaving it empty.
pub fn log() -> Vec<String> {
LOG.with(|log| std::mem::take(&mut *log.borrow_mut()))
}
fn push(line: String) {
LOG.with(|log| log.borrow_mut().push(line));
}
fn settings<T>(f: impl FnOnce(&mut Settings) -> T) -> T {
SETTINGS.with(|s| f(&mut s.borrow_mut()))
}
/// Makes the operation fail whenever it is called: the line the log has for it, without the
/// arguments that follow the name, e.g. `fail("hide 3")` (a window operation names the window) or
/// `fail("place_container")` (a hook).
pub fn fail(operation: &str) {
settings(|s| s.failing.insert(operation.to_string()));
}
pub fn set_foreground(id: Option<u32>) {
settings(|s| s.foreground = id);
}
pub fn set_cursor(point: Option<(i32, i32)>) {
settings(|s| s.cursor = point);
}
pub fn skip_updates() {
settings(|s| s.skip_update = true);
}
/// What the successive calls of `end_update` answer.
pub fn script_passes(passes: &[Pass]) {
settings(|s| s.passes = passes.iter().rev().copied().collect());
}
pub fn adopt_widths(yes: bool) {
settings(|s| s.adopt_widths = yes);
}
pub fn set_scrolling_insertion_idx(idx: Option<usize>) {
settings(|s| s.scrolling_insertion_idx = idx);
}
pub fn set_scrolling_hidden(hidden: &[bool]) {
settings(|s| s.scrolling_hidden = hidden.to_vec());
}
pub fn set_known_workspace_name(idx: usize, name: &str) {
settings(|s| s.known_names.insert(idx, name.to_string()));
}
pub fn set_match_id(id: &str) {
settings(|s| s.match_id = Some(id.to_string()));
}
pub fn set_adjust(by: i32) {
settings(|s| s.adjust = by);
}
fn fails(operation: &str) -> bool {
settings(|s| s.failing.contains(operation))
}
fn op(line: String, key: String) -> eyre::Result<()> {
push(line);
if fails(&key) {
Err(eyre::eyre!("{key} failed"))
} else {
Ok(())
}
}
impl ContainerWindow for StubWindow {
type Id = u32;
type HideSpot = u8;
fn id(&self) -> u32 {
self.id
}
fn exe_name(&self) -> Option<String> {
Some(format!("exe{}", self.id))
}
fn hide_window(&self, spot: u8) -> eyre::Result<()> {
op(
format!("hide {} @{spot}", self.id),
format!("hide {}", self.id),
)
}
fn restore_window(&self) -> eyre::Result<()> {
op(
format!("restore {}", self.id),
format!("restore {}", self.id),
)
}
fn hide_stacked(&self, spot: u8) -> eyre::Result<()> {
op(
format!("hide_stacked {} @{spot}", self.id),
format!("hide_stacked {}", self.id),
)
}
fn restore_stacked(&self) -> eyre::Result<()> {
op(
format!("restore_stacked {}", self.id),
format!("restore_stacked {}", self.id),
)
}
}
impl WorkspaceWindow for StubWindow {
fn title(&self) -> Option<String> {
Some(format!("title{}", self.id))
}
fn exe(&self) -> Option<String> {
self.exe_name()
}
fn class(&self) -> Option<String> {
Some("class".to_string())
}
fn path(&self) -> Option<String> {
Some(format!("/bin/exe{}", self.id))
}
}
pub fn rect_text(rect: &Rect) -> String {
format!(
"[{} {} {} {}]",
rect.left, rect.top, rect.right, rect.bottom
)
}
impl WorkspacePlatform for StubPlatform {
type Window = StubWindow;
type State = StubState;
fn hide_spot(workspace: &Workspace<Self>) -> u8 {
workspace.state.spot
}
/// a display spot is the spot plus 100, so that a test sees which of the two was passed
fn hide_spot_on_display(workspace: &Workspace<Self>) -> u8 {
workspace.state.spot + 100
}
fn foreground_window_id() -> Option<u32> {
settings(|s| s.foreground)
}
fn cursor_position() -> Option<(i32, i32)> {
settings(|s| s.cursor)
}
fn should_act_window(
_: &str,
_: &str,
_: &str,
_: &str,
rules: &[MatchingRule],
) -> Option<MatchingRule> {
let id = settings(|s| s.match_id.clone())?;
rules
.iter()
.find(|rule| matches!(rule, MatchingRule::Simple(r) if r.id == id))
.cloned()
}
fn should_act_window_individual(
_: &str,
_: &str,
_: &str,
_: &str,
rule: &IdWithIdentifier,
) -> bool {
settings(|s| s.match_id.clone()).is_some_and(|id| id == rule.id)
}
fn scrolling_idx_for_direction(_: &Workspace<Self>, _: OperationDirection) -> Option<usize> {
None
}
fn scrolling_insertion_idx(_: &Workspace<Self>) -> Option<usize> {
settings(|s| s.scrolling_insertion_idx)
}
fn note_scrolling_departure(_: &Workspace<Self>, idx: usize) {
push(format!("note_scrolling_departure {idx}"));
}
fn after_floating_removed(workspace: &mut Workspace<Self>) {
push(format!(
"after_floating_removed len={} focus={}",
workspace.floating_windows().len(),
workspace.focused_floating_window_idx()
));
}
fn unmaximize_window(window: &StubWindow) -> eyre::Result<()> {
op(
format!("unmaximize {}", window.id),
format!("unmaximize {}", window.id),
)
}
fn before_hide_containers(_: &mut Workspace<Self>) -> Option<Vec<Option<Rect>>> {
push("before_hide_containers".to_string());
None
}
fn begin_update(_: &mut Workspace<Self>) -> eyre::Result<Flow> {
push("begin_update".to_string());
if fails("begin_update") {
return Err(eyre::eyre!("begin_update failed"));
}
if settings(|s| s.skip_update) {
return Ok(Flow::Skip);
}
Ok(Flow::Run(Some(Box::new(DropLogger))))
}
fn containers_pruned(_: &mut Workspace<Self>, focused_before: usize) {
push(format!("containers_pruned focused_before={focused_before}"));
}
fn place_monocle(window: &mut StubWindow, rect: &Rect) -> eyre::Result<()> {
op(
format!("place_monocle {} {}", window.id, rect_text(rect)),
"place_monocle".to_string(),
)
}
fn maximize_in_layout(window: &mut StubWindow) -> eyre::Result<()> {
op(
format!("maximize_in_layout {}", window.id),
"maximize_in_layout".to_string(),
)
}
fn adopt_widths_before_layout(_: &Workspace<Self>) -> bool {
push("adopt_widths_before_layout".to_string());
settings(|s| s.adopt_widths)
}
fn adopt_actual_widths(
_: &mut Workspace<Self>,
around_window: i32,
viewport_width: i32,
) -> bool {
push(format!(
"adopt_actual_widths around={around_window} viewport={viewport_width}"
));
false
}
fn scrolling_layouts(
workspace: &mut Workspace<Self>,
adjusted_work_area: &Rect,
container_padding: i32,
) -> (Vec<Rect>, Vec<bool>) {
push(format!(
"scrolling_layouts {} padding={container_padding}",
rect_text(adjusted_work_area)
));
let count = workspace.containers().len() as i32;
let width = adjusted_work_area.right / count.max(1);
let layouts = (0..count)
.map(|i| Rect {
left: adjusted_work_area.left + i * width,
top: adjusted_work_area.top,
right: width,
bottom: adjusted_work_area.bottom,
})
.collect();
(layouts, settings(|s| s.scrolling_hidden.clone()))
}
fn adjust_layout(
container: &mut Container<StubWindow>,
layout: &mut Rect,
placement: &Placement,
) {
push(format!(
"adjust_layout {} {} scrolling={} maximized={} resize_empty={}",
window_ids(container),
rect_text(layout),
placement.is_scrolling,
placement.managed_maximized_window,
placement.resize_dimensions_is_empty,
));
let by = settings(|s| s.adjust);
layout.add_padding(by);
}
fn place_container(
container: &mut Container<StubWindow>,
layout: &Rect,
hidden: bool,
placement: &Placement,
) -> eyre::Result<()> {
op(
format!(
"place_container {} {} hidden={hidden} padding={} border={}+{}",
window_ids(container),
rect_text(layout),
placement.container_padding,
placement.border_offset,
placement.border_width,
),
"place_container".to_string(),
)
}
fn end_update(
_: &mut Workspace<Self>,
pass: usize,
around_window: i32,
viewport_width: i32,
) -> eyre::Result<Pass> {
push(format!(
"end_update pass={pass} around={around_window} viewport={viewport_width}"
));
if fails("end_update") {
return Err(eyre::eyre!("end_update failed"));
}
Ok(settings(|s| s.passes.pop()).unwrap_or(Pass::Done))
}
}
/// The guard `begin_update` hands out, which logs when the update is over.
struct DropLogger;
impl Drop for DropLogger {
fn drop(&mut self) {
push("guard dropped".to_string());
}
}
fn window_ids(container: &Container<StubWindow>) -> String {
let ids: Vec<String> = container
.windows()
.iter()
.map(|w| w.id.to_string())
.collect();
format!("({})", ids.join(","))
}
impl MonitorPlatform for StubPlatform {
type Id = u32;
type SerialNumber = String;
type Extra = NoExtra;
#[cfg(feature = "schemars")]
type IdSchema = u32;
fn serialize_id<S: Serializer>(id: &u32, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u32(*id)
}
fn deserialize_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
u32::deserialize(deserializer)
}
fn known_workspace_name(_: &Monitor<Self>, idx: usize) -> Option<String> {
settings(|s| s.known_names.get(&idx).cloned())
}
}
/// A container of the given window ids, the last one in front.
pub fn container_of(ids: &[u32]) -> Container<StubWindow> {
let mut container = Container::default();
for id in ids {
container.add_window(StubWindow { id: *id }, 0).unwrap();
}
container
}
/// A workspace with one container per window id, in order, the last one focused; the log is
/// emptied afterwards.
pub fn workspace_of(ids: &[u32]) -> Workspace<StubPlatform> {
let mut workspace = Workspace::<StubPlatform>::default();
for id in ids {
workspace
.new_container_for_window(StubWindow { id: *id })
.unwrap();
}
log();
workspace
}
/// The window ids of every container, in order.
pub fn layout_of(workspace: &Workspace<StubPlatform>) -> Vec<Vec<u32>> {
workspace
.containers()
.iter()
.map(|c| c.windows().iter().map(|w| w.id).collect())
.collect()
}
pub fn work_area(right: i32, bottom: i32) -> Rect {
Rect {
left: 0,
top: 0,
right,
bottom,
}
}
pub mod fixtures;
@@ -0,0 +1,307 @@
//! Characterization of `Container<W>`: the ring of windows, its focus index and the order of the
//! hide and restore calls it makes on its windows.
mod common;
use common::*;
use komorebi_core::Container;
use komorebi_core::Lockable;
fn ids(container: &Container<StubWindow>) -> Vec<u32> {
container.windows().iter().map(|w| w.id).collect()
}
#[test]
fn a_new_container_is_empty_unlocked_and_has_an_id_of_its_own() {
fresh();
let a = Container::<StubWindow>::default();
let b = Container::<StubWindow>::default();
assert!(a.windows().is_empty());
assert!(!a.locked);
assert_eq!(a.focused_window_idx(), 0);
assert!(a.focused_window().is_none());
assert_ne!(a.id, b.id);
assert!(!a.is_preselect());
}
#[test]
fn a_preselect_container_is_empty_and_named_preselect() {
let container = Container::<StubWindow>::preselect();
assert_eq!(container.id, "PRESELECT");
assert!(container.windows().is_empty());
assert!(container.is_preselect());
}
#[test]
fn adding_windows_appends_and_focuses_the_newest() {
fresh();
let container = container_of(&[1, 2, 3]);
assert_eq!(ids(&container), [1, 2, 3]);
assert_eq!(container.focused_window_idx(), 2);
assert_eq!(container.focused_window().map(|w| w.id), Some(3));
}
#[test]
fn adding_a_window_hides_every_other_window_at_the_spot_in_stack_order() {
fresh();
let mut container = container_of(&[1, 2]);
log();
container.add_window(StubWindow { id: 3 }, 5).unwrap();
assert_eq!(log(), ["hide 1 @5", "hide 2 @5"]);
}
#[test]
fn adding_the_first_window_hides_nothing() {
fresh();
let mut container = Container::default();
container.add_window(StubWindow { id: 1 }, 5).unwrap();
assert!(log().is_empty());
}
#[test]
fn a_window_that_cannot_be_hidden_makes_add_window_fail_but_it_is_already_in() {
fresh();
let mut container = container_of(&[1, 2]);
fail("hide 1");
log();
let result = container.add_window(StubWindow { id: 3 }, 5);
assert!(result.is_err());
// the window was pushed and focused before the hiding began, and the hiding stopped at the
// first failure, so window 2 was not hidden
assert_eq!(ids(&container), [1, 2, 3]);
assert_eq!(container.focused_window_idx(), 2);
assert_eq!(log(), ["hide 1 @5"]);
}
#[test]
fn removing_a_window_focuses_the_one_before_its_index_whatever_was_focused() {
fresh();
// (removed index, the focus index afterwards) for a container of four windows with the last
// one focused
for (removed, focused_after) in [(0, 0), (1, 0), (2, 1), (3, 2)] {
let mut container = container_of(&[10, 11, 12, 13]);
let window = container.remove_window_by_idx(removed).unwrap();
assert_eq!(window.id, 10 + removed as u32);
assert_eq!(container.windows().len(), 3);
assert_eq!(
container.focused_window_idx(),
focused_after,
"after removing index {removed}"
);
}
}
#[test]
fn removing_a_window_does_not_touch_the_windows_that_are_left() {
fresh();
let mut container = container_of(&[1, 2, 3]);
log();
container.remove_window_by_idx(1);
assert!(log().is_empty());
assert_eq!(ids(&container), [1, 3]);
}
#[test]
fn removing_the_last_window_leaves_an_empty_container_focused_at_zero() {
fresh();
let mut container = container_of(&[1]);
let window = container.remove_focused_window();
assert_eq!(window.map(|w| w.id), Some(1));
assert!(container.windows().is_empty());
assert_eq!(container.focused_window_idx(), 0);
assert!(container.focused_window().is_none());
}
#[test]
fn removing_from_an_empty_container_gives_nothing_and_keeps_focus_zero() {
fresh();
let mut container = Container::<StubWindow>::default();
assert!(container.remove_focused_window().is_none());
assert!(container.remove_window_by_idx(0).is_none());
assert_eq!(container.focused_window_idx(), 0);
}
#[test]
fn removing_past_the_end_removes_nothing_and_leaves_the_focus_dangling() {
fresh();
let mut container = container_of(&[1, 2]);
assert!(container.remove_window_by_idx(5).is_none());
// the focus moved to index 4 although there are two windows: the ring does not clamp it
assert_eq!(container.windows().len(), 2);
assert_eq!(container.focused_window_idx(), 4);
assert!(container.focused_window().is_none());
}
#[test]
fn removing_the_focused_window_of_a_stack_focuses_the_one_before_it() {
fresh();
let mut container = container_of(&[1, 2, 3]);
container.focus_window(1);
container.remove_focused_window();
assert_eq!(ids(&container), [1, 3]);
assert_eq!(container.focused_window_idx(), 0);
}
#[test]
fn focusing_a_window_only_moves_the_index_and_makes_no_window_call() {
fresh();
let mut container = container_of(&[1, 2, 3]);
log();
container.focus_window(0);
assert_eq!(container.focused_window_idx(), 0);
assert!(log().is_empty());
}
#[test]
fn windows_are_found_by_id_and_by_executable() {
fresh();
let container = container_of(&[4, 5, 6]);
assert_eq!(container.idx_for_window(6), Some(2));
assert!(container.contains_window(4));
assert!(!container.contains_window(7));
assert_eq!(container.idx_from_exe("exe5"), Some(1));
assert_eq!(container.idx_from_exe("exe9"), None);
}
#[test]
fn loading_the_focused_window_walks_the_windows_in_order_and_stops_at_a_failure() {
fresh();
let mut container = container_of(&[1, 2, 3]);
container.focus_window(1);
fail("hide_stacked 1");
log();
let result = container.load_focused_window(3);
assert!(result.is_err());
// window 1 failed first, so neither the focused window 2 nor window 3 was reached
assert_eq!(log(), ["hide_stacked 1 @3"]);
}
#[test]
fn loading_the_focused_window_of_a_single_window_container_restores_it_the_stacked_way() {
fresh();
let mut container = container_of(&[1]);
container.load_focused_window(3).unwrap();
assert_eq!(log(), ["restore_stacked 1"]);
}
#[test]
fn loading_an_empty_container_calls_nothing() {
fresh();
let mut container = Container::<StubWindow>::default();
container.load_focused_window(3).unwrap();
assert!(log().is_empty());
}
#[test]
fn hiding_goes_from_the_back_and_carries_on_after_a_window_that_fails() {
fresh();
let container = container_of(&[1, 2, 3]);
fail("hide 3");
log();
let result = container.hide(None, 9);
assert!(result.is_ok());
assert_eq!(log(), ["hide 3 @9", "hide 2 @9", "hide 1 @9"]);
}
#[test]
fn hiding_with_an_omitted_window_spares_only_that_window() {
fresh();
let container = container_of(&[1, 2, 3]);
log();
container.hide(Some(2), 9).unwrap();
assert_eq!(log(), ["hide 3 @9", "hide 1 @9"]);
}
#[test]
fn hiding_with_an_omitted_window_that_is_not_in_the_container_hides_them_all() {
fresh();
let container = container_of(&[1, 2]);
log();
container.hide(Some(42), 9).unwrap();
assert_eq!(log(), ["hide 2 @9", "hide 1 @9"]);
}
#[test]
fn restoring_shows_only_the_focused_window_and_reports_a_failure() {
fresh();
let mut container = container_of(&[1, 2]);
container.focus_window(0);
log();
container.restore().unwrap();
assert_eq!(log(), ["restore 1"]);
fail("restore 1");
assert!(container.restore().is_err());
}
#[test]
fn restoring_an_empty_container_is_not_an_error() {
fresh();
let container = Container::<StubWindow>::default();
assert!(container.restore().is_ok());
assert!(log().is_empty());
}
#[test]
fn a_container_can_be_locked_and_unlocked() {
let mut container = Container::<StubWindow>::default();
container.set_locked(true);
assert!(container.locked());
container.set_locked(false);
assert!(!container.locked());
}
#[test]
fn a_container_with_windows_is_written_as_a_ring_with_its_focus_index() {
fresh();
let mut container = container_of(&[1, 2]);
container.id = "c".to_string();
container.focus_window(0);
assert_eq!(
serde_json::to_value(&container).unwrap(),
serde_json::json!({
"id": "c",
"locked": false,
"windows": { "elements": [{ "id": 1 }, { "id": 2 }], "focused": 0 }
})
);
}
@@ -0,0 +1,363 @@
//! Characterization of `Monitor<P>`: the ring of workspaces, how it grows and shrinks, which
//! workspace has the focus, and the name a new workspace takes from what the platform knew.
mod common;
use common::*;
use komorebi_core::Monitor;
use komorebi_core::Workspace;
use komorebi_layouts::DefaultLayout;
use komorebi_layouts::Layout;
fn monitor(workspaces: usize) -> Monitor<StubPlatform> {
let mut monitor: Monitor<StubPlatform> = serde_json::from_value(serde_json::json!({
"id": 7,
"device": "Virtual-0",
"size": { "left": 0, "top": 0, "right": 1920, "bottom": 1080 },
"work_area_size": { "left": 0, "top": 0, "right": 1920, "bottom": 1040 },
"work_area_offset": null,
"window_based_work_area_offset": null,
"window_based_work_area_offset_limit": 1,
"workspaces": { "elements": [], "focused": 0 },
"container_padding": null,
"workspace_padding": null,
"wallpaper": null,
"floating_layer_behaviour": null
}))
.unwrap();
monitor.ensure_workspace_count(workspaces);
monitor
}
fn named(monitor: &mut Monitor<StubPlatform>, names: &[&str]) {
for (workspace, name) in monitor.workspaces_mut().iter_mut().zip(names) {
workspace.name = Some(name.to_string());
}
}
fn names(monitor: &Monitor<StubPlatform>) -> Vec<Option<String>> {
monitor
.workspaces()
.iter()
.map(|w| w.name.clone())
.collect()
}
#[test]
fn a_monitor_read_without_a_serial_number_has_the_platforms_default() {
let monitor = monitor(0);
assert_eq!(monitor.serial_number_id, "");
assert_eq!(monitor.id, 7);
assert!(monitor.last_focused_workspace.is_none());
}
#[test]
fn ensuring_a_count_adds_default_workspaces_and_never_removes_any() {
fresh();
let mut monitor = monitor(0);
monitor.ensure_workspace_count(3);
assert_eq!(monitor.workspaces().len(), 3);
assert_eq!(monitor.new_workspace_idx(), 3);
named(&mut monitor, &["a", "b", "c"]);
monitor.ensure_workspace_count(2);
monitor.ensure_workspace_count(0);
assert_eq!(monitor.workspaces().len(), 3);
monitor.ensure_workspace_count(4);
assert_eq!(
names(&monitor),
[Some("a".into()), Some("b".into()), Some("c".into()), None]
);
}
#[test]
fn ensuring_a_count_leaves_the_focus_alone() {
fresh();
let mut monitor = monitor(2);
monitor.focus_workspace(1).unwrap();
monitor.ensure_workspace_count(5);
assert_eq!(monitor.focused_workspace_idx(), 1);
}
#[test]
fn a_new_workspace_is_a_default_workspace() {
fresh();
let monitor = monitor(1);
assert_eq!(monitor.workspaces()[0], Workspace::default());
}
#[test]
fn focusing_a_workspace_remembers_the_one_that_had_the_focus() {
fresh();
let mut monitor = monitor(3);
monitor.focus_workspace(2).unwrap();
assert_eq!(monitor.focused_workspace_idx(), 2);
assert_eq!(monitor.last_focused_workspace, Some(0));
monitor.focus_workspace(1).unwrap();
assert_eq!(monitor.last_focused_workspace, Some(2));
}
#[test]
fn focusing_the_workspace_that_has_the_focus_makes_it_its_own_last_focused() {
fresh();
let mut monitor = monitor(2);
monitor.focus_workspace(1).unwrap();
monitor.focus_workspace(1).unwrap();
assert_eq!(monitor.last_focused_workspace, Some(1));
}
#[test]
fn focusing_past_the_end_creates_every_workspace_up_to_it() {
fresh();
let mut monitor = monitor(1);
monitor.focus_workspace(3).unwrap();
assert_eq!(monitor.workspaces().len(), 4);
assert_eq!(monitor.focused_workspace_idx(), 3);
assert_eq!(monitor.last_focused_workspace, Some(0));
}
#[test]
fn focusing_in_a_monitor_with_no_workspace_creates_it() {
fresh();
let mut monitor = monitor(0);
monitor.focus_workspace(0).unwrap();
assert_eq!(monitor.workspaces().len(), 1);
assert!(monitor.focused_workspace().is_some());
}
#[test]
fn focusing_without_a_known_name_leaves_the_names_as_they_are() {
fresh();
let mut monitor = monitor(2);
named(&mut monitor, &["a", "b"]);
monitor.focus_workspace(1).unwrap();
monitor.focus_workspace(4).unwrap();
assert_eq!(
names(&monitor),
[Some("a".into()), Some("b".into()), None, None, None]
);
}
#[test]
fn a_workspace_created_by_focusing_takes_the_name_the_platform_knew_for_it() {
fresh();
let mut monitor = monitor(1);
set_known_workspace_name(2, "known");
set_known_workspace_name(1, "skipped");
monitor.focus_workspace(2).unwrap();
// only the workspace that was focused takes the name, the one made on the way does not
assert_eq!(names(&monitor), [None, None, Some("known".into())]);
}
#[test]
fn focusing_an_existing_workspace_overwrites_its_name_with_the_known_one() {
fresh();
let mut monitor = monitor(2);
named(&mut monitor, &["mine", "other"]);
set_known_workspace_name(1, "known");
monitor.focus_workspace(1).unwrap();
// the code comment says the name is set when the workspace is created, but it is set at
// every focus: a name given at runtime is replaced by the known one
assert_eq!(monitor.focused_workspace_name().as_deref(), Some("known"));
}
#[test]
fn removing_a_workspace_by_index_takes_it_out_and_does_not_move_the_focus_index() {
fresh();
let mut monitor = monitor(3);
named(&mut monitor, &["a", "b", "c"]);
monitor.focus_workspace(2).unwrap();
let removed = monitor.remove_workspace_by_idx(0).unwrap();
assert_eq!(removed.name.as_deref(), Some("a"));
assert_eq!(names(&monitor), [Some("b".into()), Some("c".into())]);
assert_eq!(monitor.focused_workspace_idx(), 2);
}
#[test]
fn removing_a_workspace_past_the_end_removes_nothing_and_focuses_the_one_before_it() {
fresh();
let mut monitor = monitor(2);
assert!(monitor.remove_workspace_by_idx(5).is_none());
// the focus went to index 4, creating the workspaces up to it
assert_eq!(monitor.workspaces().len(), 5);
assert_eq!(monitor.focused_workspace_idx(), 4);
}
#[test]
fn removing_the_first_workspace_of_an_empty_monitor_gives_it_a_default_one() {
fresh();
let mut monitor = monitor(0);
assert!(monitor.remove_workspace_by_idx(0).is_none());
assert_eq!(monitor.workspaces().len(), 1);
}
#[test]
fn removing_every_workspace_hands_them_over_in_order_and_leaves_the_focus_index() {
fresh();
let mut monitor = monitor(3);
named(&mut monitor, &["a", "b", "c"]);
monitor.focus_workspace(2).unwrap();
let removed = monitor.remove_workspaces();
let removed_names: Vec<_> = removed.iter().map(|w| w.name.clone().unwrap()).collect();
assert_eq!(removed_names, ["a", "b", "c"]);
assert!(monitor.workspaces().is_empty());
assert!(monitor.focused_workspace().is_none());
assert_eq!(monitor.focused_workspace_idx(), 2);
assert_eq!(monitor.focused_workspace_name(), None);
}
#[test]
fn a_container_added_to_a_workspace_goes_to_its_back_and_takes_the_focus() {
fresh();
let mut monitor = monitor(2);
monitor.focus_workspace(1).unwrap();
monitor.workspaces_mut()[0].add_container_to_back(container_of(&[1]));
monitor.add_container(container_of(&[2]), Some(0)).unwrap();
assert_eq!(layout_of(&monitor.workspaces()[0]), [vec![1], vec![2]]);
assert_eq!(monitor.workspaces()[0].focused_container_idx(), 1);
assert!(monitor.workspaces()[1].containers().is_empty());
}
#[test]
fn a_container_added_without_a_workspace_goes_to_the_focused_one() {
fresh();
let mut monitor = monitor(2);
monitor.focus_workspace(1).unwrap();
monitor.add_container(container_of(&[3]), None).unwrap();
assert_eq!(layout_of(&monitor.workspaces()[1]), [[3]]);
}
#[test]
fn adding_a_container_to_a_workspace_that_is_not_there_is_an_error() {
fresh();
let mut monitor = monitor(1);
assert!(monitor.add_container(container_of(&[1]), Some(4)).is_err());
assert!(monitor.workspaces()[0].containers().is_empty());
}
#[test]
fn adding_a_container_to_a_monitor_without_workspaces_is_an_error() {
fresh();
let mut monitor = monitor(0);
assert!(monitor.add_container(container_of(&[1]), None).is_err());
}
#[test]
fn the_focused_workspace_layout_is_given_only_while_it_tiles() {
fresh();
let mut monitor = monitor(1);
assert_eq!(
monitor.focused_workspace_layout(),
Some(Layout::Default(DefaultLayout::BSP))
);
monitor.focused_workspace_mut().unwrap().tile = false;
assert_eq!(monitor.focused_workspace_layout(), None);
monitor.remove_workspaces();
assert_eq!(monitor.focused_workspace_layout(), None);
}
#[test]
fn a_monitor_writes_last_focused_workspace_only_once_a_workspace_was_focused() {
fresh();
let mut monitor = monitor(2);
let keys = |m: &Monitor<StubPlatform>| -> Vec<String> {
serde_json::to_value(m)
.unwrap()
.as_object()
.unwrap()
.keys()
.cloned()
.collect()
};
assert!(!keys(&monitor).contains(&"last_focused_workspace".to_string()));
monitor.focus_workspace(1).unwrap();
assert!(keys(&monitor).contains(&"last_focused_workspace".to_string()));
}
#[test]
fn a_monitor_with_workspaces_round_trips_through_json() {
fresh();
let mut monitor = monitor(2);
monitor.focus_workspace(1).unwrap();
monitor.add_container(container_of(&[1, 2]), None).unwrap();
let json = serde_json::to_value(&monitor).unwrap();
let back: Monitor<StubPlatform> = serde_json::from_value(json.clone()).unwrap();
assert_eq!(back, monitor);
assert_eq!(serde_json::to_value(&back).unwrap(), json);
}
#[test]
fn removing_the_workspace_at_the_length_focuses_the_last_one_and_removes_nothing() {
fresh();
let mut monitor = monitor(3);
assert!(monitor.remove_workspace_by_idx(3).is_none());
assert_eq!(monitor.workspaces().len(), 3);
assert_eq!(monitor.focused_workspace_idx(), 2);
}
#[test]
fn an_old_monitor_file_with_workspaces_and_without_optional_keys_loads() {
fresh();
let workspace = serde_json::to_value(Workspace::<StubPlatform>::default()).unwrap();
let mut workspace = workspace;
for key in ["layout_options_rules", "name", "layout_flip", "wallpaper"] {
workspace.as_object_mut().unwrap().remove(key);
}
let monitor: Monitor<StubPlatform> = serde_json::from_value(serde_json::json!({
"id": 1, "device": "d",
"size": { "left": 0, "top": 0, "right": 1, "bottom": 1 },
"work_area_size": { "left": 0, "top": 0, "right": 1, "bottom": 1 },
"work_area_offset": null, "window_based_work_area_offset": null,
"window_based_work_area_offset_limit": 1,
"workspaces": { "elements": [workspace.clone(), workspace], "focused": 1 },
"container_padding": null, "workspace_padding": null,
"wallpaper": null, "floating_layer_behaviour": null
}))
.unwrap();
assert_eq!(monitor.workspaces().len(), 2);
assert_eq!(monitor.focused_workspace_idx(), 1);
assert!(monitor.workspaces()[0].layout_options_rules.is_empty());
}
@@ -0,0 +1,191 @@
//! Characterization of the resize constraints: which sides of each tile of each layout may be
//! given a resize adjustment.
mod common;
use common::*;
use komorebi_core::Workspace;
use komorebi_layouts::DefaultLayout;
use komorebi_layouts::Layout;
use komorebi_layouts::Rect;
/// A workspace of `n` containers whose adjustments are all 5 on every side, with the layout.
fn workspace_with(layout: DefaultLayout, n: usize) -> Workspace<StubPlatform> {
Workspace {
layout: Layout::Default(layout),
resize_dimensions: vec![
Some(Rect {
left: 5,
top: 5,
right: 5,
bottom: 5
});
n
],
..Default::default()
}
}
/// The sides that are still adjustable, per tile, as the letters of "ltrb".
fn sides(workspace: &Workspace<StubPlatform>) -> Vec<String> {
workspace
.resize_dimensions
.iter()
.map(|rect| {
let Some(r) = rect else {
return "-".to_string();
};
let mut s = String::new();
for (letter, value) in [('l', r.left), ('t', r.top), ('r', r.right), ('b', r.bottom)] {
if value != 0 {
s.push(letter);
}
}
s
})
.collect()
}
fn constrained(layout: DefaultLayout, n: usize) -> Vec<String> {
fresh();
let mut workspace = workspace_with(layout, n);
workspace.enforce_resize_constraints();
sides(&workspace)
}
fn check(layout: DefaultLayout, expected: &[&[&str]]) {
for tiles in expected {
assert_eq!(
constrained(layout, tiles.len()),
*tiles,
"{layout:?} with {} containers",
tiles.len()
);
}
}
#[test]
fn bsp_alternates_the_closed_side_and_closes_the_outer_edges() {
check(
DefaultLayout::BSP,
&[&[""], &["r", "lt"], &["r", "ltb", "lt"]],
);
}
#[test]
fn columns_only_resize_sideways_and_not_beyond_the_outer_columns() {
check(
DefaultLayout::Columns,
&[&[""], &["r", "l"], &["r", "lr", "l"]],
);
}
#[test]
fn rows_only_resize_up_and_down_and_not_beyond_the_outer_rows() {
check(
DefaultLayout::Rows,
&[&[""], &["b", "t"], &["b", "tb", "t"]],
);
}
#[test]
fn the_vertical_stack_has_its_main_column_on_the_left() {
check(
DefaultLayout::VerticalStack,
&[
&[""],
&["r", "lb"],
&["r", "lb", "lt"],
&["r", "lb", "ltb", "lt"],
],
);
}
#[test]
fn the_horizontal_stack_has_its_main_row_on_top() {
check(
DefaultLayout::HorizontalStack,
&[
&[""],
&["b", "t"],
&["b", "tr", "lt"],
&["b", "tr", "ltr", "lt"],
],
);
}
#[test]
fn the_ultrawide_stack_has_its_main_column_in_the_middle() {
check(
DefaultLayout::UltrawideVerticalStack,
&[
&[""],
&["l", "r"],
&["lr", "r", "lb"],
&["lr", "r", "lb", "lt"],
],
);
}
#[test]
fn the_right_main_vertical_stack_constrains_index_one_and_leaves_index_zero_free() {
// characterization of what the code does: it follows the comment "Zero is actually on the
// right" but indexes the second container, so the first (the main one) is never constrained
// and the second may not be resized at all; the ignored test below says what the comment asks
check(
DefaultLayout::RightMainVerticalStack,
&[
&[""],
&["ltrb", ""],
&["ltrb", "", "tr"],
&["ltrb", "", "trb", "tr"],
],
);
}
#[test]
#[ignore = "bug: enforce_resize_for_right_vertical_stack indexes resize_dimensions[1] where its \
comment says zero is on the right; inherited unchanged from the Windows tree"]
fn the_right_main_vertical_stack_constrains_its_main_container_at_index_zero() {
fresh();
let mut workspace = workspace_with(DefaultLayout::RightMainVerticalStack, 3);
workspace.enforce_resize_constraints();
// the main container is on the right: it cannot go up, down or right
assert_eq!(sides(&workspace)[0], "l");
}
#[test]
fn layouts_without_a_resize_rule_take_every_adjustment_away() {
for layout in [DefaultLayout::Grid, DefaultLayout::Scrolling] {
assert_eq!(constrained(layout, 3), ["", "", ""], "{layout:?}");
}
}
#[test]
fn a_tile_without_an_adjustment_stays_without_one() {
fresh();
let mut workspace = workspace_with(DefaultLayout::Columns, 3);
workspace.resize_dimensions[1] = None;
workspace.enforce_resize_constraints();
assert_eq!(sides(&workspace), ["r", "-", "l"]);
}
#[test]
fn no_adjustments_at_all_is_fine_for_every_layout() {
for layout in [
DefaultLayout::BSP,
DefaultLayout::Columns,
DefaultLayout::Rows,
DefaultLayout::VerticalStack,
DefaultLayout::RightMainVerticalStack,
DefaultLayout::HorizontalStack,
DefaultLayout::UltrawideVerticalStack,
DefaultLayout::Grid,
] {
assert!(constrained(layout, 0).is_empty());
}
}
@@ -0,0 +1,644 @@
//! State JSON round trips from real fixtures: `komorebic state` output of the Windows and KDE
//! daemons (copied from `e2e/lib/tests/fixtures`) and a macOS-shaped one, read into the shared
//! `Monitor<P>` with each platform's window, id, serial number and extra fields, written again,
//! and compared as parsed JSON.
//!
//! The platforms here are only shaped like the real ones (what the shared types are generic over);
//! the windows keep the JSON they were read from, because the real windows write what the
//! operating system knows (title, rectangle) at the moment they are serialised.
mod common;
use common::fixtures::*;
use komorebi_config::behaviour::WindowHidingPosition;
use komorebi_core::ContainerWindow;
use komorebi_core::Monitor;
use komorebi_core::MonitorPlatform;
use komorebi_core::NoExtra;
use komorebi_core::WorkspacePlatform;
use komorebi_core::WorkspaceWindow;
use komorebi_core::ring::Ring;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde_json::Value;
use std::collections::HashMap;
/// A platform shaped like Windows, KDE or macOS: its window keeps the JSON it was read from, and
/// is named by the number under `$id_key`.
macro_rules! shaped_platform {
($platform:ident, $window:ident, $id_key:literal, $monitor_id:ty, $serial:ty, $extra:ty) => {
#[derive(Clone, Debug, PartialEq)]
struct $window {
id: i64,
json: Value,
}
impl Serialize for $window {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.json.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for $window {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let json = Value::deserialize(deserializer)?;
let id = json[$id_key]
.as_i64()
.ok_or_else(|| serde::de::Error::custom(concat!("no ", $id_key)))?;
Ok(Self { id, json })
}
}
impl ContainerWindow for $window {
type Id = i64;
type HideSpot = ();
fn id(&self) -> i64 {
self.id
}
fn exe_name(&self) -> Option<String> {
None
}
fn hide_window(&self, _: ()) -> color_eyre::eyre::Result<()> {
Ok(())
}
fn restore_window(&self) -> color_eyre::eyre::Result<()> {
Ok(())
}
fn hide_stacked(&self, _: ()) -> color_eyre::eyre::Result<()> {
Ok(())
}
fn restore_stacked(&self) -> color_eyre::eyre::Result<()> {
Ok(())
}
}
impl WorkspaceWindow for $window {
fn title(&self) -> Option<String> {
None
}
fn exe(&self) -> Option<String> {
None
}
fn class(&self) -> Option<String> {
None
}
fn path(&self) -> Option<String> {
None
}
}
#[derive(Clone, Debug, PartialEq)]
struct $platform;
impl WorkspacePlatform for $platform {
type Window = $window;
type State = ();
fn foreground_window_id() -> Option<i64> {
None
}
fn cursor_position() -> Option<(i32, i32)> {
None
}
fn should_act_window(
_: &str,
_: &str,
_: &str,
_: &str,
_: &[komorebi_config::matching::MatchingRule],
) -> Option<komorebi_config::matching::MatchingRule> {
None
}
fn should_act_window_individual(
_: &str,
_: &str,
_: &str,
_: &str,
_: &komorebi_config::matching::IdWithIdentifier,
) -> bool {
false
}
fn scrolling_idx_for_direction(
_: &komorebi_core::Workspace<Self>,
_: komorebi_layouts::OperationDirection,
) -> Option<usize> {
None
}
fn scrolling_insertion_idx(_: &komorebi_core::Workspace<Self>) -> Option<usize> {
None
}
fn note_scrolling_departure(_: &komorebi_core::Workspace<Self>, _: usize) {}
}
impl MonitorPlatform for $platform {
type Id = $monitor_id;
type SerialNumber = $serial;
type Extra = $extra;
#[cfg(feature = "schemars")]
type IdSchema = $monitor_id;
fn serialize_id<S: Serializer>(
id: &$monitor_id,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.serialize_i64(*id as i64)
}
fn deserialize_id<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<$monitor_id, D::Error> {
<$monitor_id>::deserialize(deserializer)
}
}
};
}
/// What only a Windows monitor has, as the Windows daemon declares it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct WindowsExtra {
name: String,
device_id: String,
#[serde(deserialize_with = "workspace_names")]
workspace_names: HashMap<usize, String>,
}
/// A flattened map is read through a buffer that keeps its keys as strings.
fn workspace_names<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<HashMap<usize, String>, D::Error> {
HashMap::<String, String>::deserialize(deserializer)?
.into_iter()
.map(|(key, name)| {
key.parse()
.map(|key| (key, name))
.map_err(serde::de::Error::custom)
})
.collect()
}
/// What only a macOS monitor has.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct MacosExtra {
window_hiding_position: WindowHidingPosition,
}
shaped_platform!(
Windows,
WindowsWindow,
"hwnd",
isize,
Option<String>,
WindowsExtra
);
shaped_platform!(Kde, KdeWindow, "id", u32, String, NoExtra);
shaped_platform!(Macos, MacosWindow, "id", u32, String, MacosExtra);
fn json(text: &str) -> Value {
serde_json::from_str(text).unwrap()
}
/// Reads the monitors of a state file as platform `P`, writes them again.
fn round_trip<P: MonitorPlatform>(state: &Value) -> (Ring<Monitor<P>>, Value)
where
P::Window: Serialize + for<'de> Deserialize<'de>,
{
let monitors: Ring<Monitor<P>> = serde_json::from_value(state["monitors"].clone()).unwrap();
let written = serde_json::to_value(&monitors).unwrap();
(monitors, written)
}
// ---- Windows ----------------------------------------------------------------------------------
#[test]
fn a_windows_tiled_state_is_written_as_it_was_read() {
let state = json(KFW_TILED);
let (monitors, written) = round_trip::<Windows>(&state);
assert_eq!(written, state["monitors"]);
let monitor = &monitors.elements()[0];
assert_eq!(monitor.id, 65537);
assert_eq!(monitor.serial_number_id, None);
assert_eq!(monitor.extra.name, "DISPLAY1");
assert_eq!(monitor.extra.device_id, "Default_Monitor-4&183790ca&0&UID0");
assert_eq!(monitor.workspaces().len(), 1);
assert_eq!(monitor.workspaces()[0].containers().len(), 3);
}
#[test]
fn a_windows_stacked_state_is_written_as_it_was_read() {
let state = json(KFW_STACK);
let (monitors, written) = round_trip::<Windows>(&state);
assert_eq!(written, state["monitors"]);
let stacked = monitors.elements()[0].workspaces()[0]
.containers()
.iter()
.find(|c| c.windows().len() > 1)
.expect("the fixture has a stack");
assert_eq!(stacked.windows().len(), 2);
}
#[test]
fn a_windows_state_with_a_floating_window_and_the_floating_layer_is_written_as_it_was_read() {
let state = json(KFW_FLOAT);
let (monitors, written) = round_trip::<Windows>(&state);
assert_eq!(written, state["monitors"]);
let workspace = &monitors.elements()[0].workspaces()[0];
assert_eq!(workspace.floating_windows().len(), 1);
assert_eq!(workspace.layer, komorebi_core::WorkspaceLayer::Floating);
assert!(workspace.contains_window(workspace.floating_windows()[0].id));
}
// ---- KDE --------------------------------------------------------------------------------------
#[test]
fn a_kde_tiled_state_is_written_as_it_was_read() {
let state = json(KFDE_TILED);
let (monitors, written) = round_trip::<Kde>(&state);
assert_eq!(written, state["monitors"]);
let monitor = &monitors.elements()[0];
assert_eq!(monitor.id, 1230296105);
assert_eq!(monitor.device, "Virtual-0");
assert_eq!(monitor.serial_number_id, "Virtual-0");
assert_eq!(monitor.workspaces()[0].containers().len(), 3);
}
#[test]
fn a_kde_stacked_state_is_written_as_it_was_read() {
let state = json(KFDE_STACK);
let (monitors, written) = round_trip::<Kde>(&state);
assert_eq!(written, state["monitors"]);
let first = &monitors.elements()[0].workspaces()[0].containers()[0];
assert_eq!(first.windows().len(), 2);
assert_eq!(first.focused_window_idx(), 1);
}
#[test]
fn a_kde_monitor_has_no_platform_fields_beyond_the_shared_ones() {
let state = json(KFDE_TILED);
let (_, written) = round_trip::<Kde>(&state);
let mut keys: Vec<&str> = written["elements"][0]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
keys.sort_unstable();
assert_eq!(
keys,
[
"container_padding",
"device",
"floating_layer_behaviour",
"id",
"last_focused_workspace",
"serial_number_id",
"size",
"wallpaper",
"window_based_work_area_offset",
"window_based_work_area_offset_limit",
"work_area_offset",
"work_area_size",
"workspace_padding",
"workspaces",
]
);
}
// ---- macOS ------------------------------------------------------------------------------------
#[test]
fn a_macos_shaped_state_is_written_as_it_was_read_with_the_corner_last() {
let state = json(MACOS_TILED);
let (monitors, written) = round_trip::<Macos>(&state);
assert_eq!(written, state["monitors"]);
let monitor = &monitors.elements()[0];
assert_eq!(monitor.id, 1);
assert_eq!(monitor.serial_number_id, "C02XXXXXXXX");
assert_eq!(
monitor.extra.window_hiding_position,
WindowHidingPosition::BottomLeft
);
let keys: Vec<&String> = written["elements"][0].as_object().unwrap().keys().collect();
assert_eq!(keys.last().unwrap().as_str(), "window_hiding_position");
}
#[test]
fn a_macos_state_cannot_be_read_without_its_corner() {
let mut state = json(MACOS_TILED);
state["monitors"]["elements"][0]
.as_object_mut()
.unwrap()
.remove("window_hiding_position");
assert!(serde_json::from_value::<Ring<Monitor<Macos>>>(state["monitors"].clone()).is_err());
}
// ---- shared -----------------------------------------------------------------------------------
#[test]
fn the_same_workspace_keys_are_written_whatever_the_platform() {
fn workspace_keys(written: &Value) -> Vec<String> {
let mut keys: Vec<String> = written["elements"][0]["workspaces"]["elements"][0]
.as_object()
.unwrap()
.keys()
.cloned()
.collect();
keys.sort();
keys
}
let windows = workspace_keys(&round_trip::<Windows>(&json(KFW_TILED)).1);
let kde = workspace_keys(&round_trip::<Kde>(&json(KFDE_TILED)).1);
let macos = workspace_keys(&round_trip::<Macos>(&json(MACOS_TILED)).1);
assert_eq!(windows, kde);
assert_eq!(kde, macos);
}
#[test]
fn a_container_without_locked_is_read_from_a_state_file() {
let mut state = json(KFDE_TILED);
for container in
state["monitors"]["elements"][0]["workspaces"]["elements"][0]["containers"]["elements"]
.as_array_mut()
.unwrap()
{
container.as_object_mut().unwrap().remove("locked");
}
let (monitors, _) = round_trip::<Kde>(&state);
assert!(
monitors.elements()[0].workspaces()[0]
.containers()
.iter()
.all(|c| !c.locked)
);
}
/// Reads a KDE-shaped state with `key` taken out of the object at `level`, to say whether it loads.
fn loads_without(level: &str, key: &str) -> bool {
let mut state = json(KFDE_TILED);
let monitor = &mut state["monitors"]["elements"][0];
let target = match level {
"monitor" => monitor,
"workspace" => &mut monitor["workspaces"]["elements"][0],
_ => &mut monitor["workspaces"]["elements"][0]["containers"]["elements"][0],
};
assert!(
target.as_object_mut().unwrap().remove(key).is_some(),
"the fixture has no {level} key {key}"
);
serde_json::from_value::<Ring<Monitor<Kde>>>(state["monitors"].clone()).is_ok()
}
#[test]
fn an_old_state_file_without_the_optional_keys_still_loads() {
let optional = [
("monitor", "serial_number_id"),
("monitor", "work_area_offset"),
("monitor", "window_based_work_area_offset"),
("monitor", "container_padding"),
("monitor", "workspace_padding"),
("monitor", "last_focused_workspace"),
("monitor", "wallpaper"),
("monitor", "floating_layer_behaviour"),
("workspace", "name"),
("workspace", "monocle_container"),
("workspace", "maximized_window"),
("workspace", "layout_options"),
("workspace", "layout_options_rules"),
("workspace", "layout_flip"),
("workspace", "workspace_padding"),
("workspace", "container_padding"),
("workspace", "work_area_offset"),
("workspace", "window_container_behaviour"),
("workspace", "window_container_behaviour_rules"),
("workspace", "float_override"),
("workspace", "floating_layer_behaviour"),
("workspace", "wallpaper"),
("container", "locked"),
];
for (level, key) in optional {
assert!(
loads_without(level, key),
"a {level} without {key} should load"
);
}
}
#[test]
fn a_state_file_cannot_be_read_without_the_keys_the_shared_types_require() {
// characterization: these have no default, so a file from before one of them existed (the
// layer, the work area offset rules, the window-based offset flag) is not read
let required = [
("monitor", "id"),
("monitor", "device"),
("monitor", "workspaces"),
("monitor", "size"),
("monitor", "work_area_size"),
("monitor", "window_based_work_area_offset_limit"),
("workspace", "containers"),
("workspace", "floating_windows"),
("workspace", "layout"),
("workspace", "layout_rules"),
("workspace", "latest_layout"),
("workspace", "resize_dimensions"),
("workspace", "tile"),
("workspace", "work_area_offset_rules"),
("workspace", "apply_window_based_work_area_offset"),
("workspace", "layer"),
("container", "id"),
("container", "windows"),
];
for (level, key) in required {
assert!(
!loads_without(level, key),
"a {level} without {key} should not load"
);
}
}
#[test]
fn a_workspace_written_after_a_missing_optional_key_has_the_key_again() {
let mut state = json(KFDE_TILED);
state["monitors"]["elements"][0]["workspaces"]["elements"][0]
.as_object_mut()
.unwrap()
.remove("layout_options_rules");
let (_, written) = round_trip::<Kde>(&state);
assert_eq!(
written["elements"][0]["workspaces"]["elements"][0]["layout_options_rules"],
serde_json::json!([])
);
}
#[test]
fn the_runtime_only_parts_of_a_workspace_are_never_written() {
let (monitors, written) = round_trip::<Kde>(&json(KFDE_TILED));
let mut monitors = monitors;
let workspace = &mut monitors.elements_mut()[0].workspaces_mut()[0];
workspace.globals.border_width = 9;
workspace.monocle_container_restore_idx = Some(1);
let rewritten = serde_json::to_value(&monitors).unwrap();
let keys = rewritten["elements"][0]["workspaces"]["elements"][0]
.as_object()
.unwrap();
assert!(!keys.contains_key("globals"));
assert!(!keys.contains_key("state"));
assert!(!keys.contains_key("scrolling"));
// a restore index is written once there is one, and not before
assert!(keys.contains_key("monocle_container_restore_idx"));
assert!(
!written["elements"][0]["workspaces"]["elements"][0]
.as_object()
.unwrap()
.contains_key("monocle_container_restore_idx")
);
}
/// The copies in `common/fixtures.rs` are the files of `e2e/lib/tests/fixtures` when the checkout
/// has them (the nix source of the crate does not).
#[test]
fn the_fixtures_are_the_ones_the_e2e_library_has() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../e2e/lib/tests/fixtures");
if !dir.is_dir() {
return;
}
for (name, copy) in [
("kfw-tiled", KFW_TILED),
("kfw-stack", KFW_STACK),
("kfw-float", KFW_FLOAT),
("kfde-tiled", KFDE_TILED),
("kfde-stack", KFDE_STACK),
] {
let original = std::fs::read_to_string(dir.join(format!("{name}.json"))).unwrap();
assert_eq!(
json(&original),
json(copy),
"{name}.json changed: update common/fixtures.rs"
);
}
}
#[test]
fn a_platform_that_overrides_no_optional_hook_gets_the_documented_defaults() {
use komorebi_layouts::DefaultLayout;
use komorebi_layouts::Layout;
let workspace = komorebi_core::Workspace::<Kde>::default();
assert_eq!(
Kde::primary_container_idx(&Layout::Default(DefaultLayout::BSP)).unwrap(),
0
);
assert!(
Kde::unmaximize_window(&KdeWindow {
id: 1,
json: Value::Null
})
.is_ok()
);
let () = Kde::hide_spot_on_display(&workspace);
assert_eq!(Kde::default_padding(), (None, None));
let mut workspace = workspace;
assert!(Kde::before_hide_containers(&mut workspace).is_none());
assert!(matches!(
Kde::begin_update(&mut workspace).unwrap(),
komorebi_core::Flow::Run(None)
));
assert_eq!(
Kde::end_update(&mut workspace, 0, 0, 0).unwrap(),
komorebi_core::Pass::Done
);
assert!(!Kde::adopt_widths_before_layout(&workspace));
assert_eq!(
Kde::scrolling_layouts(&mut workspace, &Default::default(), 0),
(vec![], vec![])
);
}
#[test]
fn the_default_place_hooks_fail_so_a_platform_must_override_them_to_use_update_shared() {
let mut workspace = komorebi_core::Workspace::<Kde>::default();
workspace
.new_container_for_window(KdeWindow {
id: 1,
json: Value::Null,
})
.unwrap();
workspace.globals.work_area = komorebi_layouts::Rect {
left: 0,
top: 0,
right: 100,
bottom: 100,
};
assert!(workspace.update_shared().is_err());
}
#[test]
fn the_json_keys_of_a_monitor_per_platform_extra() {
fn keys(written: &Value) -> Vec<String> {
let mut keys: Vec<String> = written["elements"][0]
.as_object()
.unwrap()
.keys()
.cloned()
.collect();
keys.sort();
keys
}
let windows = keys(&round_trip::<Windows>(&json(KFW_TILED)).1);
let macos = keys(&round_trip::<Macos>(&json(MACOS_TILED)).1);
assert!(windows.starts_with(&[
"container_padding".to_string(),
"device".to_string(),
"device_id".to_string()
]));
for key in ["name", "device_id", "workspace_names"] {
assert!(windows.contains(&key.to_string()), "{key}");
}
assert!(!windows.contains(&"last_focused_workspace".to_string()));
assert!(macos.contains(&"window_hiding_position".to_string()));
assert!(!macos.contains(&"name".to_string()));
}
+641
View File
@@ -0,0 +1,641 @@
//! Characterization of `Workspace::update_shared`: the order of the hook calls and their
//! arguments for every kind of workspace, and what each hook's failure does to the update.
//!
//! The work area is 1000 x 800 with a workspace padding of 20 and a container padding of 10 unless
//! a test says otherwise, so a BSP workspace of two containers has tiles
//! `[30 30 460 740]` and `[510 30 460 740]` (rects are left, top, width, height).
mod common;
use common::*;
use komorebi_config::behaviour::WindowContainerBehaviour;
use komorebi_core::Container;
use komorebi_core::Pass;
use komorebi_core::Workspace;
use komorebi_layouts::DefaultLayout;
use komorebi_layouts::Layout;
use komorebi_layouts::Rect;
fn w(id: u32) -> StubWindow {
StubWindow { id }
}
fn on_screen(ids: &[u32]) -> Workspace<StubPlatform> {
let mut workspace = workspace_of(ids);
workspace.globals.work_area = work_area(1000, 800);
workspace.globals.container_padding = Some(10);
workspace.globals.workspace_padding = Some(20);
workspace
}
fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
Rect {
left,
top,
right,
bottom,
}
}
#[test]
fn a_tiling_workspace_calls_the_hooks_in_order_and_holds_the_guard_to_the_end() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.update_shared().unwrap();
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=1",
"adjust_layout (1) [30 30 460 740] scrolling=false maximized=false resize_empty=false",
"place_container (1) [30 30 460 740] hidden=false padding=10 border=0+0",
"adjust_layout (2) [510 30 460 740] scrolling=false maximized=false resize_empty=false",
"place_container (2) [510 30 460 740] hidden=false padding=10 border=0+0",
"end_update pass=0 around=10 viewport=960",
"guard dropped",
]
);
}
#[test]
fn the_borders_are_in_the_placement_and_in_the_around_window_width() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.globals.border_offset = 3;
workspace.globals.border_width = 2;
workspace.update_shared().unwrap();
let log = log();
assert!(log.contains(
&"place_container (1) [30 30 940 740] hidden=false padding=10 border=3+2".to_string()
));
assert!(log.contains(&"end_update pass=0 around=15 viewport=960".to_string()));
}
#[test]
fn the_layout_the_hooks_got_is_kept_as_the_latest_layout_after_the_adjustment() {
fresh();
let mut workspace = on_screen(&[1, 2]);
set_adjust(2);
workspace.update_shared().unwrap();
assert_eq!(
workspace.latest_layout,
[rect(32, 32, 456, 736), rect(512, 32, 456, 736)]
);
let log = log();
assert!(
log.iter()
.any(|l| l.starts_with("place_container (1) [32 32 456 736]"))
);
}
#[test]
fn a_monocle_container_gets_the_work_area_less_every_padding_and_nothing_else_is_placed() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.globals.border_offset = 3;
workspace.globals.border_width = 2;
workspace.new_monocle_container().unwrap();
log();
workspace.update_shared().unwrap();
// 20 workspace padding, then 10 + 3 + 2 more on each side
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=0",
"place_monocle 2 [35 35 930 730]",
"guard dropped",
]
);
}
#[test]
fn a_maximized_window_is_laid_out_by_the_platform_and_the_containers_are_left_alone() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.maximized_window = Some(w(9));
workspace.update_shared().unwrap();
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=1",
"maximize_in_layout 9",
"guard dropped",
]
);
assert!(workspace.latest_layout.is_empty());
}
#[test]
fn the_monocle_container_wins_over_a_maximized_window() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.new_monocle_container().unwrap();
workspace.maximized_window = Some(w(9));
log();
workspace.update_shared().unwrap();
let log = log();
assert!(log.iter().any(|l| l.starts_with("place_monocle 2")));
assert!(!log.iter().any(|l| l.starts_with("maximize_in_layout")));
}
#[test]
fn an_empty_workspace_prunes_and_places_nothing() {
fresh();
let mut workspace = on_screen(&[]);
workspace.update_shared().unwrap();
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=0",
"guard dropped"
]
);
assert!(workspace.resize_dimensions.is_empty());
}
#[test]
fn a_workspace_that_is_not_tiling_prunes_and_places_nothing() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.tile = false;
workspace.resize_dimensions = vec![None; 5];
workspace.update_shared().unwrap();
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=1",
"guard dropped"
]
);
// the resize adjustments are still brought to the number of containers
assert_eq!(workspace.resize_dimensions.len(), 2);
}
#[test]
fn a_skipped_update_calls_nothing_after_begin_update_and_changes_nothing() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.resize_dimensions = vec![None; 5];
skip_updates();
workspace.update_shared().unwrap();
assert_eq!(log(), ["begin_update"]);
assert_eq!(workspace.resize_dimensions.len(), 5);
}
#[test]
fn a_failing_begin_update_is_the_error_of_the_update_and_nothing_else_runs() {
fresh();
let mut workspace = on_screen(&[1, 2]);
fail("begin_update");
assert!(workspace.update_shared().is_err());
assert_eq!(log(), ["begin_update"]);
}
#[test]
fn empty_containers_are_dropped_but_a_preselected_one_stays() {
fresh();
let mut workspace = on_screen(&[1, 3]);
workspace.containers_mut().insert(1, Container::default());
workspace.focus_container(2);
workspace.containers_mut().push_back(Container::preselect());
workspace.update_shared().unwrap();
let log = log();
assert!(log.contains(&"containers_pruned focused_before=2".to_string()));
assert_eq!(workspace.containers().len(), 3);
assert!(workspace.containers()[2].is_preselect());
// the shared code leaves the focus where it was: the hook is for the platform to fix it
assert_eq!(workspace.focused_container_idx(), 2);
}
#[test]
fn end_update_asking_again_lays_the_workspace_out_and_places_the_windows_once_more() {
fresh();
let mut workspace = on_screen(&[1, 2]);
script_passes(&[Pass::Again, Pass::Again, Pass::Done]);
workspace.update_shared().unwrap();
let log = log();
let ends: Vec<&String> = log.iter().filter(|l| l.starts_with("end_update")).collect();
assert_eq!(
ends,
[
"end_update pass=0 around=10 viewport=960",
"end_update pass=1 around=10 viewport=960",
"end_update pass=2 around=10 viewport=960",
]
);
assert_eq!(
log.iter()
.filter(|l| l.starts_with("place_container"))
.count(),
6
);
assert_eq!(
log.iter()
.filter(|l| l.starts_with("adjust_layout"))
.count(),
6
);
// begin_update and the pruning run once, however many passes there are
assert_eq!(log.iter().filter(|l| *l == "begin_update").count(), 1);
assert_eq!(
log.iter()
.filter(|l| l.starts_with("containers_pruned"))
.count(),
1
);
assert_eq!(log.last().unwrap(), "guard dropped");
}
#[test]
fn a_failing_place_container_stops_the_update_before_end_update_and_the_bookkeeping() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.resize_dimensions = vec![None; 5];
fail("place_container");
assert!(workspace.update_shared().is_err());
// the first container failed: the second was not tried, end_update was not called, the
// guard was still dropped, and neither the latest layout nor the resize vector was set
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=1",
"adjust_layout (1) [30 30 460 740] scrolling=false maximized=false resize_empty=false",
"place_container (1) [30 30 460 740] hidden=false padding=10 border=0+0",
"guard dropped",
]
);
assert!(workspace.latest_layout.is_empty());
assert_eq!(workspace.resize_dimensions.len(), 5);
}
#[test]
fn a_failing_place_monocle_is_the_error_of_the_update() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.new_monocle_container().unwrap();
workspace.resize_dimensions = vec![None; 5];
fail("place_monocle");
assert!(workspace.update_shared().is_err());
assert_eq!(workspace.resize_dimensions.len(), 5);
assert_eq!(log().last().unwrap(), "guard dropped");
}
#[test]
fn a_failing_maximize_in_layout_is_the_error_of_the_update() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.maximized_window = Some(w(9));
fail("maximize_in_layout");
assert!(workspace.update_shared().is_err());
}
#[test]
fn a_failing_end_update_is_the_error_of_the_update_after_the_layout_was_kept() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.resize_dimensions = vec![None; 5];
fail("end_update");
assert!(workspace.update_shared().is_err());
assert_eq!(workspace.latest_layout.len(), 2);
assert_eq!(workspace.resize_dimensions.len(), 5);
}
#[test]
fn a_scrolling_workspace_asks_the_platform_for_its_tiles_and_which_rest_hidden() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.layout = Layout::Default(DefaultLayout::Scrolling);
set_scrolling_hidden(&[false, true]);
workspace.update_shared().unwrap();
assert_eq!(
log(),
[
"begin_update",
"containers_pruned focused_before=1",
"adopt_widths_before_layout",
"scrolling_layouts [20 20 960 760] padding=10",
"adjust_layout (1) [20 20 480 760] scrolling=true maximized=false resize_empty=false",
"place_container (1) [20 20 480 760] hidden=false padding=10 border=0+0",
"adjust_layout (2) [500 20 480 760] scrolling=true maximized=false resize_empty=false",
"place_container (2) [500 20 480 760] hidden=true padding=10 border=0+0",
"end_update pass=0 around=10 viewport=960",
"guard dropped",
]
);
}
#[test]
fn a_scrolling_workspace_adopts_the_widths_the_windows_have_when_the_platform_says_so() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.layout = Layout::Default(DefaultLayout::Scrolling);
adopt_widths(true);
workspace.update_shared().unwrap();
let log = log();
let at = |prefix: &str| log.iter().position(|l| l.starts_with(prefix)).unwrap();
assert_eq!(
log[at("adopt_actual_widths")],
"adopt_actual_widths around=10 viewport=960"
);
assert!(at("adopt_widths_before_layout") < at("adopt_actual_widths"));
assert!(at("adopt_actual_widths") < at("scrolling_layouts"));
}
#[test]
fn a_tiling_workspace_never_asks_about_the_widths_or_the_scrolling_tiles() {
fresh();
let mut workspace = on_screen(&[1]);
adopt_widths(true);
workspace.update_shared().unwrap();
let log = log();
assert!(
!log.iter()
.any(|l| l.contains("adopt_") || l.starts_with("scrolling_layouts"))
);
}
#[test]
fn a_scrolling_workspace_that_asks_again_asks_for_its_tiles_again() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.layout = Layout::Default(DefaultLayout::Scrolling);
script_passes(&[Pass::Again, Pass::Done]);
workspace.update_shared().unwrap();
let log = log();
assert_eq!(
log.iter()
.filter(|l| l.starts_with("scrolling_layouts"))
.count(),
2
);
// the widths are adopted once, before the first pass
assert_eq!(
log.iter()
.filter(|l| *l == "adopt_widths_before_layout")
.count(),
1
);
}
#[test]
fn the_layout_rule_with_the_highest_threshold_reached_replaces_the_layout_for_good() {
fresh();
let mut workspace = on_screen(&[1, 2, 3]);
workspace.layout_rules = vec![
(2, Layout::Default(DefaultLayout::Columns)),
(3, Layout::Default(DefaultLayout::Rows)),
(4, Layout::Default(DefaultLayout::Grid)),
];
workspace.update_shared().unwrap();
assert_eq!(workspace.layout, Layout::Default(DefaultLayout::Rows));
// a rule that is no longer reached does not put the old layout back
workspace.containers_mut().pop_back();
workspace.layout_rules = vec![(5, Layout::Default(DefaultLayout::Grid))];
workspace.update_shared().unwrap();
assert_eq!(workspace.layout, Layout::Default(DefaultLayout::Rows));
}
#[test]
fn the_layout_in_force_decides_the_tiles_of_the_update() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.layout = Layout::Default(DefaultLayout::Rows);
workspace.update_shared().unwrap();
assert_eq!(
workspace.latest_layout,
[rect(30, 30, 940, 360), rect(30, 410, 940, 360)]
);
}
#[test]
fn the_container_behaviour_rules_set_the_behaviour_and_none_reached_clears_it() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.window_container_behaviour_rules = Some(vec![
(1, WindowContainerBehaviour::Append),
(2, WindowContainerBehaviour::Create),
]);
workspace.update_shared().unwrap();
assert_eq!(
workspace.window_container_behaviour,
Some(WindowContainerBehaviour::Create)
);
workspace.window_container_behaviour_rules = Some(vec![(3, WindowContainerBehaviour::Append)]);
workspace.update_shared().unwrap();
assert_eq!(workspace.window_container_behaviour, None);
}
#[test]
fn without_rules_the_container_behaviour_is_left_as_it_was() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.window_container_behaviour = Some(WindowContainerBehaviour::Append);
workspace.update_shared().unwrap();
assert_eq!(
workspace.window_container_behaviour,
Some(WindowContainerBehaviour::Append)
);
}
fn viewport_of(workspace: &mut Workspace<StubPlatform>) -> String {
log();
workspace.update_shared().unwrap();
log()
.iter()
.find_map(|l| l.split("viewport=").nth(1).map(str::to_string))
.unwrap()
}
#[test]
fn the_padding_of_the_workspace_wins_over_the_monitors_even_when_it_is_zero() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.workspace_padding = Some(0);
workspace.container_padding = Some(0);
workspace.update_shared().unwrap();
assert_eq!(workspace.latest_layout, [rect(0, 0, 1000, 800)]);
}
#[test]
fn no_padding_anywhere_is_none_at_all() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.globals.workspace_padding = None;
workspace.globals.container_padding = None;
workspace.update_shared().unwrap();
assert_eq!(workspace.latest_layout, [rect(0, 0, 1000, 800)]);
}
#[test]
fn the_work_area_offset_comes_from_the_rule_then_the_workspace_then_the_monitor() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.globals.workspace_padding = None;
workspace.globals.work_area_offset = Some(rect(1, 0, 10, 0));
assert_eq!(viewport_of(&mut workspace), "990");
workspace.work_area_offset = Some(rect(2, 0, 20, 0));
assert_eq!(viewport_of(&mut workspace), "980");
workspace.work_area_offset_rules = vec![(1, rect(3, 0, 30, 0)), (2, rect(4, 0, 40, 0))];
assert_eq!(viewport_of(&mut workspace), "960");
// a rule that is not reached is not used
workspace.work_area_offset_rules = vec![(3, rect(4, 0, 40, 0))];
assert_eq!(viewport_of(&mut workspace), "980");
}
#[test]
fn a_monocle_container_counts_as_one_container_for_the_work_area_offset_rules() {
fresh();
let mut workspace = on_screen(&[1, 2, 3]);
workspace.globals.workspace_padding = None;
workspace.globals.container_padding = None;
workspace.work_area_offset_rules = vec![(1, rect(0, 0, 100, 0)), (3, rect(0, 0, 300, 0))];
workspace.new_monocle_container().unwrap();
log();
workspace.update_shared().unwrap();
// two containers are left beside the monocle one: the rule for three is not reached, and the
// one for the monocle's count of one is
assert_eq!(log()[2], "place_monocle 3 [0 0 900 800]");
}
#[test]
fn the_window_based_offset_applies_up_to_its_limit_and_when_the_workspace_takes_it() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.globals.workspace_padding = None;
workspace.globals.window_based_work_area_offset = Some(rect(0, 0, 50, 0));
workspace.globals.window_based_work_area_offset_limit = 1;
assert_eq!(viewport_of(&mut workspace), "1000");
workspace.globals.window_based_work_area_offset_limit = 2;
assert_eq!(viewport_of(&mut workspace), "950");
workspace.apply_window_based_work_area_offset = false;
assert_eq!(viewport_of(&mut workspace), "1000");
}
#[test]
fn the_window_based_offset_applies_to_a_monocle_container_whatever_the_count_when_the_limit_is_set()
{
fresh();
let mut workspace = on_screen(&[1, 2, 3]);
workspace.globals.workspace_padding = None;
workspace.globals.container_padding = None;
workspace.globals.window_based_work_area_offset = Some(rect(0, 0, 50, 0));
workspace.globals.window_based_work_area_offset_limit = 1;
workspace.new_monocle_container().unwrap();
log();
workspace.update_shared().unwrap();
assert_eq!(log()[2], "place_monocle 3 [0 0 950 800]");
}
#[test]
fn the_resize_adjustments_are_brought_to_the_number_of_containers() {
fresh();
let mut workspace = on_screen(&[1, 2, 3]);
workspace.resize_dimensions = vec![];
workspace.update_shared().unwrap();
assert_eq!(workspace.resize_dimensions, [None, None, None]);
workspace.resize_dimensions = vec![None; 7];
workspace.update_shared().unwrap();
assert_eq!(workspace.resize_dimensions.len(), 3);
}
#[test]
fn the_resize_adjustments_are_not_cut_while_a_container_is_the_monocle() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.resize_dimensions = vec![Some(rect(1, 1, 1, 1)); 2];
workspace.new_monocle_container().unwrap();
workspace.update_shared().unwrap();
assert_eq!(workspace.resize_dimensions.len(), 2);
}
#[test]
fn the_resize_constraints_are_enforced_before_the_layout_is_calculated() {
fresh();
let mut workspace = on_screen(&[1, 2]);
workspace.resize_dimensions = vec![Some(rect(5, 5, 5, 5)); 2];
workspace.update_shared().unwrap();
assert_eq!(workspace.resize_dimensions[0], Some(rect(0, 0, 5, 0)));
assert_eq!(workspace.resize_dimensions[1], Some(rect(5, 5, 0, 0)));
// an adjustment shows in the placement
assert!(log().iter().any(|l| l.contains("resize_empty=false")));
}
#[test]
fn the_placement_says_when_there_are_no_resize_adjustments() {
fresh();
let mut workspace = on_screen(&[1]);
workspace.resize_dimensions = vec![];
workspace.update_shared().unwrap();
assert!(log().iter().any(|l| l.contains("resize_empty=true")));
}
@@ -0,0 +1,751 @@
//! Characterization of `Workspace<P>`: the ring of containers, the index and focus invariants of
//! adding, removing, stacking and moving them, and the resize adjustments that follow them.
mod common;
use common::*;
use komorebi_config::placement::InitialWindowPlacementRules;
use komorebi_config::placement::PlacementTarget;
use komorebi_config::placement::WindowPlacement;
use komorebi_core::Container;
use komorebi_core::Lockable;
use komorebi_core::Workspace;
use komorebi_layouts::CycleDirection;
use komorebi_layouts::DefaultLayout;
use komorebi_layouts::Layout;
use komorebi_layouts::OperationDirection;
use komorebi_layouts::Rect;
fn w(id: u32) -> StubWindow {
StubWindow { id }
}
fn mark(workspace: &mut Workspace<StubPlatform>, n: i32) {
workspace.resize_dimensions = (0..n)
.map(|i| {
Some(Rect {
left: i + 1,
top: i + 1,
right: i + 1,
bottom: i + 1,
})
})
.collect();
}
#[test]
fn an_empty_workspace_has_nothing_in_it() {
fresh();
let workspace = Workspace::<StubPlatform>::default();
assert!(workspace.is_empty());
assert_eq!(workspace.focused_container_idx(), 0);
assert!(workspace.focused_container().is_none());
assert!(workspace.visible_windows().iter().all(Option::is_none));
assert!(!workspace.contains_window(1));
assert_eq!(workspace.container_idx_for_window(1), None);
}
#[test]
fn the_first_window_goes_to_index_zero_and_each_next_after_the_focused_container() {
fresh();
let mut workspace = workspace_of(&[1]);
assert_eq!(layout_of(&workspace), [[1]]);
workspace.new_container_for_window(w(2)).unwrap();
workspace.focus_container(0);
workspace.new_container_for_window(w(3)).unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![3], vec![2]]);
assert_eq!(workspace.focused_container_idx(), 1);
}
#[test]
fn a_new_container_is_focused_and_gets_an_empty_resize_slot_at_its_index() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
mark(&mut workspace, 2);
workspace.focus_container(0);
workspace.new_container_for_window(w(3)).unwrap();
assert_eq!(workspace.focused_container_idx(), 1);
assert_eq!(workspace.resize_dimensions.len(), 3);
assert!(workspace.resize_dimensions[1].is_none());
assert!(workspace.resize_dimensions[0].is_some());
assert!(workspace.resize_dimensions[2].is_some());
}
#[test]
fn the_scrolling_hook_chooses_the_index_of_a_new_container_in_a_non_empty_workspace() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
set_scrolling_insertion_idx(Some(0));
workspace.new_container_for_window(w(4)).unwrap();
assert_eq!(layout_of(&workspace)[0], [4]);
}
#[test]
fn a_new_window_takes_the_container_a_preselection_reserved() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.preselect_container_idx(1);
assert_eq!(workspace.containers().len(), 3);
assert!(workspace.containers()[1].is_preselect());
assert_eq!(workspace.preselected_container_idx, Some(1));
workspace.new_container_for_window(w(3)).unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![3], vec![2]]);
assert_eq!(workspace.preselected_container_idx, None);
assert!(!workspace.containers().iter().any(Container::is_preselect));
}
#[test]
fn cancelling_a_preselection_removes_its_container_and_does_nothing_without_one() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.cancel_preselect();
assert_eq!(workspace.containers().len(), 2);
workspace.preselect_container_idx(0);
workspace.cancel_preselect();
assert_eq!(layout_of(&workspace), [vec![1], vec![2]]);
assert_eq!(workspace.preselected_container_idx, None);
}
#[test]
fn initial_placement_rules_choose_where_a_new_window_goes() {
fresh();
let cases = [
(WindowPlacement::AfterFocused, vec![1, 2, 9, 3]),
(WindowPlacement::BeforeFocused, vec![1, 9, 2, 3]),
(WindowPlacement::Last, vec![1, 2, 3, 9]),
(WindowPlacement::Primary, vec![9, 1, 2, 3]),
];
for (placement, order) in cases {
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(1);
workspace.initial_window_placement_rules = Some(InitialWindowPlacementRules::Target(
PlacementTarget::Placement(placement),
));
workspace.new_container_for_window(w(9)).unwrap();
let firsts: Vec<u32> = layout_of(&workspace).iter().map(|c| c[0]).collect();
assert_eq!(firsts, order, "{placement:?}");
}
}
#[test]
fn a_one_based_placement_index_is_zero_based_and_out_of_range_falls_back_after_the_focused() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(0);
workspace.initial_window_placement_rules = Some(InitialWindowPlacementRules::Target(
PlacementTarget::Index(3),
));
assert_eq!(workspace.resolve_placement_index(&w(9)), 2);
// index 0 saturates to the first place
workspace.initial_window_placement_rules = Some(InitialWindowPlacementRules::Target(
PlacementTarget::Index(0),
));
assert_eq!(workspace.resolve_placement_index(&w(9)), 0);
// one more than the containers is the end, two more falls back to after the focused one
workspace.initial_window_placement_rules = Some(InitialWindowPlacementRules::Target(
PlacementTarget::Index(4),
));
assert_eq!(workspace.resolve_placement_index(&w(9)), 3);
workspace.initial_window_placement_rules = Some(InitialWindowPlacementRules::Target(
PlacementTarget::Index(5),
));
assert_eq!(workspace.resolve_placement_index(&w(9)), 1);
}
#[test]
fn with_no_rules_a_window_goes_after_the_focused_container() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(0);
assert_eq!(workspace.resolve_placement_index(&w(9)), 1);
}
#[test]
fn inserting_past_the_end_appends_and_pushes_a_resize_slot() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
mark(&mut workspace, 2);
let idx = workspace.insert_container_at_idx(9, container_of(&[3]));
assert_eq!(idx, 2);
assert_eq!(workspace.focused_container_idx(), 2);
assert_eq!(workspace.resize_dimensions.len(), 3);
assert!(workspace.resize_dimensions[2].is_none());
}
#[test]
fn a_locked_container_keeps_its_index_when_another_is_inserted_before_it() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.containers_mut()[1].set_locked(true);
let idx = workspace.insert_container_at_idx(0, container_of(&[9]));
assert_eq!(layout_of(&workspace), [vec![9], vec![2], vec![1], vec![3]]);
assert_eq!(idx, 0);
}
#[test]
fn removing_a_container_tells_the_scrolling_hook_first_and_drops_its_resize_slot() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
mark(&mut workspace, 3);
let removed = workspace.remove_container_by_idx(1).unwrap();
assert_eq!(removed.windows()[0].id, 2);
assert_eq!(log(), ["note_scrolling_departure 1"]);
assert_eq!(workspace.resize_dimensions.len(), 2);
assert_eq!(workspace.resize_dimensions[1].unwrap().left, 3);
}
#[test]
fn removing_past_the_end_removes_nothing() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
mark(&mut workspace, 2);
assert!(workspace.remove_container_by_idx(7).is_none());
assert_eq!(workspace.containers().len(), 2);
assert_eq!(workspace.resize_dimensions.len(), 2);
}
#[test]
fn removing_a_container_focuses_the_one_before_the_focused_container_not_before_the_removed_one() {
fresh();
// the focus was on the last of four containers: whichever is removed, it moves to the index
// before the old focus, which can name a different container than the one that was focused
for removed in 0..4 {
let mut workspace = workspace_of(&[1, 2, 3, 4]);
workspace.remove_container(removed).unwrap();
assert_eq!(workspace.focused_container_idx(), 2, "removed {removed}");
}
// with the focus on the first, it stays there
let mut workspace = workspace_of(&[1, 2, 3, 4]);
workspace.focus_container(0);
workspace.remove_container(2).unwrap();
assert_eq!(workspace.focused_container_idx(), 0);
}
#[test]
fn removing_the_focused_container_focuses_the_one_before_it_and_the_last_leaves_none() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(1);
let removed = workspace.remove_focused_container().unwrap();
assert_eq!(removed.windows()[0].id, 2);
assert_eq!(workspace.focused_container_idx(), 0);
workspace.remove_focused_container();
workspace.remove_focused_container();
assert!(workspace.containers().is_empty());
assert_eq!(workspace.focused_container_idx(), 0);
assert!(workspace.remove_focused_container().is_none());
}
#[test]
fn a_container_added_to_the_back_or_the_front_takes_the_focus() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.add_container_to_back(container_of(&[3]));
assert_eq!(workspace.focused_container_idx(), 2);
workspace.add_container_to_front(container_of(&[4]));
assert_eq!(workspace.focused_container_idx(), 0);
assert_eq!(layout_of(&workspace), [vec![4], vec![1], vec![2], vec![3]]);
}
#[test]
fn focusing_the_first_last_and_previous_container_on_an_empty_workspace_stays_at_zero() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
workspace.focus_last_container();
assert_eq!(workspace.focused_container_idx(), 0);
workspace.focus_previous_container();
assert_eq!(workspace.focused_container_idx(), 0);
workspace.focus_first_container();
assert_eq!(workspace.focused_container_idx(), 0);
}
#[test]
fn swapping_containers_focuses_the_second_and_the_lock_stays_with_the_position() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.containers_mut()[0].set_locked(true);
workspace.swap_containers(0, 2);
assert_eq!(layout_of(&workspace), [vec![3], vec![2], vec![1]]);
assert_eq!(workspace.focused_container_idx(), 2);
assert!(workspace.containers()[0].locked);
assert!(!workspace.containers()[2].locked);
}
#[test]
fn cycling_wraps_around_and_an_empty_workspace_has_nowhere_to_cycle() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
assert_eq!(
workspace.new_idx_for_cycle_direction(CycleDirection::Next),
Some(0)
);
workspace.focus_container(0);
assert_eq!(
workspace.new_idx_for_cycle_direction(CycleDirection::Previous),
Some(2)
);
assert_eq!(
Workspace::<StubPlatform>::default().new_idx_for_cycle_direction(CycleDirection::Next),
None
);
}
#[test]
fn directions_follow_the_layout_and_the_flip() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.focus_container(0);
assert_eq!(
workspace.new_idx_for_direction(OperationDirection::Right),
Some(1)
);
assert_eq!(
workspace.new_idx_for_direction(OperationDirection::Left),
None
);
workspace.layout_flip = Some(komorebi_layouts::Axis::Horizontal);
assert_eq!(
workspace.new_idx_for_direction(OperationDirection::Left),
Some(1)
);
assert_eq!(
workspace.new_idx_for_direction(OperationDirection::Right),
None
);
assert_eq!(
Workspace::<StubPlatform>::default().new_idx_for_direction(OperationDirection::Left),
None
);
}
#[test]
fn stacking_moves_the_focused_window_in_front_of_the_target_and_hides_the_one_it_covers() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.state.spot = 4;
workspace.focus_container(2);
workspace.move_window_to_container(0).unwrap();
// container 2 is empty and goes; container 0 now holds 1 and 3, 3 in front
assert_eq!(layout_of(&workspace), [vec![1, 3], vec![2]]);
assert_eq!(workspace.focused_container_idx(), 0);
assert_eq!(workspace.containers()[0].focused_window_idx(), 1);
assert_eq!(
log(),
[
"note_scrolling_departure 2",
"hide 1 @4",
"hide_stacked 1 @4",
"restore_stacked 3",
]
);
}
#[test]
fn stacking_onto_a_later_container_counts_its_index_after_the_emptied_one_went() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(0);
// after container 0 is removed, the target 2 is the old container 3 at index 1
workspace.move_window_to_container(2).unwrap();
assert_eq!(layout_of(&workspace), [vec![2], vec![3, 1]]);
assert_eq!(workspace.focused_container_idx(), 1);
}
#[test]
fn stacking_out_of_a_stack_shows_the_next_window_of_the_container_it_left() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.containers_mut()[0].add_window(w(5), 0).unwrap();
workspace.focus_container(0);
log();
workspace.move_window_to_container(1).unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![2, 5]]);
assert_eq!(
log(),
[
"restore_stacked 1",
"hide 2 @0",
"hide_stacked 2 @0",
"restore_stacked 5",
]
);
}
#[test]
fn stacking_onto_a_container_that_does_not_exist_is_an_error_after_the_window_left() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.focus_container(1);
let result = workspace.move_window_to_container(9);
assert!(result.is_err());
// the window is out of its container, which was removed: it is lost to the workspace
assert_eq!(layout_of(&workspace), [vec![1]]);
}
#[test]
fn stacking_in_an_empty_workspace_is_an_error() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
assert!(workspace.move_window_to_container(0).is_err());
}
#[test]
fn unstacking_puts_the_focused_window_in_a_container_after_the_one_it_left() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.containers_mut()[0].add_window(w(5), 0).unwrap();
workspace.focus_container(0);
log();
workspace.new_container_for_focused_window().unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![5], vec![2]]);
assert_eq!(workspace.focused_container_idx(), 1);
assert_eq!(log(), ["restore_stacked 1"]);
}
#[test]
fn unstacking_a_single_window_container_moves_nothing_but_still_succeeds() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.focus_container(0);
workspace.new_container_for_focused_window().unwrap();
// the container left empty is removed, the window gets a container after the focused one
assert_eq!(workspace.containers().len(), 2);
assert!(workspace.contains_window(1));
}
#[test]
fn promoting_puts_the_focused_container_first_and_focuses_it() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(1);
workspace.promote_container().unwrap();
assert_eq!(layout_of(&workspace), [vec![2], vec![1], vec![3]]);
assert_eq!(workspace.focused_container_idx(), 0);
}
#[test]
fn promoting_with_no_container_is_an_error() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
assert!(workspace.promote_container().is_err());
}
#[test]
fn a_locked_container_keeps_its_place_when_another_is_promoted() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.containers_mut()[0].set_locked(true);
workspace.focus_container(2);
workspace.promote_container().unwrap();
assert_eq!(layout_of(&workspace)[0], [1]);
}
#[test]
fn windows_are_found_in_containers_monocle_maximized_and_floating() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.monocle_container = Some(container_of(&[3]));
workspace.maximized_window = Some(w(4));
workspace.floating_windows_mut().push_back(w(5));
for id in [1, 2, 3, 4, 5] {
assert!(workspace.contains_window(id), "{id}");
}
// the floating window is not one that komorebi tiles
for id in [1, 2, 3, 4] {
assert!(workspace.contains_managed_window(id), "{id}");
}
assert!(!workspace.contains_managed_window(5));
assert!(!workspace.contains_window(6));
assert!(!workspace.is_empty());
}
#[test]
fn a_workspace_with_only_a_floating_window_is_not_empty() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
workspace.floating_windows_mut().push_back(w(5));
assert!(!workspace.is_empty());
}
#[test]
fn the_location_of_an_executable_is_looked_for_in_the_order_of_the_layers() {
use komorebi_core::WorkspaceWindowLocation as Location;
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.maximized_window = Some(w(4));
workspace.monocle_container = Some(container_of(&[3]));
workspace.floating_windows_mut().push_back(w(5));
assert!(matches!(
workspace.location_from_exe("exe2"),
Some(Location::Container(1, 0))
));
assert!(matches!(
workspace.location_from_exe("exe4"),
Some(Location::Maximized)
));
assert!(matches!(
workspace.location_from_exe("exe3"),
Some(Location::Monocle(0))
));
assert!(matches!(
workspace.location_from_exe("exe5"),
Some(Location::Floating(0))
));
assert!(workspace.location_from_exe("nothing").is_none());
}
#[test]
fn the_last_container_that_has_a_window_is_the_one_found_for_it() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.containers_mut()[0].add_window(w(2), 0).unwrap();
assert_eq!(workspace.container_idx_for_window(2), Some(1));
}
#[test]
fn focusing_by_window_brings_a_stacked_window_to_the_front_and_loads_the_stack() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.state.spot = 6;
workspace.containers_mut()[0].add_window(w(5), 6).unwrap();
workspace.containers_mut()[0].focus_window(1);
log();
workspace.focus_container_by_window(1).unwrap();
assert_eq!(workspace.focused_container_idx(), 0);
assert_eq!(workspace.containers()[0].focused_window_idx(), 0);
assert_eq!(log(), ["restore_stacked 1", "hide_stacked 5 @6"]);
}
#[test]
fn focusing_by_a_window_already_in_front_loads_nothing() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.focus_container_by_window(1).unwrap();
assert_eq!(workspace.focused_container_idx(), 0);
assert!(log().is_empty());
}
#[test]
fn focusing_by_an_unknown_window_is_an_error_and_changes_nothing() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
assert!(workspace.focus_container_by_window(9).is_err());
assert_eq!(workspace.focused_container_idx(), 1);
}
#[test]
fn the_pointer_finds_the_container_whose_last_laid_out_tile_it_is_in() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.latest_layout = vec![
Rect {
left: 0,
top: 0,
right: 100,
bottom: 100,
},
Rect {
left: 100,
top: 0,
right: 100,
bottom: 100,
},
];
assert_eq!(workspace.container_idx_from_current_point(), None);
set_cursor(Some((150, 50)));
assert_eq!(workspace.container_idx_from_current_point(), Some(1));
set_cursor(Some((50, 50)));
assert_eq!(workspace.container_idx_from_current_point(), Some(0));
set_cursor(Some((500, 50)));
assert_eq!(workspace.container_idx_from_current_point(), None);
}
#[test]
fn the_visible_windows_are_maximized_then_monocle_then_each_container_then_floating() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.containers_mut()[0].add_window(w(5), 0).unwrap();
workspace.maximized_window = Some(w(4));
workspace.monocle_container = Some(container_of(&[3]));
workspace.floating_windows_mut().push_back(w(6));
let ids: Vec<Option<u32>> = workspace
.visible_windows()
.iter()
.map(|w| w.map(|w| w.id))
.collect();
assert_eq!(ids, [Some(4), Some(3), Some(5), Some(2), Some(6)]);
}
#[test]
fn without_a_maximized_window_the_first_visible_entry_is_none() {
fresh();
let workspace = workspace_of(&[1]);
let ids: Vec<Option<u32>> = workspace
.visible_windows()
.iter()
.map(|w| w.map(|w| w.id))
.collect();
assert_eq!(ids, [None, Some(1)]);
}
#[test]
fn only_the_default_layouts_are_the_scrolling_layout_when_it_is_scrolling() {
fresh();
let mut workspace = workspace_of(&[1]);
assert!(!workspace.is_scrolling());
workspace.layout = Layout::Default(DefaultLayout::Scrolling);
assert!(workspace.is_scrolling());
}
#[test]
fn a_placement_rule_that_matches_the_window_decides_where_it_goes() {
use komorebi_config::placement::InitialWindowPlacementRules;
fresh();
let rules = |json: serde_json::Value| -> InitialWindowPlacementRules {
serde_json::from_value(json).unwrap()
};
let single = serde_json::json!({ "Last": { "kind": "Exe", "id": "exe9" } });
let many = serde_json::json!({ "Last": [{ "kind": "Exe", "id": "other" }, { "kind": "Exe", "id": "exe9" }] });
let secondary = serde_json::json!({ "Secondary": { "kind": "Exe", "id": "exe9" } });
for (json, expected) in [(single, 3), (many, 3), (secondary, 1)] {
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(0);
workspace.initial_window_placement_rules = Some(rules(json.clone()));
// no rule matches this window: after the focused container
assert_eq!(workspace.resolve_placement_index(&w(9)), 1, "{json}");
set_match_id("exe9");
assert_eq!(workspace.resolve_placement_index(&w(9)), expected, "{json}");
fresh();
}
}
#[test]
fn the_hooks_a_platform_does_not_override_do_nothing_to_the_workspace() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.floating_windows_mut().push_back(w(5));
workspace.floating_windows_mut().push_back(w(6));
workspace.focus_floating_window(1);
// the stub overrides after_floating_removed only to log: the focus index is the workspace's
// own business, and the default platform of the other tests keeps it
workspace.remove_floating_window(6);
assert_eq!(workspace.focused_floating_window_idx(), 1);
}
#[test]
fn the_json_keys_of_a_default_workspace_are_the_ones_every_daemon_prints() {
fresh();
let value = serde_json::to_value(Workspace::<StubPlatform>::default()).unwrap();
let mut keys: Vec<&str> = value
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
keys.sort_unstable();
assert_eq!(
keys,
[
"apply_window_based_work_area_offset",
"container_padding",
"containers",
"float_override",
"floating_layer_behaviour",
"floating_windows",
"latest_layout",
"layer",
"layout",
"layout_flip",
"layout_options",
"layout_options_rules",
"layout_rules",
"maximized_window",
"monocle_container",
"name",
"resize_dimensions",
"tile",
"wallpaper",
"window_container_behaviour",
"window_container_behaviour_rules",
"work_area_offset",
"work_area_offset_rules",
"workspace_padding",
]
);
}
@@ -0,0 +1,534 @@
//! Characterization of the windows a workspace keeps outside its tiles (the monocle container, the
//! maximized window, the floating windows), the layer the focus commands act on, and hiding.
mod common;
use common::*;
use komorebi_core::Container;
use komorebi_core::Workspace;
use komorebi_core::WorkspaceLayer;
use komorebi_layouts::CycleDirection;
fn w(id: u32) -> StubWindow {
StubWindow { id }
}
// ---- monocle ----------------------------------------------------------------------------------
#[test]
fn toggling_monocle_takes_the_focused_container_out_and_remembers_its_index() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(1);
workspace.new_monocle_container().unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![3]]);
assert_eq!(
workspace.monocle_container.as_ref().unwrap().windows()[0].id,
2
);
assert_eq!(workspace.monocle_container_restore_idx, Some(1));
// the focus goes to the container before the index it was taken from
assert_eq!(workspace.focused_container_idx(), 0);
}
#[test]
fn toggling_monocle_loads_the_stack_it_took_at_the_hide_spot() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.state.spot = 8;
workspace.containers_mut()[1].add_window(w(3), 8).unwrap();
log();
workspace.new_monocle_container().unwrap();
assert_eq!(log(), ["hide_stacked 2 @8", "restore_stacked 3"]);
}
#[test]
fn monocle_on_an_empty_workspace_is_an_error_and_sets_nothing() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
assert!(workspace.new_monocle_container().is_err());
assert!(workspace.monocle_container.is_none());
assert_eq!(workspace.monocle_container_restore_idx, None);
}
#[test]
fn monocle_leaves_the_resize_adjustments_alone_so_the_container_returns_at_its_size() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.resize_dimensions = vec![None, None];
workspace.new_monocle_container().unwrap();
assert_eq!(workspace.resize_dimensions.len(), 2);
}
#[test]
fn reintegrating_monocle_puts_the_container_back_at_its_index_and_focuses_it() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(1);
workspace.new_monocle_container().unwrap();
log();
workspace.reintegrate_monocle_container().unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![2], vec![3]]);
assert_eq!(workspace.focused_container_idx(), 1);
assert!(workspace.monocle_container.is_none());
assert_eq!(workspace.monocle_container_restore_idx, None);
assert_eq!(log(), ["restore_stacked 2"]);
}
#[test]
fn reintegrating_without_monocle_is_an_error() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
assert!(workspace.reintegrate_monocle_container().is_err());
assert_eq!(workspace.containers().len(), 2);
}
#[test]
fn reintegrating_at_an_index_past_the_end_pads_with_empty_containers() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(2);
workspace.new_monocle_container().unwrap();
// the other containers went away while it was monocle
workspace.containers_mut().truncate(1);
workspace.reintegrate_monocle_container().unwrap();
// restore index 2 with one container: one empty container pads the gap
assert_eq!(layout_of(&workspace), [vec![1], vec![], vec![3]]);
assert_eq!(workspace.focused_container_idx(), 2);
}
#[test]
fn cycling_monocle_hands_the_monocle_to_the_next_container_and_wraps() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(2);
workspace.new_monocle_container().unwrap();
workspace
.cycle_monocle_container(CycleDirection::Next)
.unwrap();
// 3 went back at index 2 and focus moved to the next after it, wrapping to 0
assert_eq!(
workspace.monocle_container.as_ref().unwrap().windows()[0].id,
1
);
assert_eq!(layout_of(&workspace), [vec![2], vec![3]]);
assert_eq!(workspace.monocle_container_restore_idx, Some(0));
}
#[test]
fn cycling_monocle_with_no_other_container_leaves_the_workspace_as_it_is() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.new_monocle_container().unwrap();
workspace
.cycle_monocle_container(CycleDirection::Next)
.unwrap();
assert!(workspace.monocle_container.is_some());
assert!(workspace.containers().is_empty());
}
#[test]
fn monocle_and_maximized_windows_are_reported_for_the_focused_window() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
assert!(workspace.is_focused_window_monocle_or_maximized().is_err());
set_foreground(Some(1));
assert!(!workspace.is_focused_window_monocle_or_maximized().unwrap());
workspace.monocle_container = Some(container_of(&[1]));
assert!(workspace.is_focused_window_monocle_or_maximized().unwrap());
workspace.monocle_container = None;
workspace.maximized_window = Some(w(1));
assert!(workspace.is_focused_window_monocle_or_maximized().unwrap());
}
// ---- floating windows -------------------------------------------------------------------------
#[test]
fn floating_the_focused_window_of_a_stack_leaves_the_container_with_its_other_windows() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.state.spot = 2;
workspace.containers_mut()[1].add_window(w(3), 2).unwrap();
log();
workspace.new_floating_window().unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![2]]);
assert_eq!(workspace.floating_windows().len(), 1);
assert_eq!(workspace.floating_windows()[0].id, 3);
assert_eq!(log(), ["restore_stacked 2"]);
}
#[test]
fn floating_the_only_window_of_the_last_container_focuses_the_new_last_container() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.new_floating_window().unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![2]]);
assert_eq!(workspace.focused_container_idx(), 1);
}
#[test]
fn floating_the_only_window_of_a_middle_container_keeps_the_focus_index() {
fresh();
let mut workspace = workspace_of(&[1, 2, 3]);
workspace.focus_container(1);
workspace.new_floating_window().unwrap();
assert_eq!(layout_of(&workspace), [vec![1], vec![3]]);
assert_eq!(workspace.focused_container_idx(), 1);
assert_eq!(log(), ["note_scrolling_departure 1"]);
}
#[test]
fn floating_the_maximized_window_unmaximizes_it_first_and_clears_the_maximized_state() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.maximized_window = Some(w(4));
workspace.maximized_window_restore_idx = Some(0);
workspace.new_floating_window().unwrap();
assert_eq!(log(), ["unmaximize 4"]);
assert!(workspace.maximized_window.is_none());
assert_eq!(workspace.maximized_window_restore_idx, None);
assert_eq!(workspace.floating_windows()[0].id, 4);
assert_eq!(workspace.containers().len(), 1);
}
#[test]
fn a_maximized_window_that_cannot_be_unmaximized_stays_maximized() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.maximized_window = Some(w(4));
fail("unmaximize 4");
assert!(workspace.new_floating_window().is_err());
assert!(workspace.maximized_window.is_some());
assert!(workspace.floating_windows().is_empty());
}
#[test]
fn floating_the_monocle_window_drops_an_emptied_monocle_container() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.monocle_container = Some(container_of(&[5]));
workspace.monocle_container_restore_idx = Some(0);
workspace.new_floating_window().unwrap();
assert!(workspace.monocle_container.is_none());
assert_eq!(workspace.monocle_container_restore_idx, None);
assert_eq!(workspace.floating_windows()[0].id, 5);
}
#[test]
fn floating_the_monocle_window_of_a_stack_keeps_the_monocle_and_shows_the_next() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.monocle_container = Some(container_of(&[5, 6]));
log();
workspace.new_floating_window().unwrap();
assert_eq!(
workspace
.monocle_container
.as_ref()
.unwrap()
.windows()
.len(),
1
);
assert_eq!(log(), ["restore_stacked 5"]);
}
#[test]
fn floating_with_nothing_to_float_is_an_error() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
assert!(workspace.new_floating_window().is_err());
}
#[test]
fn a_floating_window_is_removed_by_id_and_the_hook_runs_before_it_goes() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.floating_windows_mut().push_back(w(7));
workspace.floating_windows_mut().push_back(w(8));
let removed = workspace.remove_floating_window(8).unwrap();
assert_eq!(removed.id, 8);
assert_eq!(log(), ["after_floating_removed len=2 focus=0"]);
assert!(workspace.remove_floating_window(8).is_none());
// nothing is logged for a window that is not there
assert!(log().is_empty());
}
#[test]
fn the_focused_floating_window_is_the_one_the_platform_says_has_the_focus() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.floating_windows_mut().push_back(w(7));
assert!(workspace.remove_focused_floating_window().is_none());
set_foreground(Some(7));
assert_eq!(workspace.remove_focused_floating_window().unwrap().id, 7);
}
#[test]
fn a_floating_window_returns_to_the_layout_in_a_container_at_the_focused_index() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.focus_container(0);
workspace.floating_windows_mut().push_back(w(7));
set_foreground(Some(7));
workspace.new_container_for_floating_window().unwrap();
assert_eq!(layout_of(&workspace), [vec![7], vec![1], vec![2]]);
assert_eq!(workspace.focused_container_idx(), 0);
assert!(workspace.floating_windows().is_empty());
}
#[test]
fn a_window_that_is_not_floating_cannot_return_to_the_layout() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
set_foreground(Some(1));
assert!(workspace.new_container_for_floating_window().is_err());
assert_eq!(workspace.containers().len(), 2);
}
#[test]
fn the_floating_focus_moves_to_the_previous_window_and_stops_at_the_first() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
for id in [1, 2, 3] {
workspace.floating_windows_mut().push_back(w(id));
}
workspace.focus_floating_window(2);
workspace.focus_previous_floating_window();
assert_eq!(workspace.focused_floating_window_idx(), 1);
workspace.focus_previous_floating_window();
workspace.focus_previous_floating_window();
assert_eq!(workspace.focused_floating_window_idx(), 0);
assert_eq!(workspace.focused_floating_window().map(|w| w.id), Some(1));
}
// ---- layer ------------------------------------------------------------------------------------
#[test]
fn a_workspace_starts_on_its_tiling_layer() {
let workspace = Workspace::<StubPlatform>::default();
assert_eq!(workspace.layer, WorkspaceLayer::Tiling);
}
#[test]
fn the_layers_are_named_tiling_and_floating_in_text_and_json() {
assert_eq!(WorkspaceLayer::Tiling.to_string(), "Tiling");
assert_eq!(WorkspaceLayer::Floating.to_string(), "Floating");
assert_eq!(
serde_json::to_string(&WorkspaceLayer::Floating).unwrap(),
"\"Floating\""
);
assert_eq!(
serde_json::from_str::<WorkspaceLayer>("\"Tiling\"").unwrap(),
WorkspaceLayer::Tiling
);
}
#[test]
fn the_layer_is_a_field_of_the_workspace_that_the_shared_code_never_changes() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.layer = WorkspaceLayer::Floating;
workspace.new_floating_window().unwrap();
workspace.new_container_for_window(w(9)).unwrap();
workspace.new_monocle_container().unwrap();
workspace.reintegrate_monocle_container().unwrap();
assert_eq!(workspace.layer, WorkspaceLayer::Floating);
}
// ---- hiding -----------------------------------------------------------------------------------
#[test]
fn hiding_a_workspace_goes_floating_then_containers_then_maximized_then_monocle() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.state.spot = 3;
workspace.containers_mut()[0].add_window(w(5), 3).unwrap();
workspace.floating_windows_mut().push_back(w(7));
workspace.floating_windows_mut().push_back(w(8));
workspace.maximized_window = Some(w(9));
workspace.monocle_container = Some(container_of(&[10, 11]));
log();
workspace.hide(None).unwrap();
// floating windows from the back at the window spot; the containers at the display spot, each
// from its last window; the maximized window at the window spot; the monocle container at the
// display spot
assert_eq!(
log(),
[
"hide 8 @3",
"hide 7 @3",
"before_hide_containers",
"hide 5 @103",
"hide 1 @103",
"hide 2 @103",
"hide 9 @3",
"hide 11 @103",
"hide 10 @103",
]
);
}
#[test]
fn hiding_but_one_window_spares_it_in_a_container_the_floating_layer_and_the_monocle() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.floating_windows_mut().push_back(w(7));
workspace.monocle_container = Some(container_of(&[10]));
log();
workspace.hide(Some(2)).unwrap();
assert_eq!(
log(),
[
"hide 7 @0",
"before_hide_containers",
"hide 1 @100",
"hide 10 @100"
]
);
workspace.hide(Some(7)).unwrap();
assert_eq!(
log(),
[
"before_hide_containers",
"hide 1 @100",
"hide 2 @100",
"hide 10 @100"
]
);
}
#[test]
fn a_floating_window_that_will_not_hide_is_skipped_and_the_rest_are_hidden() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.floating_windows_mut().push_back(w(7));
fail("hide 7");
log();
assert!(workspace.hide(None).is_ok());
assert_eq!(
log(),
["hide 7 @0", "before_hide_containers", "hide 1 @100"]
);
}
#[test]
fn a_container_window_that_will_not_hide_is_skipped_and_the_rest_are_hidden() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
fail("hide 2");
log();
assert!(workspace.hide(None).is_ok());
assert_eq!(
log(),
["before_hide_containers", "hide 1 @100", "hide 2 @100"]
);
}
#[test]
fn a_maximized_window_that_will_not_hide_is_an_error_and_the_monocle_is_not_reached() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.maximized_window = Some(w(9));
workspace.monocle_container = Some(container_of(&[10]));
fail("hide 9");
log();
assert!(workspace.hide(None).is_err());
assert_eq!(
log(),
["before_hide_containers", "hide 1 @100", "hide 9 @0"]
);
}
#[test]
fn restoring_the_focused_container_shows_only_its_front_window() {
fresh();
let mut workspace = workspace_of(&[1, 2]);
workspace.containers_mut()[1].add_window(w(3), 0).unwrap();
log();
workspace.focused_container().unwrap().restore().unwrap();
assert_eq!(log(), ["restore 3"]);
}
#[test]
fn an_empty_container_among_the_containers_is_hidden_without_a_call() {
fresh();
let mut workspace = workspace_of(&[1]);
workspace.containers_mut().push_back(Container::default());
log();
workspace.hide(None).unwrap();
assert_eq!(log(), ["before_hide_containers", "hide 1 @100"]);
}
#[test]
fn the_floating_removal_hook_runs_before_the_window_is_taken_out() {
fresh();
let mut workspace = Workspace::<StubPlatform>::default();
workspace.floating_windows_mut().push_back(w(1));
workspace.floating_windows_mut().push_back(w(2));
workspace.focus_floating_window(1);
assert_eq!(workspace.remove_floating_window(2).map(|w| w.id), Some(2));
// pins today's order (the KDE and macOS order): the hook sees both windows and the old
// focus, although the trait doc says "after a floating window was taken out"
assert_eq!(log(), ["after_floating_removed len=2 focus=1"]);
}
+134
View File
@@ -0,0 +1,134 @@
# komorebi after the consolidation: a map of the repository
Status (wip-cand4): current map. Windows, KDE Plasma and macOS build from one workspace and one
`komorebi`, one `komorebic`, one `komorebi-client` and one `komorebi-bar` package, the platform chosen by
`cfg(target_os)`. The cutover (shim packages, one flake, final directories, one version number) is not done;
section 6 lists what is still old. macOS has only been type-checked on Linux and compiled/unit-tested on a
Mac Mini; no macOS daemon behaviour has been observed.
How to build and test: [build-and-test.md](build-and-test.md). Why things are shaped as they are:
[seam.md](seam.md) (the `Backend` trait), [core-model.md](core-model.md) (the shared model),
[settings.md](settings.md), [unified-binaries.md](unified-binaries.md), [bar-unification.md](bar-unification.md),
[backend-switch.md](backend-switch.md). What a person with a Mac has to check: [macos-handcheck.md](macos-handcheck.md).
## 1. Three platform trees, one workspace
The root `Cargo.toml` is the only workspace. It has members in three places:
| Tree | What is in it | Platform |
|---|---|---|
| the repository root (`komorebi/`, `komorebi-bar/`, `komorebic/`, ...) | the Windows daemon library, the unified packages, the Windows-only tools (`komorebi-gui`, `komorebi-shortcuts`, `komorebic-no-console`), `komorebi-layouts`, `komorebi-scrolling`, `komorebi-themes`, `e2e/`, `wix/` | Windows (the original) |
| `komorebi-for-kde/` | the KDE daemon library `komorebi-linux` (`komorebi/`), `komorebi-hotkeys/`, the `version-linux` crate, the NixOS module, the VM test suites (`nix/tests/vm`), KDE docs (`docs/dev`) | Linux, KDE Plasma on KWin (Wayland) |
| `komorebi-for-mac/` | the macOS daemon library `komorebi-macos` (`komorebi/`), the `version-macos` crate, the nix darwin module, macOS docs | macOS |
`komorebi-for-kde/` and `komorebi-for-mac/` still have their own flakes, `justfile`s and docs; the root flake
imports them as `kfde-*` and `kfm-*` (section 5). They have no `Cargo.toml` workspace of their own any more:
`cargo` run inside them uses the root one.
## 2. The packages (what a user runs)
| Package (binary) | Directory | How the platform is chosen |
|---|---|---|
| `komorebi` (`komorebi`) | `komorebi-daemon/` | `src/main.rs` is a `cfg_select!` that calls `daemon::run()` of the library of the target OS; the libraries are target-gated dependencies in `Cargo.toml` |
| `komorebic` (`komorebic`) | `komorebic/` | `src/windows.rs`, `src/linux/`, `src/macos/`, one `cfg` per target; the arguments are in `crates/komorebic-core` |
| `komorebi-client` (library) | `komorebi-client/` | `src/windows.rs`, `src/linux.rs`, `src/macos.rs` re-export the daemon library of the target OS behind one `Connection` |
| `komorebi-bar` (`komorebi-bar`) | `komorebi-bar/` | `src/windows/` and `src/macos/` modules; shared code in `crates/komorebi-bar-core`. **KDE has no bar** |
The daemon libraries are `komorebi-windows` (`komorebi/`), `komorebi-linux` (`komorebi-for-kde/komorebi/`) and
`komorebi-macos` (`komorebi-for-mac/komorebi/`). They have no binary: each has a `daemon.rs` with
`run()`, the old `main`. `-p komorebi-windows` etc. still build, as libraries.
Shim packages exist until the cutover (each is a `#[path]` include of the unified module, same binary
name): `komorebic-linux`, `komorebic-macos`, `komorebi-client-linux`, `komorebi-client-macos`,
`komorebi-bar-macos`. Never build `komorebic` together with `komorebic-linux` or `komorebic-macos`: the
binary name is the same.
## 3. The shared crates (`crates/`)
| Crate | What it holds | Used by |
|---|---|---|
| `komorebi-protocol` | the wire types: `SocketMessage` and payloads; per-platform goldens in `tests/golden/` | daemons, client, komorebic |
| `komorebi-config` | the `komorebi.json` types (`StaticConfig` and what it is made of) and schema generation | daemons, komorebic |
| `komorebi-collections` | `Ring`, `LockableSequence` | the three daemons |
| `komorebi-transport` | the command transport: pause filter, listener, subscriber registry | the three daemons |
| `komorebi-backend` | the `Backend` trait (what a daemon asks of its platform), `WindowId`, plain-data infos, `FakeBackend`, the contract tests every backend must pass | daemons; Windows goes through it for the clusters in backend-switch.md |
| `komorebi-core` | the shared model, generic over the platform window: `Container<W>`, `Monitor<P>`, `Workspace<P>` with `update_shared`, `WorkspaceGlobals`. `WindowManager<P>` is not shared yet | the three daemons |
| `komorebi-settings` | the settings a daemon reads at run time as one immutable snapshot, instead of process-wide statics | the three daemons |
| `komorebi-bar-core` | the bar's configuration, widgets and platform seam | `komorebi-bar` |
| `komorebic-core` | the command line definitions of every platform (`cli`, `docgen`, `platform::{windows,macos,...}`) | `komorebic` |
Also shared by path from the Windows tree: `komorebi-layouts`, `komorebi-scrolling`, `komorebi-themes`.
## 4. Where the platforms differ on purpose
These are intentional, not leftovers; before "unifying" one, read the document named.
- Window system and hiding: Win32 (cloaking, own border windows, DWM animations), KWin (a JavaScript
bridge loaded into KWin, desktops as workspaces, parking desktop), AppKit/Accessibility (own `NSWindow`
borders). `komorebi-backend` is the seam; the rules and what each platform keeps are in [seam.md](seam.md).
- The model: `Container`, `Monitor`, `Workspace` are shared; `WindowManager`, the command router and event
processing are still per platform, with the blockers listed in [core-model.md](core-model.md) sections 17
and 18.
- Settings: [settings.md](settings.md) says which process-wide statics became snapshot fields and which
remain.
- Packaging: [unified-binaries.md](unified-binaries.md): library per OS, one binary; `cfg(target_os)`, not
features.
- The bar: [bar-unification.md](bar-unification.md): one package, one module per OS; rendering code differs
(frame margins, `network.rs`, window seams) and B4 (merging it) was not done.
- Command line: each platform keeps its help text and its own commands (Windows 34, KDE 2, macOS 1 are
platform-only; most are common). `komorebic` pages in `docs/cli` of each tree are the oracle.
- macOS: everything except compile and unit tests is unverified; [macos-handcheck.md](macos-handcheck.md).
- KDE: no bar; hotkeys through `komorebi-hotkeys` and exported KDE shortcuts; the module is NixOS.
- Windows: the e2e under QEMU (`e2e/`), `komorebi-gui`, `komorebi-shortcuts`, `komorebic-no-console`, wix.
## 5. The oracles (what stops a refactor from changing behaviour silently)
| Oracle | Where | Detects | Run by |
|---|---|---|---|
| Wire goldens | `crates/komorebi-protocol/tests/golden*` | a change of what each daemon sends or accepts on the socket | `cargo test -p komorebi-protocol` |
| Config schemas | `schema.json`, `schema.asc.json` of the three trees; `crates/komorebi-config/tests/schemas.rs`; KDE `komorebi/tests/schemas.rs` | a changed key of `komorebi.json` | `cargo test -p komorebi-config` (KDE: `-p komorebi-linux --test schemas -- --test-threads=1`) |
| Bar schema views | `schema.bar.json` (Windows), `komorebi-for-mac/schema.bar.json`; `crates/komorebi-bar-core/tests/schema_oracle.rs` pins size and hash; `komorebi-bar --schema` prints the view of the target OS | a changed bar configuration | `cargo test -p komorebi-bar-core`; Windows e2e scenario `bar` compares `--schema` byte for byte |
| CLI docs | `docs/cli` of each tree; `crates/komorebic-core/tests/docs_cli.rs` and `platforms.rs` | a changed subcommand or help text | `cargo test -p komorebic-core`; `komorebic docgen --output DIR` regenerates |
| Schema docs completeness | `check_schema_docs.py` (root) | schema entries with no description | by hand |
| Drift of derivations | `nix eval .#packages.x86_64-linux.default.drvPath` and the check derivations | an unintended change of what nix builds | by hand (see build-and-test.md) |
| Backend contract | `komorebi-backend/src/contract.rs` | a backend that breaks a rule of the trait | `cargo test -p komorebi-backend` and each daemon's tests |
| Runtime | Windows e2e (QEMU), KDE VM suites | real behaviour | tier 3 below |
Windows `docs/cli` was found stale against the binary in the step-4 measurement (see the progress notes,
decision D20); regenerate before treating it as an oracle.
## 6. What is still the old layout (cutover list)
Shim packages and their directories under `komorebi-for-kde/` and `komorebi-for-mac/`; `version-linux` and
`version-macos`; three flakes (the root one imports the other two as `kfde-*` and `kfm-*`); three `deny.toml`;
three version numbers (Windows libraries and packages 0.1.42, KDE 0.1.0, macOS library 0.1.1 and its `version` crate 0.1.0). Some docs still describe the old layout; those that were
found wrong have been corrected, [COMPARE.md](../../komorebi-for-kde/docs/dev/COMPARE.md) is marked stale.
`komorebi-for-kde/justfile` still has recipes written for a KDE-only workspace (`just check` runs
`cargo test --workspace`, which on Linux would build the Windows crates): use the commands in
build-and-test.md.
## 7. Feedback loops, from cheap to expensive
| Tier | What | Time | How |
|---|---|---|---|
| 0 | docs and links | none | nothing builds; a docs-only commit leaves every nix check a cache hit, except text under `komorebi-for-kde/` and `komorebi-for-mac/`, which are inputs of their derivations |
| 1 | native Linux: `cargo check/test` of the shared crates and the KDE daemon | seconds to minutes | build-and-test.md, section 2 |
| 2 | cross-compile and nix checks: Windows clippy, macOS type-check with a fake C compiler, KDE non-VM checks, schema and CLI oracles | minutes | build-and-test.md, sections 1 and 3 |
| 3 | e2e: Windows QEMU scenarios, KDE VM suites (`fast`, `slow`) | tens of minutes, batched | build-and-test.md, sections 4 and 5 |
| 4 | a real Mac | by hand | macos-handcheck.md |
### The helper tools (outside the repository)
The agents that did the consolidation used scripts that live outside the repository, in
`/home/jado/komomono-work/tools` on the build host. They are not part of the repository. Proposal, not
done: commit the ones that encode project knowledge under `scripts/dev/`, and leave the host-specific ones out.
| Tool | What it does | Worth committing? |
|---|---|---|
| `fast-check` (+ its README) | runs only the checks that the touched paths need (tier 1 and 2), with persistent target dirs | yes: it is the quickest way to get the right gate for a change; needs its scratch paths made configurable (`FAST_CHECK_SCRATCH`, already an env var) |
| `mac-check.sh` | macOS type-check through a fake C compiler | yes, merged into `fast-check` (it has hard-coded paths to a workspace) |
| `kde-closure-check` | fails when `komorebi-for-kde/nix/root-crates.json` and the KDE cargo closure differ | yes: it protects the KDE source filter; run after any dependency change in the KDE tree or the crates it uses |
| `lite-env` | env vars for builds without debug info | optional (one `.env` file) |
| `gate-lock` | host-wide FIFO lock so heavy gates and timing-sensitive e2e do not overlap | host policy; commit only if more than one person shares a build host |
| `e2e-needed` | says whether a diff touches anything the Windows e2e binaries are built from (decides whether the e2e gate is owed) | yes, next to `fast-check` |
| `host-sample`, `jitter-probe`, `trim-target`, `mini` | measurement and housekeeping for this host (`mini` is an SSH wrapper for one Mac Mini) | no |
+2
View File
@@ -1,5 +1,7 @@
# Windows: which call sites go through `backend()`
> **Status (wip-cand4):** in progress. The clusters in "Switched" are landed (each BEHAVIOUR, e2e-gated); the rest is deliberately left on `WindowsApi`, see the two "not switched" tables; nothing here is planned further until `WindowManager<P>` ([core-model.md](core-model.md) section 18).
Step 8 of the unified-binaries plan. `komorebi::windows_backend::backend()` returns the shared
`komorebi_backend::Backend` (a stateless `WindowsBackend` over `WindowsApi` and `Window`). The daemon
is switched one cluster at a time; each switch is its own revision marked BEHAVIOUR.
+2
View File
@@ -1,5 +1,7 @@
# Windows e2e for komorebi-bar
> **Status (wip-cand4):** current; the `bar` scenario exists and is the runtime gate for `komorebi-bar` and `komorebi-bar-core` on Windows.
The `bar` scenario (`e2e/platforms/qemu_windows/extras/bar.py`, registered as `EXTRAS["bar"]` in
`run.py`) is the runtime gate for changes to `komorebi-bar` and `komorebi-bar-core`: the unit tests
and the schema oracle cannot run the bar. Run it on the golden Windows guest:
+2
View File
@@ -1,5 +1,7 @@
# One `komorebi-bar` for Windows and macOS
> **Status (wip-cand4):** B0-B3 done (one `komorebi-bar` package, a module per platform, schema views); B4 (merging the rendering code) not done and cannot be shown mechanical without a screen; macOS bar never rendered by these changes.
Status at the revision that adds this file. Everything below was measured on this tree with
`diff` (counts are lines that differ, `<`/`>` lines of `diff`, hunks in parentheses). Nothing
here was rendered: the bars cannot run on Linux. Gates that did run are named; the ones that
+231
View File
@@ -0,0 +1,231 @@
# Build and test, per platform
Status (wip-cand4): current. Every command below was read from `flake.nix`, the justfiles, the Cargo
manifests or the e2e README; the ones marked "ran" were run on the Linux host at this revision (cheap checks
only: `cargo metadata --no-deps`, `cargo check -p komorebi-linux -p komorebi -p komorebic` in
`komorebi-for-kde/`). Everything else, including every nix build, e2e and VM run, is documented but was not
run for this page. macOS cannot be built or run on Linux; Linux can only type-check it.
The map of the repository is [ARCHITECTURE-UNIFIED.md](ARCHITECTURE-UNIFIED.md). Package names in this
repository (`cargo metadata --no-deps`, ran): `komorebi` (the daemon, `komorebi-daemon/`), `komorebic`,
`komorebi-client`, `komorebi-bar`, the libraries `komorebi-windows`, `komorebi-linux`, `komorebi-macos`, the
shims `komorebic-linux`, `komorebic-macos`, `komorebi-client-linux`, `komorebi-client-macos`,
`komorebi-bar-macos`, and `komorebi-backend`, `-bar-core`, `komorebic-core`, `-collections`, `-config`,
`-core`, `-protocol`, `-settings`, `-transport`.
## 0. General rules
- Platform is chosen by `cfg(target_os)`: `cargo build -p komorebi -p komorebic -p komorebi-bar` builds the
program of the OS you are on. The Windows daemon is only buildable for the Windows target (cross build in
section 1); on Linux `-p komorebi` is the KDE daemon, on macOS the macOS one.
- Never put `komorebic` and `komorebic-linux`/`komorebic-macos` in one command (same binary name). The shims
stay until the cutover.
- Without a `.git` (a jj workspace) the build script of the macOS and KDE trees needs `COMMIT_HASH=dev`; the
`nix flake check --no-build` command fails with `attribute 'dirtyRev' missing` for the same reason. Do not run
`nix flake check` on the root flake at all (it builds the VM suites); name the check.
- Text edits under `komorebi-for-kde/` and `komorebi-for-mac/` change those trees' nix derivations (they are
inputs); a docs-only edit elsewhere does not, because the commit stamp is a constant in the checks
(`COMMIT_HASH=nix-check`) and only `packages.default` carries the real commit.
- Heavy builds and e2e should not run at the same time as a timing-sensitive e2e: the Windows `commands`
scenario is the most sensitive (section 6).
## 1. Windows (cross build from Linux via nix)
Binaries (the flake cross-compiles to `x86_64-pc-windows-msvc` with an xwin SDK):
```sh
nix build .#komorebi .#komorebic .#komorebi-bar # result*/bin/*.exe; also komorebic-no-console, komorebi-gui, komorebi-shortcuts, komorebi-testwin
nix build .#default # komorebi-full: everything, with the real commit stamp
```
Checks (crane; the clippy one is the pre-landing gate, about 3.5 min warm deps; the dependency derivation is
shared by all of them):
```sh
nix build -L --no-link .#checks.x86_64-linux.komorebi-workspace-clippy
nix build -L --no-link .#checks.x86_64-linux.komorebi-workspace-nextest
nix build -L --no-link .#checks.x86_64-linux.komorebi-workspace-fmt .#checks.x86_64-linux.komorebi-workspace-toml-fmt .#checks.x86_64-linux.komorebi-workspace-deny
nix build -L --no-link .#checks.x86_64-linux.e2e-tests # the Python of the e2e (pytest), no guest needed
```
Quick loop without nix (what `fast-check` runs; clippy of the Windows tree from the nix dev shell):
```sh
nix develop --command cargo clippy --workspace --locked --all-targets -- -D warnings
```
On a Windows machine itself: `just build` / `just install` (the root `justfile`, PowerShell), or
`cargo build -p komorebi -p komorebic -p komorebi-bar --locked`.
Platform-neutral crates test natively on Linux, with no cross toolchain: `cargo test -p komorebi-protocol
-p komorebi-config -p komorebi-collections -p komorebi-core -p komorebi-backend -p komorebi-settings
-p komorebi-transport -p komorebic-core -p komorebi-bar-core -p komorebi-layouts -p komorebi-scrolling`.
## 2. KDE Plasma (native Linux)
From `komorebi-for-kde/` (cargo finds the root workspace; a C compiler is needed, `nix shell nixpkgs#gcc -c`
or the dev shell):
```sh
cargo check -p komorebi-linux -p komorebi -p komorebic # ran, 27 s with a warm target
cargo test -p komorebi-linux --lib # the daemon's unit tests (294 passed at the step-8 measurement)
cargo test -p komorebi-linux --test schemas -- --test-threads=1 # the schema oracle; shares a pid-only socket path, keep one thread
cargo test -p komorebi -p komorebic -p komorebi-client -p komorebi-hotkeys # daemon-binary, CLI and client tests (tests/linux_*.rs)
```
A single test file: `cargo test -p komorebi-linux --test NAME` (the files are in `komorebi-for-kde/komorebi/tests`).
The `-p komorebi --lib` that older notes use is the thin binary package now: the unit tests are in
`komorebi-linux`.
Run `tools/kde-closure-check` after any dependency change in the KDE tree or the crates it uses: the KDE
flake takes only the crates listed in `komorebi-for-kde/nix/root-crates.json`.
KDE nix checks (no VM): from the root flake they are prefixed `kfde-`, and the VM checks are left out:
```sh
nix build -L --no-link .#checks.x86_64-linux.kfde-komorebi-workspace-clippy
nix build -L --no-link .#checks.x86_64-linux.kfde-komorebi-workspace-nextest
# also kfde-komorebi-workspace-{fmt,toml-fmt,deny,doc}, kfde-nix-options-validation, kfde-nixos-module-eval,
# kfde-keybindings-fixtures, kfde-schema-fresh
nix build -L .#packages.x86_64-linux.kfde-komorebi .#packages.x86_64-linux.kfde-komorebic
```
Inside `komorebi-for-kde/` the same checks have no prefix (`nix build .#checks.x86_64-linux.NAME`).
`komorebi-for-kde/justfile` (`just check`, `just docgen`, `just jsonschema`) still assumes a KDE-only
workspace: `just check` runs `cargo test --workspace`, which would build the Windows crates on Linux. Use the
commands above; `just vm NAME` and `just nixgen` are fine.
### KDE VM suites
Each suite under `komorebi-for-kde/nix/tests/vm/suites/NAME` boots NixOS with Plasma and KWin; they need KVM
(nested is enough under WSL2; `nix run .#wsl2-probe` from `komorebi-for-kde/` measures it).
```sh
# from komorebi-for-kde/
just vm NAME # = nix build -L .#checks.x86_64-linux.vm-NAME
just vm-all # every suite in the order of the flake
# from the repository root (the VM checks are left out of the root `checks`, the suites are here)
nix build -L .#legacyPackages.x86_64-linux.kfde-vm.NAME
# from komorebi-for-kde/: the names of each tier as JSON (ran; CI reads it)
nix eval --json .#legacyPackages.x86_64-linux.vmTiers
```
Tiers (the `tier` in each suite's `default.nix`; CI runs `fast` on every pull request, `slow` on master):
- fast: `check hotplug commands kwin-restart kwin-events scrolling workspace-rules core-e2e kwin-contract kwin
workspace-switch stacks module placement user-maximize run-kde`
- slow: `client-geometry restart-survival keys-whkd core-lock keys-sxhkd render-smoke drag-resize rdp features
focus-follows-mouse latency keys-engine live-resize lock-sleep look keys-skhd keys-static wallpaper`
- `vm-lib` (a check, not a suite) runs the unit tests of the VM library; no VM boots.
To run only some steps of a suite: `E2E_ONLY=stacks,monocle nix build --impure .#checks.x86_64-linux.vm-core-e2e -L`
(from `komorebi-for-kde/`; a substring of the printed `module.function`; `KFDE_ONLY` is the old name).
To record a run: `KOMOREBI_RECORDER=$(nix build ~/komorebi-recorder#komorebi-recorder --no-link --print-out-paths)
nix build --impure .#checks.x86_64-linux.vm-core-lock -L` (the recorder's repository is private; `core-e2e` and
`core-lock` keep `recording-NAME.tar.gz`). Details, the library and how to add a suite:
[komorebi-for-kde/docs/dev/vm-tests.md](../../komorebi-for-kde/docs/dev/vm-tests.md). The suites use a daemon
built once with the constant stamp, so a new commit does not rebuild it.
## 3. macOS
On a Mac (aarch64-darwin), from the repository root (a `.git` checkout, or `COMMIT_HASH=dev` in the
environment). These are the commands for the Mac Mini; none has been run on a Mac against wip-cand4 unless
[macos-handcheck.md](macos-handcheck.md) says so:
```sh
cargo build --locked -p komorebi -p komorebic -p komorebi-bar
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
target/debug/komorebi --version # komorebi 0.1.0 (the macOS version crate)
target/debug/komorebic --help; target/debug/komorebic docgen --output /tmp/docs-mac
target/debug/komorebi-bar --schema | cmp - komorebi-for-mac/schema.bar.json
```
Never `-p komorebic-macos` together with `-p komorebic` (the shims `komorebic-macos`, `komorebi-client-macos`
and `komorebi-bar-macos` still build alone). Before any change that touches macOS code, run the unit tests on
the Mac first: nothing else can run them. After that walk [macos-handcheck.md](macos-handcheck.md).
On Linux, macOS can only be type-checked, through a fake C compiler and the target
`aarch64-apple-darwin` (`tools/fast-check` does it; it cannot link or run):
```sh
COMMIT_HASH=dev cargo check --target aarch64-apple-darwin --workspace --all-targets # with CC_aarch64_apple_darwin set to a fake cc
```
Nix, on a Mac: the checks of `komorebi-for-mac/flake.nix` (`komorebi-workspace-{clippy,fmt,toml-fmt,deny,nextest}`,
`nix-options-validation`, `darwin-module-validation`). From Linux they can be evaluated only
(`nix flake show --all-systems`, `nix eval`), which proves nothing builds. Through the root flake they are
`kfm-*`.
## 4. Windows e2e (QEMU guest)
Full text: `e2e/platforms/qemu_windows/README.md` (building the golden image, every variable). Short form:
```sh
E2E_GOLDEN=golden nix run .#e2e-windows -- OUT SCENARIO... # e.g. OUT tiling focus commands
E2E_GOLDEN=golden KOMOREBI_E2E_SCALE=1.5 nix run .#e2e-windows -- OUT bar # the komorebi-bar scenario
```
The app uses this checkout's binaries, built with the constant stamp `e2e` (so a docs-only commit reuses them);
the commit under test is `KOMOREBI_E2E_COMMIT` (default: the flake revision). To test another commit:
`build-ref.sh REF bins` then `KOMOREBI_E2E_BINS=bins ...` (`bins` needs `komorebi-bar.exe` for `bar`).
| Variable | Effect |
|---|---|
| `E2E_ONLY=word,word` | run only the steps whose printed name contains a word (a rerun of one step) |
| `KOMOREBI_E2E_LOG_LEVEL=trace` | the daemon's log level (`debug`, `trace`) |
| `KOMOREBI_E2E_RECORDER=DIR` | record with komorebi-recorder (a folder with `komorebi-recorder.exe`); comes back as `recording.zip` |
| `KOMOREBI_E2E_KEEP_GUEST=1` | keep the guest's run directory (overlay, TPM state) instead of deleting it |
| `KOMOREBI_E2E_SCALE=1.5` | every wait is 1.5 times as long, for a busy host |
| `KOMOREBI_E2E_STATE=DIR` | restore guests from a saved state (3 s instead of 50-90 s start) |
| `KOMOREBI_E2E_CAPTURE=DIR` | save raw `komorebic state` fixtures |
| `SWEEP_TWO_DISPLAYS=1` | `commands` adds a second display |
Keep output and run directories on a short path (unix socket paths are limited to about 108 bytes). Each
scenario gets its own guest (about 4 vCPU and 6 GB). Results are in `OUT/<scenario>/result.json`; trust it over
the printed line. `docs/dev/bar-e2e.md` describes the `bar` scenario.
A change to the Windows daemon or bar needs these before it is considered landed (commit types BEHAVIOUR):
`commands`, plus the scenario of the cluster named in the revision body (see backend-switch.md for the table).
## 5. What runs where (summary)
| Change touches | Run |
|---|---|
| `crates/*` (not bar/komorebic) | section 1 native crate tests, then Windows clippy (section 1), KDE (section 2) and macOS type-check (section 3) |
| `komorebi/` (Windows daemon) | Windows clippy and nextest, then e2e (section 4) |
| `komorebi-for-kde/` | section 2 cargo, then KDE checks, VM `fast` tier |
| `komorebi-for-mac/` | macOS type-check on Linux; build and tests on a Mac |
| `komorebi-bar/`, `komorebi-bar-core` | Windows clippy, `cargo test -p komorebi-bar-core`, macOS type-check, e2e `bar` |
| `komorebic*`, `komorebic-core` | `cargo test -p komorebic-core` (CLI doc oracle), all three platforms' checks |
| `*.nix`, `flake.lock` | evaluation only (`nix eval ...drvPath`) before a build |
| docs only | nothing, unless under a platform tree (see section 0) |
## 6. Known flakes
Policy: on any e2e or VM failure, check this list by check name and by log signature first; do not soak to
re-prove a known flake. Write rates as `failures/runs` with the commit and host load. A known flake needs
`baseline-seen` evidence (it occurred before the consolidation) or at least 3 occurrences with the same
signature. A name-only match gets one rerun on a calm host at `trace` with logs kept; no match gets one calm
rerun, and a second failure is a regression candidate to bisect by revision. A soak is only for a candidate
that failed twice or a flake whose rate looks more than 2x higher with at least 3 failures. Passing under
load stays a pass; failing under high load is not evidence of a regression. A full `commands` sweep takes 4
to 6 minutes, so the `E2E_ONLY` runs come first.
| Check | Platform | What is seen | Rate (from a measured set) |
|---|---|---|---|
| `commands`, daemon stops answering `komorebic state` | Windows | the daemon logs nothing from any thread for 3 to 3.6 s after answering `State`; the reply write hits a closed socket (`os error 10054`); `border manager: stuck for ~3000 ms in locking the window manager`; `could not acquire window manager lock`. Cause not found (host I/O stalls are a candidate) | 1/10 sweeps before the consolidation, 1/12 after; probe 0.35% vs 0.39% of calls |
| `lifecycle_hidden` (monocle after crash) | Windows | no signature captured (capture at `trace` next time) | 1/10 before, 2/12 after |
| `resize` (drag checks `win2:bottomleft`, `win3:top`) | Windows | drag checks fail, pass on rerun; documented as flaky | 1 failure in the first run, passed twice |
| daemon does not start (`failed call to AllowSetForegroundWindow after 5 retries`) | Windows | the scenario prints "did not run, counted as 1 failed", no `result.json`; only seen at load 6.6-8 | candidate, 4/~45 starts at that load vs 0/~150 at load 3-5 |
| `hotplug` with the recorder on (`AgentLost ... during exec tasklist`) | Windows | after the display unplug, in the recorder collection step; the rerun passed | candidate, 1 occurrence |
| `maximizing.user`, `placement` (integer case), `unknown_monitor` (2) | Windows | not flakes: the same 4 checks fail on every commit (stale known-failure markers) | fix or re-mark them |
| `focus_follows_mouse` "did not run" | Windows | reporting quirk of the runner, `result.json` says 15/0 | ignore the line |
| `vm-commands`, `vm-core-e2e` | KDE | `commands.py` (guest D-Bus stops replying, BrokenPipe), `handover.py` ("win3 is inside the work area and not on a tile"), `lifecycle_hidden.py`, `manage_rules.py` (window never appeared, 30 s), `core_e2e.py` (KWin script never reported in) | 0 green in 6 runs before the consolidation at host load 25 to 190; load-dependent is plausible, not shown; no gate decision until one calm-host run exists |
| `golden` test of `komorebi-protocol` | native | "5 passed; 1 failed" once, six reruns passed, text not captured | 1 occurrence; keep the text if it recurs |
| KDE `tests/schemas.rs` | native | shares a pid-only socket path | keep `--test-threads=1` |
Observed rates are consistent with a wide range: 1 failure in 10 runs fits anything from about 0.3% to 45% per
run. Quote the counts, not "flaky". The source registry of the consolidation runs (with commits and logs) is
kept by whoever runs the gates; add new occurrences there and update this table when a rate changes.
+16 -1
View File
@@ -1,5 +1,7 @@
# The core model: KDE and Windows compared, and the split into `komorebi-core`
> **Status (wip-cand4):** measurement plus a running log. `komorebi-core` has `Container`, `Monitor`, `Workspace` (incl. `update_shared`) over KDE, Windows and macOS; `WindowManager<P>`, the router and `process_event` are NOT shared yet (sections 17 and 18 give the blockers); sections 8 and 12 are the designs that were then implemented.
Status: measurement and proposal (plan step 9 preparation, KDE side). Measured at the tip of
`wip-u-kfde` (based on `wip-main` 633e7453); the Windows tree is `komorebi/src`, KDE is
`komorebi-for-kde/komorebi/src`, macOS (`komorebi-for-mac/komorebi/src`) is listed only where it
@@ -1122,7 +1124,7 @@ compiles unchanged; the defaults of the ones a daemon must provide return an err
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.
its `?`); the Windows title-bar tables were first read once per container instead of once per pass, which was a regression, not an improvement: section 19 (the `begin_pass` hook) takes them once per pass again.
**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
@@ -1302,3 +1304,16 @@ Recommended next step: shared text first between KDE and macOS (kfm and kfde), w
functions and most router arms are already identical, then Windows converges onto it function by
function against the blocker list above; creating `WindowManager<P>` before blockers 1 to 3 are decided
would move less than half of the file.
## 19. Corrections after the review of `komorebi-core` (findings F2 and F3)
- **F2, the floating-window hook.** `Workspace::remove_floating_window` calls the hook before it takes the
window out of the ring (the KDE and macOS originals move the focus first, and the focus index moves
back by one whatever the length), so the hook is `before_floating_removed`, not `after_floating_removed`
as sections 8 to 11 call it. Behaviour is unchanged; a test pins the order.
- **F3, the title-bar snapshot.** The original Windows `update` read `REMOVE_TITLEBARS`, `NO_TITLEBAR` and
`REGEX_IDENTIFIERS` once per placement pass; the first Windows `place_container` read them per container,
so a configuration reload in the middle of a pass could give two containers two tables (section 16
wrongly called this an improvement). `WorkspacePlatform::begin_pass` is called once per pass after the
layout is computed and its answer reaches the hooks as `Placement::pass`; Windows takes the snapshot
there and `place_container` reads it, as the original did.
+70
View File
@@ -1,5 +1,7 @@
# macOS hand-check list
> **Status (wip-cand4):** OPEN, for the user on a real Mac; only compile and unit tests have run on a Mac Mini, no macOS daemon behaviour has been observed; commands for the Mac are in [build-and-test.md](build-and-test.md).
Status: written by the `kfm` agent for the user, 2026-10-31. Nothing here has been run: macOS cannot be built, linked or tested on the Linux host, only type-checked through a fake C compiler (`tools/fast-check`). Every revision below is `type-checks, not run`. Revision ids are jj change ids (stable) with the commit id they had when this was written (commit ids change when a revision is rewritten; use `jj log -r <change id>`).
How to use it: build the unified (or, until they exist, the per-tree) macOS `komorebi`, `komorebic` and `komorebi-bar`, run `cargo test --workspace` on the Mac first (the 399+ unit tests have never run against these changes), then walk the sections in order. For before/after capture use `komorebi-recorder` against a build of the baseline `wip-main` ancestor `ff3711dc` and the tip. A section is done when the "look for" column is true.
@@ -8,6 +10,73 @@ How to use it: build the unified (or, until they exist, the per-tree) macOS `kom
The real-Mac runs so far (Mac Mini, rustc and clippy 1.93, tip a35573d8) are **compile and unit tests only**: `cargo test --workspace` in komorebi-for-mac passed (daemon 366 passed, 1 ignored; 368 total, 0 failed) and clippy `-D warnings` was clean apart from the two items fixed afterwards. Nothing was run as a daemon: no focus, tiling, borders, animations or bar rendering has been observed on the Mini. Every walk-through item below is still open.
## Prioritised checks from the independent review (H1-H12)
Source: the macOS review of the candidate (S/review/mac.md). It found no must-fix; the fixes it asked for
are the `wip-u-kfm3` revisions (inert application in the registry, register on observe, no forget in
`Window::drop`, `forget_pid` first, forget on reap). Prerequisites: build `komorebi-macos` from the
candidate, grant Accessibility and Screen Recording, run `komorebi` with `RUST_LOG=komorebi=debug`;
use `komorebic state` for state. Order is by risk to a user's day.
1. **H1 hide spot on the right display (HideSpot).** Two displays; one workspace with a window
straddling the left edge of display 2 (drag it half off). Switch workspace on display 2 and back.
Expect: the window is hidden in the `BottomLeft` corner of display 2 (not display 1, not left in
view) and restored to the same frame. Repeat with `window_hiding_position: BottomRight` in the
monitor config. Stacks: a 3-window stack (`komorebic stack`), `cycle-stack`: only the front window is
visible, the others sit in the monitor corner.
2. **H3 event latency and stall.** A many-window app (Chrome, about 20 windows): restart komorebi and
note the time to ready in the log against the original build (registering is now once per observed
window, which removes the n x n cost of the first revision). Then `kill -STOP <pid>` an app with a managed
window and press `komorebic focus right` 5 times: commands are handled again within the AX timeout
after `kill -CONT`; a log line `invalidating application observer for process id` for a live app
after the CONT is the bug.
3. **H7 native tabs.** Finder or Terminal with two native tabs: switch tab, close the first tab; the
window stays managed, focus works, and `komorebic state` shows one window id per container with
no duplicates.
4. **H2 floating and monocle on workspace switch.** `toggle-float` a window, switch workspaces twice:
it hides and comes back at its old frame. `toggle-monocle`, switch workspace and back.
5. **H8 scrolling workspace.** `komorebic change-layout scrolling`, open 5 windows, pan with the
gesture and with `focus left/right`; windows scrolled out of view are parked at the screen edge (not in
the corner) and return on focus; switch workspace and back.
6. **H9 config reload visibility.** Set `default_container_padding`, `default_workspace_padding`,
`floating_window_aspect_ratio`, `layout_defaults` and `display_index_preferences` in komorebi.json and
apply with `komorebic replace-configuration` (or restart): padding on every workspace (not only the
focused one), `toggle-float` aspect ratio; removing `layout_defaults` or `floating_window_aspect_ratio`
and reapplying resets them (none, and Standard 4:3), while removing a padding key keeps the previous
value.
7. **H10 old state and the bar.** `komorebic state > old.json` on the ORIGINAL build; start the new
`komorebi-bar` against the new daemon and confirm it renders; the new daemon's `komorebic state` must
parse in the bar (workspaces, monitors with `window_hiding_position`).
8. **H6 pause and quit.** `komorebic toggle-pause`, quit an app with managed windows, `komorebic
toggle-pause`: its windows are gone from `komorebic state`. (That its registry entries are gone
is covered by the unit test of `forget_pid` and visible only in a debug log.)
9. **H11 bar config.** Put a Keyboard, Media and Systray widget and a `mouse` block in
komorebi.bar.json: the bar starts, logs "the Keyboard widget is not supported on this platform and is
skipped" (three times) and the `mouse` warning, and renders the other widgets. Then break the file
(`"mouse": {"on_scroll_up": 5}`, or an unknown widget name): the bar must refuse to load it with an error.
10. **H12 unsupported commands.** `echo '"ToggleMaximize"' | nc -U $DATA_DIR/komorebi.sock`: a
not-supported reply, no state change, the daemon keeps running.
11. **H4 registry growth.** Note `lsof -p $(pgrep -x komorebi) | wc -l` and `lsmp -p $(pgrep -x
komorebi) | tail -1` (Mach ports). In TextEdit open and close the Open and Save panels 200 times.
Compare the counts: steady growth means entries (and observers) are retained; it would also answer
whether an `AXObserver` holds a port (not verified).
12. **H5 hung subscriber (known, pre-existing).** `kill -STOP $(pgrep komorebi-bar)`; run `komorebic
focus left` 10 times and watch the log for "could not acquire window manager lock". Expect the
daemon to stop reacting once the socket buffer fills; `kill -CONT` recovers it. See the known issue
below: this is how the original behaves and it is deliberately not changed.
### Known issue, not fixed: a subscriber that stops reading can stall the daemon
`notify_subscribers` writes to each subscriber socket under the window manager lock, and the macOS
connect closure sets no write timeout, so a subscriber that accepted the connection and does not read
(a stopped bar, a debugger) makes `write_all` block once the notification outgrows the socket buffer;
the event thread then holds the lock and every command logs "could not acquire window manager lock".
The original daemon behaves the same. A write timeout was considered and **not added**: the
Windows review found that a write timeout can truncate the JSON notification in the middle (the
subscriber then reads half a message) and does not bound the stall in the way the timeout suggests, so
the fix needs a design (a bounded queue per subscriber written off the lock) and not a one-line
timeout. Until then H5 documents the hang.
## A. Revisions that change what the daemon does (BEHAVIOUR)
| Revision | What changed | Look for on a Mac |
@@ -27,6 +96,7 @@ The real-Mac runs so far (Mac Mini, rustc and clippy 1.93, tip a35573d8) are **c
| 11(iii) Container: `refactor(mac): the daemon's Container is komorebi_core::Container<Window>` (see `jj log -r wip-u-kfm2`) | `Container` is the shared generic type over the macOS `Window` (its id, windows, focus, `remove_*`, `idx_*` functions are the shared ones). The four functions that need the monitor's hiding corner and can fail (`add_window`, `load_focused_window`, `hide`, `restore`) stay macOS's, renamed `add_window_at`, `load_focused_window_at`, `hide_on`, `restore_focused_window` (`ContainerExt`); `Window::hide/restore/minimize/unminimize` take `&self`. State JSON must not change (pinned by two tests in container.rs). | Run `cargo test` (the container, workspace and scrolling tests use these). Then by hand: stack windows (`komorebic stack`), unstack, cycle the stack (hidden members go to the monitor's corner, the front one is restored); switch workspaces and come back (restore of the front window of each stack); `komorebic state | jq '.monitors.elements[0].workspaces.elements[0].containers.elements[0]'` still has `id`, `locked`, `windows.{elements,focused}` and nothing else. Set `window_hiding_position` per monitor in the config and check each monitor hides into its own corner. |
| 11(iii) Workspace: `refactor(mac): the daemon's Workspace is komorebi_core::Workspace<MacosPlatform>` (see `jj log -r wip-u-kfm2`) | About 50 workspace functions (container and focus operations, placement, resize constraints, window lookups, floating helpers, the stack and monocle operations that hide windows) are now the shared ones; `hide`, `new_container_for_window` and the stack functions pass the monitor's corner through `MacosPlatform::hide_spot` (kept in `MacosWorkspaceState`, set by the monitor with the globals), and `hide` passes the display bounds for the containers through `hide_spot_on_display`. macOS's own `update`, `apply_wallpaper`, `restore`, `remove_window`, `load_static_config`, `prune_duplicate_windows`, `visible_window_details`, `reap_invalid_windows_for_application`, `restore_windows`, `calculate_layouts` and `set_scrolling_columns` are `WorkspaceExt`; the scrolling methods are `WorkspaceScrolling`. | `cargo test` first (the workspace, scrolling and window_manager tests). Then: stack and unstack, switch workspaces both ways (each stack shows its front window, the hidden ones are in their monitor's corner), toggle monocle and back, float and unfloat a window, cycle the monocle container, move a window to another workspace, move a container across monitors; with a different `window_hiding_position` on each monitor check each monitor's windows park in their own corner and that a floating window that overhangs the edge of a display is still parked on its own display. `komorebic state` keys of a workspace are unchanged (pinned by `state_pin`). Scrolling layout: focus, move, consume and expel, pan, resize a column. |
| 11(iii) Monitor: `refactor(mac): the daemon's Monitor is komorebi_core::Monitor<MacosPlatform>` (see `jj log -r wip-u-kfm2`) | The monitor is the shared generic type; the corner (`window_hiding_position`) is the platform's flattened `extra` (written last, as before), the constructors, `update_*_globals`, `load_focused_workspace`, `move_container_to_workspace(1)`, `add_container_with_direction`, `hide_unfocused_workspaces` and `restore_focused_workspace` are `MonitorExt`; `focus_workspace`, `add_container`, `remove_workspace*`, `ensure_workspace_count` and the name and layout lookups are the shared ones. The monitor gives its workspaces the corner through `workspace.state` when it updates their globals. | `cargo test` (monitor tests, `state_pin`). By hand: `komorebic state | jq '.monitors.elements[0] | keys_unsorted'` is the same list as before with `window_hiding_position` last; switch workspaces on each monitor (hide and restore of the whole workspace), focus-workspace by index and by name, move a container to another workspace and to another monitor, unplug and replug a display (the monitor and its workspaces are rebuilt through `Monitor::new` and `update_all_workspace_globals`), a config with `window_hiding_position` per monitor. |
| `wip-u-kfm3` registry fixes (see `jj log -r wip-u-kfm3`) | The registry keeps inert application copies (no blocking Accessibility call when an entry is dropped), a window is registered when its observer is attached, a clone being dropped no longer deregisters its window, `forget_pid` runs ahead of the pause and other-space returns, and the application reaper forgets what it reaps. Nothing reads the registry except the unused `MacosBackend`. | H3, H4, H6, H7 above, and the usual walk-through: no change in what the daemon does is expected. |
Revisions in section B change no behaviour on purpose (rename, move, route); they still need the sections C walk-through, because a mechanical mistake would show there.
+2
View File
@@ -1,5 +1,7 @@
# The platform seam: evidence
> **Status (wip-cand4):** the evidence for `crates/komorebi-backend`, which has landed (trait, `FakeBackend`, contract tests); the Windows daemon goes through it for the clusters in [backend-switch.md](backend-switch.md); read section 8 as the list of what was never verified.
Status: evidence document (step 7a of the consolidation). No `Backend` trait is proposed here as code, and none may be written before this document has been reviewed. Every statement about the code carries a citation; where I could not confirm something it says "not verified" and the item is collected in section 8.
## 1. Purpose and how to read it
+2
View File
@@ -1,5 +1,7 @@
# Settings: replacing the process-wide statics
> **Status (wip-cand4):** design plus landing log. `crates/komorebi-settings` exists and the three daemons read the paddings, aspect ratio, layout defaults and display preferences through it; the remaining statics (see the section list) are still process-wide; macOS runtime is unverified.
Status: design (plan step 10, phase 1). Measured on `wip-main` 633e7453 (the Windows tree
`komorebi/src`, KDE `komorebi-for-kde/komorebi/src`, macOS `komorebi-for-mac/komorebi/src`). Nothing
here was run: counts come from `grep` and reading, and macOS cannot run on this host. The shared type
+2
View File
@@ -1,5 +1,7 @@
# One `komorebi`, one `komorebic`, one `komorebi-bar`
> **Status (wip-cand4):** steps 0-8 done: one `komorebi` (`komorebi-daemon/`), `komorebic`, `komorebi-client` and `komorebi-bar` package, platform by `cfg(target_os)`; the cutover (shim packages, one flake, final directories, one version) is open. The older sections below are history: in particular the note "never write `-p komorebi`" was true before step 8 and is wrong now; see [build-and-test.md](build-and-test.md) for current commands.
Goal: three packages and three binaries that build on Windows, KDE (Linux) and macOS, the platform
chosen by `cfg(target_os)` (generics, `cfg_select!`, exhaustive `match`; no macros as a design tool).
This file records a spike (throwaway revisions on bookmark `wip-u-pkg-spike`, titled `spike:`; nothing
+2 -2
View File
@@ -184,8 +184,8 @@ nixpkgs is not pinned back.
## Releases
A release is a tag. Set `version` under `[workspace.package]` in
[`Cargo.toml`](Cargo.toml) to the new version, commit it, and push the tag
A release is a tag. Set `version` in
[`komorebi/Cargo.toml`](komorebi/Cargo.toml) (which the flake reads) to the new version, commit it, and push the tag
`vVERSION` on that commit. For every run, the `build` job of `ci.yaml` builds
`komorebi` and `komorebic` with nix on an x86_64 and an arm64 runner, and keeps
them as an artifact of the run for 14 days. On a tag, once `lint`, `vm-fast` and
+13 -13
View File
@@ -1267,12 +1267,12 @@ too.
- [`backend`](../../komorebi/src/backend/mod.rs): the trait, the two data types, and the
process-wide handle ([`set_backend`], [`backend`], [`with_backend`]).
- [`backend::fake`](../../komorebi/src/backend/fake.rs): the fake.
- [`ring`](../../komorebi/src/ring.rs): the [`Ring`], and the macro that gives every type
- [`ring`](../../../crates/komorebi-collections/src/ring.rs): the [`Ring`], and the macro that gives every type
holding one the same accessors (`containers()`, `focused_container_mut()`, ...).
- [`monitor`](../../komorebi/src/monitor.rs), [`workspace`](../../komorebi/src/workspace.rs),
[`container`](../../komorebi/src/container.rs), [`window`](../../komorebi/src/window.rs):
the four levels of the tree; `window` also has the rule engine ([`should_act`]).
- [`lockable_sequence`](../../komorebi/src/lockable_sequence.rs): inserting, removing and
- [`lockable_sequence`](../../../crates/komorebi-collections/src/lockable_sequence.rs): inserting, removing and
swapping in a list where some elements are locked in place, which is how a workspace
changes its containers.
- [`window_manager`](../../komorebi/src/window_manager.rs): the [`WindowManager`] and the
@@ -1333,11 +1333,11 @@ too.
- [`komorebi-client`](../../komorebi-client/src/lib.rs): a library that writes messages on
the socket and reads the answers, and subscribes to notifications, for programs that talk
to the daemon.
- [`komorebic`](../../komorebic/src/main.rs): the command line. A subcommand that asks
- [`komorebic`](../../../komorebic/src/linux/mod.rs): the command line. A subcommand that asks
something of the daemon is one message, sent with `komorebi-client`; `start` runs the
daemon, `log` follows its log file in [`LOG_DIR`], and the hidden `docgen` writes
`docs/cli`.
- [`main.rs`](../../komorebi/src/main.rs): the daemon. It connects to KWin, or installs the
- [`daemon.rs`](../../komorebi/src/daemon.rs): the daemon. It connects to KWin, or installs the
fake with `--fake-backend`, makes the window manager from `komorebi.json` when there is one,
which binds the socket, loads the desktop, gives the monitors their configuration, asks for the
borders and tiles, starts the threads that listen on the socket, handle events and take the
@@ -1677,7 +1677,7 @@ daemons: skhd (macOS), whkd (Windows) and sxhkd (X11).
### The front end
[`komorebic/src/hotkeys.rs`](../../komorebic/src/hotkeys.rs) is the command line over the
[`komorebic/src/linux/hotkeys.rs`](../../../komorebic/src/linux/hotkeys.rs) is the command line over the
crate, and decides nothing about what a file means. `komorebic hotkeys compile` reads a file (by default the
first of `skhdrc`, `whkdrc` and `sxhkdrc` in the komorebi config directory, its format from
the end of its name), plans it in the mode it is given (by default `PlanMode::default()`),
@@ -1797,7 +1797,7 @@ plan needs no engine. A failure to start is logged, and the window manager runs
- [`komorebi/src/static_config.rs`](../../komorebi/src/static_config.rs): `komorebi.json`.
[`komorebi/tests/config.rs`](../../komorebi/tests/config.rs) loads files over the fake
desktop, [`komorebi/tests/config_displays.rs`](../../komorebi/tests/config_displays.rs) one
with several monitors, [`komorebi/tests/hot_reload.rs`](../../komorebi/tests/hot_reload.rs) the
with several monitors, [`komorebi-daemon/tests/linux_hot_reload.rs`](../../../komorebi-daemon/tests/linux_hot_reload.rs) the
daemon following a file, and
[`komorebi/tests/config_parity.rs`](../../komorebi/tests/config_parity.rs) the files of other
platforms and the example, which load;
@@ -1813,7 +1813,7 @@ plan needs no engine. A failure to start is logged, and the window manager runs
the applications files; [`komorebi/src/core/asc.rs`](../../komorebi/src/core/asc.rs) their
format.
- [`komorebi/src/check.rs`](../../komorebi/src/check.rs): the checks of `komorebic check`, with
their tests; [`komorebic/tests/check.rs`](../../komorebic/tests/check.rs) runs the command on
their tests; [`komorebic/tests/linux_check.rs`](../../../komorebic/tests/linux_check.rs) runs the command on
configurations, on key binding files and on buses that are not there, and reads what it prints
and its exit status;
[`nix/tests/vm/suites/check`](../../nix/tests/vm/suites/check/test.py), the desktop check against
@@ -1824,10 +1824,10 @@ plan needs no engine. A failure to start is logged, and the window manager runs
each message does, and the tests that send messages through a real socket.
- [`komorebi-client/src/lib.rs`](../../komorebi-client/src/lib.rs): the client side of the
socket.
- [`komorebi-client/tests/subscribe.rs`](../../komorebi-client/tests/subscribe.rs):
- [`komorebi-client/tests/linux_subscribe.rs`](../../../komorebi-client/tests/linux_subscribe.rs):
subscribers and the notifications they are sent, through real sockets.
- [`komorebic/src/main.rs`](../../komorebic/src/main.rs): the subcommands, and
[`komorebic/tests/cli.rs`](../../komorebic/tests/cli.rs), what each writes on the socket.
- [`komorebic/src/linux/mod.rs`](../../../komorebic/src/linux/mod.rs): the subcommands, and
[`komorebic/tests/linux_cli.rs`](../../../komorebic/tests/linux_cli.rs), what each writes on the socket.
- [`komorebi/src/kwin/mod.rs`](../../komorebi/src/kwin/mod.rs): the KWin backend, its D-Bus
service and the held call.
- [`komorebi/src/kwin/state.rs`](../../komorebi/src/kwin/state.rs): the table, with the
@@ -1878,7 +1878,7 @@ plan needs no engine. A failure to start is logged, and the window manager runs
real Plasma shell.
- [`komorebi/tests/wm_events.rs`](../../komorebi/tests/wm_events.rs): the window manager
driven end to end against the fake.
- [`komorebi/tests/socket.rs`](../../komorebi/tests/socket.rs): the daemon over its socket,
- [`komorebi-daemon/tests/linux_socket.rs`](../../../komorebi-daemon/tests/linux_socket.rs): the daemon over its socket,
from its start to a `Stop`.
- [`komorebi/tests/focus.rs`](../../komorebi/tests/focus.rs),
[`komorebi/tests/moving.rs`](../../komorebi/tests/moving.rs) and
@@ -1965,9 +1965,9 @@ plan needs no engine. A failure to start is logged, and the window manager runs
[`sxhkd.rs`](../../komorebi-hotkeys/src/sxhkd.rs);
[`plan.rs`](../../komorebi-hotkeys/src/plan.rs) and [`kde.rs`](../../komorebi-hotkeys/src/kde.rs)
for the shortcuts, [`engine.rs`](../../komorebi-hotkeys/src/engine.rs) for the engine.
- [`komorebic/src/hotkeys.rs`](../../komorebic/src/hotkeys.rs): `export-kde-shortcuts` and
- [`komorebic/src/linux/hotkeys.rs`](../../../komorebic/src/linux/hotkeys.rs): `export-kde-shortcuts` and
`hotkeys compile`, and the key bindings section of `komorebic check`;
[`komorebic/tests/hotkeys.rs`](../../komorebic/tests/hotkeys.rs), what they write.
[`komorebic/tests/linux_hotkeys.rs`](../../../komorebic/tests/linux_hotkeys.rs), what they write.
- [`nix/tests/vm/suites/keys-static`](../../nix/tests/vm/suites/keys-static/test.py): static
shortcuts run by a real KWin.
- [`komorebi/src/kwin/hotkeys.rs`](../../komorebi/src/kwin/hotkeys.rs): the engine against
+2
View File
@@ -1,5 +1,7 @@
# komorebi for KDE Plasma compared with komorebi for Windows and for macOS
> **STALE (snapshot of 2026-10-27, kfw 173aa802, kfm 125a9a5):** this comparison predates the consolidation. The three programs now share `crates/` (protocol, config, collections, transport, backend, core, settings, komorebic-core) and one `komorebi`, `komorebic`, `komorebi-client` and `komorebi-bar` package, so counts of duplicated commands, messages and keys below are out of date, and `scripts/compare-gen.py` no longer runs against the current tree (it fails with `cannot find '^enum SubCommand'`, because the command definitions moved to `crates/komorebic-core`). For what is shared and what differs on purpose now, read the repository-level [docs/dev/ARCHITECTURE-UNIFIED.md](../../../docs/dev/ARCHITECTURE-UNIFIED.md) and [docs/dev/core-model.md](../../../docs/dev/core-model.md). The platform-difference tables (KWin versus Win32 versus AppKit mechanisms) remain a fair description of the platform layers.
This document compares komorebi for KDE Plasma on KWin and Wayland (kfde) with komorebi for
Windows (kfw), the original, and komorebi for macOS (kfm). It is written for a reader who knows
komorebi on one of those two systems and wants to know what is the same on KDE, what is different,
+1 -1
View File
@@ -54,7 +54,7 @@ is, whether it is hidden, how wide it really is) is a call to the backend in kfd
- `komorebi/tests/scrolling.rs` and `layout_options.rs`: the commands through
`WindowManager::process_command` against the fake desktop, a strip next to another monitor, and a
drag of the left edge of a column.
- `komorebic/tests/cli.rs`: each new subcommand sends its message.
- `komorebic/tests/linux_cli.rs`: each new subcommand sends its message.
- `nix/tests/vm/lib/komorebi_vm/core/scenarios/scrolling.py` (`columns`, shared with komorebi for
Windows), run by `vm-scrolling` and `core-e2e`: where the daemon keeps a window at the edge and the
commands of the columns, in a real session. Run on KDE: the `scrolling` suite passes
+5 -5
View File
@@ -63,12 +63,12 @@
//! | The keys are the ones komorebi reads, at every level | [`known_keys`] reads them from the JSON schema of [`StaticConfig`] | `check::tests::the_keys_come_from_the_schema_at_every_level`, `check::tests::a_whole_example_configuration_has_nothing_the_check_does_not_know` |
//! | Placement rules that no window can use are a note | [`check_configuration`] compares the `initial_window_placement_rules` of a workspace with its `window_container_behaviour`, or the file's when it has none: windows that are appended to a container have no place of their own | `check::tests::placement_rules_that_are_not_used_while_windows_are_appended_are_noted` |
//! | A wallpaper that is not a file is an error, and a picture no theme can be made from is a warning | [`check_configuration`] looks at the wallpaper of each monitor and workspace once, and asks the theme generator for a palette when the wallpaper does not turn it off | `check::tests::a_wallpaper_that_is_not_there_and_a_rules_file_that_is_not_there_are_found` for the error, the `vm-check` VM suite for the warning |
//! | No session bus, or no KWin on it, is an error, and the desktop is looked at no further | [`check_environment`] stops at the first finding the rest depends on | `komorebic/tests/check.rs::without_a_session_bus_the_desktop_is_an_error`, the `vm-check` VM suite |
//! | No session bus, or no KWin on it, is an error, and the desktop is looked at no further | [`check_environment`] stops at the first finding the rest depends on | `komorebic/tests/linux_check.rs::without_a_session_bus_the_desktop_is_an_error`, the `vm-check` VM suite |
//! | komorebi running without its script in KWin is an error | [`check_environment`] compares the daemon's socket with KWin's answer to `isScriptLoaded` | the `vm-check` VM suite |
//! | An effect is komorebi's build because of what it contains, not because of its name | [`check_environment`] looks for the colors interface in the border effect, and for a `Curve` setting in the animation effect's script | `check::tests::the_border_effect_is_komorebis_when_it_has_the_colours_interface`, `check::tests::the_effects_are_told_apart_by_what_they_contain` |
//! | Effects are looked for where KWin looks, not where the shell that runs the command would | [`check_environment`] reads KWin's environment from `/proc` | the `vm-check` VM suite |
//! | No D-Bus call delays the check by more than two seconds | convention: every call [`check_environment`] makes goes through a timeout | `komorebic/tests/check.rs::a_session_bus_that_never_answers_is_given_up_on` |
//! | `komorebic check` exits with status 1 if and only if a finding is an error | `komorebic`, through [`Report::has_errors`] | `komorebic/tests/check.rs` |
//! | No D-Bus call delays the check by more than two seconds | convention: every call [`check_environment`] makes goes through a timeout | `komorebic/tests/linux_check.rs::a_session_bus_that_never_answers_is_given_up_on` |
//! | `komorebic check` exits with status 1 if and only if a finding is an error | `komorebic`, through [`Report::has_errors`] | `komorebic/tests/linux_check.rs` |
#![deny(missing_docs)]
@@ -681,7 +681,7 @@ pub fn check_keys(value: &serde_json::Value, known: &KnownKeys) -> Vec<Finding>
/// ```
///
/// The files that are read are covered by the tests in `komorebi/src/check.rs` and
/// `komorebic/tests/check.rs`.
/// `komorebic/tests/linux_check.rs`.
pub fn check_configuration(path: &Path) -> (Vec<Finding>, Wants) {
let mut findings = vec![];
let mut wants = Wants::default();
@@ -1441,7 +1441,7 @@ fn autostart_findings() -> Vec<Finding> {
///
/// # Example
///
/// Covered by `komorebic/tests/check.rs::without_a_session_bus_the_desktop_is_an_error` and the
/// Covered by `komorebic/tests/linux_check.rs::without_a_session_bus_the_desktop_is_an_error` and the
/// `vm-check` VM suite. The example needs a desktop session, so it is compiled and not run here:
///
/// ```rust,no_run
+1 -1
View File
@@ -119,7 +119,7 @@ impl komorebi_core::WorkspacePlatform for KdePlatform {
workspace.note_scrolling_departure(idx);
}
fn after_floating_removed(workspace: &mut Workspace) {
fn before_floating_removed(workspace: &mut Workspace) {
workspace.focus_previous_floating_window();
}
@@ -6,7 +6,7 @@ komorebi's builds because of what they contain, that a daemon is told from its s
own answer, that a bus with no KWin on it is an error with an exit status that says so, and that
the shortcut files the check compares with are in the directory `komorebic hotkeys compile`
writes to in a session. The configuration and the exit status are covered by
`komorebi/src/check.rs` and `komorebic/tests/check.rs`, against no desktop.
`komorebi/src/check.rs` and `komorebic/tests/linux_check.rs`, against no desktop.
"""
import base64
@@ -6,7 +6,7 @@
# own answer, that a bus with no KWin on it is an error with an exit status that says so, and that
# the shortcut files the check compares with are in the directory `komorebic hotkeys compile`
# writes to in a session. The configuration and the exit status are covered by
# `komorebi/src/check.rs` and `komorebic/tests/check.rs`, against no desktop.
# `komorebi/src/check.rs` and `komorebic/tests/linux_check.rs`, against no desktop.
from komorebi_vm import Checks
from komorebi_vm.core.suite import platform_only, run_suite
+6
View File
@@ -1,6 +1,12 @@
#!/usr/bin/env python3
"""Generate the tables of docs/dev/COMPARE.md from the source trees.
NOTE (wip-cand4): STALE. The command definitions moved to crates/komorebic-core, the daemons' message
types to crates/komorebi-protocol and the configuration types to crates/komorebi-config, so the
readers below (`Tree.commands`, `socket_messages`, `struct_keys`, ...) find nothing and the script
exits with "cannot find ^enum SubCommand". It runs only against the pre-consolidation checkouts
named in COMPARE.md. Port it to the crates before using it again, or retire it with COMPARE.md.
komorebi for Windows (kfw), komorebi for macOS (kfm) and komorebi for KDE Plasma (kfde, this
repository) are read as they are on disk. Nothing in the tables is typed from memory, except the
small hand-written tables in the NOTES section of this file, which hold what a source file cannot
@@ -121,6 +121,16 @@ impl Application {
})
}
/// A clone that does nothing when it is dropped: [`Application::drop`] asks the application
/// whether it is still there (a blocking Accessibility round trip) and may invalidate the
/// observer that every clone shares, which is for the clones a window carries and not for the
/// ones that a table keeps.
pub fn inert(&self) -> Self {
let mut inert = self.clone();
inert.is_observable = false;
inert
}
/// The AX element of the application itself, as opposed to one of its windows
pub fn element(&self) -> &AccessibilityUiElement {
&self.element
+105 -7
View File
@@ -7,15 +7,29 @@
//!
//! # Lifetime
//!
//! An entry is created by `Window::new` and by [`sync`] when a window's element or id changes
//! (a native tab). It ends at every place the daemon learns of a death:
//! An entry is created by `Window::observe`, when the window's observer has been attached to the run
//! loop (a `Window` made only to ask an application about a window is never observed, so never
//! registered, and the observer in the table is the attached one), and by [`sync`] when a window's
//! element or id changes (a native tab). The entry holds an *inert* copy of the application
//! ([`crate::application::Application::inert`]): dropping a normal copy asks the application
//! something over Accessibility and may invalidate the shared observer, which must never happen
//! inside a table operation.
//!
//! - `Window::drop`, when the window is no longer alive ([`forget`]);
//! - the reaper, when it reaps a window ([`forget`]);
//! - an application terminating ([`forget_pid`], from `WindowManagerEvent::Destroy`).
//! It ends where the daemon knows a window is gone:
//!
//! A window that is alive and never managed stays registered until it dies or its application
//! quits: the entry only holds retained references that the `Window` clones held anyway.
//! - the reaper, when it reaps a window ([`forget`]), and the application reaper
//! (`reap_invalid_windows_for_application`, [`forget`]);
//! - an application terminating ([`forget_pid`], the first thing `process_event` does for
//! `NSWorkspaceDidTerminateApplication`, ahead of the pause and other-space returns).
//!
//! It does not end in `Window::drop`: that runs for every clone, `alive()` is false for any failed
//! Accessibility call, and a transient failure must not deregister a live window.
//!
//! Not enforced: an observed window that closes without passing through the reapers keeps its entry
//! until its application quits (`WindowManagerEvent::Destroy` carries no window id). The table is
//! bounded by the windows observed per running application; a sweep would cost one Accessibility call
//! per entry under the window manager lock. What an unattached observer costs (a Mach port?) is not
//! verified (hand check H4).
//!
//! # Threads
//!
@@ -112,3 +126,87 @@ pub fn identify(
) -> std::result::Result<u32, crate::accessibility::error::AccessibilityError> {
crate::accessibility::AccessibilityApi::window_id(element)
}
#[cfg(test)]
mod tests {
use super::*;
fn window_of(id: u32, pid: i32) -> Window {
let mut window = Window::from(id);
window.application.process_id = pid;
window
}
fn id(raw: u32) -> WindowId {
WindowId::from_u32(raw)
}
/// `Application::drop` asks the application whether it is still there (a blocking
/// Accessibility round trip) when `is_observable`; the table must hold copies that skip it.
#[test]
fn a_registered_entry_does_not_ask_the_app_when_it_is_dropped() {
let mut window = window_of(0x5101, 6_100_001);
window.application.is_observable = true;
assert!(!window.entry().application.is_observable);
register(&window);
assert!(!get(id(0x5101)).unwrap().application.is_observable);
forget(0x5101);
}
#[test]
fn a_window_made_from_an_entry_is_inert_too() {
let mut window = window_of(0x5102, 6_100_002);
window.application.is_observable = true;
register(&window);
assert!(!super::window(id(0x5102)).unwrap().application.is_observable);
forget(0x5102);
}
}
#[cfg(test)]
mod drop_tests {
use super::*;
/// `State::from` clones every window on every command and event notification; whatever a
/// clone's drop finds out about the window (the stand-in element answers differently with and
/// without Accessibility permission), the entry of a window that was not reaped stays.
#[test]
fn dropping_a_clone_does_not_deregister_a_window() {
let mut window = Window::from(0x5201);
window.application.process_id = 6_200_001;
register(&window);
drop(window.clone());
assert!(get(WindowId::from_u32(0x5201)).is_ok());
forget(0x5201);
}
}
#[cfg(test)]
mod pid_tests {
use super::*;
#[test]
fn an_application_quitting_takes_its_windows_and_no_other() {
let mut quitter = Window::from(0x5301);
quitter.application.process_id = 6_300_001;
let mut stayer = Window::from(0x5302);
stayer.application.process_id = 6_300_002;
register(&quitter);
register(&stayer);
forget_pid(6_300_001);
assert!(get(WindowId::from_u32(0x5301)).is_err());
assert!(get(WindowId::from_u32(0x5302)).is_ok());
forget(0x5302);
}
}
+13 -1
View File
@@ -98,6 +98,19 @@ impl WindowManager {
window_manager_event_listener::resize_step_taken();
}
// an application that quit takes its windows out of the registry whatever else is going on:
// this is ahead of the pause and the other-space returns below, which would otherwise discard
// the notification and leave the entries to be inherited by a process that reuses the pid
if let WindowManagerEvent::Destroy(
SystemNotification::AppKitWorkspace(
AppKitWorkspaceNotification::NSWorkspaceDidTerminateApplicationNotification,
),
process_id,
) = &event
{
crate::ax_registry::forget_pid(*process_id);
}
if matches!(event, WindowManagerEvent::ScreenLock(_, _)) {
let application = self.application(event.process_id())?;
if application.name().unwrap_or_default() == "loginwindow" {
@@ -749,7 +762,6 @@ impl WindowManager {
)
) {
enhanced_ui::forget(process_id);
crate::ax_registry::forget_pid(process_id);
}
// some apps like Discord in all of their relentless Electron slop stupidity
+16 -15
View File
@@ -475,8 +475,10 @@ impl Drop for Window {
// for now - hopefully it doesn't break anything else
reaper::send_notification(ReaperNotification::InvalidWindow(self.id));
// and the id no longer names anything
crate::ax_registry::forget(self.id);
// the registry is not told here: `alive()` is false for any failed Accessibility call, and
// this runs for every clone (State::from makes one of each window on every command), so a
// window that answered badly once would lose its entry; the places that know a window
// is gone (the reaper, an application quitting) forget it
// make sure the observer gets removed from any run loops
AccessibilityApi::invalidate_observer(&self.observer);
@@ -559,18 +561,13 @@ impl Window {
Some(window_observer_callback),
)?;
let window = Self {
Ok(Self {
id: AccessibilityApi::window_id(&element)?,
element: AccessibilityUiElement(element),
application,
observer: AccessibilityObserver(Some(observer)),
details: None,
};
// so that the window can be found again from its id alone
crate::ax_registry::register(&window);
Ok(window)
})
}
/// The handles that act on this window, as the registry keeps them
@@ -578,7 +575,8 @@ impl Window {
crate::ax_registry::AxEntry {
element: self.element.clone(),
observer: self.observer.clone(),
application: self.application.clone(),
// inert: dropping an entry must not ask the application anything (see `Application::inert`)
application: self.application.inert(),
}
}
@@ -626,7 +624,13 @@ impl Window {
NOTIFICATIONS,
run_loop,
refcon,
)
)?;
// the registry holds the window whose observer is attached: a Window that was only made to
// ask an app about a window is never observed, so it is never registered
crate::ax_registry::register(self);
Ok(())
}
/// Hide the window in the corner of the display that it is on
@@ -634,10 +638,7 @@ impl Window {
/// Prefer [`Window::hide_on`] when the display is known, since a window that hangs over the
/// edge of a display is not always on the display that the lookup by position finds.
#[tracing::instrument(skip_all)]
pub fn hide(
&self,
hiding_position: WindowHidingPosition,
) -> Result<(), AccessibilityError> {
pub fn hide(&self, hiding_position: WindowHidingPosition) -> Result<(), AccessibilityError> {
self.hide_on(hiding_position, None)
}
+3 -1
View File
@@ -143,7 +143,7 @@ impl komorebi_core::WorkspacePlatform for MacosPlatform {
workspace.note_scrolling_departure(idx);
}
fn after_floating_removed(workspace: &mut Workspace) {
fn before_floating_removed(workspace: &mut Workspace) {
workspace.focus_previous_floating_window();
}
}
@@ -432,10 +432,12 @@ impl WorkspaceExt for Workspace {
for window_id in &invalid_window_ids {
// Ignore errors - window may have already been removed by the reaper thread
let _ = self.remove_window(*window_id);
crate::ax_registry::forget(*window_id);
}
for window_id in &invalid_floating_window_ids {
self.remove_floating_window(*window_id);
crate::ax_registry::forget(*window_id);
}
tracing::debug!(
+26 -5
View File
@@ -11,6 +11,13 @@ pub(crate) use komorebi_core::sorted_layout_options_rules;
/// platform's methods added by [`WorkspaceExt`] and the scrolling ones of [`WorkspaceScrolling`]
pub type Workspace = komorebi_core::Workspace<WindowsPlatform>;
/// The title-bar rules of one placement pass, taken once by `begin_pass`
struct TitleBarRules {
should_remove_titlebars: bool,
no_titlebar: Vec<crate::core::config_generation::MatchingRule>,
regex_identifiers: HashMap<String, regex::Regex>,
}
/// The Windows daemon as the platform of the shared workspace
#[derive(Debug, Clone, PartialEq)]
pub struct WindowsPlatform;
@@ -159,15 +166,29 @@ impl komorebi_core::WorkspacePlatform for WindowsPlatform {
}
}
fn begin_pass(_workspace: &Workspace) -> Option<Box<dyn std::any::Any>> {
// read once for the whole pass: a configuration reload in the middle of it must not give
// two containers two different tables
Some(Box::new(TitleBarRules {
should_remove_titlebars: REMOVE_TITLEBARS.load(Ordering::SeqCst),
no_titlebar: NO_TITLEBAR.lock().clone(),
regex_identifiers: REGEX_IDENTIFIERS.lock().clone(),
}))
}
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();
let rules = placement
.pass
.and_then(|pass| pass.downcast_ref::<TitleBarRules>())
.ok_or_eyre("the title-bar rules of this pass were not taken")?;
let should_remove_titlebars = rules.should_remove_titlebars;
let no_titlebar = &rules.no_titlebar;
let regex_identifiers = &rules.regex_identifiers;
for window in container.windows() {
if container
@@ -179,8 +200,8 @@ impl komorebi_core::WorkspacePlatform for WindowsPlatform {
&window.exe().unwrap_or_default(),
&window.class().unwrap_or_default(),
&window.path().unwrap_or_default(),
&no_titlebar,
&regex_identifiers,
no_titlebar,
regex_identifiers,
)
.is_some();