diff --git a/README.md b/README.md index 5b821fac..cb746e00 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,28 @@ Bookmarks are exported as workspaces over `ext-workspace-v1` — bars that suppo it can list them and click to jump. It's an export for tooling, not real workspaces; driftwm is still one canvas. +### Scratchpad + +`toggle-scratchpad ` is a one-key dropdown: it spawns the app +if it isn't running, instantly stows its window when showing, and brings it +back at the exact place and size you left it. Paired with a `pinned_to_screen` +window rule, it makes a Yakuake-style dropdown terminal (or a mail client, a +music player) with no animation and no external script. The app keeps running +while stowed. + +```toml +[keybindings] +"mod+w" = "toggle-scratchpad dropdown-term kitty --class dropdown-term" + +[[window_rules]] +app_id = "dropdown-term" +pinned_to_screen = true +position = [0, 185] +size = [1200, 450] +``` + +See [docs/scratchpad.md](docs/scratchpad.md). + ### Window suspend & session restore https://github.com/user-attachments/assets/a91d92bd-55af-4646-8be8-81f35f8f38ca diff --git a/config.reference.toml b/config.reference.toml index 3f6d0b34..31f88130 100644 --- a/config.reference.toml +++ b/config.reference.toml @@ -357,6 +357,8 @@ # # fit-window-snapped — fit-window, moving its snap cluster along # # fill-window — grow the focused window into the free space around it; again to restore # # toggle-pin-to-screen — pin the focused window to the screen, ignoring pan and zoom +# # toggle-scratchpad — hide or show the window with that app_id, spawning if none exists; +# # such apps are not session-restored (a `restore_windows = true` rule overrides) # # reload-config — hot-reload the config file # # toggle-cursor-pan — toggle bare-cursor edge-pan (see [navigation.edge_pan]) # # set-trackpad on|off|toggle — turn every trackpad on or off for this session @@ -434,6 +436,8 @@ # # Example: set-trackpad (unbound by default) # # "mod+f10" = "set-trackpad toggle" # flip the trackpad between on and off # # "mod+shift+f10" = "set-trackpad off" # turn it off whatever the current state +# # Example: dropdown terminal; pair with a pinned_to_screen window rule for its place +# # "mod+grave" = "toggle-scratchpad dropdown kitty --class dropdown" # # Example: grow and shrink the right edge by resize_step screen px (unbound by default) # # "mod+ctrl+alt+right" = "grow-window right" # # "mod+ctrl+alt+left" = "shrink-window right" diff --git a/dev/site/src/SUMMARY.md b/dev/site/src/SUMMARY.md index 48c66f57..8720e653 100644 --- a/dev/site/src/SUMMARY.md +++ b/dev/site/src/SUMMARY.md @@ -3,6 +3,7 @@ - [Home](index.md) - [Configuration](config.md) - [Window rules](window-rules.md) +- [Scratchpad](scratchpad.md) - [Window suspend & session restore](session.md) - [IPC](ipc.md) - [CLI](cli.md) diff --git a/docs/config.md b/docs/config.md index c8cc46dd..c945e77a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -779,6 +779,7 @@ Actions: - `fit-window-snapped` — fit-window, moving its snap cluster along - `fill-window` — grow the focused window into the free space around it; again to restore - `toggle-pin-to-screen` — pin the focused window to the screen, ignoring pan and zoom +- `toggle-scratchpad ` — hide or show the window with that app_id, spawning if none exists; such apps are not session-restored (a `restore_windows = true` rule overrides) - `reload-config` — hot-reload the config file - `toggle-cursor-pan` — toggle bare-cursor edge-pan (see [navigation.edge_pan]) - `set-trackpad on|off|toggle` — turn every trackpad on or off for this session @@ -880,6 +881,12 @@ Directions: up, down, left, right, up-left, up-right, down-left, down-right "mod+shift+f10" = "set-trackpad off" # turn it off whatever the current state ``` +**Example: dropdown terminal; pair with a pinned_to_screen window rule for its place** + +```toml +"mod+grave" = "toggle-scratchpad dropdown kitty --class dropdown" +``` + **Example: grow and shrink the right edge by resize_step screen px (unbound by default)** ```toml diff --git a/docs/scratchpad.md b/docs/scratchpad.md new file mode 100644 index 00000000..d76d308b --- /dev/null +++ b/docs/scratchpad.md @@ -0,0 +1,102 @@ +# Scratchpad + +A scratchpad is a window you summon and dismiss with one key: a dropdown +terminal, a mail client, a music player. Pressing the key **spawns** the app if +it isn't running, **stows** its window when it is showing, and **shows** it +again when it is stowed. Stowing is instant and animation-free, the window +stays mapped and its app keeps running (a terminal keeps its shell and +scrollback), and showing it puts it back exactly where, and at the size, you +left it. + +driftwm has no minimize, so this is the way to get a Quake/Yakuake-style +dropdown without an external script. + +## Set one up + +Three steps: bind a key, give the window a place, reload. + +**1. Find the app's `app_id`.** Start the app and run `driftwm msg state`; each +window is listed with its `app_id`. The binding matches it **exactly** +(`kitty` and `Kitty` are different). Many terminals let you choose it, which +keeps a dropdown terminal apart from your ordinary ones: + +| Terminal | Flag | +| --------- | ------------------------ | +| kitty | `--class dropdown-term` | +| foot | `--app-id dropdown-term` | +| alacritty | `--class dropdown-term` | + +**2. Bind a key.** `toggle-scratchpad ` takes the +`app_id` to look for and the command that spawns it when no such window exists: + +```toml +[keybindings] +"mod+w" = "toggle-scratchpad dropdown-term kitty --class dropdown-term" +``` + +Any binding type works: a key, a tap-modifier chord, a mouse button or a +gesture. + +**3. Give it a place.** Where the window appears is decided by an ordinary +[window rule](window-rules.md). Pin it to the screen so it floats above +everything and always comes back on screen, wherever the canvas is panned: + +```toml +[[window_rules]] +app_id = "dropdown-term" +pinned_to_screen = true +position = [0, 185] # output-relative, Y-up from the output centre +size = [1200, 450] +``` + +See [screen-pinned windows](window-rules.md#screen-pinned-windows) for how +`position` works. To find the numbers, run the app, pin it with +`toggle-pin-to-screen` (`Mod+T`), drag and resize it into place, and copy +`position`/`size` from the `pinned` section of `driftwm msg state`. + +Reload with `driftwm msg action reload-config` (rules apply to windows opened +afterwards, so close any copy that is already running), then press the key. + +## How it behaves + +- **It remembers.** The rule only sets the *first* placement. If you move or + resize the window while it is up, the next show restores that geometry. +- **It follows the display.** With several monitors, showing a pinned + scratchpad puts it on the monitor the pointer is on, not the one it was + stowed from. It keeps its position relative to the monitor (centred stays + centred and flush stays flush, whatever the sizes; the share of free space + around the window is kept, so it never ends up off a smaller monitor), and that becomes its position for the next + show. +- **Focus.** Showing raises and focuses the window. Stowing the focused window + hands focus to the most recently used other window. +- **Hidden means gone.** A stowed window is not drawn, takes no clicks, and is + left out of Alt-Tab, the overview and focus-nearest. It still gets frame + callbacks at a throttled rate, so a terminal keeps processing output. +- **Everything of the app toggles together.** All windows with that `app_id` + (a mail client's compose windows, say) and their dialogs are stowed and shown + as one. +- **Fullscreen.** Stowing a fullscreen window leaves fullscreen so you see the + desktop, and showing it puts it back into fullscreen. A fullscreen or maximize + the app asks for while stowed is applied when it is shown. +- **Slow starters.** A repeat press within 3 seconds of a spawn does not launch + the app twice, and a window is never stowed before its first placement, so + its rules still apply. +- **No placeholders.** A scratchpad app is not [session-restored](session.md): + no stand-in comes back after a restart, since the key respawns the app. A + `restore_windows = true` rule for the app overrides this. +- **Reload.** If a reload leaves a stowed window with no binding that can reach + it, it is shown again instead of being stranded. + +You can drive one without a binding too: +`driftwm msg action toggle-scratchpad dropdown-term kitty --class dropdown-term`. + +## Limitations + +- **Pin it.** Scratchpads are meant for `pinned_to_screen` windows. An unpinned + one works, but showing it does not pan the camera to it, so it may be off + screen. +- **Monitor changes.** Unplugging the monitor a pinned window lives on moves it + to a remaining monitor, clamped to fit, and plugging the monitor back in does + not restore the original spot. This is how pinned windows behave in general. +- **IPC wording.** `msg focus`, `move`, `pin` and `suspend` refuse a stowed + window, with a "mid-relaunch" error that does not describe the situation. diff --git a/docs/session.md b/docs/session.md index 77d38739..45db1828 100644 --- a/docs/session.md +++ b/docs/session.md @@ -143,6 +143,11 @@ app_id = "footclient" restore_windows = false ``` +A window that a `toggle-scratchpad` binding (key, tap, mouse or gesture) manages +defaults to `false` here, since its binding respawns it on demand and a restored +stand-in would only sit next to the fresh window. A `restore_windows = true` rule +for that app overrides this. + Two things to keep in mind: - The flag is **independent of `suspend_on_close`**: that one governs closes, diff --git a/docs/window-rules.md b/docs/window-rules.md index 6d1c04d8..84262d16 100644 --- a/docs/window-rules.md +++ b/docs/window-rules.md @@ -189,6 +189,9 @@ decoration = "none" - **Dragging it across monitors** reassigns it to that output. Combine with `widget = true` to make it immovable. +A pinned window also makes a [scratchpad](scratchpad.md): a key that stows and +shows it without animation. + To find the numbers for a rule, pin the window live with `toggle-pin-to-screen` (`Mod+T`), drag and resize it into place, then copy `position`/`size` from its entry in the per-output `pinned` section of `driftwm msg state` — those are @@ -481,7 +484,8 @@ evaluated per frame (likewise), the session is saved or loaded. On load, `restore_windows` is matched against a saved record, which carries an `app_id` but no title, so only the `app_id` criterion is consulted there (see -[session restore](session.md#restore_windows)). +[session restore](session.md#restore_windows)). With no rule, an app managed by a +`toggle-scratchpad` binding resolves to `false`. ## Debugging diff --git a/src/config/mod.rs b/src/config/mod.rs index 16fe02cf..f1de3e50 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -321,6 +321,29 @@ impl Config { self.bindings.get(&combo) } + /// Whether any binding (key, tap, mouse, gesture or touch) toggles `app_id` + /// as a scratchpad. A scratchpad is respawned by its own binding, so a + /// restored stand-in for it is only in the way. + pub fn is_scratchpad_app(&self, app_id: &str) -> bool { + let is = |action: &Action| matches!(action, Action::ToggleScratchpad { app_id: a, .. } if a == app_id); + let gesture = |entry: &GestureConfigEntry| { + matches!( + entry, + GestureConfigEntry::Threshold(ThresholdAction::Fixed(a)) if is(a) + ) + }; + self.bindings + .values() + .chain(self.tap_bindings.values()) + .any(is) + || self + .mouse + .values() + .any(|m| matches!(m, MouseAction::Action(a) if is(a))) + || self.gestures.values().any(gesture) + || self.touch_gestures.values().any(gesture) + } + /// Look up a tap-modifier binding by the completed chord's modifier set. pub fn tap_lookup(&self, mods: &Modifiers) -> Option<&Action> { self.tap_bindings.get(mods) diff --git a/src/config/parse.rs b/src/config/parse.rs index 10498e22..e92b469d 100644 --- a/src/config/parse.rs +++ b/src/config/parse.rs @@ -106,6 +106,16 @@ pub fn parse_action(s: &str) -> Result { let cmd = arg.ok_or("spawn requires a command argument")?; Ok(Action::Spawn(cmd.to_string())) } + "toggle-scratchpad" => { + let arg = arg.ok_or("toggle-scratchpad requires an app_id and a command")?; + let (app_id, command) = arg + .split_once(char::is_whitespace) + .ok_or("toggle-scratchpad requires a command after the app_id")?; + Ok(Action::ToggleScratchpad { + app_id: app_id.to_string(), + command: command.trim().to_string(), + }) + } "exec-terminal" => Ok(Action::ExecTerminal), "exec-launcher" => Ok(Action::ExecLauncher), "close-window" => Ok(Action::CloseWindow), @@ -273,6 +283,7 @@ pub const ACTION_NAMES: &[(&str, &str)] = &[ ("toggle-cursor-pan", "toggle-cursor-pan"), ("toggle-fullscreen", "toggle-fullscreen"), ("toggle-pin-to-screen", "toggle-pin-to-screen"), + ("toggle-scratchpad", "toggle-scratchpad foo foo"), ("zoom-in", "zoom-in"), ("zoom-out", "zoom-out"), ("zoom-reset", "zoom-reset"), @@ -632,6 +643,7 @@ mod tests { Action::ExecTerminal => "exec-terminal", Action::ExecLauncher => "exec-launcher", Action::Spawn(_) => "spawn", + Action::ToggleScratchpad { .. } => "toggle-scratchpad", Action::CloseWindow => "close-window", Action::SuspendWindow => "suspend-window", Action::NudgeWindow(_) => "nudge-window", diff --git a/src/config/types.rs b/src/config/types.rs index ecf4b0df..f6a37b25 100644 --- a/src/config/types.rs +++ b/src/config/types.rs @@ -52,6 +52,11 @@ pub enum Action { ExecTerminal, ExecLauncher, Spawn(String), + /// Show or hide the window with this `app_id`, spawning `command` when none exists. + ToggleScratchpad { + app_id: String, + command: String, + }, CloseWindow, SuspendWindow, NudgeWindow(Direction), @@ -63,7 +68,9 @@ pub enum Action { CenterWindow, CenterNearest(Direction), FocusNearest(Direction), - CycleWindows { backward: bool }, + CycleWindows { + backward: bool, + }, HomeToggle, GoToBookmark(String), SetBookmark(String), @@ -418,6 +425,14 @@ impl ContextBindings { } } + /// Every bound value across all three contexts. + pub fn values(&self) -> impl Iterator { + self.on_window + .values() + .chain(self.on_canvas.values()) + .chain(self.anywhere.values()) + } + pub fn lookup(&self, key: &K, context: BindingContext) -> Option<&V> { let specific = match context { BindingContext::OnWindow => &self.on_window, diff --git a/src/input/actions.rs b/src/input/actions.rs index 0c96e652..ba87f8a9 100644 --- a/src/input/actions.rs +++ b/src/input/actions.rs @@ -206,6 +206,9 @@ impl DriftWm { tracing::info!("Spawning (no cursor): {cmd}"); crate::state::spawn_command(cmd, &self.config.child_env); } + Action::ToggleScratchpad { app_id, command } => { + self.toggle_scratchpad_from(app_id, command, was_fullscreen.as_ref()); + } Action::CloseWindow => match self.focused_element() { // A focused stand-in has no client to close — the close binding // dismisses it instead. diff --git a/src/input/mod.rs b/src/input/mod.rs index b91e083b..5889ba38 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -1910,6 +1910,9 @@ impl DriftWm { let Some(p) = self.stage.pin_of(window) else { continue; }; + if self.hidden_by_deferred_adopt(window) { + continue; + } if p.output != output_name { continue; } @@ -2066,6 +2069,9 @@ impl DriftWm { let Some(p) = self.stage.pin_of(window) else { continue; }; + if self.hidden_by_deferred_adopt(window) { + continue; + } if p.output != output_name { continue; } @@ -2153,6 +2159,9 @@ impl DriftWm { let Some(p) = self.stage.pin_of(window) else { continue; }; + if self.hidden_by_deferred_adopt(window) { + continue; + } if p.output != output_name { continue; } @@ -2575,7 +2584,8 @@ impl DriftWm { .filter_map(|w| w.client()) .find(|&window| { self.stage.pin_of(window).is_some_and(|p| { - p.output == output_name + !self.hidden_by_deferred_adopt(window) + && p.output == output_name && self .resize_margin_hit_for(window, p.screen_pos, screen_pos) .is_some() diff --git a/src/render/lifecycle.rs b/src/render/lifecycle.rs index 2fb9e0b4..17533f4e 100644 --- a/src/render/lifecycle.rs +++ b/src/render/lifecycle.rs @@ -265,7 +265,9 @@ pub fn post_render(state: &mut crate::state::DriftWm, output: &Output) { let geom_loc = window.geometry().loc; let mut bbox = window.bbox_with_popups(); bbox.loc += loc - geom_loc; - let on_screen = visible_rect.overlaps(bbox); + // A stowed scratchpad window is not drawn but keeps its client alive, so + // it gets the off-screen heartbeat and a terminal can keep rendering. + let on_screen = visible_rect.overlaps(bbox) && !state.hidden_by_deferred_adopt(window); window.send_frame( output, diff --git a/src/state/init.rs b/src/state/init.rs index ac424f30..8a96b2bd 100644 --- a/src/state/init.rs +++ b/src/state/init.rs @@ -371,6 +371,8 @@ impl DriftWm { pending_relaunches: BTreeMap::new(), pending_adoptions: HashMap::new(), deferred_adoptions: Vec::new(), + scratchpad_hidden: Vec::new(), + scratchpad_spawns: HashMap::new(), session_store: super::SessionStore::default(), bookmarks, window_focus: None, diff --git a/src/state/mod.rs b/src/state/mod.rs index 4ee2e30b..f175502b 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -34,6 +34,7 @@ mod redraw; mod reload; mod render_cache; mod resize; +mod scratchpad; pub(crate) mod session_lock; mod session_store; mod stage_window; @@ -925,6 +926,14 @@ pub struct DriftWm { /// ([`DriftWm::reveal_deferred_adopt`] hands all of that back), so an entry /// that outlives its purpose is an invisible window. pub(crate) deferred_adoptions: Vec, + /// Root surfaces of windows stowed by `toggle-scratchpad`. A stowed window + /// stays mapped and keeps its pin site, but is off the screen and out of + /// every canvas relation, like a first-commit deferred adopt; see + /// [`DriftWm::root_hidden`]. + pub(crate) scratchpad_hidden: Vec, + /// When `toggle-scratchpad` last spawned each `app_id`, so a press while the + /// app is still starting up does not spawn it twice. + pub(crate) scratchpad_spawns: HashMap, /// Durable session store (session restore): the `session.json` path, dirty /// timer, carried-forward entries, and fresh-boot camera seed. pub session_store: SessionStore, @@ -1434,6 +1443,7 @@ impl DriftWm { ("pending_relaunches", self.pending_relaunches.len()), ("pending_adoptions", self.pending_adoptions.len()), ("deferred_adoptions", self.deferred_adoptions.len()), + ("scratchpad_hidden", self.scratchpad_hidden.len()), ( "idle_inhibiting_surfaces", self.idle_inhibiting_surfaces.len(), diff --git a/src/state/pinned.rs b/src/state/pinned.rs index 31b9ffeb..cda80b00 100644 --- a/src/state/pinned.rs +++ b/src/state/pinned.rs @@ -186,6 +186,18 @@ impl DriftWm { /// (clamped into the target output's bounds) and rebinding the pin to it. /// No-op if the window isn't pinned or is already on `target`. pub(crate) fn send_pinned_to_output(&mut self, window: &Window, target: &Output) { + self.rebind_pinned(window, target, false); + } + + /// Like [`send_pinned_to_output`](Self::send_pinned_to_output), but keeps + /// the window's position *relative* to the output: a window centred on the + /// old output is centred on `target`, and one flush to an edge stays flush, + /// whatever the two sizes (see the free-space scaling in `rebind_pinned`). + pub(crate) fn send_pinned_to_output_relative(&mut self, window: &Window, target: &Output) { + self.rebind_pinned(window, target, true); + } + + fn rebind_pinned(&mut self, window: &Window, target: &Output, relative: bool) { let Some(mut site) = self.stage.pin_of(window).cloned() else { return; }; @@ -194,9 +206,31 @@ impl DriftWm { } let target_size = output_logical_size(target); let chrome = self.element_chrome(window); + let content_size = window.geometry().size; + if relative && let Some(from) = self.output_by_name(&site.output) { + // Scale the share of free space (output minus frame) on each + // side, not the centre: a fixed-size frame is a bigger part of a + // smaller output, so scaling the centre pushes it off-screen. + // Centred stays centred, flush stays flush, and it never leaves + // the output while it fits. + let from_size = output_logical_size(&from); + let frame_size = chrome.frame_size(content_size); + let frame = chrome.frame_loc(site.screen_pos); + let scale = |pos: i32, len: i32, from: i32, to: i32| { + let (from_free, to_free) = (from - len, to - len); + if from_free <= 0 { + return to_free / 2; + } + let share = (pos as f64 / from_free as f64).clamp(0.0, 1.0); + (share * to_free as f64).round() as i32 + }; + site.screen_pos = chrome.content_loc(Point::from(( + scale(frame.x, frame_size.w, from_size.w, target_size.w), + scale(frame.y, frame_size.h, from_size.h, target_size.h), + ))); + } site.output = target.name(); - site.screen_pos = - clamp_pin_frame(site.screen_pos, window.geometry().size, target_size, chrome); + site.screen_pos = clamp_pin_frame(site.screen_pos, content_size, target_size, chrome); self.stage.set_pin(window, site); // Re-anchor the Space loc to the new output now — `sync_pinned_locs` // only fires on camera changes, which this rebind doesn't trigger, so diff --git a/src/state/reload.rs b/src/state/reload.rs index b4b8ba1c..64f1e1c2 100644 --- a/src/state/reload.rs +++ b/src/state/reload.rs @@ -219,6 +219,7 @@ impl DriftWm { } self.config = new_config; + self.release_unreachable_scratchpads(); let kde_mode = driftwm::window_ext::decoration_mode_to_kde_manager( &self.config.decorations.default_mode, diff --git a/src/state/scratchpad.rs b/src/state/scratchpad.rs new file mode 100644 index 00000000..07b50d82 --- /dev/null +++ b/src/state/scratchpad.rs @@ -0,0 +1,224 @@ +//! Scratchpad windows: `toggle-scratchpad` stows a window by `app_id` without +//! unmapping it, and brings it back at the pin site it left from. +//! +//! The window stays on the stage with its client, size and pin site intact. +//! Stowing only adds it to `scratchpad_hidden`, the same off-screen, +//! out-of-every-relation state a first-commit deferred adopt uses +//! ([`DriftWm::root_hidden`]), so showing it again is one frame with no +//! animation. It shows on the output in use, not the one it was stowed from. + +use std::time::{Duration, Instant}; + +use driftwm::window_ext::WindowExt; +use smithay::desktop::Window; +use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface; +use smithay::utils::SERIAL_COUNTER; +use smithay::wayland::seat::WaylandFocus; + +use super::{DriftWm, StageWindow}; + +/// How long a spawned scratchpad command is given to map its window before +/// another press may spawn it again. Covers slow starters (a mail client can +/// take seconds to show anything), where each extra press would otherwise +/// launch another instance. +const SPAWN_DEBOUNCE: Duration = Duration::from_secs(3); + +impl DriftWm { + #[cfg(test)] + pub(crate) fn toggle_scratchpad(&mut self, app_id: &str, command: &str) { + self.toggle_scratchpad_from(app_id, command, None); + } + + /// `was_fullscreen` is the window that was fullscreen on the active output + /// before the action guard ended it: if that is one of the windows being + /// stowed, it is put back into fullscreen when shown. + pub(crate) fn toggle_scratchpad_from( + &mut self, + app_id: &str, + command: &str, + was_fullscreen: Option<&Window>, + ) { + let windows = self.scratchpad_windows(app_id); + if windows.is_empty() { + let recent = self + .scratchpad_spawns + .get(app_id) + .is_some_and(|at| at.elapsed() < SPAWN_DEBOUNCE); + if !recent { + self.scratchpad_spawns + .insert(app_id.to_owned(), Instant::now()); + crate::state::spawn_command(command, &self.config.child_env); + } + return; + } + self.scratchpad_spawns.remove(app_id); + let surfaces: Vec = windows + .iter() + .filter_map(|w| w.wl_surface().map(|s| s.into_owned())) + .collect(); + // A window that hasn't had its first placement yet would be stowed + // before its rules apply, and placement skips what is hidden. + if surfaces.iter().any(|s| self.pending_center.contains(s)) { + return; + } + if surfaces.iter().all(|s| self.scratchpad_hidden.contains(s)) { + self.show_scratchpad(&windows, &surfaces); + } else { + self.hide_scratchpad(&windows, surfaces, was_fullscreen); + } + } + + /// Every window of the scratchpad: all non-widget windows with this exact + /// `app_id` (a mail client's compose windows share its `app_id`), plus + /// their transient children and dialogs. The toggle acts on them together. + fn scratchpad_windows(&self, app_id: &str) -> Vec { + let clients: Vec = self + .stage + .windows() + .filter_map(|w| w.client()) + .cloned() + .collect(); + let mut group: Vec = clients + .iter() + .filter(|w| !w.is_widget() && w.app_id_or_class().as_deref() == Some(app_id)) + .cloned() + .collect(); + loop { + let before = group.len(); + for w in &clients { + if group.contains(w) { + continue; + } + let child_of_group = w + .parent_surface() + .is_some_and(|p| group.iter().any(|g| g.wl_surface().as_deref() == Some(&p))); + if child_of_group { + group.push(w.clone()); + } + } + if group.len() == before { + return group; + } + } + } + + fn show_scratchpad(&mut self, windows: &[Window], surfaces: &[WlSurface]) { + self.scratchpad_hidden.retain(|s| !surfaces.contains(s)); + // The scratchpad follows the display in use: a pin left on another + // output is rebound to the active one, at the same relative position. + if let Some(active) = self.active_output() { + for window in windows { + self.send_pinned_to_output_relative(window, &active); + } + } + for (window, surface) in windows.iter().zip(surfaces) { + // Cancelled so a stale entry can't ease it in from where it last was. + self.cancel_window_animation(window); + // A fullscreen / maximize the app asked for while stowed was queued. + self.apply_queued_geometry_request(surface); + } + // Stage order, so a parent is raised before its children. + let serial = SERIAL_COUNTER.next_serial(); + for window in windows { + self.raise_and_focus(window, serial); + } + } + + fn hide_scratchpad( + &mut self, + windows: &[Window], + surfaces: Vec, + was_fullscreen: Option<&Window>, + ) { + let was_focused = self.focused_window().is_some_and(|f| windows.contains(&f)); + for (window, surface) in windows.iter().zip(surfaces) { + if !self.scratchpad_hidden.contains(&surface) { + self.scratchpad_hidden.push(surface); + } + self.cancel_window_animation(window); + // The guard has already ended its fullscreen so the desktop shows; + // queue it to be entered again on show, as for a request made + // while stowed. + if was_fullscreen == Some(window) + && let Some(s) = window.wl_surface() + { + self.pending_fullscreen.insert(s.into_owned(), None); + } + self.stage + .drop_from_focus_history(&StageWindow::from(window.clone())); + } + if was_focused { + self.focus_most_recent(); + } + } + + /// Show again any stowed window the config no longer lets a binding reach + /// (its binding was removed or points at another `app_id`). Run after a + /// reload; a stowed window that is still bound is left alone. + pub(crate) fn release_unreachable_scratchpads(&mut self) { + let stranded: Vec = self + .scratchpad_hidden + .iter() + .filter(|s| { + let Some(w) = self.window_for_surface(s) else { + return false; + }; + // A child is reached through its parent's binding. + let parent_stowed = w + .parent_surface() + .is_some_and(|p| self.scratchpad_hidden.contains(&p)); + let bound = w + .app_id_or_class() + .is_some_and(|a| self.config.is_scratchpad_app(&a)); + !parent_stowed && !bound + }) + .cloned() + .collect(); + if stranded.is_empty() { + return; + } + let mut release = stranded; + // Children of a released window go with it. + for s in release.clone() { + if let Some(w) = self.window_for_surface(&s) { + for c in self.scratchpad_children(&w) { + if let Some(cs) = c.wl_surface().map(|x| x.into_owned()) { + release.push(cs); + } + } + } + } + self.scratchpad_hidden.retain(|s| !release.contains(s)); + for s in &release { + self.apply_queued_geometry_request(s); + } + } + + fn scratchpad_children(&self, parent: &Window) -> Vec { + let Some(ps) = parent.wl_surface().map(|s| s.into_owned()) else { + return Vec::new(); + }; + self.stage + .windows() + .filter_map(|w| w.client()) + .filter(|w| w.parent_surface().as_ref() == Some(&ps)) + .cloned() + .collect() + } + + /// Hand focus to the most recently focused visible window, or to nothing. + fn focus_most_recent(&mut self) { + let serial = SERIAL_COUNTER.next_serial(); + let next = self + .stage + .focus_history() + .iter() + .filter_map(|w| w.client()) + .find(|w| !self.hidden_by_deferred_adopt(*w)) + .cloned(); + match next { + Some(w) => self.raise_and_focus(&w, serial), + None => self.set_window_focus(None, serial), + } + } +} diff --git a/src/state/session_store.rs b/src/state/session_store.rs index 31919afc..f5ae4952 100644 --- a/src/state/session_store.rs +++ b/src/state/session_store.rs @@ -544,7 +544,14 @@ impl DriftWm { self.config .resolve_window_rules(app_id, title) .and_then(|r| r.restore_windows) - .unwrap_or(self.config.session.restore_windows) + .unwrap_or_else(|| self.restore_windows_default(app_id)) + } + + /// What `restore_windows` falls back to with no rule saying: off for an app + /// a `toggle-scratchpad` binding manages (it respawns on demand), the global + /// setting otherwise. An explicit rule still wins over this. + fn restore_windows_default(&self, app_id: &str) -> bool { + !self.config.is_scratchpad_app(app_id) && self.config.session.restore_windows } /// The effective `restore_windows` for a saved record. A record carries an @@ -562,7 +569,7 @@ impl DriftWm { .rev() .filter(|rule| rule.app_id.as_ref().is_some_and(|p| p.matches(app_id))) .find_map(|rule| rule.restore_windows) - .unwrap_or(self.config.session.restore_windows) + .unwrap_or_else(|| self.restore_windows_default(app_id)) } /// A `Quit` record for one live client window, or `None` when it can't come diff --git a/src/state/suspended.rs b/src/state/suspended.rs index 03cd00a1..2bd203ab 100644 --- a/src/state/suspended.rs +++ b/src/state/suspended.rs @@ -470,13 +470,14 @@ impl DriftWm { self.deferred_adoptions .iter() .any(|d| d.root == *surface && d.origin == AdoptOrigin::FirstCommit) + || self.scratchpad_hidden.contains(surface) } /// [`Self::root_hidden_by_deferred_adopt`] for callers holding an element /// rather than a surface. Guarded on the (near-always empty) stash first, so /// the surface lookup never runs on the per-motion hit-test walks. pub(crate) fn hidden_by_deferred_adopt(&self, element: &Q) -> bool { - !self.deferred_adoptions.is_empty() + (!self.deferred_adoptions.is_empty() || !self.scratchpad_hidden.is_empty()) && element .wl_surface() .is_some_and(|s| self.root_hidden_by_deferred_adopt(&s)) diff --git a/src/state/window_lifecycle.rs b/src/state/window_lifecycle.rs index ec55c703..09073ae8 100644 --- a/src/state/window_lifecycle.rs +++ b/src/state/window_lifecycle.rs @@ -143,6 +143,7 @@ impl DriftWm { let entry = self.deferred_adoptions.remove(idx); self.reveal_deferred_adopt(&entry.root, entry.origin, RevealCause::Abandoned); } + self.scratchpad_hidden.retain(|s| s != surface); self.auto_anchor_snapshot.remove(surface); // Drop snapshots pointing at the destroyed surface as their anchor. // Keep `None`-anchor entries (user had no focus) and stand-in anchors diff --git a/src/tests/mod.rs b/src/tests/mod.rs index c0673035..046a7b17 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -74,6 +74,7 @@ mod render_pixels; mod resize_actions; mod resize_ipc; mod resize_parity; +mod scratchpad; mod screenshot_write; mod send_to_output; mod session_lock; diff --git a/src/tests/scratchpad.rs b/src/tests/scratchpad.rs new file mode 100644 index 00000000..d19f5f32 --- /dev/null +++ b/src/tests/scratchpad.rs @@ -0,0 +1,417 @@ +//! `toggle-scratchpad` stows a window without unmapping it and brings it back +//! at the pin site it left from. + +use smithay::desktop::Window; +use smithay::wayland::seat::WaylandFocus; + +use driftwm::stage::ElementId; + +use smithay::utils::Point; + +use super::{Fixture, config, is_activated, map_window, tick_until_settled, window_by_app_id}; + +/// A pinned, focused 400x300 window (`"dd"`) beside an unpinned one (`"other"`), +/// both settled. +fn setup() -> (Fixture, Window, Window, ElementId) { + let mut f = Fixture::new(); + f.add_output(1, (1920, 1080)); + let client = f.add_client(); + map_window(&mut f, client, "other", (300, 200)); + map_window(&mut f, client, "dd", (400, 300)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + let other = window_by_app_id(&mut f, "other").unwrap(); + f.state().pin_window(&dd).unwrap(); + tick_until_settled(&mut f); + let eid = f.state().stage.id_of(&dd).unwrap(); + (f, dd, other, eid) +} + +#[test] +fn hide_keeps_the_window_mapped_and_hands_focus_back() { + let (mut f, dd, other, _) = setup(); + let site = f.state().stage.pin_of(&dd).cloned().unwrap(); + f.state().raise_and_focus(&other, 0.into()); + f.state().raise_and_focus(&dd, 0.into()); + assert!(is_activated(&dd), "starts focused"); + + f.state().toggle_scratchpad("dd", "true"); + + assert!(f.state().hidden_by_deferred_adopt(&dd), "stowed"); + assert!(f.state().stage.contains(&dd), "still on the stage"); + assert_eq!(f.state().stage.pin_of(&dd), Some(&site), "pin site kept"); + assert!(!is_activated(&dd), "focus left the stowed window"); + assert!(is_activated(&other), "focus went to the other window"); +} + +#[test] +fn hiding_the_focused_window_focuses_the_most_recent_one() { + let (mut f, dd, other, _) = setup(); + f.state().raise_and_focus(&other, 0.into()); + f.state().raise_and_focus(&dd, 0.into()); + + f.state().toggle_scratchpad("dd", "true"); + tick_until_settled(&mut f); + + assert!(!is_activated(&dd)); + assert!(is_activated(&other)); +} + +#[test] +fn show_restores_the_same_site_focused_and_unanimated() { + let (mut f, dd, _other, eid) = setup(); + let site = f.state().stage.pin_of(&dd).cloned().unwrap(); + let pos = f.state().stage.position_of(&dd); + + f.state().toggle_scratchpad("dd", "true"); + tick_until_settled(&mut f); + f.state().toggle_scratchpad("dd", "true"); + + assert!(!f.state().hidden_by_deferred_adopt(&dd), "shown again"); + assert_eq!(f.state().stage.pin_of(&dd), Some(&site), "same pin site"); + assert_eq!(f.state().stage.position_of(&dd), pos, "same position"); + assert!(is_activated(&dd), "focused on show"); + assert!( + f.state() + .window_animations + .geometry_visual_rect(eid) + .is_none(), + "no animation to ease it in" + ); + assert_eq!( + f.state().stage.windows().last(), + Some(&dd.clone().into()), + "raised" + ); +} + +const PIN_RULE: &str = r#" +[[window_rules]] +app_id = "dd" +pinned_to_screen = true +size = [320, 240] +"#; + +#[test] +fn hidden_scratchpad_follows_its_pin_when_its_output_is_unplugged() { + let mut f = Fixture::with_config(config(PIN_RULE)); + let out2 = f.add_output(2, (1920, 1080)); + let _out1 = f.add_output(1, (800, 600)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (320, 240)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + assert_eq!(f.state().stage.pin_of(&dd).unwrap().output, "HEADLESS-2"); + + f.state().toggle_scratchpad("dd", "true"); + f.remove_output(&out2); + + let site = f.state().stage.pin_of(&dd).cloned().unwrap(); + assert_eq!(site.output, "HEADLESS-1", "rehomed onto the survivor"); + assert!(f.state().hidden_by_deferred_adopt(&dd), "still stowed"); + + f.state().toggle_scratchpad("dd", "true"); + + assert!(!f.state().hidden_by_deferred_adopt(&dd), "shown"); + assert!(is_activated(&dd), "focused"); + assert_eq!( + f.state().stage.pin_of(&dd), + Some(&site), + "at the rehomed site" + ); +} + +#[test] +fn hidden_scratchpad_survives_losing_and_regaining_the_last_output() { + let mut f = Fixture::with_config(config(PIN_RULE)); + let out1 = f.add_output(1, (1920, 1080)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (320, 240)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + + f.state().toggle_scratchpad("dd", "true"); + f.remove_output(&out1); + let out2 = f.add_output(2, (1280, 720)); + f.roundtrip(client); + + assert!(f.state().hidden_by_deferred_adopt(&dd), "still stowed"); + assert_eq!(f.state().stage.pin_of(&dd).unwrap().output, out2.name()); + + f.state().toggle_scratchpad("dd", "true"); + + assert!(!f.state().hidden_by_deferred_adopt(&dd), "shown"); + assert!(is_activated(&dd), "focused"); +} + +#[test] +fn hidden_scratchpad_is_not_hit_by_the_pointer() { + let mut f = Fixture::with_config(config(PIN_RULE)); + f.add_output(1, (1920, 1080)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (320, 240)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + tick_until_settled(&mut f); + let site = f.state().stage.pin_of(&dd).cloned().unwrap(); + let inside = (site.screen_pos + Point::from((160, 120))).to_f64(); + let on_edge = (site.screen_pos + Point::from((-2, 120))).to_f64(); + + assert_eq!(f.state().pinned_element_under(inside), Some(dd.clone())); + assert_eq!(f.state().pinned_owner_under(on_edge), Some(dd.clone())); + assert_eq!( + f.state().pinned_resize_margin_under(on_edge), + Some(dd.clone()) + ); + assert!(f.state().pinned_window_under(inside, inside).is_some()); + + f.state().toggle_scratchpad("dd", "true"); + + assert_eq!(f.state().pinned_element_under(inside), None, "content"); + assert_eq!(f.state().pinned_owner_under(inside), None, "owner"); + assert_eq!(f.state().pinned_owner_under(on_edge), None, "chrome"); + assert_eq!( + f.state().pinned_resize_margin_under(on_edge), + None, + "margin" + ); + assert!(f.state().pinned_window_under(inside, inside).is_none()); + assert!(matches!( + f.state().pinned_decoration_under(on_edge), + crate::input::PinnedChrome::Miss + )); +} + +#[test] +fn a_window_awaiting_its_first_placement_is_left_alone() { + let (mut f, dd, _other, _) = setup(); + let surface = dd.wl_surface().unwrap().into_owned(); + f.state().pending_center.insert(surface.clone()); + + f.state().toggle_scratchpad("dd", "true"); + + assert!( + !f.state().hidden_by_deferred_adopt(&dd), + "not stowed before placement" + ); + f.state().pending_center.remove(&surface); +} + +#[test] +fn a_fullscreen_asked_for_while_stowed_applies_on_show() { + let mut f = Fixture::new(); + f.add_output(1, (1920, 1080)); + let client = f.add_client(); + let surface = map_window(&mut f, client, "dd", (400, 300)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + tick_until_settled(&mut f); + + f.state().toggle_scratchpad("dd", "true"); + f.client(client).window(&surface).set_fullscreen(None); + f.double_roundtrip(client); + assert!(!f.state().stage.is_fullscreen(&dd), "queued while stowed"); + + f.state().toggle_scratchpad("dd", "true"); + f.double_roundtrip(client); + + assert!(f.state().stage.is_fullscreen(&dd), "applied on show"); +} + +#[test] +fn windows_sharing_the_app_id_and_their_children_toggle_together() { + let mut f = Fixture::new(); + f.add_output(1, (1920, 1080)); + let client = f.add_client(); + let main = map_window(&mut f, client, "dd", (400, 300)); + // A second top-level of the app (a compose window) and a dialog on it. + map_window(&mut f, client, "dd", (300, 200)); + let toplevel = f.client(client).window(&main).xdg_toplevel.clone(); + let dialog = f.client(client).create_window(); + let dsurface = dialog.surface.clone(); + dialog.set_app_id("other-app"); + dialog.set_parent(Some(&toplevel)); + dialog.commit(); + f.roundtrip(client); + let dwin = f.client(client).window(&dsurface); + dwin.set_size(200, 100); + dwin.attach_new_buffer(); + dwin.ack_last_and_commit(); + f.double_roundtrip(client); + tick_until_settled(&mut f); + let all: Vec = f + .state() + .stage + .windows() + .filter_map(|w| w.client()) + .cloned() + .collect(); + assert_eq!(all.len(), 3); + + f.state().toggle_scratchpad("dd", "true"); + assert!( + all.iter().all(|w| f.state().hidden_by_deferred_adopt(w)), + "both windows and the dialog are stowed" + ); + + f.state().toggle_scratchpad("dd", "true"); + assert!( + all.iter().all(|w| !f.state().hidden_by_deferred_adopt(w)), + "and shown together" + ); +} + +#[test] +fn a_repeat_press_while_the_app_starts_does_not_spawn_it_again() { + let mut f = Fixture::new(); + f.add_output(1, (1920, 1080)); + + f.state().toggle_scratchpad("slow", "true"); + let first = f.state().scratchpad_spawns["slow"]; + f.state().toggle_scratchpad("slow", "true"); + + assert_eq!(f.state().scratchpad_spawns["slow"], first, "debounced"); +} + +const BOUND: &str = "[keybindings]\n\"mod+w\" = \"toggle-scratchpad dd true\"\n"; + +#[test] +fn reload_releases_a_stowed_window_nothing_can_reach() { + let mut f = Fixture::with_config(config(BOUND)); + // A reload leaves its own mode-change intent behind. + f.skip_baseline_check(); + f.add_output(1, (1920, 1080)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (400, 300)); + map_window(&mut f, client, "kept", (400, 300)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + let kept = window_by_app_id(&mut f, "kept").unwrap(); + f.state().toggle_scratchpad("dd", "true"); + f.state().toggle_scratchpad("kept", "true"); + assert!(f.state().hidden_by_deferred_adopt(&dd)); + assert!(f.state().hidden_by_deferred_adopt(&kept)); + + f.state().reload_config_from_contents( + "[keybindings]\n\"mod+w\" = \"toggle-scratchpad dd true\"\n\"mod+k\" = \"toggle-scratchpad kept true\"\n", + ); + assert!(f.state().hidden_by_deferred_adopt(&dd), "still bound"); + assert!(f.state().hidden_by_deferred_adopt(&kept), "still bound"); + + f.state().reload_config_from_contents( + "[keybindings]\n\"mod+k\" = \"toggle-scratchpad kept true\"\n", + ); + + assert!(!f.state().hidden_by_deferred_adopt(&dd), "released"); + assert!(f.state().hidden_by_deferred_adopt(&kept), "bound ones stay"); + f.state().toggle_scratchpad("kept", "true"); +} + +#[test] +fn every_binding_kind_marks_a_scratchpad_app() { + for toml in [ + "[keybindings]\n\"mod+w\" = \"toggle-scratchpad dd true\"\n", + "[mouse.anywhere]\n\"mod+middle\" = \"toggle-scratchpad dd true\"\n", + "[gestures.anywhere]\n\"mod+3-finger-pinch-out\" = \"toggle-scratchpad dd true\"\n", + "[touch.anywhere]\n\"3-finger-doubletap\" = \"toggle-scratchpad dd true\"\n", + ] { + let cfg = driftwm::config::Config::from_toml(toml).unwrap(); + assert!(cfg.is_scratchpad_app("dd"), "{toml}"); + assert!(!cfg.is_scratchpad_app("other"), "{toml}"); + } +} + +#[test] +fn a_fullscreen_window_comes_back_fullscreen_after_stow_and_show() { + let mut f = Fixture::new(); + f.add_output(1, (1920, 1080)); + let client = f.add_client(); + let surface = map_window(&mut f, client, "dd", (400, 300)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + f.client(client).window(&surface).set_fullscreen(None); + f.double_roundtrip(client); + f.client(client).window(&surface).ack_last_and_commit(); + f.double_roundtrip(client); + assert!(f.state().stage.is_fullscreen(&dd), "starts fullscreen"); + + // What the action guard does before the toggle runs. + let was = f.state().active_fullscreen_window(); + f.state().exit_fullscreen(); + f.state().toggle_scratchpad_from("dd", "true", was.as_ref()); + f.double_roundtrip(client); + assert!(f.state().hidden_by_deferred_adopt(&dd), "stowed"); + assert!(!f.state().stage.is_fullscreen(&dd), "desktop is showing"); + + f.state().toggle_scratchpad("dd", "true"); + f.double_roundtrip(client); + + assert!(f.state().stage.is_fullscreen(&dd), "fullscreen again"); +} + +#[test] +fn show_follows_the_active_output() { + let mut f = Fixture::with_config(config(PIN_RULE)); + let out2 = f.add_output(2, (1920, 1080)); + let out1 = f.add_output(1, (1920, 1080)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (320, 240)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + assert_eq!(f.state().stage.pin_of(&dd).unwrap().output, out2.name()); + + f.state().toggle_scratchpad("dd", "true"); + f.state().focused_output = Some(out1.clone()); + f.state().toggle_scratchpad("dd", "true"); + + assert!(!f.state().hidden_by_deferred_adopt(&dd), "shown"); + assert_eq!( + f.state().stage.pin_of(&dd).unwrap().output, + out1.name(), + "pinned to the output in use" + ); + assert!(is_activated(&dd), "focused"); +} + +#[test] +fn show_keeps_the_position_relative_to_the_output() { + let mut f = Fixture::with_config(config(PIN_RULE)); + let out2 = f.add_output(2, (1920, 1080)); + let out1 = f.add_output(1, (3440, 1440)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (320, 240)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + let mut site = f.state().stage.pin_of(&dd).cloned().unwrap(); + assert_eq!(site.output, out2.name()); + // Centred on the 1920x1080 output. + site.screen_pos = (1920 / 2 - 160, 1080 / 2 - 120).into(); + f.state().stage.set_pin(&dd, site); + + f.state().toggle_scratchpad("dd", "true"); + f.state().focused_output = Some(out1.clone()); + f.state().toggle_scratchpad("dd", "true"); + + let site = f.state().stage.pin_of(&dd).cloned().unwrap(); + assert_eq!(site.output, out1.name()); + assert_eq!( + site.screen_pos, + (3440 / 2 - 160, 1440 / 2 - 120).into(), + "still centred" + ); +} + +#[test] +fn show_keeps_a_large_window_inside_a_smaller_output() { + let mut f = Fixture::with_config(config(PIN_RULE)); + let out2 = f.add_output(2, (3440, 1440)); + let out1 = f.add_output(1, (1920, 1080)); + let client = f.add_client(); + map_window(&mut f, client, "dd", (1600, 700)); + let dd = window_by_app_id(&mut f, "dd").unwrap(); + let mut site = f.state().stage.pin_of(&dd).cloned().unwrap(); + assert_eq!(site.output, out2.name()); + // Horizontally centred, 100px down: a dropdown on the ultrawide. + site.screen_pos = ((3440 - 1600) / 2, 100).into(); + f.state().stage.set_pin(&dd, site); + + f.state().toggle_scratchpad("dd", "true"); + f.state().focused_output = Some(out1.clone()); + f.state().toggle_scratchpad("dd", "true"); + + let site = f.state().stage.pin_of(&dd).cloned().unwrap(); + assert_eq!(site.output, out1.name()); + // Same share of the free space: 0.5 of 320, 100/740 of 380. + assert_eq!(site.screen_pos, (160, 51).into()); +} diff --git a/src/tests/session_restore.rs b/src/tests/session_restore.rs index 2154e155..097210e4 100644 --- a/src/tests/session_restore.rs +++ b/src/tests/session_restore.rs @@ -2227,6 +2227,105 @@ fn restore_windows_false_rule_quit_record_carries_forward_inert() { } } +const SCRATCHPAD_BINDING: &str = "[keybindings]\n\"mod+w\" = \"toggle-scratchpad pad true\"\n"; + +/// An app a `toggle-scratchpad` binding manages is respawned by that binding, +/// so its live window stays out of the durable save without any rule, while an +/// ordinary app's window still saves. +#[test] +fn scratchpad_app_is_not_saved_without_a_rule() { + let cache = TempDir::new(); + let tmp = TempDir::new(); + let path = tmp.path().join("session.json"); + + let config = config_restore_with_rule(true, SCRATCHPAD_BINDING); + let mut f = Fixture::with_config(config); + f.add_output(1, (1920, 1080)); + inject_cache(&mut f, &cache, &["pad", "plain"]); + f.state().session_store.path = Some(path.clone()); + + let a = f.add_client(); + map_at(&mut f, a, "pad", (400, 300), (300, 300)); + let b = f.add_client(); + map_at(&mut f, b, "plain", (400, 300), (800, 300)); + + f.state().session_store_write_now(); + + let saved = session::read(&path); + assert!(saved.entries.iter().all(|e| e.app_id != "pad")); + assert!(saved.entries.iter().any(|e| e.app_id == "plain")); +} + +/// A saved record for a scratchpad app does not come back as a stand-in, and is +/// carried forward inert like any other excluded record. +#[test] +fn scratchpad_app_quit_record_does_not_materialize() { + let tmp = TempDir::new(); + let path = tmp.path().join("session.json"); + + let envelope = SessionEnvelope { + version: session::VERSION, + bookmarks: BTreeMap::new(), + saved_at: 0, + entries: vec![ + entry(1, "alpha", Origin::Quit), + entry(2, "pad", Origin::Quit), + ], + outputs: BTreeMap::new(), + }; + session::write(&path, &envelope, false).unwrap(); + + let mut f = Fixture::with_config(config_restore_with_rule(true, SCRATCHPAD_BINDING)); + f.add_output(1, (1920, 1080)); + f.state().session_store.path = Some(path.clone()); + f.state().load_session(); + + let restored = suspended_in_order(&mut f); + assert_eq!( + restored + .iter() + .map(|(s, _)| s.identity.app_id.clone()) + .collect::>(), + vec!["alpha"], + "only the ordinary app comes back" + ); + + for (s, _) in restored { + f.state().dismiss_suspended(s.id); + } +} + +/// An explicit `restore_windows = true` rule still wins over the scratchpad +/// default, for someone who does want the stand-in. +#[test] +fn explicit_restore_rule_overrides_the_scratchpad_default() { + let tmp = TempDir::new(); + let path = tmp.path().join("session.json"); + + let envelope = SessionEnvelope { + version: session::VERSION, + bookmarks: BTreeMap::new(), + saved_at: 0, + entries: vec![entry(1, "pad", Origin::Quit)], + outputs: BTreeMap::new(), + }; + session::write(&path, &envelope, false).unwrap(); + + let rules = + format!("{SCRATCHPAD_BINDING}[[window_rules]]\napp_id = \"pad\"\nrestore_windows = true\n"); + let mut f = Fixture::with_config(config_restore_with_rule(true, &rules)); + f.add_output(1, (1920, 1080)); + f.state().session_store.path = Some(path.clone()); + f.state().load_session(); + + let restored = suspended_in_order(&mut f); + assert_eq!(restored.len(), 1, "the explicit rule brings it back"); + + for (s, _) in restored { + f.state().dismiss_suspended(s.id); + } +} + /// Dropping the rule that excluded a carried `Quit` record lets it materialize /// again on the next load: nothing about the earlier exclusion destroyed the /// record, it just sat inert in the file.