feat(wm): windows, containers, workspaces and monitors

The window manager tiles a tree of four levels: monitors, each with a ring of
workspaces, each with a ring of containers, each with a ring of windows. It is
the model komorebi has on Windows and macOS, and the first thing the daemon
keeps that the backend does not give it.

A window is a Copy handle that carries the compositor's id and asks the backend
for everything else, so moving one is a call on the handle and needs no context
passed to it. A workspace tiles itself: the layout gives each container a tile
of the work area its monitor hands it, less the offset and the padding, and
every window of the container is asked to move there. A locked container keeps
its index because the workspace inserts, removes and swaps its containers
through LockableSequence.

This is tiling only. Stacks, monocle, maximize, the floating layer, resize
adjustments, placement rules and the link between workspaces and KWin's desktops
come with the commits that use them. impl_ring_elements!, which gives every
holder of a ring the same accessors, lands here with its first users.
This commit is contained in:
LGUG2Z committed 2026-10-27 14:07:28 -07:00
1 parent ed6a8e96c3
commit c0345eb0e9
12 files changed
+2135 -7

No files matched your search

Generated
+95 -1
View File
@@ -418,6 +418,17 @@ dependencies = [
"slab",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.4.3"
@@ -713,7 +724,7 @@ version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom",
"getrandom 0.4.3",
"libc",
]
@@ -735,12 +746,15 @@ dependencies = [
"clap",
"color-eyre",
"komorebi-layouts",
"nanoid",
"parking_lot",
"pastey",
"schemars 1.2.3",
"serde",
"serde_json_lenient",
"serde_with",
"strum",
"tracing",
"version",
]
@@ -852,6 +866,15 @@ dependencies = [
"adler2",
]
[[package]]
name = "nanoid"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
dependencies = [
"rand",
]
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -926,6 +949,12 @@ dependencies = [
"windows-link",
]
[[package]]
name = "pastey"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -974,6 +1003,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -998,6 +1036,36 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -1546,6 +1614,12 @@ dependencies = [
"shadow-rs",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
@@ -1688,6 +1762,26 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
+1
View File
@@ -15,6 +15,7 @@ komorebi-layouts = { git = "https://github.com/LGUG2Z/komorebi", rev = "f08aa555
clap = { version = "4", features = ["derive", "wrap_help"] }
color-eyre = "0.6"
pastey = "0.2"
schemars = "1.1"
serde = { version = "1", features = ["derive"] }
serde_json = { package = "serde_json_lenient", version = "0.2" }
+7 -1
View File
@@ -24,7 +24,8 @@ without a checkout of the toolchain.
- [`komorebi`](komorebi): the daemon, and the library behind it. The library has
the vocabulary the window manager is written in (`core`), the `Backend` trait
through which it reaches a compositor and the in-memory desktop the tests use
(`backend`), the `Ring` that holds monitors, workspaces and containers, and the
(`backend`), the model of what it tiles (`monitor`, `workspace`, `container`,
`window`), the `Ring` that holds monitors, workspaces and containers, and the
lists in which some elements are locked in place.
- [`version`](version): the version string every binary reports.
@@ -54,6 +55,11 @@ so the window manager logic runs against a real compositor and against an
in-memory fake desktop alike. [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
describes the trait and where each of its rules is enforced.
The window manager models the desktop as monitors, each with a ring of
workspaces, each with a ring of containers, each with a ring of windows. A
workspace's layout gives each of its containers a tile of the monitor's work
area, and every window of a container is moved onto its tile.
## Documentation
`cargo doc --workspace --no-deps --open` builds the API documentation.
+56 -3
View File
@@ -5,9 +5,9 @@ compositor to put it there. Everything it needs from the compositor is behind on
[`Backend`](../../komorebi/src/backend/mod.rs), so the window manager is written, and
tested, without one.
This page describes that trait, who implements and calls it, and where each of its rules
is enforced. It grows with the code: each part of the daemon that is added has its place
here.
This page describes that trait, who implements and calls it, where each of its rules is
enforced, and the model of the desktop the window manager tiles. It grows with the code:
each part of the daemon that is added has its place here.
## Vocabulary
@@ -15,6 +15,12 @@ here.
compositor's `u32` id.
- **Monitor**: a connected output, with its bounds and its work area (its bounds minus
the panels).
- **Workspace**: the containers a monitor shows, in order, and the layout that tiles
them. A monitor has a ring of workspaces and shows one of them.
- **Container**: what a layout places. It gets one tile, and every window in it is put on
that tile.
- **Layout**: the arrangement (BSP, columns, rows, ...) that turns a work area and a
number of containers into one rectangle, a **tile**, for each container.
- **Compositor**: the program that owns the screen and the windows. On KDE Plasma it is
KWin.
- **Backend**: the implementation of the [`Backend`](../../komorebi/src/backend/mod.rs)
@@ -48,11 +54,39 @@ The desktop, as the window manager sees it, is two lists and a pointer:
A command is one of: move and resize a window, focus it, raise it, minimize it or bring it
back, close it, and put the pointer in the middle of a rectangle.
The window manager tiles a tree of four levels, each level a [`Ring`]: a list with one
element focused, so that "the focused workspace" or "the focused container" means
the same thing at every level.
- A **monitor** ([`Monitor`]) is one of the backend's monitors: its bounds, its work area,
its padding, an optional work area offset, and its workspaces. It shows the focused one.
- A **workspace** ([`Workspace`]) has a layout, its padding, and its containers, in order.
- A **container** ([`Container`]) has its windows. A new window gets a container of its
own. A container can be locked, which keeps it at its index while others are inserted,
removed or swapped around it.
- A **window** ([`Window`]) is a `Copy` handle that carries only the compositor's id.
Everything else about the window, and every change to it, goes through the backend.
Tiling a workspace ([`Workspace::update`]) is a function of this tree and a work area. The
monitor gives its focused workspace the work area, the padding to fall back to and the
offset ([`WorkspaceGlobals`]). The workspace takes the offset and its padding off the work
area, the layout gives one tile per container, in order, each shrunk by the container
padding, and every window of a container is asked to move onto its tile with `set_rect`. A
tile is clamped to the work area, so it cannot reach onto a neighboring monitor.
## The parts
- [`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
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.
- [`lockable_sequence`](../../komorebi/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.
The handle is a process-wide singleton so that a window can be a small `Copy` value
that carries only its id, and ask the backend for what it needs. A test replaces it for
@@ -84,6 +118,7 @@ the fake. The window manager is its only caller, through [`backend`]. The contra
| The window manager asks for a backend that was never installed | runtime error: [`backend`] panics, naming [`set_backend`] and [`with_backend`] | `# Panics` on [`backend`] | none |
| A test's backend does not outlive the test | framework path: [`with_backend`] restores the previous one on drop | `with_backend_puts_the_previous_backend_back_when_the_closure_panics` | none |
| A command about a missing window is an error, not a panic | test | `a_command_about_a_window_nobody_opened_is_an_error` and `a_command_about_a_closed_window_is_an_error`, against the fake only | none |
| A locked container keeps its index | framework path: a [`Workspace`] inserts, removes and swaps its containers through `LockableSequence` | `test_locked_containers_with_new_window` and `test_locked_containers_remove_window` | `containers_mut()` is the `VecDeque` itself |
| Queries never block on the compositor | convention only | none | none |
| Only the backend module reaches the compositor | convention only | none | none |
@@ -97,3 +132,21 @@ breaks the first, and a module that talks to D-Bus directly breaks the second.
tests.
- [`komorebi/src/core`](../../komorebi/src/core/mod.rs): the vocabulary the rest is written
in.
- [`komorebi/src/workspace.rs`](../../komorebi/src/workspace.rs): tiling, in
`Workspace::update`.
- [`komorebi/src/monitor.rs`](../../komorebi/src/monitor.rs): the work area, padding and
offset a monitor gives the workspace it shows.
[`Backend`]: ../../komorebi/src/backend/mod.rs
[`WindowInfo`]: ../../komorebi/src/backend/mod.rs
[`MonitorInfo`]: ../../komorebi/src/backend/mod.rs
[`set_backend`]: ../../komorebi/src/backend/mod.rs
[`backend`]: ../../komorebi/src/backend/mod.rs
[`with_backend`]: ../../komorebi/src/backend/mod.rs
[`Ring`]: ../../komorebi/src/ring.rs
[`Monitor`]: ../../komorebi/src/monitor.rs
[`Workspace`]: ../../komorebi/src/workspace.rs
[`Workspace::update`]: ../../komorebi/src/workspace.rs
[`WorkspaceGlobals`]: ../../komorebi/src/workspace.rs
[`Container`]: ../../komorebi/src/container.rs
[`Window`]: ../../komorebi/src/window.rs
+3 -1
View File
@@ -12,7 +12,9 @@ komorebi has a Windows implementation, the original, and a macOS one. The Window
the reference. I used it as the reference for what to adapt, and I prefer what KDE and
Wayland do natively over a workaround that the other two platforms need. The events the
window manager reacts to follow the Windows ones (a window is shown, destroyed, focused,
minimized, moved, resized), and a window is a small `Copy` handle, as there.
minimized, moved, resized), and a window is a small `Copy` handle, as there. The model the
window manager tiles is the one both platforms have: monitors, each with workspaces, each
with containers, each with windows.
## Why is everything the window manager needs behind one trait?
+3
View File
@@ -10,11 +10,14 @@ version = { path = "../version" }
clap = { workspace = true }
color-eyre = { workspace = true }
nanoid = "0.4"
parking_lot = "0.12"
pastey = { workspace = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true }
serde_with = { version = "3", features = ["schemars_1"] }
strum = { version = "0.28", features = ["derive"] }
tracing = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+218
View File
@@ -0,0 +1,218 @@
//! [`Container`], the windows that share one tile of a workspace's layout.
//!
//! A container is a ring of windows. The layout gives each container a tile, and every window of
//! the container is put on that tile. A new window gets a container of its own
//! ([`Workspace::new_container_for_window`](crate::workspace::Workspace::new_container_for_window)).
//!
//! A container can be locked ([`Lockable`]): a locked container keeps its index in the workspace
//! while others are inserted, removed or swapped around it.
use crate::lockable_sequence::Lockable;
use crate::ring::Ring;
use crate::window::Window;
use color_eyre::eyre;
use nanoid::nanoid;
use serde::Deserialize;
use serde::Serialize;
impl_ring_elements!(Container, Window);
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Container {
pub id: String,
pub locked: bool,
pub windows: Ring<Window>,
}
impl Default for Container {
fn default() -> Self {
Self {
id: nanoid!(),
locked: false,
windows: Default::default(),
}
}
}
impl Lockable for Container {
fn locked(&self) -> bool {
self.locked
}
fn set_locked(&mut self, locked: bool) -> &mut Self {
self.locked = locked;
self
}
}
impl Container {
pub fn contains_window(&self, window_id: u32) -> bool {
for window in self.windows() {
if window.id == window_id {
return true;
}
}
false
}
pub fn idx_for_window(&self, window_id: u32) -> Option<usize> {
for (i, window) in self.windows().iter().enumerate() {
if window.id == window_id {
return Option::from(i);
}
}
None
}
pub fn remove_focused_window(&mut self) -> Option<Window> {
let focused_idx = self.focused_window_idx();
self.remove_window_by_idx(focused_idx)
}
pub fn add_window(&mut self, window: &Window) -> eyre::Result<()> {
self.windows_mut().push_back(*window);
self.focus_window(self.windows().len().saturating_sub(1));
Ok(())
}
#[tracing::instrument(skip(self))]
pub fn focus_window(&mut self, idx: usize) {
tracing::info!("focusing window");
self.windows.focus(idx);
}
pub fn remove_window_by_idx(&mut self, idx: usize) -> Option<Window> {
let window = self.windows_mut().remove(idx);
self.focus_window(idx.saturating_sub(1));
window
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn test_contains_window() {
let mut container = Container::default();
for i in 0..3 {
container.add_window(&Window::from(i)).unwrap();
}
// Should return true for existing windows
assert!(container.contains_window(1));
assert_eq!(container.idx_for_window(1), Some(1));
// Should return false since window 4 doesn't exist
assert!(!container.contains_window(4));
assert_eq!(container.idx_for_window(4), None);
}
#[test]
fn test_remove_window_by_idx() {
let mut container = Container::default();
for i in 0..3 {
container.add_window(&Window::from(i)).unwrap();
}
// Remove window 1
container.remove_window_by_idx(1);
// Should only have 2 windows left
assert_eq!(container.windows().len(), 2);
// Should return false since window 1 was removed
assert!(!container.contains_window(1));
}
#[test]
fn test_remove_focused_window() {
let mut container = Container::default();
for i in 0..3 {
container.add_window(&Window::from(i)).unwrap();
}
// Should be focused on the last created window
assert_eq!(container.focused_window_idx(), 2);
// Remove the focused window
container.remove_focused_window();
// Should be focused on the window before the removed one
assert_eq!(container.focused_window_idx(), 1);
// Should only have 2 windows left
assert_eq!(container.windows().len(), 2);
}
#[test]
fn test_add_window() {
let mut container = Container::default();
container.add_window(&Window::from(1)).unwrap();
assert_eq!(container.windows().len(), 1);
assert_eq!(container.focused_window_idx(), 0);
assert!(container.contains_window(1));
}
#[test]
fn test_focus_window() {
let mut container = Container::default();
for i in 0..3 {
container.add_window(&Window::from(i)).unwrap();
}
// Should focus on the last created window
assert_eq!(container.focused_window_idx(), 2);
// focus on the window at index 1
container.focus_window(1);
// Should be focused on window 1
assert_eq!(container.focused_window_idx(), 1);
// focus on the window at index 0
container.focus_window(0);
// Should be focused on window 0
assert_eq!(container.focused_window_idx(), 0);
}
#[test]
fn test_idx_for_window() {
let mut container = Container::default();
for i in 0..3 {
container.add_window(&Window::from(i)).unwrap();
}
// Should return the index of the window
assert_eq!(container.idx_for_window(1), Some(1));
// Should return None since window 4 doesn't exist
assert_eq!(container.idx_for_window(4), None);
}
#[test]
fn serializes_and_deserializes() {
let mut container = Container::default();
container.set_locked(true);
let serialized = serde_json::to_string(&container).expect("Should serialize");
let deserialized: Container =
serde_json::from_str(&serialized).expect("Should deserialize");
assert!(deserialized.locked);
assert_eq!(deserialized.id, container.id);
}
}
+18
View File
@@ -1,9 +1,27 @@
//! The komorebi daemon's library: the vocabulary the window manager is written in and the data
//! structures it is built from.
//!
//! The desktop is modeled as monitors ([`monitor::Monitor`]), each with a ring of workspaces
//! ([`workspace::Workspace`]), each with a ring of containers ([`container::Container`]), each with
//! a ring of windows ([`window::Window`]). A workspace tiles its containers by its layout, and a
//! window is moved by asking the [`backend`].
use std::sync::atomic::AtomicI32;
#[macro_use]
pub mod ring;
pub mod backend;
pub mod container;
pub mod core;
pub mod lockable_sequence;
pub mod monitor;
pub mod window;
pub mod workspace;
/// The padding, in pixels, between the edge of a monitor's work area and the tiles of its
/// workspaces, for a monitor that sets none of its own. The default for this is 5.
pub static DEFAULT_WORKSPACE_PADDING: AtomicI32 = AtomicI32::new(5);
/// The padding, in pixels, around each tile, for a monitor that sets none of its own. The default
/// for this is 5.
pub static DEFAULT_CONTAINER_PADDING: AtomicI32 = AtomicI32::new(5);
+416
View File
@@ -0,0 +1,416 @@
//! [`Monitor`], a connected output and the ring of workspaces it can show.
//!
//! A monitor has the bounds and the work area the backend reports for it
//! ([`MonitorInfo`](crate::backend::MonitorInfo)), and shows one of its workspaces, the focused
//! one. Before the focused workspace is tiled it is given the monitor's work area, the monitor's
//! padding (or [`DEFAULT_CONTAINER_PADDING`] and [`DEFAULT_WORKSPACE_PADDING`]) and the work area
//! offset ([`WorkspaceGlobals`]).
use crate::DEFAULT_CONTAINER_PADDING;
use crate::DEFAULT_WORKSPACE_PADDING;
use crate::container::Container;
use crate::core::Rect;
use crate::ring::Ring;
use crate::workspace::Workspace;
use crate::workspace::WorkspaceGlobals;
use color_eyre::eyre;
use color_eyre::eyre::OptionExt;
use serde::Deserialize;
use serde::Serialize;
use std::collections::VecDeque;
use std::sync::atomic::Ordering;
impl_ring_elements!(Monitor, Workspace);
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Monitor {
pub id: u32,
pub device: String,
pub serial_number_id: String,
pub workspaces: Ring<Workspace>,
pub size: Rect,
pub work_area_offset: Option<Rect>,
pub work_area_size: Rect,
pub container_padding: Option<i32>,
pub workspace_padding: Option<i32>,
}
impl Monitor {
#[allow(clippy::field_reassign_with_default)]
pub fn new(
id: u32,
size: Rect,
work_area_size: Rect,
device: &str,
serial_number_id: &str,
) -> Self {
let mut workspaces = Ring::default();
workspaces.elements_mut().push_back(Workspace::default());
Self {
id,
device: device.to_string(),
serial_number_id: serial_number_id.to_string(),
workspaces,
size,
work_area_offset: None,
work_area_size,
container_padding: None,
workspace_padding: None,
}
}
/// Tiles the focused workspace in this monitor's work area, less `offset` if the monitor has
/// no offset of its own
#[tracing::instrument(skip_all)]
pub fn update_focused_workspace(&mut self, offset: Option<Rect>) -> eyre::Result<()> {
let offset = if self.work_area_offset.is_some() {
self.work_area_offset
} else {
offset
};
let focused_workspace_idx = self.focused_workspace_idx();
self.update_workspace_globals(focused_workspace_idx, offset);
self.focused_workspace_mut()
.ok_or_eyre("there is no workspace")?
.update()?;
Ok(())
}
/// Updates the `globals` field of workspace with index `workspace_idx`
pub fn update_workspace_globals(&mut self, workspace_idx: usize, offset: Option<Rect>) {
let container_padding = self
.container_padding
.or(Some(DEFAULT_CONTAINER_PADDING.load(Ordering::Relaxed)));
let workspace_padding = self
.workspace_padding
.or(Some(DEFAULT_WORKSPACE_PADDING.load(Ordering::Relaxed)));
let work_area = self.work_area_size;
let work_area_offset = self.work_area_offset.or(offset);
if let Some(workspace) = self.workspaces_mut().get_mut(workspace_idx) {
workspace.globals = WorkspaceGlobals {
container_padding,
workspace_padding,
work_area,
work_area_offset,
}
}
}
#[tracing::instrument(skip(self))]
pub fn focus_workspace(&mut self, idx: usize) -> eyre::Result<()> {
tracing::info!("focusing workspace");
{
let workspaces = self.workspaces_mut();
if workspaces.get(idx).is_none() {
workspaces.resize(idx + 1, Workspace::default());
}
self.workspaces.focus(idx);
}
Ok(())
}
pub fn new_workspace_idx(&self) -> usize {
self.workspaces().len()
}
pub fn remove_workspace_by_idx(&mut self, idx: usize) -> Option<Workspace> {
if idx < self.workspaces().len() {
return self.workspaces_mut().remove(idx);
}
if idx == 0 {
self.workspaces_mut().push_back(Workspace::default());
} else {
self.focus_workspace(idx.saturating_sub(1)).ok()?;
};
None
}
pub fn add_container(
&mut self,
container: Container,
workspace_idx: Option<usize>,
) -> eyre::Result<()> {
let workspace = if let Some(idx) = workspace_idx {
self.workspaces_mut()
.get_mut(idx)
.ok_or_eyre(format!("there is no workspace at index {}", idx))?
} else {
self.focused_workspace_mut()
.ok_or_eyre("there is no workspace")?
};
workspace.add_container_to_back(container);
Ok(())
}
pub fn remove_workspaces(&mut self) -> VecDeque<Workspace> {
std::mem::take(self.workspaces_mut())
}
pub fn ensure_workspace_count(&mut self, ensure_count: usize) {
if self.workspaces().len() < ensure_count {
self.workspaces_mut()
.resize(ensure_count, Workspace::default());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::fake::FakeBackend;
use crate::backend::with_backend;
use crate::window::Window;
use std::sync::Arc;
#[test]
fn test_add_container() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
// Add container to the default workspace
m.add_container(Container::default(), Some(0)).unwrap();
// Should contain a container in the current focused workspace
let workspace = m.focused_workspace_mut().unwrap();
assert_eq!(workspace.containers().len(), 1);
}
#[test]
fn test_remove_workspace_by_idx() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
let new_workspace_index = m.new_workspace_idx();
assert_eq!(new_workspace_index, 1);
// Create workspace 2
m.focus_workspace(new_workspace_index).unwrap();
// Should have 2 workspaces
assert_eq!(m.workspaces().len(), 2);
// Create workspace 3
m.focus_workspace(new_workspace_index + 1).unwrap();
// Should have 3 workspaces
assert_eq!(m.workspaces().len(), 3);
// Remove workspace 1
m.remove_workspace_by_idx(1);
// Should have only 2 workspaces
assert_eq!(m.workspaces().len(), 2);
}
#[test]
fn test_remove_workspaces() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
let new_workspace_index = m.new_workspace_idx();
assert_eq!(new_workspace_index, 1);
// Create workspace 2
m.focus_workspace(new_workspace_index).unwrap();
// Should have 2 workspaces
assert_eq!(m.workspaces().len(), 2);
// Create workspace 3
m.focus_workspace(new_workspace_index + 1).unwrap();
// Should have 3 workspaces
assert_eq!(m.workspaces().len(), 3);
// Remove all workspaces
m.remove_workspaces();
// All workspaces should be removed
assert_eq!(m.workspaces().len(), 0);
}
#[test]
fn test_remove_nonexistent_workspace() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
// Try to remove a workspace that doesn't exist
let removed_workspace = m.remove_workspace_by_idx(1);
// Should return None since there is no workspace at index 1
assert!(removed_workspace.is_none());
}
#[test]
fn test_focus_workspace() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
let new_workspace_index = m.new_workspace_idx();
assert_eq!(new_workspace_index, 1);
// Focus workspace 2
m.focus_workspace(new_workspace_index).unwrap();
// Should have 2 workspaces
assert_eq!(m.workspaces().len(), 2);
// Should be focused on workspace 2
assert_eq!(m.focused_workspace_idx(), 1);
}
#[test]
fn test_new_workspace_idx() {
let m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
let new_workspace_index = m.new_workspace_idx();
// Should be the last workspace index: 1
assert_eq!(new_workspace_index, 1);
}
#[test]
fn test_ensure_workspace_count_workspace_contains_two_workspaces() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
// Create and focus another workspace
let new_workspace_index = m.new_workspace_idx();
m.focus_workspace(new_workspace_index).unwrap();
// Should have 2 workspaces now
assert_eq!(m.workspaces().len(), 2, "Monitor should have 2 workspaces");
// Ensure the monitor has at least 5 workspaces
m.ensure_workspace_count(5);
// Monitor should have 5 workspaces
assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces");
}
#[test]
fn test_ensure_workspace_count_only_default_workspace() {
let mut m = Monitor::new(
0,
Rect::default(),
Rect::default(),
"TestDevice",
"TestDeviceId",
);
// Ensure the monitor has at least 5 workspaces
m.ensure_workspace_count(5);
// Monitor should have 5 workspaces
assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces");
// Try to call the ensure workspace count again to ensure it doesn't change
m.ensure_workspace_count(3);
assert_eq!(m.workspaces().len(), 5, "Monitor should have 5 workspaces");
}
fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
Rect {
left,
top,
right,
bottom,
}
}
/// The fake's monitor, as a [`Monitor`], with one window tiled on its focused workspace
fn monitor_with_window(id: u32) -> (Arc<FakeBackend>, Monitor) {
let fake = Arc::new(FakeBackend::with_one_monitor());
fake.open_window(id, "foot", "foot", "a terminal");
let mut m = Monitor::new(
1,
rect(0, 0, 1920, 1080),
rect(0, 0, 1920, 1050),
"Virtual-0",
"Virtual-0",
);
m.focused_workspace_mut()
.unwrap()
.new_container_for_window(&Window::from(id))
.unwrap();
(fake, m)
}
#[test]
fn the_focused_workspace_is_tiled_in_the_work_area_with_the_default_padding() -> eyre::Result<()>
{
let (fake, mut m) = monitor_with_window(501);
with_backend(fake.clone(), || m.update_focused_workspace(None))?;
// the work area leaves the panel alone; the default workspace padding and the default
// container padding are 5 each
assert_eq!(fake.rect_of(501), Some(rect(10, 10, 1900, 1030)));
Ok(())
}
#[test]
fn the_monitors_own_padding_and_offset_win_over_what_it_is_given() -> eyre::Result<()> {
let (fake, mut m) = monitor_with_window(511);
m.container_padding = Some(0);
m.workspace_padding = Some(0);
m.work_area_offset = Some(rect(100, 0, 100, 0));
with_backend(fake.clone(), || {
m.update_focused_workspace(Some(rect(0, 200, 0, 200)))
})?;
assert_eq!(fake.rect_of(511), Some(rect(100, 0, 1820, 1050)));
Ok(())
}
}
+66 -1
View File
@@ -1,7 +1,8 @@
//! [`Ring`], a list of elements with one of them focused.
//!
//! Monitors, workspaces and containers each keep their children in a ring, so that "the focused
//! one" is the same thing everywhere.
//! one" is the same thing everywhere, and `impl_ring_elements!` gives each of them the same
//! accessors for it.
use std::collections::VecDeque;
@@ -75,10 +76,74 @@ impl<T> Ring<T> {
}
}
/// Gives a type that keeps its children in a [`Ring`] the accessors every such type has.
///
/// `impl_ring_elements!(Workspace, Container)` reads the field `containers: Ring<Container>` and
/// gives `Workspace` the methods `containers()`, `containers_mut()`, `focused_container()`,
/// `focused_container_idx()` and `focused_container_mut()`. The field is named after the element
/// type in lower case with an `s` appended, and the methods after the field, so that "the focused
/// container" is spelled the same way on every type that has one.
macro_rules! impl_ring_elements {
($name:ty, $element:ident) => {
pastey::paste! {
impl $name {
pub const fn [<$element:lower s>](&self) -> &std::collections::VecDeque<$element> {
self.[<$element:lower s>].elements()
}
pub fn [<$element:lower s_mut>](&mut self) -> &mut std::collections::VecDeque<$element> {
self.[<$element:lower s>].elements_mut()
}
#[allow(dead_code)]
pub fn [<focused_ $element:lower>](&self) -> Option<&$element> {
self.[<$element:lower s>].focused()
}
pub const fn [<focused_ $element:lower _idx>](&self) -> usize {
self.[<$element:lower s>].focused_idx()
}
pub fn [<focused_ $element:lower _mut>](&mut self) -> Option<&mut $element> {
self.[<$element:lower s>].focused_mut()
}
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, PartialEq)]
struct Book(&'static str);
struct Shelf {
books: Ring<Book>,
}
impl_ring_elements!(Shelf, Book);
#[test]
fn impl_ring_elements_names_the_accessors_after_the_element() {
let mut shelf = Shelf {
books: Ring::default(),
};
shelf.books_mut().extend([Book("a"), Book("b")]);
shelf.books.focus(1);
assert_eq!(shelf.books().len(), 2);
assert_eq!(shelf.focused_book(), Some(&Book("b")));
assert_eq!(shelf.focused_book_idx(), 1);
if let Some(book) = shelf.focused_book_mut() {
*book = Book("c");
}
assert_eq!(shelf.books()[1], Book("c"));
}
#[test]
fn an_empty_ring_focuses_nothing() {
let mut ring: Ring<u8> = Ring::default();
+304
View File
@@ -0,0 +1,304 @@
//! [`Window`], the window manager's handle to a window on the desktop.
//!
//! A window is a `Copy` value that carries only the compositor's id for it. Everything else about
//! the window (its title, its class, where it is) is asked of the
//! [`Backend`](crate::backend::Backend) when it is needed, and everything done to it (a move, the
//! focus, a close) is a command to the backend. Nothing is cached, so a window that changed its
//! title, or closed, is seen as it is now.
use crate::backend::backend;
use crate::core::Rect;
use color_eyre::eyre;
use color_eyre::eyre::OptionExt;
use serde::Deserialize;
use serde::Serialize;
use serde::Serializer;
use serde::ser::SerializeStruct;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Write;
use std::path::PathBuf;
/// A handle to a window on the desktop: just its id.
///
/// It is `Copy`, events carry it by value, and everything else (title, class, geometry, ...) is
/// asked of the [`crate::backend::Backend`] when needed. The id is the compositor's
/// ([`WindowInfo::id`](crate::backend::WindowInfo::id)), and stays the same for the life of the
/// window.
#[derive(Debug, Default, Clone, Copy, Deserialize, PartialEq, Eq, Hash)]
pub struct Window {
pub id: u32,
}
impl From<u32> for Window {
fn from(id: u32) -> Self {
Self { id }
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WindowDetails {
pub title: String,
pub exe: String,
pub class: String,
pub path: String,
}
impl From<&Window> for WindowDetails {
fn from(value: &Window) -> Self {
Self::from(*value)
}
}
impl From<Window> for WindowDetails {
fn from(value: Window) -> Self {
Self {
title: value.title().unwrap_or_default(),
exe: value.exe().unwrap_or_default(),
class: value.class().unwrap_or_default(),
path: value
.path()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default(),
}
}
}
impl Display for Window {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut display = format!("(window_id: {}", self.id);
if let Some(info) = self.info() {
write!(display, ", process_id: {}", info.pid)?;
write!(display, ", title: {}", info.title)?;
write!(display, ", exe: {}", info.exe)?;
write!(display, ", class: {}", info.class)?;
}
write!(display, ")")?;
write!(f, "{display}")
}
}
impl Serialize for Window {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Window", 3)?;
state.serialize_field("id", &self.id)?;
state.serialize_field("rect", &self.rect().unwrap_or_default())?;
state.serialize_field("details", &WindowDetails::from(*self))?;
state.end()
}
}
#[cfg(feature = "schemars")]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
struct SerializedWindow {
id: u32,
title: String,
exe: String,
class: String,
path: String,
rect: Rect,
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Window {
fn schema_name() -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed("Window")
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
<SerializedWindow as schemars::JsonSchema>::json_schema(generator)
}
}
impl Window {
/// What the compositor knows about this window, including for a few moments after it closed
pub fn info(self) -> Option<crate::backend::WindowInfo> {
backend().window(self.id)
}
/// Whether the window still exists
pub fn is_valid(self) -> bool {
backend().is_window(self.id)
}
pub fn is_focused(self) -> bool {
backend().foreground_window() == Some(self.id)
}
pub fn is_minimized(self) -> bool {
self.info().is_some_and(|i| i.minimized)
}
pub fn title(self) -> Option<String> {
self.info().map(|i| i.title)
}
pub fn exe(self) -> Option<String> {
self.info().map(|i| i.exe)
}
/// The Wayland `app_id` (or X11 `WM_CLASS`)
pub fn class(self) -> Option<String> {
self.info().map(|i| i.class)
}
pub fn path(self) -> Option<PathBuf> {
self.info().map(|i| PathBuf::from(i.path))
}
pub fn process_id(self) -> i32 {
self.info().map_or(0, |i| i.pid)
}
/// The window's current frame geometry, as last reported by the compositor
pub fn rect(self) -> eyre::Result<Rect> {
backend()
.window_rect(self.id)
.ok_or_eyre("the window does not exist")
}
/// Asks the compositor to move and resize the window to `rect`; where the window ends up is
/// [`Window::rect`], since a client may refuse a size
pub fn set_position(self, rect: &Rect) -> eyre::Result<()> {
backend().set_rect(self.id, rect)
}
pub fn focus(self, mouse_follows_focus: bool) -> eyre::Result<()> {
backend().focus(self.id, mouse_follows_focus)
}
pub fn raise(self) -> eyre::Result<()> {
backend().raise(self.id)
}
pub fn close(self) -> eyre::Result<()> {
backend().close(self.id)
}
pub fn minimize(self) -> eyre::Result<()> {
backend().minimize(self.id)
}
pub fn unminimize(self) -> eyre::Result<()> {
backend().unminimize(self.id)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::fake::Command;
use crate::backend::fake::FakeBackend;
use crate::backend::with_backend;
use std::sync::Arc;
fn fake_with(id: u32) -> Arc<FakeBackend> {
let fake = Arc::new(FakeBackend::with_one_monitor());
fake.open_window(id, "foot", "foot", "a terminal");
fake
}
#[test]
fn a_window_is_what_the_backend_says_it_is() -> eyre::Result<()> {
let fake = fake_with(201);
fake.set_foreground(Some(201));
with_backend(fake, || {
let window = Window::from(201);
assert!(window.is_valid());
assert!(window.is_focused());
assert!(!window.is_minimized());
assert_eq!(window.title().as_deref(), Some("a terminal"));
assert_eq!(window.exe().as_deref(), Some("foot"));
assert_eq!(window.class().as_deref(), Some("foot"));
assert_eq!(window.path(), Some(PathBuf::from("/usr/bin/foot")));
assert_eq!(window.process_id(), 1201);
assert_eq!(
window.rect()?,
Rect {
left: 100,
top: 100,
right: 800,
bottom: 600,
}
);
assert_eq!(
window.to_string(),
"(window_id: 201, process_id: 1201, title: a terminal, exe: foot, class: foot)"
);
Ok(())
})
}
#[test]
fn a_window_the_backend_does_not_know_has_no_details() {
let fake = Arc::new(FakeBackend::with_one_monitor());
with_backend(fake, || {
let window = Window::from(202);
assert!(!window.is_valid());
assert_eq!(window.title(), None);
assert_eq!(window.process_id(), 0);
assert!(window.rect().is_err());
assert_eq!(window.to_string(), "(window_id: 202)");
});
}
#[test]
fn every_change_to_a_window_is_a_command_to_the_backend() -> eyre::Result<()> {
let fake = fake_with(203);
let tile = Rect {
left: 0,
top: 0,
right: 960,
bottom: 1050,
};
with_backend(fake.clone(), || {
let window = Window::from(203);
window.set_position(&tile)?;
window.focus(false)?;
window.raise()?;
window.minimize()?;
window.unminimize()?;
window.close()
})?;
assert_eq!(
fake.commands(),
[
Command::SetRect(203, tile),
Command::Focus(203, false),
Command::Raise(203),
Command::Minimize(203),
Command::Unminimize(203),
Command::Close(203),
]
);
Ok(())
}
#[test]
fn a_window_serializes_with_what_the_backend_knows_about_it() -> eyre::Result<()> {
let fake = fake_with(204);
let json = with_backend(fake, || serde_json::to_value(Window::from(204)))?;
assert_eq!(json["id"], 204);
assert_eq!(json["rect"]["right"], 800);
assert_eq!(json["details"]["title"], "a terminal");
assert_eq!(json["details"]["path"], "/usr/bin/foot");
Ok(())
}
}
+948
View File
@@ -0,0 +1,948 @@
//! [`Workspace`], a ring of containers tiled by a layout.
//!
//! A workspace keeps its containers in order. [`Workspace::update`] asks the layout for one tile
//! per container in the work area it was given, less its padding, and puts every window of each
//! container on its tile with [`Window::set_position`]. The work area and the padding a workspace
//! falls back to come from the monitor it is on ([`WorkspaceGlobals`]).
use crate::container::Container;
use crate::core::DefaultLayout;
use crate::core::Layout;
use crate::core::Rect;
use crate::lockable_sequence::LockableSequence;
use crate::ring::Ring;
use crate::window::Window;
use color_eyre::eyre;
use color_eyre::eyre::OptionExt;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::num::NonZeroUsize;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Workspace {
pub containers: Ring<Container>,
pub layout: Layout,
pub workspace_padding: Option<i32>,
pub container_padding: Option<i32>,
#[serde(skip)]
pub globals: WorkspaceGlobals,
}
impl_ring_elements!(Workspace, Container);
impl Default for Workspace {
fn default() -> Self {
Self {
containers: Default::default(),
workspace_padding: None,
container_padding: None,
layout: Layout::Default(DefaultLayout::BSP),
globals: Default::default(),
}
}
}
#[derive(Debug, Default, Copy, Clone, Serialize, Deserialize, PartialEq)]
/// The work area a monitor gives the workspace it shows, and the padding and the offset the
/// workspace falls back to when it sets none of its own
pub struct WorkspaceGlobals {
pub container_padding: Option<i32>,
pub workspace_padding: Option<i32>,
pub work_area: Rect,
pub work_area_offset: Option<Rect>,
}
impl Workspace {
#[tracing::instrument(skip(self))]
pub fn focus_container(&mut self, idx: usize) {
tracing::info!("focusing container");
self.containers.focus(idx);
}
pub fn swap_containers(&mut self, i: usize, j: usize) {
self.containers.elements_mut().swap_respecting_locks(i, j);
self.focus_container(j);
}
pub fn container_idx_for_window(&self, window_id: u32) -> Option<usize> {
let mut idx = None;
for (i, x) in self.containers().iter().enumerate() {
if x.contains_window(window_id) {
idx = Option::from(i);
}
}
idx
}
pub fn focus_container_by_window(&mut self, window_id: u32) -> eyre::Result<()> {
let container_idx = self
.container_idx_for_window(window_id)
.ok_or_eyre("there is no container/window")?;
let container = self
.containers_mut()
.get_mut(container_idx)
.ok_or_eyre("there is no container")?;
let window_idx = container
.idx_for_window(window_id)
.ok_or_eyre("there is no window")?;
container.focus_window(window_idx);
self.focus_container(container_idx);
Ok(())
}
/// Puts the window in a container of its own, after the focused container (at the start of an
/// empty workspace), and focuses that container
pub fn new_container_for_window(&mut self, window: &Window) -> eyre::Result<()> {
let next_idx = if self.containers().is_empty() {
0
} else {
self.focused_container_idx() + 1
};
let mut container = Container::default();
container.add_window(window)?;
self.insert_container_at_idx(next_idx, container);
Ok(())
}
// this fn respects locked container indexes - we should use it for pretty much everything
// except monocle and maximize toggles
pub fn insert_container_at_idx(&mut self, idx: usize, container: Container) -> usize {
let insertion_idx = self
.containers_mut()
.insert_respecting_locks(idx, container);
self.focus_container(insertion_idx);
insertion_idx
}
pub fn prune_duplicate_windows(&mut self) -> eyre::Result<()> {
let mut tracker = HashMap::new();
let mut to_prune_from_containers = vec![];
for container in self.containers() {
for window in container.windows() {
let entry = tracker.entry(window.id).or_insert(0);
*entry += 1;
}
}
for (window_id, count) in &tracker {
if *count > 1 {
to_prune_from_containers.push(*window_id);
}
}
for id in to_prune_from_containers {
self.remove_window(id)?;
tracker.remove(&id);
}
Ok(())
}
pub fn remove_window(&mut self, window_id: u32) -> eyre::Result<Window> {
let container_idx = self
.container_idx_for_window(window_id)
.ok_or_eyre("there is no window")?;
let container = self
.containers_mut()
.get_mut(container_idx)
.ok_or_eyre("there is no container")?;
let window_idx = container
.windows()
.iter()
.position(|window| window.id == window_id)
.ok_or_eyre("there is no window")?;
let window = container
.remove_window_by_idx(window_idx)
.ok_or_eyre("there is no window")?;
if container.windows().is_empty() {
self.remove_container_by_idx(container_idx);
self.focus_previous_container();
}
Ok(window)
}
// this fn respects locked container indexes - we should use it for pretty much everything
// except monocle and maximize toggles
pub fn remove_container_by_idx(&mut self, idx: usize) -> Option<Container> {
self.containers_mut().remove_respecting_locks(idx)
}
pub fn focus_previous_container(&mut self) {
let focused_idx = self.focused_container_idx();
self.focus_container(focused_idx.saturating_sub(1));
}
pub fn is_empty(&self) -> bool {
self.containers().is_empty()
}
pub fn contains_window(&self, window_id: u32) -> bool {
for container in self.containers() {
if container.contains_window(window_id) {
return true;
}
}
false
}
pub fn remove_focused_container(&mut self) -> Option<Container> {
let focused_idx = self.focused_container_idx();
let container = self.remove_container_by_idx(focused_idx);
self.focus_previous_container();
container
}
pub fn remove_container(&mut self, idx: usize) -> Option<Container> {
let container = self.remove_container_by_idx(idx);
self.focus_previous_container();
container
}
pub fn add_container_to_back(&mut self, container: Container) {
self.containers_mut().push_back(container);
self.focus_last_container();
}
pub fn add_container_to_front(&mut self, container: Container) {
self.containers_mut().push_front(container);
self.focus_first_container();
}
fn focus_last_container(&mut self) {
self.focus_container(self.containers().len().saturating_sub(1));
}
fn focus_first_container(&mut self) {
self.focus_container(0);
}
}
impl Workspace {
/// Tiles the workspace: asks the layout for a tile per container in the work area, less the
/// offset and the workspace padding, and puts every window of each container on its tile.
///
/// Containers that have no windows left are dropped first, and so is a window that is in more
/// than one container. A tile is clamped to the work area, so it cannot bleed onto a
/// neighboring monitor.
pub fn update(&mut self) -> eyre::Result<()> {
// make sure we are never holding on to empty containers
self.prune_duplicate_windows()?;
let focused_container_idx = self.focused_container_idx();
self.containers_mut().retain(|c| !c.windows().is_empty());
// make sure we are never focused on a no longer existent final empty container
if focused_container_idx >= self.containers().len() {
self.focus_container(focused_container_idx.saturating_sub(1));
}
let container_padding = self
.container_padding
.or(self.globals.container_padding)
.unwrap_or_default();
let workspace_padding = self
.workspace_padding
.or(self.globals.workspace_padding)
.unwrap_or_default();
let work_area = self.globals.work_area;
let work_area_offset = self.globals.work_area_offset;
let mut adjusted_work_area = work_area_offset.map_or_else(
|| work_area,
|offset| {
let mut with_offset = work_area;
with_offset.left += offset.left;
with_offset.top += offset.top;
with_offset.right -= offset.right;
with_offset.bottom -= offset.bottom;
with_offset
},
);
adjusted_work_area.add_padding(workspace_padding);
// the backend batches the commands this produces and sends them together
let result = (|| -> eyre::Result<()> {
if !self.containers().is_empty() {
let mut layouts = self.layout.as_boxed_arrangement().calculate(
&adjusted_work_area,
NonZeroUsize::new(self.containers().len()).ok_or_eyre(
"there must be at least one container to calculate a workspace layout",
)?,
Some(container_padding),
None,
&[],
self.focused_container_idx(),
None,
&[],
);
let containers = self.containers_mut();
for (i, container) in containers.iter_mut().enumerate() {
if let Some(layout) = layouts.get_mut(i) {
// Every tile is clamped to the work area so it cannot bleed onto an
// adjacent monitor.
// horizontal
if layout.left < adjusted_work_area.left {
layout.right -= adjusted_work_area.left - layout.left;
layout.left = adjusted_work_area.left;
}
let max_right_edge = adjusted_work_area.left + adjusted_work_area.right;
let current_right_edge = layout.left + layout.right;
if current_right_edge > max_right_edge {
layout.right = max_right_edge - layout.left;
}
// vertical
if layout.top < adjusted_work_area.top {
layout.bottom -= adjusted_work_area.top - layout.top;
layout.top = adjusted_work_area.top;
}
let max_bottom_edge = adjusted_work_area.top + adjusted_work_area.bottom;
let current_bottom_edge = layout.top + layout.bottom;
if current_bottom_edge > max_bottom_edge {
layout.bottom = max_bottom_edge - layout.top;
}
for window in container.windows_mut() {
if let Err(error) = window.set_position(layout) {
tracing::warn!("failed to set window position: {error}")
}
}
}
}
}
Ok(())
})();
result?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::backend::fake::FakeBackend;
use crate::backend::with_backend;
use crate::container::Container;
use crate::window::Window;
use std::collections::HashMap;
use std::sync::Arc;
#[test]
fn test_locked_containers_with_new_window() {
let mut ws = Workspace::default();
let mut state = HashMap::new();
// add 4 containers
for i in 0..4 {
let mut container = Container::default();
if i == 3 {
container.locked = true; // set index 3 locked
}
state.insert(i, container.id.to_string());
ws.add_container_to_back(container);
}
assert_eq!(ws.containers().len(), 4);
// focus container at index 2
ws.focus_container(2);
// simulate a new window being launched on this workspace
ws.new_container_for_window(&Window::from(123)).unwrap();
// new length should be 5, with the focus on the new window at index 4
assert_eq!(ws.containers().len(), 5);
assert_eq!(ws.focused_container_idx(), 4);
assert_eq!(
ws.focused_container().unwrap().focused_window().unwrap().id,
123
);
// when inserting a new container at index 0, index 3's container should not change
ws.focus_container(0);
ws.new_container_for_window(&Window::from(234)).unwrap();
assert_eq!(
ws.containers()[3].id.to_string(),
state.get(&3).unwrap().to_string()
);
}
#[test]
fn test_locked_containers_remove_window() {
let mut ws = Workspace::default();
// add 4 containers
for i in 0..4 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
if i == 1 {
container.locked = true;
}
ws.add_container_to_back(container);
}
assert_eq!(ws.containers().len(), 4);
ws.remove_window(0).unwrap();
assert_eq!(ws.containers()[0].focused_window().unwrap().id, 2);
// index 1 should still be the same
assert_eq!(ws.containers()[1].focused_window().unwrap().id, 1);
assert_eq!(ws.containers()[2].focused_window().unwrap().id, 3);
}
#[test]
fn test_contains_window() {
// Create default workspace
let mut workspace = Workspace::default();
// Add a window to the container
let mut container = Container::default();
container.windows_mut().push_back(Window::from(0));
// Add container
workspace.add_container_to_back(container);
// Should be true
assert!(workspace.contains_window(0));
// Should be false
assert!(!workspace.is_empty())
}
#[test]
fn test_add_container_to_back() {
let mut workspace = Workspace::default();
{
// Container with 3 windows
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_back(container);
}
{
// Container with 1 window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
}
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
// Get focused container. Should be the index of the last container added
let container = workspace.focused_container_mut().unwrap();
// Should be focused on the container with 1 window
assert_eq!(container.windows().len(), 1);
}
#[test]
fn test_add_container_to_front() {
let mut workspace = Workspace::default();
{
// Container with 1 window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_front(container);
}
{
// Container with 3 windows
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_front(container);
}
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
// Get focused container. Should be the index of the last container added
let container = workspace.focused_container_mut().unwrap();
// Should be focused on the container with 3 windows
assert_eq!(container.windows().len(), 3);
}
#[test]
fn test_remove_non_existent_window() {
let mut workspace = Workspace::default();
{
// Add a container with one window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
}
// Attempt to remove a non-existent window
let result = workspace.remove_window(2);
// Should return an error
assert!(
result.is_err(),
"Expected an error when removing a non-existent window"
);
// Get focused container. Should be the index of the last container added
let container = workspace.focused_container_mut().unwrap();
// Should still have 1 window
assert_eq!(container.windows().len(), 1);
}
#[test]
fn test_remove_focused_container() {
let mut workspace = Workspace::default();
{
// Container with 1 window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
}
{
// Container with 1 window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
}
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
// Should be focused on the container at index 1
assert_eq!(workspace.focused_container_idx(), 1);
// Store the container at index 1 before removal
let container_to_remove = workspace.containers().get(1).cloned();
workspace.remove_focused_container();
// Should only have 1 container
assert_eq!(workspace.containers().len(), 1);
// Should be focused on the container at index 0
assert_eq!(workspace.focused_container_idx(), 0);
// Ensure the container at index 1 before removal is no longer present
assert!(container_to_remove.is_some());
assert!(
!workspace
.containers()
.contains(&container_to_remove.unwrap())
);
}
#[test]
fn test_insert_container_at_idx() {
let mut workspace = Workspace::default();
for i in 0..4 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 4 containers
assert_eq!(workspace.containers().len(), 4);
// Should be focused on the last container
assert_eq!(workspace.focused_container_idx(), 3);
// Insert a container at index 4
workspace.insert_container_at_idx(4, Container::default());
// Should have 5 containers
assert_eq!(workspace.containers().len(), 5);
// Should be focused on the newly inserted container
assert_eq!(workspace.focused_container_idx(), 4);
}
#[test]
fn test_remove_container_by_idx() {
let mut workspace = Workspace::default();
for i in 0..3 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 3 containers
assert_eq!(workspace.containers().len(), 3);
// Should be focused on the last container
assert_eq!(workspace.focused_container_idx(), 2);
// Store the container at index 1 before removal
let container_to_remove = workspace.containers().get(1).cloned();
// Remove the container at index 1
workspace.remove_container_by_idx(1);
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
// Ensure the container at index 1 before removal is no longer present
assert!(container_to_remove.is_some());
assert!(
!workspace
.containers()
.contains(&container_to_remove.unwrap())
);
}
#[test]
fn test_remove_container() {
let mut workspace = Workspace::default();
for i in 0..3 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 3 containers
assert_eq!(workspace.containers().len(), 3);
// Should be focused on the last container
assert_eq!(workspace.focused_container_idx(), 2);
// Store the container at index 2 before removal
let container_to_remove = workspace.containers().get(2).cloned();
// Remove the container at index 2
workspace.remove_container(2);
// Should be focused on the previous container which is index 1
assert_eq!(workspace.focused_container_idx(), 1);
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
// Ensure the container at index 1 before removal is no longer present
assert!(container_to_remove.is_some());
assert!(
!workspace
.containers()
.contains(&container_to_remove.unwrap())
);
}
#[test]
fn test_focus_container() {
let mut workspace = Workspace::default();
for i in 0..3 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 3 containers
assert_eq!(workspace.containers().len(), 3);
// Should be focused on the last container
assert_eq!(workspace.focused_container_idx(), 2);
// Focus on container 1
workspace.focus_container(1);
assert_eq!(workspace.focused_container_idx(), 1);
// Focus on container 0
workspace.focus_container(0);
assert_eq!(workspace.focused_container_idx(), 0);
// Focus on container 2
workspace.focus_container(2);
assert_eq!(workspace.focused_container_idx(), 2);
}
#[test]
fn test_focus_previous_container() {
let mut workspace = Workspace::default();
for i in 0..3 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 3 containers
assert_eq!(workspace.containers().len(), 3);
// Should be focused on the last container
assert_eq!(workspace.focused_container_idx(), 2);
// Focus on the previous container
workspace.focus_previous_container();
// Should be focused on container 1
assert_eq!(workspace.focused_container_idx(), 1);
}
#[test]
fn test_focus_last_container() {
let mut workspace = Workspace::default();
for i in 0..3 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 3 containers
assert_eq!(workspace.containers().len(), 3);
// Change focus to the first container for the test
workspace.focus_container(0);
assert_eq!(workspace.focused_container_idx(), 0);
// Focus on the last container
workspace.focus_last_container();
// Should be focused on container 1
assert_eq!(workspace.focused_container_idx(), 2);
}
#[test]
fn test_focus_first_container() {
let mut workspace = Workspace::default();
for i in 0..3 {
let mut container = Container::default();
container.windows_mut().push_back(Window::from(i));
workspace.add_container_to_back(container);
}
// Should have 3 containers
assert_eq!(workspace.containers().len(), 3);
// Should be focused on the last container
assert_eq!(workspace.focused_container_idx(), 2);
// Focus on the first container
workspace.focus_first_container();
// Should be focused on container 1
assert_eq!(workspace.focused_container_idx(), 0);
}
#[test]
fn test_swap_containers() {
let mut workspace = Workspace::default();
{
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_back(container);
}
{
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
}
// Should have 2 containers
assert_eq!(workspace.containers().len(), 2);
{
// Should be focused on container 1
assert_eq!(workspace.focused_container_idx(), 1);
// Should have 1 window
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 1);
}
// Swap containers 0 and 1
workspace.swap_containers(0, 1);
{
// Should be focused on container 0
assert_eq!(workspace.focused_container_idx(), 1);
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 3);
}
}
#[test]
fn test_new_container_for_window() {
let mut workspace = Workspace::default();
{
let mut container = Container::default();
container.windows_mut().push_back(Window::from(1));
workspace.add_container_to_back(container);
}
// Add new window to container
workspace
.new_container_for_window(&Window::from(2))
.unwrap();
// Container 0 should have 1 window
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 1);
// Should return true that window 2 exists
assert!(workspace.contains_window(2));
}
#[test]
fn test_remove_window() {
let mut workspace = Workspace::default();
{
// Container with 1 window
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_back(container);
}
// Remove window 1
workspace.remove_window(1).ok();
// Should have 2 windows
let container = workspace.focused_container_mut().unwrap();
assert_eq!(container.windows().len(), 2);
// Check that window 1 is removed
assert!(!workspace.contains_window(1));
}
#[test]
fn test_focus_container_by_window() {
let mut workspace = Workspace::default();
{
// Container with 3 windows
let mut container = Container::default();
for i in 0..3 {
container.windows_mut().push_back(Window::from(i));
}
workspace.add_container_to_back(container);
}
{
// Container with 1 window
let mut container = Container::default();
container.windows_mut().push_back(Window::from(4));
workspace.add_container_to_back(container);
}
// Focus container by window
workspace.focus_container_by_window(1).unwrap();
// Should be focused on workspace 0
assert_eq!(workspace.focused_container_idx(), 0);
// Should be focused on window 1 and hwnd should be 1
let focused_container = workspace.focused_container_mut().unwrap();
assert_eq!(focused_container.focused_window().unwrap().id, 1);
assert_eq!(focused_container.focused_window_idx(), 1);
}
fn tile(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
Rect {
left,
top,
right,
bottom,
}
}
/// A workspace on the fake's 1920x1080 monitor, whose work area is 1920x1050, with a container
/// for each of `ids`
fn workspace_with(ids: &[u32]) -> (Arc<FakeBackend>, Workspace) {
let fake = Arc::new(FakeBackend::with_one_monitor());
let mut workspace = Workspace::default();
workspace.globals.work_area = tile(0, 0, 1920, 1050);
for id in ids {
fake.open_window(*id, "foot", "foot", &format!("terminal {id}"));
workspace
.new_container_for_window(&Window::from(*id))
.unwrap();
}
(fake, workspace)
}
#[test]
fn update_puts_each_window_on_its_tile() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with(&[401, 402]);
with_backend(fake.clone(), || workspace.update())?;
assert_eq!(fake.rect_of(401), Some(tile(0, 0, 960, 1050)));
assert_eq!(fake.rect_of(402), Some(tile(960, 0, 960, 1050)));
Ok(())
}
#[test]
fn update_leaves_the_padding_and_the_offset_free() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with(&[411]);
workspace.workspace_padding = Some(10);
workspace.container_padding = Some(5);
workspace.globals.work_area_offset = Some(tile(0, 40, 0, 40));
with_backend(fake.clone(), || workspace.update())?;
// the offset moves the top edge down by 40, the workspace padding takes 10 off every edge,
// and the container padding 5 more
assert_eq!(fake.rect_of(411), Some(tile(15, 55, 1890, 980)));
Ok(())
}
#[test]
fn update_drops_a_container_that_has_no_windows_left() -> eyre::Result<()> {
let (fake, mut workspace) = workspace_with(&[421]);
workspace.add_container_to_back(Container::default());
with_backend(fake.clone(), || workspace.update())?;
assert_eq!(workspace.containers().len(), 1);
assert_eq!(workspace.focused_container_idx(), 0);
assert_eq!(fake.rect_of(421), Some(tile(0, 0, 1920, 1050)));
Ok(())
}
}