Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

updates

oxydizer9e28bd42c3de
diff --git a/AGENTS.md b/AGENTS.md
index 95dcc4a..3d133fc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -158,6 +158,13 @@ the one for the directory you work in: `src/files`, `src/editor`,
`files/settings.zig` before the first frame (PDF: before its sandbox).
* Secrets live in `secret_input.Input` over caller-owned mlocked storage;
hand-laid secret fields draw the caret with `CaretOverlay`.
+* **Dead keys:** `xkb_state_key_get_utf8` returns nothing for them, so any
+ code turning xkb presses into text feeds `ui.compose.Compose` first (shared
+ lazy table from the user's language: ´+c is ç in `pt_BR`, ć elsewhere):
+ `Keyboard.composeShell` for compositor fields, `deliverKey` in app clients.
+ Reset on focus loss or Ctrl/Alt, no repeat for a consumed key
+ (`willConsume`/`consumed`), `compose.preload` before a sandbox closes the
+ filesystem (PDF). `tests/dead_keys.py`.
## Build and platform
diff --git a/README.md b/README.md
index 49459a5..eacdbc3 100644
--- a/README.md
+++ b/README.md
@@ -85,7 +85,107 @@ RediWM); it refuses to parse a document if isolation cannot be established.
| Super+Z | undo the last window move or resize |
| Super+Shift+E | quit |
-All bindings live in `[keybinds]`; `"noop"` disables one.
+Canvas bindings live in `[keybinds]`; `"noop"` disables one.
+
+**Optional automatically tiled workspaces:** select **Settings → Desktop → Workspaces**, or
+set `[compositor] desktop_mode = "workspaces"`. Each output shows one workspace;
+selecting a workspace on another output focuses that output. Switching back to
+Canvas restores surviving windows' canvas positions, sizes and zoom.
+
+Workspace mode uses a separate, stable Hyprland-style preset: Super+Q opens the
+configured terminal, C closes, E opens Files, R opens the launcher, M opens the
+power menu, and arrows focus. Super+1…9/0 selects workspace 1…10; adding Shift
+moves the focused window (including its tabs and dialogs) there and follows it.
+Super+wheel cycles existing workspaces. Super+left-drag inserts a tile beside
+another tile with a preview; Super+right-drag adjusts its split dividers.
+Floating windows keep ordinary move/resize behavior. Escape cancels an
+insertion or restores the split sizes from before a resize.
+Fullscreen, lock, Alt+Tab, screenshots and undo remain
+available. Canvas panning and window zoom are inactive in workspace mode.
+
+Override the preset in `[keybinds.workspace]`, including `"noop"` to disable a
+binding, or edit the active preset in Settings → Keyboard Shortcuts. Mode
+changes never rewrite `[keybinds]`. Configurable actions are `workspace N`,
+`move_to_workspace N`, `workspace_next`, `workspace_prev` and
+`toggle_power_menu` (workspace IDs 1–32).
+
+| Workspace tiling shortcut | Action |
+| --- | --- |
+| Super+V | Toggle the focused window between floating and automatic tiling |
+| Super+J | Rotate the nearest active split |
+| Super+Shift+arrows | Swap with a tile in that direction |
+| Super+Ctrl+arrows | Move the relevant split divider by 32 logical pixels |
+| Super+Shift+Space | Toggle automatic tiling for the current workspace |
+
+The last three are RediWM extensions. All are editable in Keyboard Shortcuts
+and `[keybinds.workspace]`. Their action names are `toggle_floating`,
+`toggle_split`, `toggle_workspace_tiling`, `swap_left/right/up/down`, and
+`resize_split_left/right/up/down` (choose one direction, e.g. `swap_left`).
+IPC uses the same actions: `tiling_action` takes an `action` string and an
+optional window `id`; without `id`, it uses the focused window/current workspace.
+
+New workspace windows use a recursive split layout, with an 8 px gap around
+and between frames by default. Set `[compositor] window_gap` to override it,
+including `0` for no gap; Canvas keeps its default gap of 0 px. Existing explicit
+gap settings are preserved. The active workspace window has a 1 px red outline,
+including floating windows and clients that draw their own decorations;
+fullscreen windows have no outline. The colour is configurable through
+`[theme] workspace_active_border` (default `"#ed1b2e"`).
+Focus never changes tile order. Dialogs and fixed-size
+clients float; each tab group occupies one tile. A window that cannot fit its
+minimum size floats until space becomes available. Earlier workspace members
+keep priority when an output shrinks. Maximum sizes leave unused tile space.
+Manual snapping or explicit IPC placement/size requests remove a window from
+automatic arrangement; the remaining tiles reflow. Minimize, maximize and
+fullscreen temporarily suspend a tile and restore its split afterwards.
+
+Floating toggles and remapped clients remember a nearby split for reinsertion;
+if its neighbor has closed, stable member order supplies a fallback. Tab groups
+and launch placeholders keep one tile. Cross-output drops and workspace
+transfers reflow both layouts.
+
+Super+Z (or IPC `undo`) restores the last layout operation across all affected
+windows: swaps, split direction/size changes, floating and automatic-layout
+toggles, manual snaps, moves/resizes, and workspace transfers. Cross-output
+operations restore both layouts. Closed windows stay closed; surviving tiles
+are reconciled with current client limits and outputs. Escape cancels a tiled
+gesture; canceled and no-op layout changes do not add an undo entry.
+
+Settings → Desktop exposes each workspace's automatic/floating placement, window
+spacing, and a checklist of floating apps. The checklist saves app ID patterns in
+`[compositor] floating_apps`; advanced exceptions use the existing rule matchers:
+
+```toml
+[[window_rules]]
+app_id = "utility*"
+floating = true
+
+[[window_rules]]
+app_id = "utility-editor"
+title = "Main*"
+floating = false
+```
+
+The last matching `floating` rule overrides the checklist default. Super+V and
+manual placement override the default for that window or tab group. Rule/config
+reloads update windows without replacing an explicit window override. Dialogs
+and fixed-size clients continue to float.
+
+Workspace mode saves a version 2 JSON snapshot to
+`$XDG_STATE_HOME/rediwm/workspace-layout.json` (normally
+`~/.local/state/rediwm/workspace-layout.json`), leaving the canvas autosave separate.
+Membership, output ownership, layout choices, split structure/ratios, floating
+restore geometry, tab groups and saved canvas state survive restarts. Existing
+apps must reopen themselves; snapshots do not launch apps. Each window matches
+once by app/backend, preferring its title and X11 instance, with saved occurrence
+order as a fallback. Missing members are pruned and missing outputs use a surviving
+output. Periodic writes wait for pending startup matches, up to 37 seconds; user layout edits protect
+that workspace from later split restoration.
+
+`save_layout NAME` and `restore_layout NAME` support workspace snapshots too.
+Named files retain their historical `layouts/NAME.toml` path; workspace snapshots
+inside them use versioned JSON. Older canvas TOML remains readable. Restoring an
+older canvas save while in workspace mode updates the saved return-to-canvas state.
- **Mouse:** Alt+drag moves windows, Alt+right-drag resizes. Super+Alt+drag (or middle-drag) pans the desktop, Super+Alt+scroll zooms it, and Alt+scroll zooms a single window.
- **Zoom on window switch:** `[compositor] focus_zoom` (also in Settings → Appearance) controls what Alt+Tab, directional focus and taskbar activation do. `"boost"` (default) shows the window at 100% until you switch away, `"keep"` only pans, and `"camera"` zooms the desktop to the window's depth.
@@ -110,7 +210,7 @@ Beyond xdg-shell, layer-shell and Xwayland:
| Remote input | `virtual-pointer-v1`, `virtual-keyboard-v1` | wayvnc, KDE Connect, wtype |
| Clipboard | `wlr-data-control-v1`, `ext-data-control-v1`, primary selection | wl-clipboard |
| Input | `text-input-v3`, `input-method-v2`, `relative-pointer-v1`, `pointer-constraints-v1`, `keyboard-shortcuts-inhibit-v1`, `pointer-gestures-v1`, `cursor-shape-v1` | fcitx5, IBus, games, virt-manager |
-| Workspace | `ext-workspace-v1` | one active Canvas workspace shared by all outputs |
+| Workspace | `ext-workspace-v1` | Canvas, or per-output workspaces with activation |
| Window metadata | `xdg-toplevel-tag-v1`, `content-type-v1`, `xdg-activation-v1` | window rules, content hints, authorized activation |
| Colour | `color-management-v1`, `color-representation-v1` | renderer-supported colour spaces and pixel representations |
| Presentation | `tearing-control-v1`, `drm-lease-v1` | opt-in fullscreen tearing, DRM-connected VR headsets |
@@ -159,10 +259,19 @@ uses this envelope (command names are case-sensitive snake_case):
{"version":1,"id":2,"command":"move_cursor","params":{"x":100,"y":200}}
```
-Settings and desktop inspection also work without opening Settings:
+Settings and desktop inspection also work without opening Settings.
+`set_desktop_mode`, `set_window_gap` and `set_floating_apps` persist by default;
+`persist: false` makes a temporary change until config reload:
| Query/action | Parameters and behavior |
| --- | --- |
+| `workspaces` | Output, visibility, automatic/floating placement, gap, and a preorder split tree (`nodes`). Leaf `id` is a window's `workspace_order`, or `tab_group` when `group` is true. `windows` reports placement and explicit floating overrides. |
+| `set_desktop_mode` | `mode`: `canvas` or `workspaces`. |
+| `set_workspace_layout` | `workspace`: 1–32, `automatic`: boolean. Saved in workspace state; participates in layout undo. |
+| `switch_workspace` | `workspace`: 1–32. |
+| `move_to_workspace` | Window `id`, `workspace`: 1–32; moves dialogs/tab members together and follows. |
+| `set_window_gap` | `gap`: 0–512 logical pixels. |
+| `set_floating_apps` | `apps`: app ID glob strings; replaces the checklist defaults. |
| `get_services` | System services, raw systemd state, activation times (`activation_us`) and total `boot_us`. First requests may report `loading`/`analyzing`; unavailable times are null. |
| `set_service_mode` | `service`, `mode`: `on`, `disabled`, or `on-demand`. Changes boot policy without starting/stopping the unit. `on-demand` requires an existing activation trigger and disables boot enablement; it does not create or enable a socket/timer. `deferred` returns `UnsupportedServiceMode`. Static/masked units are read-only. |
| `get_sounds` | Configured theme and registered events, including enabled/available flags and resolved files. |
diff --git a/TESTING.md b/TESTING.md
index f66d028..d7906c5 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -84,8 +84,20 @@ slide to the visible screen for windows panned or zoomed away from the world
origin), `zoom_osd.py` (shared zoom OSD,
100% camera cap, pixels, timeout and input), `decorations.py`, `kde_decorations.py`, `window_corners.py`
(border antialiasing and filled side edges on dark/light backgrounds at
-integer/fractional scales), `switcher.py`,
-`switcher_live.py`, `window_snapping.py`, `initial_window_state.py` (startup
+integer/fractional scales, plus workspace focus outlines on server/client
+decorations, mode transitions, fullscreen and default/explicit gaps), `switcher.py`,
+`switcher_live.py`, `workspaces.py` (floating rules, Settings/IPC layout controls,
+versioned restart/named-save restoration, duplicate app occurrences, restored tab groups,
+saved canvas state and multi-window layout undo, both sides of tiled/floating
+output transfers, dialog transfers, closed-member reconciliation, late configure
+replies, keyboard/IPC tiling controls, drag previews and Escape, live
+split resizing, unmap/remap, placeholder replacement, automatic split geometry,
+constraints/overflow, stable focus,
+minimize/maximize/fullscreen reinsertion, manual placement, workspace membership,
+hidden input, dialog transfers, Settings, workspace protocol activation,
+canvas restore and shortcut overrides; supports `REDIWM_TEST_OUTPUTS=2`,
+`REDIWM_TEST_SCALE=1.5`, `REDIWM_TEST_NEGATIVE=1`, and `REDIWM_TEST_XWAYLAND=1` for real GTK click delivery;
+GLES requires a render node; `--persistence-only` runs the restart/control checks), `window_snapping.py`, `initial_window_state.py` (startup
maximize/fullscreen placement, restore, window rules and depth), `taskbar_peek.py`,
`taskbar_title_repaint.py`, `window_urgency.py`, `start_menu.py`,
`power_menu.py` (only ever activates Log Out), `control_center.py`,
@@ -111,6 +123,8 @@ and off-canvas reachability).
disabling without closing clients, close-confirmation dialogs, fullscreen and
failed launches. It supports `REDIWM_TEST_SCALE`,
`REDIWM_TEST_RENDERER`, and `REDIWM_TABS_PREVIEW`.
+`REDIWM_TEST_WORKSPACES=1` also checks group layout undo, selected-tab closure
+and remapping into the surviving group.
`appearance_settings.py --app-colors-only` exercises the GTK/Qt apply buttons,
configuration preservation and backups, failure reporting, and the persisted
@@ -131,7 +145,9 @@ wlr-randr, wlr-foreign-toplevel via wlrctl, wlr-screencopy, virtual-pointer,
ext-session-lock via a fixture and real swaylock; workspace enumeration, tags,
content/tearing hints and renderer colour negotiation via the same fixture), `input_protocols.py`
(data-control with wl-clipboard, xdg-activation, text-input/IME,
-virtual-keyboard), `pointer_constraints.py`, `shortcuts_inhibit.py`, `cursor_shape.py`,
+virtual-keyboard), `dead_keys.py` (a virtual `latam` keyboard types dead-key
+sequences into the start menu and Files' rename field under `pt_BR` and
+`es_MX`; acute then c must give ç and ć), `pointer_constraints.py`, `shortcuts_inhibit.py`, `cursor_shape.py`,
`single_pixel.py`, `xdg_output.py` (`--xwayland` adds RandR via `xrandr`),
`presentation_time.py`, `explicit_sync.py` (gles2; vkcube), `layer_lifecycle.py`,
`idle.py`, `layout_ipc.py`, `clipboard_gtk_client.py`/`dnd_gtk_client.py`
@@ -172,6 +188,29 @@ WirePlumber's smart filters, `dbus-run-session`, `pw-record`, `pw-link`,
mutes, unmute fades in, a quick re-press turns the fade around, quitting
mid-fade still mutes.
+`python3 tests/workspaces.py --controls-only` isolates tiling controls and lifecycle
+checks; `--automatic-only` skips the older workspace-mode suite.
+`--acceptance-only` runs live scale/origin reloads, tile-grab cancellation,
+actual Wayland click delivery, per-thread idle wakeups, configure stability and
+workspace IPC/protocol lock guards, including lock-client death. It uses
+per-output scaling (`REDIWM_SCALE=auto`) and also supports two outputs.
+The split engine also has pure unit tests in `src/auto_layout.zig`, included in
+`zig build test`.
+
+The [optional tiling qualification record](docs/plans/optional-tiling-qualification.md)
+contains the renderer-specific GLES results, HEAD failure comparisons and the
+pending physical-display checklist. Workspace GTK/Xwayland routing honors
+`REDIWM_TEST_RENDERER` too. Select `WLR_RENDER_DRM_DEVICE` explicitly on multi-GPU
+machines: headless multi-output idle and glass results can differ by driver.
+
+`REDIWM_TEST_WORKSPACES=1 python3 tests/output_destroy.py` repeats hot-unplug
+and reconnects the same connector, checking visible/hidden workspace ownership,
+activation after migration and undo of transfers to the reconnected output. Use the same
+flag with `keyboard_shortcuts.py` to exercise workspace preset editing and
+disabling through Settings, or `window_tabs.py` for tab groups in automatically
+tiled workspaces. `shortcuts_inhibit.py` also supports this flag for tiled/floating
+bindings, Alt+Tab, number/wheel navigation, Super-drag and Super+Escape revocation.
+
**Xwayland**: `xwayland.py` (needs Xwayland, libxcb, `xdpyinfo`, PyGObject/GTK 3;
never uses the host `DISPLAY`), `xwayland_fractional.py`,
`xwayland_hardening.py` (extreme/invalid client size hints and recovery; needs
diff --git a/icons/battery.svg b/assets/icons/battery.svg
similarity index 100%
rename from icons/battery.svg
rename to assets/icons/battery.svg
diff --git a/icons/bluetooth.svg b/assets/icons/bluetooth.svg
similarity index 100%
rename from icons/bluetooth.svg
rename to assets/icons/bluetooth.svg
diff --git a/icons/clock.svg b/assets/icons/clock.svg
similarity index 100%
rename from icons/clock.svg
rename to assets/icons/clock.svg
diff --git a/assets/icons/comments.svg b/assets/icons/comments.svg
new file mode 100644
index 0000000..d3c2e8e
--- /dev/null
+++ b/assets/icons/comments.svg
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg fill="#000000" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
+ width="800px" height="800px" viewBox="0 0 428.428 428.428"
+ xml:space="preserve">
+<g>
+ <g>
+ <g>
+ <path d="M145.978,96.146h163.125c-1.146-15.041-13.742-26.931-29.073-26.931H29.169C13.085,69.215,0,82.301,0,98.384v129.44
+ c0,16.084,13.085,29.17,29.169,29.17h22.029v51.382c0,3.552,2.072,6.778,5.302,8.255c1.208,0.553,2.497,0.823,3.775,0.823
+ c2.14,0,4.255-0.755,5.938-2.21l39.048-33.74c-1.338-4.141-2.069-8.551-2.069-13.131v-129.44
+ C103.191,115.341,122.385,96.146,145.978,96.146z"/>
+ <path d="M399.259,110.975h-250.86c-16.084,0-29.17,13.085-29.17,29.169v129.441c0,16.084,13.086,29.169,29.17,29.169h146.403
+ l67.414,58.25c1.683,1.453,3.798,2.209,5.938,2.209c1.276,0,2.564-0.271,3.773-0.823c3.23-1.478,5.303-4.702,5.303-8.255v-51.38
+ h22.028c16.084,0,29.169-13.085,29.169-29.169V140.145C428.428,124.061,415.343,110.975,399.259,110.975z M201.202,226.324
+ c-12.785,0-23.15-10.365-23.15-23.15s10.365-23.149,23.15-23.149c12.785,0,23.149,10.365,23.149,23.149
+ C224.352,215.96,213.987,226.324,201.202,226.324z M273.829,226.324c-12.785,0-23.149-10.365-23.149-23.15
+ s10.365-23.149,23.149-23.149c12.785,0,23.148,10.365,23.148,23.149C296.979,215.96,286.614,226.324,273.829,226.324z
+ M346.456,226.324c-12.785,0-23.15-10.365-23.15-23.15s10.365-23.149,23.15-23.149s23.147,10.365,23.147,23.149
+ C369.604,215.96,359.24,226.324,346.456,226.324z"/>
+ </g>
+ </g>
+</g>
+</svg>
diff --git a/icons/copy.svg b/assets/icons/copy.svg
similarity index 100%
rename from icons/copy.svg
rename to assets/icons/copy.svg
diff --git a/icons/crop.svg b/assets/icons/crop.svg
similarity index 100%
rename from icons/crop.svg
rename to assets/icons/crop.svg
diff --git a/icons/cut.svg b/assets/icons/cut.svg
similarity index 100%
rename from icons/cut.svg
rename to assets/icons/cut.svg
diff --git a/icons/display.svg b/assets/icons/display.svg
similarity index 100%
rename from icons/display.svg
rename to assets/icons/display.svg
diff --git a/icons/drive.svg b/assets/icons/drive.svg
similarity index 100%
rename from icons/drive.svg
rename to assets/icons/drive.svg
diff --git a/icons/edit.svg b/assets/icons/edit.svg
similarity index 100%
rename from icons/edit.svg
rename to assets/icons/edit.svg
diff --git a/icons/eject.svg b/assets/icons/eject.svg
similarity index 100%
rename from icons/eject.svg
rename to assets/icons/eject.svg
diff --git a/icons/ethernet.svg b/assets/icons/ethernet.svg
similarity index 100%
rename from icons/ethernet.svg
rename to assets/icons/ethernet.svg
diff --git a/icons/eye-off.svg b/assets/icons/eye-off.svg
similarity index 100%
rename from icons/eye-off.svg
rename to assets/icons/eye-off.svg
diff --git a/icons/eye.svg b/assets/icons/eye.svg
similarity index 100%
rename from icons/eye.svg
rename to assets/icons/eye.svg
diff --git a/icons/filter.svg b/assets/icons/filter.svg
similarity index 100%
rename from icons/filter.svg
rename to assets/icons/filter.svg
diff --git a/icons/fit.svg b/assets/icons/fit.svg
similarity index 100%
rename from icons/fit.svg
rename to assets/icons/fit.svg
diff --git a/icons/folder.svg b/assets/icons/folder.svg
similarity index 100%
rename from icons/folder.svg
rename to assets/icons/folder.svg
diff --git a/icons/git-branch.svg b/assets/icons/git-branch.svg
similarity index 100%
rename from icons/git-branch.svg
rename to assets/icons/git-branch.svg
diff --git a/icons/git.svg b/assets/icons/git.svg
similarity index 100%
rename from icons/git.svg
rename to assets/icons/git.svg
diff --git a/icons/globe.svg b/assets/icons/globe.svg
similarity index 100%
rename from icons/globe.svg
rename to assets/icons/globe.svg
diff --git a/icons/headphones.svg b/assets/icons/headphones.svg
similarity index 100%
rename from icons/headphones.svg
rename to assets/icons/headphones.svg
diff --git a/icons/home.svg b/assets/icons/home.svg
similarity index 100%
rename from icons/home.svg
rename to assets/icons/home.svg
diff --git a/icons/joined-displays.svg b/assets/icons/joined-displays.svg
similarity index 100%
rename from icons/joined-displays.svg
rename to assets/icons/joined-displays.svg
diff --git a/icons/keyboard.svg b/assets/icons/keyboard.svg
similarity index 100%
rename from icons/keyboard.svg
rename to assets/icons/keyboard.svg
diff --git a/icons/lock.svg b/assets/icons/lock.svg
similarity index 100%
rename from icons/lock.svg
rename to assets/icons/lock.svg
diff --git a/icons/logout.svg b/assets/icons/logout.svg
similarity index 100%
rename from icons/logout.svg
rename to assets/icons/logout.svg
diff --git a/icons/mouse.svg b/assets/icons/mouse.svg
similarity index 100%
rename from icons/mouse.svg
rename to assets/icons/mouse.svg
diff --git a/icons/music.svg b/assets/icons/music.svg
similarity index 100%
rename from icons/music.svg
rename to assets/icons/music.svg
diff --git a/icons/notification-bell.svg b/assets/icons/notification-bell.svg
similarity index 100%
rename from icons/notification-bell.svg
rename to assets/icons/notification-bell.svg
diff --git a/icons/open.svg b/assets/icons/open.svg
similarity index 100%
rename from icons/open.svg
rename to assets/icons/open.svg
diff --git a/icons/paste.svg b/assets/icons/paste.svg
similarity index 100%
rename from icons/paste.svg
rename to assets/icons/paste.svg
diff --git a/icons/power-button.svg b/assets/icons/power-button.svg
similarity index 100%
rename from icons/power-button.svg
rename to assets/icons/power-button.svg
diff --git a/icons/print.svg b/assets/icons/print.svg
similarity index 100%
rename from icons/print.svg
rename to assets/icons/print.svg
diff --git a/icons/redi-fm-icon.png b/assets/icons/redi-fm-icon.png
similarity index 100%
rename from icons/redi-fm-icon.png
rename to assets/icons/redi-fm-icon.png
diff --git a/icons/refresh.svg b/assets/icons/refresh.svg
similarity index 100%
rename from icons/refresh.svg
rename to assets/icons/refresh.svg
diff --git a/icons/restart.svg b/assets/icons/restart.svg
similarity index 100%
rename from icons/restart.svg
rename to assets/icons/restart.svg
diff --git a/icons/rotate.svg b/assets/icons/rotate.svg
similarity index 100%
rename from icons/rotate.svg
rename to assets/icons/rotate.svg
diff --git a/icons/save.svg b/assets/icons/save.svg
similarity index 100%
rename from icons/save.svg
rename to assets/icons/save.svg
diff --git a/icons/search.svg b/assets/icons/search.svg
similarity index 100%
rename from icons/search.svg
rename to assets/icons/search.svg
diff --git a/icons/settings.svg b/assets/icons/settings.svg
similarity index 100%
rename from icons/settings.svg
rename to assets/icons/settings.svg
diff --git a/icons/sort.svg b/assets/icons/sort.svg
similarity index 100%
rename from icons/sort.svg
rename to assets/icons/sort.svg
diff --git a/icons/speaker-xmark.svg b/assets/icons/speaker-xmark.svg
similarity index 100%
rename from icons/speaker-xmark.svg
rename to assets/icons/speaker-xmark.svg
diff --git a/icons/speaker.svg b/assets/icons/speaker.svg
similarity index 100%
rename from icons/speaker.svg
rename to assets/icons/speaker.svg
diff --git a/icons/squares.svg b/assets/icons/squares.svg
similarity index 100%
rename from icons/squares.svg
rename to assets/icons/squares.svg
diff --git a/icons/trash-outline.svg b/assets/icons/trash-outline.svg
similarity index 100%
rename from icons/trash-outline.svg
rename to assets/icons/trash-outline.svg
diff --git a/icons/trash.svg b/assets/icons/trash.svg
similarity index 100%
rename from icons/trash.svg
rename to assets/icons/trash.svg
diff --git a/icons/undo.svg b/assets/icons/undo.svg
similarity index 100%
rename from icons/undo.svg
rename to assets/icons/undo.svg
diff --git a/icons/usb-stick.svg b/assets/icons/usb-stick.svg
similarity index 100%
rename from icons/usb-stick.svg
rename to assets/icons/usb-stick.svg
diff --git a/icons/users.svg b/assets/icons/users.svg
similarity index 100%
rename from icons/users.svg
rename to assets/icons/users.svg
diff --git a/icons/view-grid.svg b/assets/icons/view-grid.svg
similarity index 100%
rename from icons/view-grid.svg
rename to assets/icons/view-grid.svg
diff --git a/icons/view-list.svg b/assets/icons/view-list.svg
similarity index 100%
rename from icons/view-list.svg
rename to assets/icons/view-list.svg
diff --git a/icons/wifi.svg b/assets/icons/wifi.svg
similarity index 100%
rename from icons/wifi.svg
rename to assets/icons/wifi.svg
diff --git a/icons/zoom-in.svg b/assets/icons/zoom-in.svg
similarity index 100%
rename from icons/zoom-in.svg
rename to assets/icons/zoom-in.svg
diff --git a/icons/zoom-out.svg b/assets/icons/zoom-out.svg
similarity index 100%
rename from icons/zoom-out.svg
rename to assets/icons/zoom-out.svg
diff --git a/assets/mockups/polkit-dialog.html b/assets/mockups/polkit-dialog.html
index fb4cd0d..4afa18b 100644
--- a/assets/mockups/polkit-dialog.html
+++ b/assets/mockups/polkit-dialog.html
@@ -45,7 +45,7 @@
<main>
<section class="dialog" role="dialog" aria-labelledby="title" aria-describedby="description">
<header>
- <div class="badge"><img class="lock-icon" src="../../icons/lock.svg" alt=""></div>
+ <div class="badge"><img class="lock-icon" src="../icons/lock.svg" alt=""></div>
<div><h1 id="title">Authentication required</h1><p id="description">Enter your password to continue.</p></div>
</header>
<div class="request">
@@ -58,7 +58,7 @@
</div>
<label id="password-label">Password</label>
<div class="field" role="img" aria-labelledby="password-label" aria-label="Password field preview, example masked characters">
- <img class="lock-icon" src="../../icons/lock.svg" alt=""><span aria-hidden="true">••••••••</span>
+ <img class="lock-icon" src="../icons/lock.svg" alt=""><span aria-hidden="true">••••••••</span>
</div>
<p class="hint" id="status" aria-live="polite">Administrator privileges are required to continue.</p>
<footer><button id="cancel">Cancel</button><button class="primary" id="authenticate">Authenticate</button></footer>
diff --git a/src/assets/redi-logo.svg b/assets/redi-logo.svg
similarity index 100%
rename from src/assets/redi-logo.svg
rename to assets/redi-logo.svg
diff --git a/src/assets/themes/redi-blue.toml b/assets/themes/redi-blue.toml
similarity index 100%
rename from src/assets/themes/redi-blue.toml
rename to assets/themes/redi-blue.toml
diff --git a/src/assets/themes/rediwm-dark.toml b/assets/themes/rediwm-dark.toml
similarity index 100%
rename from src/assets/themes/rediwm-dark.toml
rename to assets/themes/rediwm-dark.toml
diff --git a/src/assets/themes/rediwm-light.toml b/assets/themes/rediwm-light.toml
similarity index 100%
rename from src/assets/themes/rediwm-light.toml
rename to assets/themes/rediwm-light.toml
diff --git a/build.zig b/build.zig
index 471c129..1b7cc1a 100644
--- a/build.zig
+++ b/build.zig
@@ -78,10 +78,11 @@ pub fn build(b: *std.Build) void {
const ui_mod = b.createModule(.{ .root_source_file = b.path("src/ui/mod.zig"), .target = target, .optimize = optimize, .link_libc = true });
ui_mod.addImport("memory", memory_mod);
ui_mod.addImport("wayland", wayland);
+ ui_mod.linkSystemLibrary("xkbcommon", .{});
addShellUi(b, ui_mod);
- ui_mod.addAnonymousImport("theme-rediwm-dark", .{ .root_source_file = b.path("src/assets/themes/rediwm-dark.toml") });
- ui_mod.addAnonymousImport("theme-rediwm-light", .{ .root_source_file = b.path("src/assets/themes/rediwm-light.toml") });
- ui_mod.addAnonymousImport("theme-redi-blue", .{ .root_source_file = b.path("src/assets/themes/redi-blue.toml") });
+ ui_mod.addAnonymousImport("theme-rediwm-dark", .{ .root_source_file = b.path("assets/themes/rediwm-dark.toml") });
+ ui_mod.addAnonymousImport("theme-rediwm-light", .{ .root_source_file = b.path("assets/themes/rediwm-light.toml") });
+ ui_mod.addAnonymousImport("theme-redi-blue", .{ .root_source_file = b.path("assets/themes/redi-blue.toml") });
const dbus_mod = b.createModule(.{ .root_source_file = b.path("src/dbus/mod.zig"), .target = target, .optimize = optimize, .link_libc = true });
dbus_mod.addImport("wayland", wayland);
dbus_mod.linkSystemLibrary("wayland-server", .{});
@@ -179,7 +180,7 @@ pub fn build(b: *std.Build) void {
b.getInstallStep().dependOn(&install_files.step);
b.getInstallStep().dependOn(&install_files_desktop_entry.step);
const install_files_icon = b.addSystemCommand(&.{ "install", "-Dm644" });
- install_files_icon.addFileArg(b.path("icons/redi-fm-icon.png"));
+ install_files_icon.addFileArg(b.path("assets/icons/redi-fm-icon.png"));
install_files_icon.addArg(b.getInstallPath(.prefix, "share/icons/hicolor/256x256/apps/redi-fm-icon.png"));
b.getInstallStep().dependOn(&install_files_icon.step);
// rediwm-files links neither wlroots-server nor libinput/libpulse, so it
@@ -781,7 +782,8 @@ fn addShellUi(b: *std.Build, module: *std.Build.Module) void {
// Bundle shell glyphs so installed binaries never depend on the checkout.
fn addShellIcons(b: *std.Build, module: *std.Build.Module) void {
+ module.addAnonymousImport("redi-logo", .{ .root_source_file = b.path("assets/redi-logo.svg") });
inline for (.{ "git-branch", "home", "folder", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares" }) |name| {
- module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("icons/" ++ name ++ ".svg") });
+ module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("assets/icons/" ++ name ++ ".svg") });
}
}
diff --git a/docs/plans/i18n.md b/docs/plans/i18n.md
new file mode 100644
index 0000000..d68bd2e
--- /dev/null
+++ b/docs/plans/i18n.md
@@ -0,0 +1,395 @@
+# Plan: translating the RediWM UI
+
+Status: decided. Phase 0 (survey) done 2026-10-08, results below. Next step is
+Phase 1.
+
+Scope: this is the groundwork only. It stops hardcoding English so that a
+language can be added later by dropping in one `po/<lang>.po` file, with no
+code change. No real translation ships as part of it; the `qps`
+pseudo-locale is what proves the machinery works.
+
+## Where we are
+
+Every user-facing string is an English literal at its call site
+(`"Cancel"`, `"Forget Device"`, `"Delete {s}?"` through `std.fmt.allocPrint`).
+There is no gettext, string table or catalog. A rough grep finds ~1,300
+capitalised literals under `src/`: `control_center` 609, `files` 361, top-level
+`src/*.zig` 531 (power menu, taskbar, notifications, dialogs), `network` 104,
+`start_menu` 68, `images` 65, `ui` 56, `desktop` 55, `screenshot` 47,
+`editor` 43, `pdf` 38, `polkit` 34. A large share of that is not UI text
+(IPC error names, D-Bus members, widget ids, log lines), so the real count is
+an output of Phase 0, not an input.
+
+What already exists and the plan builds on:
+
+* `[region] language` is an installed glibc locale (`en_NZ.utf8`).
+ `child_env.applyRegion` writes it into `LANG`, `LC_MESSAGES` and `LC_CTYPE`
+ of every app the compositor launches, so GTK/Qt apps already follow it.
+* `[region] formats` drives the clock (`Taskbar.zig` keeps a private
+ `locale_t`) and the `LC_TIME`/`LC_NUMERIC`/... categories for children.
+* `start_menu/applications.zig` parses `Name[de]=` locale keys in `.desktop`
+ files.
+* Text goes through FreeType + HarfBuzz (`ui/text.zig`) with fontconfig
+ fallback for missing glyphs, so CJK, accents and emoji draw. The Editor uses
+ Pango and has `ime.zig`.
+* Tests find widgets by `name` (`ui.find(name, panel=...)`), not by label, so
+ most of the suite is insulated from wording. Six files still reference
+ English labels (`app_activation`, `keyboard_shortcuts`, `notifications`,
+ `bluetooth`, `control_center`, `power`); they run in English and stay valid.
+
+What is missing: any lookup, any catalog, plural handling, and a layout that
+tolerates strings of other lengths.
+
+## Goals and non-goals
+
+Goals:
+
+* One lookup API used by the compositor, the standalone apps (Files, Images,
+ PDF, Editor, share picker), the lock screen, polkit dialog and greeter.
+* English stays the source of truth and the zero-cost default.
+* No new runtime library: catalogs are compiled in.
+* No per-frame cost: no allocation, no string hashing, no wakeups, no
+ growth in idle CPU (`AGENTS.md` "Idle makes no wakeups").
+* A pseudo-locale that makes clipped or fixed-width layouts visible without
+ knowing any language.
+
+Non-goals (separate plans if wanted):
+
+* **Right-to-left languages.** `ui/text.zig` runs HarfBuzz per run with
+ `hb_buffer_guess_segment_properties` but has no bidi reordering (no
+ FriBidi) and widgets do not mirror. Arabic/Hebrew/Persian need both.
+ Translated Arabic strings would render in the wrong visual order.
+* **Input methods in the shell's own text fields.** Only the Editor has IME
+ support. A Japanese UI whose control-center fields cannot take Japanese
+ input is half-done. Confirmed in Phase 0: the shell has no IME.
+* Translating IPC, logs, config keys, `rediwm-msg`, or text produced by other
+ programs (D-Bus error messages from NetworkManager/bluez/logind, notification
+ bodies, tray menu labels). Those stay as received.
+
+## Design
+
+### The `i18n` module
+
+A leaf named module with no dependencies, importable from `ui`, `config`,
+the compositor and every executable, like `ui`/`dbus`/`config` (`AGENTS.md`
+"Build and platform").
+
+```zig
+i18n.tr("Cancel") // msgid is the English text
+i18n.trc("menu", "Open") // context, for same word / different sense
+i18n.trn("{n} item", "{n} items", n) // plural
+i18n.fmt(buf, i18n.tr("Delete {name}?"), .{ .name = user })
+```
+
+* **English text is the msgid.** Conversion is mechanical (`"Cancel"` →
+ `tr("Cancel")`), readable at the call site, and an untranslated string
+ falls back to itself. `trc` disambiguates the few collisions.
+* **`tr` is allocation-free and hash-free at runtime.** The msgid is a
+ comptime literal, so its hash is computed at compile time; the runtime step
+ is one probe into the active catalog's open-addressed table plus one `memcmp`
+ to confirm. Catalogs are static data in rodata. English is the identity
+ with no table at all.
+* **Formatting needs a runtime formatter.** `std.fmt` takes a comptime format
+ string, and a translated one is only known at runtime. `i18n.fmt` therefore
+ substitutes named placeholders (`{name}`, `{n}`) from a struct of strings
+ and integers, so translators can reorder arguments. Every existing
+ `allocPrint("Delete {s}?", ...)` that carries wording converts to this.
+* **Plurals** use CLDR rules, one function per rule family (English/German,
+ French, Russian/Polish, Japanese/Chinese: one form, ...). Phase 1 ships the
+ rule table; adding a language that needs a new family is a one-function
+ change plus a test.
+* **Language resolution.** The compositor takes `[region] language` and falls
+ back to its own `LC_ALL`/`LC_MESSAGES`/`LANG`. Standalone apps and the
+ share picker read the POSIX environment, which `applyRegion` already sets
+ when the compositor launches them. Tag `en_NZ.utf8` resolves through
+ `en_NZ` → `en` → English. A language with no catalog leaves RediWM's own
+ UI in English while apps still get the locale.
+* **Pseudo-locale** `qps` (expanded ~40%, accented, bracketed:
+ `[Çàñçéł !!!]`) is an ordinary generated catalog selected through the normal
+ config key, not an environment hook, so it respects "No test hooks in
+ production". It is unlisted in the language picker.
+
+### Catalogs and tooling
+
+* Source: `po/rediwm.pot` (extracted) and `po/<lang>.po`. Standard PO files
+ mean contributors can use Poedit, Weblate or any editor, and the format
+ carries context and plural forms.
+* Extraction and compilation are `build.zig` steps built from one small Zig
+ tool (`tools/i18n.zig`), no gettext toolchain needed on the build machine:
+ * `zig build i18n-extract` regenerates the `.pot` from `tr`/`trc`/`trn`
+ call sites.
+ * The normal build compiles each `.po` into a generated Zig file with the
+ hash table, embedded in the binaries that use it.
+ * `zig build i18n-check` fails on a `tr` literal missing from the `.pot`,
+ a stale entry, a placeholder set that differs between msgid and
+ translation, or a wrong plural-form count.
+* Catalogs are per product, not per executable, so the compositor,
+ `rediwm-files` and the rest share one table layout; each binary embeds only
+ what it uses if size matters (measure in Phase 1).
+
+### Keeping untranslated strings from creeping back
+
+The risk after the conversion is someone adding `.label = "Foo"`. Two layers:
+
+* `zig build i18n-lint` flags a bare string literal passed to a known UI sink
+ (`.label`, `.placeholder`, `text(...)`, `button.paint` labels, dialog
+ titles, Cairo `drawText`). A `// i18n: raw` comment marks intentional
+ exceptions.
+* The lint is opt-in per directory and the list grows with each phase, so it
+ never reports the not-yet-converted code.
+
+Widget `name` ids, which tests use, are never translated.
+
+### Switching language
+
+* **Compositor UI:** treated like a theme or scale change. Config reload
+ invalidates cached text and rebuilds the panels (taskbar, start menu,
+ control center, power menu). No polling; it rides the existing reload path.
+* **Running app clients:** pick up the new language on next launch. Nothing
+ broadcasts; the Control Center says so next to the setting. (Revisit only
+ if users ask.)
+
+### Layout
+
+Translated text is typically 20–40% longer (German, Russian, Finnish) and CJK
+text is taller. Likely trouble spots:
+
+* 129 `fixed = N` sizes in `control_center`, `start_menu` and `ui`.
+* Hand-placed Cairo layouts with literal offsets and widths, for example the
+ Editor close dialog (`.w = 115`, `.w = 120`) and parts of Files.
+* Fixed-height rows where a fallback font (CJK, Indic) has taller metrics than
+ Manrope.
+
+Policy: prefer content-sized or flex layouts; where a width is unavoidable,
+measure the translated string and ellipsize through the existing text API
+instead of overflowing. The pseudo-locale is the detector: IPC screenshots in
+`qps` for every panel, compared against English.
+
+## Phases
+
+**Phase 0: survey (small). Done, see [Phase 0 results](#phase-0-results).**
+Classify the ~1,300 literals by sink (UI / protocol / log / id) to get the
+real count per area; confirm which standalone apps get `LC_MESSAGES` from
+`applyRegion` (Files, Images, PDF, Editor, share picker); check whether the
+IPC widget tree exposes text extents, which would allow an automated
+overflow assertion; check IME in shell text fields; check dead keys and
+compose in every text field (see
+[First languages](#first-languages-spanish-and-portuguese)); check how
+`applications.zig` picks its `Name[xx]` locale and make it use the same
+resolver.
+
+**Phase 1: module and tooling.**
+`i18n` with `tr`/`trc`/`trn`/`fmt`, plural rules, language resolution, the PO
+compiler, `i18n-extract`/`-check`/`-lint`, the `qps` generator. Unit tests for
+plural rules, placeholder substitution, fallback chain and catalog lookup.
+Convert one small surface end to end as the proof (the power menu: 7 labels
+plus the `"Uptime {d}h {d}m"` format). Measure binary size and confirm
+`tr` adds nothing to the frame profile (`perf stat`, instructions).
+
+**Phase 2: shell chrome.**
+Power menu, taskbar, start menu, calendar and battery popups, notification
+toast/OSD text we own, delete/rename dialogs, screenshot selector, tray
+chrome, lock screen, polkit dialog. First `qps` layout pass. Lock screen and
+polkit dialog are security-sensitive: the strings only change language, never
+which action a button performs; keep buttons identifiable by position and
+role, not wording.
+
+**Phase 3: Control Center.**
+The largest area (609 literals). Most formatted strings live here
+(`"Account details · {s}"`, `"Boot time: {s}"`, `"Delete {s}?"`) and need
+`fmt`/`trn`. The Region section's language list should show which locales
+RediWM itself is translated into. One section per commit; extend the lint list
+after each.
+
+**Phase 4: app clients.**
+Files (361), Images, PDF, Editor, share picker. Resolve language from the
+environment in each `*_main.zig`, before the first frame, alongside theme
+loading. Files has selection-count strings
+(`"{n} selected, {size}"` built with `if (n == 1) "" else "s"`) that become
+`trn`. Audit the hand-drawn Cairo layouts.
+
+**Phase 5: login.**
+`rediwm --greeter` and `rediwm-dm`. The greeter writes nothing under `$HOME`
+and has no user config, so it takes the system locale (`/etc/locale.conf` via
+the DM's environment) or a per-user choice only if the DM already knows it;
+this is a decision, see below. `rediwm-dm` and the accounts helper run as root
+and must not parse catalogs or build user-facing text: they return error codes
+and the unprivileged UI maps them to strings. Audit both for English text
+that crosses the boundary.
+
+**Phase 6: docs (last phase of the groundwork).**
+Document how to add a language in the wiki (`docs/wiki`), `README.md` and
+`TESTING.md`: copy `po/rediwm.pot` to `po/<lang>.po`, translate, run
+`zig build i18n-check`, build.
+
+**Later, not part of this plan: adding actual languages.**
+Each one is a `.po` file plus a check of fonts and fallback metrics on real
+text. A language whose plural rules are not yet in the table needs one
+function and a test.
+
+## Phase 0 results
+
+Done 2026-10-08. Read-only; nothing in `src/` changed.
+
+**How many strings.** A script over non-test `src/**/*.zig` (skipping `test`
+blocks, comments, log/error/compare lines) classified distinct capitalised or
+multi-word literals by whether they feed a UI sink. It misses lower-case
+labels and multi-line `\\` literals, so treat the figures as +/-20%.
+
+* In UI-facing areas: 404 distinct strings reach a UI sink, and 814 more are
+ unclassified. A 25-string sample of the remainder was ~80% UI text (the rest
+ were D-Bus members, config templates, log text). Expect **about 1,000
+ translatable strings** (range 800–1,200), not the 1,300 occurrences first
+ counted.
+* Sink-matched + remainder by area: `control_center` 241+318, `files` 84+134,
+ top-level `src/*.zig` 20+155, `network` 22+65, `images` 12+46, `editor`
+ 13+25, `screenshot` 10+26, `pdf` 3+33, `desktop` 1+33, `polkit` 2+31,
+ `start_menu` 7+13, `share_picker` 4+10, `taskbar` 2+4, `notifications` 0+5,
+ `ui` 1+6.
+* Not translated (protocol, CLI, config template or logs): `ipc` (~290),
+ `msg`, `config`, `dbus`, `dm`, `accounts_helper`, `input`, `audio`,
+ `capture`, `night_light`, `config_runtime`. Exception: `session` holds a few
+ user-facing power/logind errors ("Blocked by an active inhibitor lock.",
+ "Lost contact with login service. Try again."), converted by hand in Phase 2.
+* Keybinding descriptions ("Increase system volume.", "Move the relevant split
+ divider left.") are user-visible and numerous; they count toward
+ `control_center`.
+
+**Language reaches launched apps, but not the apps' own code.**
+`child_env.apply` calls `applyRegion` (`child_env.zig:34`) and every launch
+path goes through `applyChildEnv*`, so apps get `LANG`/`LC_MESSAGES`/`LC_CTYPE`
+from `[region] language`, and `LC_ALL`/`LANGUAGE` are removed. The standalone
+clients (`files_main`, `images_main`, `pdf_main`, `editor_main`,
+`share_picker_main`) read no language variable today; Phase 4 adds the
+resolver there, reading `LC_ALL` → `LC_MESSAGES` → `LANG`.
+
+**The compositor does not follow `[region] language` yet.** `applyRegion`
+edits only child environments; the compositor's own process environment is
+unchanged. `start_menu/applications.zig` builds its `Locale` from that process
+environment at startup (`Locale.fromEnv`, and the cache key in
+`catalog_cache.envKeys` uses the same variables), so `Name[xx]` desktop-entry
+names follow the login locale, not the setting, and do not update when it
+changes. The shared resolver replaces both: the cache key must include the
+resolved language, and a language change must rescan.
+
+**IPC widget tree.** `WidgetNodeData` carries `label`, `box`, `global_box`,
+`clipped` and `text_length`, but not the measured text width, so a test cannot
+assert overflow. Phase 1 adds a `text_width` field (layout pixels); the `qps`
+tests then assert `text_width <= box.w` for every labelled widget.
+
+**IME in the shell.** None. `input/text_input.zig` relays text-input-v3 and
+input-method-v2 for client apps only. The shell's own fields (control center,
+start menu, lock, polkit) and the Files/Images/PDF fields take xkb keysyms
+only. Irrelevant for Spanish and Portuguese; it confirms CJK input would be a
+separate project.
+
+**Dead keys: confirmed broken everywhere but the Editor.**
+
+* Checked with libxkbcommon: on `latam`, `es`, `br`, `pt` and `us(intl)`
+ the dead keys (acute, grave, tilde) return **0 bytes** from
+ `xkb_state_key_get_utf8`.
+* Every text path outside the Editor uses that call with no
+ `xkb_compose_state`: `Keyboard.zig:819,847,885` (compositor shell: start
+ menu, control center fields, lock screen, polkit, wifi popup, desktop),
+ `files/main.zig:547,554`, `images/main.zig:476,483`, `pdf/main.zig:404,411`.
+ By code reading, an empty result is dropped (`utf8.len > 0` else no
+ character). I have not typed it on a live session.
+* Beyond names and search: the **lock screen and polkit password fields**
+ read the same way, so a password containing an accent typed with a dead key
+ cannot be entered. The same applies to the greeter, which is the same
+ compositor. That is a lockout risk for exactly the target users.
+* The compose table depends on locale, and not only for tidiness:
+ `´`+`c` composes to `ć` in `C`, `en_US` and `es_MX` but to `ç` in
+ `pt_BR`. A table loaded from the wrong locale gives Brazilian users the wrong
+ letter. `C`/`C.UTF-8` do resolve to a working table (á, ã); an invalid or
+ uninstalled locale returns no table and logs an xkbcommon error, so the
+ loader needs a fallback to `C.UTF-8`.
+* Fix: move `editor/compose.zig` to `ui/compose.zig`; one compose state per
+ keyboard in the compositor (reset on focus or layout change) and one per
+ client; build the table from the resolved UI language. Composed text for
+ lock and polkit goes through the existing `clearKeyScratch` scrub, and a
+ pending dead key is cleared when a secret field loses focus. This is a
+ separate small change that does not wait for the `i18n` module.
+* **Fixed 2026-10-08 (uncommitted).** `ui/compose.zig` replaces
+ `editor/compose.zig`: lazy shared table built from the user's language
+ (`[region] language` in the compositor, `LC_ALL`/`LC_CTYPE`/`LANG` in app
+ clients), locale names normalised to `ll_CC.UTF-8` (a bare `pt_BR` maps to
+ the unparseable ISO 8859-1 file), fallback to `C.UTF-8`. Wired into
+ `Keyboard.composeShell` (start menu, control center, lock, polkit, wifi
+ popup, desktop), Files, Images, PDF (table preloaded before its sandbox) and
+ the Editor. A dead key, or the key completing a sequence, never repeats.
+ `tests/dead_keys.py` types through a virtual `latam` keyboard under `pt_BR`
+ and `es_MX`. Known limits: a key that does not fit a pending sequence is
+ swallowed (as in the Editor); a dead key left pending across a lock/unlock
+ cycle can combine with the first key of the next lock prompt; text-input-v3
+ clients are unaffected (they compose themselves).
+
+## Testing
+
+* Unit tests (`zig build test`): plural rules for every family, placeholder
+ substitution and mismatch rejection, fallback chain, PO parser, catalog
+ round trip.
+* Existing integration tests run unchanged in English. They are the proof
+ that the default path is untouched.
+* One new integration test per phase launches with `[region] language` set to
+ the `qps` locale (with a scratch `XDG_STATE_HOME`, or the run clobbers the
+ live autosave layout), opens each converted panel, and checks
+ that widgets are still found by `name`, that bounds do not overflow, and
+ that IPC screenshots differ from English only in text.
+* Per `AGENTS.md`: build Debug and ReleaseSafe, and `strings` the ReleaseSafe
+ binary to confirm no test hook leaked.
+
+## Risks
+
+* **The mechanical conversion hides non-text strings.** Wrapping an ID or an
+ IPC name in `tr` breaks behaviour only when a translation exists, so it
+ would pass English tests. Mitigation: Phase 0 classification by sink, and
+ `i18n-check` rejecting `tr` on strings used as map keys or `std.mem.eql`
+ operands in the same function where it can see them.
+* **Cached rasters keyed by text** stay correct (the key includes the text),
+ but anything caching measured widths across a language change must be
+ invalidated with the rest on reload.
+* **Translations drift** as English changes. `i18n-check` reports stale and
+ missing entries; fuzzy-matching is left to the translation tools.
+* **Scope creep into RTL and IME**, which are each a project of their own.
+
+## Decisions
+
+Made 2026-10-08, taking the recommendations:
+
+1. **UI language is `[region] language`.** One "Language" setting; no
+ separate `ui_language` key.
+2. **English text is the msgid**, with `trc` for the few collisions. No
+ symbolic keys.
+3. **Greeter uses the system locale only** for v1; no per-user choice at
+ login.
+4. **Translations are `.po` files contributed by pull request.** No hosted
+ translation tool.
+5. **Right-to-left is out of scope** and needs its own plan (bidi
+ reordering plus mirrored layouts).
+
+## First languages: Spanish and Portuguese
+
+The intended first additions (Latin America is the target audience), added
+after this plan. Neither needs RTL, an input method or special fonts: Manrope
+covers the accents. What they do need from the groundwork:
+
+* **Regional chains.** Locales arrive as `es_MX`, `es_AR`, `es_CO`, `pt_BR`,
+ `pt_PT`. Resolution tries the exact tag, then the language, so ship one
+ neutral `es` (imperative forms, no voseo or regional vocabulary, serves all
+ of Latin America and Spain) and `pt_BR` (`pt` resolves to it unless a
+ `pt_PT` catalog exists). Regional overrides are small `.po` files that
+ carry only the strings that differ.
+* **Plural rules.** Spanish: `n == 1` is singular. Brazilian Portuguese
+ differs: 0 and 1 are both singular ("0 arquivo"), European Portuguese
+ follows Spanish. CLDR also defines a `many` form for exact multiples of a
+ million ("1 millón de archivos"); the table ignores it and uses `other`,
+ which is wrong only for counts that large.
+* **Length.** Both run roughly 15–30% longer than English, so the `qps`
+ pseudo-locale (+40%) is a sufficient stress test.
+* **Dead keys and compose (prerequisite, not i18n).** Confirmed broken
+ outside the Editor and fixed 2026-10-08; details in
+ [Phase 0 results](#phase-0-results).
+* **Other dependencies.** `region.formats` already handles LATAM date and
+ number differences (comma decimals, 24-hour clock). Desktop entries use the
+ same resolver as the UI, so `Name[es]`/`Name[pt_BR]` fall in line.
diff --git a/docs/plans/optional-tiling-qualification.md b/docs/plans/optional-tiling-qualification.md
new file mode 100644
index 0000000..6ff223b
--- /dev/null
+++ b/docs/plans/optional-tiling-qualification.md
@@ -0,0 +1,192 @@
+# Optional tiling qualification
+
+Updated 2026-10-08. Canvas remains the shipped default; workspace mode is opt-in.
+This records qualification of the uncommitted stages 1–6 implementation against
+HEAD `a3f4a316bc850169edf55e81325f4b197697e780`. Physical-display qualification
+has started after the user compiled, installed and restarted into the new build.
+Startup inspection is recorded below; interactive checks remain pending.
+
+## Automated results
+
+Debug, ReleaseSafe (`--prefix zig-out/release-safe`) and `zig build test` pass.
+All integration runs use private headless compositors and scratch state.
+The baseline was built in a fresh detached worktree at
+`/tmp/rediwm-tiling-head`. Logs for this run are in
+`/tmp/rediwm-tiling-qualification`; these temporary paths are evidence from this
+run, not repository fixtures.
+
+| Check | Implementation | HEAD comparison |
+| --- | --- | --- |
+| Full `wlr_protocols.py` | Fails at `session_lock`: second client prints EOF instead of `finished`; preceding protocol cases pass | Same assertion in the unmodified HEAD suite |
+| Full `xwayland.py` | Reaches native-scaling managed-window test; expects titlebar 41, receives 35 | Focused `test_native_scaling_managed_window()` reproduces 41 vs 35 on HEAD; the unmodified full HEAD suite stops earlier at its legacy stop-server envelope |
+| Full workspace suite, pixman, two outputs, 1.5×, negative origins, GTK/Xwayland | Pass | Feature absent on HEAD |
+| Full workspace suite, NVIDIA GLES, two outputs, 1.5×, negative origins, GTK/Xwayland | Pass, including scale/origin reload, real input, lock guards, restart, undo and idle | Feature absent on HEAD |
+| Intel GLES workspace controls, persistence and automatic layout, two outputs, 1.5×, negative origins | Pass | Feature absent on HEAD |
+| Full workspace suite, Intel GLES, one output, GTK/Xwayland | Pass, including idle, lock guards, persistence, controls and canvas restoration | Feature absent on HEAD |
+| Intel GLES workspace acceptance, two outputs | Fails idle bound: 70 voluntary main-thread switches in 1.2 s, limit 4 | Matched canvas probe also wakes repeatedly on HEAD; see below |
+| Intel GLES GTK/Xwayland workspace routing and canvas restoration, two outputs, 1.5×, negative origins | Pass | Feature absent on HEAD |
+| Intel GLES `window_corners.py` | Pass at 1, 1.25, 1.5 and 2×, including Settings resize and light/dark edges | No baseline failure to compare |
+| Intel `zig build test-glass` | Pass | Pass |
+| NVIDIA `zig build test-glass` | Fails: incompatible EGLImage/target, FBO creation failure, `effect->valid && !engine->failed` assertion | Same failure |
+
+The workspace GTK routing fixture now honors `REDIWM_TEST_RENDERER`; previously
+that branch silently used pixman even when the rest of the suite used GLES.
+No assertions were relaxed or failures skipped for qualification.
+
+The machine exposes `/dev/dri/renderD128` through i915 and
+`/dev/dri/renderD129` through NVIDIA (driver 615.71.09), on kernel
+7.2.8-zen1-2-zen. Render-node numbers are machine-specific; discover them again
+on another machine. Only `card1-eDP-1` was connected during this run.
+
+The Intel idle comparison used the same three Wayland fixture windows, two
+headless outputs, per-output scale/origin reload sequence and 1.2 s sample:
+
+| Configuration | Main-thread voluntary switches | Other surviving threads |
+| --- | --- | --- |
+| HEAD canvas, GLES | 84 | 0 |
+| Implementation canvas, GLES | 76 | 0 |
+| Implementation workspaces, GLES | 96 | 0 |
+| Implementation workspaces, pixman | 1 | 0 |
+
+This reproduces repeated Intel GLES wakeups without tiling; it does not establish
+their cause or prove equal rendering cost. NVIDIA's full workspace acceptance
+sample recorded 1 main-thread switch and 0 on other surviving threads, with no
+additional client configures. Intel's one-output acceptance also recorded 1/0.
+Intel two-output idle and NVIDIA glass remain open renderer qualifications.
+
+## Reproduction
+
+Build HEAD in an isolated worktree and run the failing protocol cases with its
+own binary and fixtures:
+
+```sh
+git worktree add --detach /tmp/rediwm-tiling-head HEAD
+cd /tmp/rediwm-tiling-head
+zig build
+umask 077
+baseline_state=$(mktemp -d /tmp/rediwm-head-state.XXXXXX)
+export XDG_STATE_HOME="$baseline_state"
+python3 -u tests/wlr_protocols.py
+PYTHONPATH=tests python3 -u -c 'import xwayland; xwayland.test_native_scaling_managed_window()'
+```
+
+Run from the implementation checkout, selecting each available render node:
+
+```sh
+zig build
+zig build -Doptimize=ReleaseSafe --prefix zig-out/release-safe
+zig build test
+umask 077
+REDIWM_TEST_RENDERER=gles2 WLR_RENDER_DRM_DEVICE=/dev/dri/renderD129 \
+ REDIWM_TEST_OUTPUTS=2 REDIWM_TEST_SCALE=1.5 REDIWM_TEST_NEGATIVE=1 \
+ REDIWM_TEST_XWAYLAND=1 python3 -u tests/workspaces.py
+REDIWM_TEST_RENDERER=gles2 WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128 \
+ python3 -u tests/workspaces.py --acceptance-only
+WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128 zig build test-glass
+WLR_RENDER_DRM_DEVICE=/dev/dri/renderD129 zig build test-glass
+REDIWM_TEST_RENDERER=gles2 WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128 \
+ python3 -u tests/window_corners.py
+```
+
+Repeat the two-output workspace command with Intel to reproduce the idle
+failure. To exercise its later GTK/canvas cases independently after that failure:
+
+```sh
+REDIWM_TEST_RENDERER=gles2 WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128 \
+ REDIWM_TEST_OUTPUTS=2 REDIWM_TEST_SCALE=1.5 REDIWM_TEST_NEGATIVE=1 \
+ PYTHONPATH=tests python3 -u -c 'import workspaces; workspaces.xwayland_routing(); workspaces.run(2)'
+```
+
+## Physical-display qualification
+
+After the user's rebuild and restart on 2026-10-08, the running
+`/proc/3159569/exe` hash matches both `/usr/local/bin/rediwm` and the checkout's
+`zig-out/release-safe/bin/rediwm`:
+`98ce6266aebba7d4febd49ff4ec56052123bf5533c09915527a6b5698d3c8b1c`.
+Read-only IPC reports GLES2, `nested = false`, one enabled BOE `0x0A0B` panel
+on `eDP-1`, 2560×1600 pixels / 1706×1066 logical units, scale 1.5 and 60 Hz.
+The active workspace is Canvas. This verifies startup on the intended build
+and physical output; it does not qualify interactive tiling or scanout changes.
+The runtime/output/workspace snapshot is saved at
+`/tmp/rediwm-tiling-qualification/physical-startup.json`.
+
+The user subsequently confirmed that workspace tiling, real clicks, tile
+rearrangement, live split resizing and Escape cancellation work on this display.
+Other physical checks remain pending. Their follow-up request adds a 1 logical
+pixel red active-window outline and an 8 px workspace gap default; those visual
+changes need a rebuild/restart before physical confirmation. Explicit gap
+settings, including zero, remain authoritative; Canvas defaults stay unchanged.
+
+Focus-style validation: Debug and ReleaseSafe builds and all 789 unit tests pass.
+The expanded `window_corners.py` passes on pixman and Intel GLES at 1, 1.25,
+1.5 and 2×, covering focus transfer, straight edges and both corner bands, CSD
+edge clicks, fullscreen, mode transitions and default/explicit-zero gaps.
+The NVIDIA GLES focus check also passes at 1.5×. Complete two-output workspace
+suites pass on pixman and NVIDIA GLES at 1.5× with negative origins and real
+GTK/Xwayland clicks. Snapping, decoration negotiation, workspace tabs and
+focus/zoom integrations pass. Logs are in `/tmp/rediwm-tiling-focus`.
+
+### Checklist
+
+Run the checkout's ReleaseSafe binary in a disposable physical session. The
+installed binary had a different hash during the earlier automated run; the
+new running binary now matches, as recorded above. A nested Wayland window or a headless GLES pass does not verify
+DRM modesetting, scanout, physical input or EDID-derived scale.
+
+Save work and leave the existing graphical session before starting the test from
+a normal user's local VT login. Run without root. Keep the installed binaries
+and normal configuration intact; use scratch configuration and state instead:
+
+```sh
+cd /home/alex/projects/wlroots
+umask 077
+qualification_dir=$(mktemp -d /tmp/rediwm-physical-tiling.XXXXXX)
+mkdir -p "$qualification_dir/config" "$qualification_dir/state" \
+ "$qualification_dir/cache" "$qualification_dir/data"
+cat > "$qualification_dir/config.toml" <<'EOF'
+[compositor]
+xwayland = true
+EOF
+sha256sum zig-out/release-safe/bin/rediwm > "$qualification_dir/binary.sha256"
+dbus-run-session -- env -u WAYLAND_DISPLAY -u DISPLAY -u REDIWM_SOCKET \
+ REDIWM_CONFIG="$qualification_dir/config.toml" REDIWM_SCALE=auto \
+ XDG_CONFIG_HOME="$qualification_dir/config" XDG_STATE_HOME="$qualification_dir/state" \
+ XDG_CACHE_HOME="$qualification_dir/cache" XDG_DATA_HOME="$qualification_dir/data" \
+ WLR_BACKENDS=drm WLR_RENDERER=gles2 \
+ /home/alex/projects/wlroots/zig-out/release-safe/bin/rediwm \
+ > "$qualification_dir/compositor.log" 2>&1
+```
+
+Use a terminal launched inside that session for inspection. Record the scratch
+directory, binary hash, driver/kernel versions, connector names, modes, refresh
+rates, effective scales and results below. `rediwm-msg runtime`, `outputs`,
+`workspaces`, `windows` and `window-debug ID` inspect the test compositor;
+verify `nested = false`, GLES and the real connector names before counting a pass.
+Use the checkout's `zig-out/release-safe/bin/rediwm-msg`.
+
+| Exercise | Pass criterion | Result |
+| --- | --- | --- |
+| Default startup | Starts in Canvas; original pan/zoom, manual snapping and canvas bindings work | Canvas startup verified; interactive canvas behavior pending |
+| Opt-in and return | Select Workspaces in Settings; select Canvas again; surviving window positions, size, zoom and canvas shortcuts return | Pending |
+| Physical input | Real keyboard, mouse/touchpad and Super+wheel reach the active workspace; hidden clients receive no clicks/keys | Pending |
+| Tile geometry | Open three native Wayland clients and real GTK/Xwayland clients; gaps, titlebars, footer skirts and borders remain clean and non-overlapping | Pending |
+| Tile controls | Super+V/J, directional focus/swap/resize, automatic/floating workspace toggle, tile insertion and live divider resize work | User confirmed tiling, real clicks, pointer rearrangement and split resizing; remaining controls pending |
+| Cancellation and undo | Escape restores a grab; Super+Z restores both layouts after a transfer; closing a member mid-grab leaves no stale tile | User confirmed Escape cancellation; undo/closure cases pending |
+| Lifecycle | Minimize/restore, maximize/fullscreen, dialogs, Settings, tabs and client closure preserve focus and valid layout | Pending |
+| Scale and scanout | Test scale 1, auto and 1.5 on the physical connector; check sharpness, hover borders, glass and real native/X11 menu click alignment | Pending |
+| Two physical outputs | One visible workspace per connector; focus/transfer across outputs and a negative origin preserve real input and geometry | Pending; needs another display |
+| Physical unplug/reconnect | Unplug an external display during a tile grab; grab ends, hidden/visible membership survives separately, reconnect gets valid ownership | Pending; needs another display |
+| Modes/rotation | Change a supported mode, refresh and rotation in Settings; layout reflows without configure storms or stale imagery | Pending |
+| Idle | After startup and animations settle, compare Canvas/Workspaces per-thread voluntary switches over equal samples with static clients; no tiling-driven repeating wakeups/configures | Pending |
+| Lock/unlock | Lock and unlock this disposable session normally; geometry, focus and real input resume correctly | Pending |
+| Restart | In the scratch config, select Workspaces, save layout and exit; restart the same binary/config/state and reopen matching apps; membership, splits and floating overrides restore | Pending |
+
+For pixels, use compositor IPC screenshots with automation enabled only in this
+disposable session, or the compositor's own screenshot action. Do not use host
+`grim` as evidence about a nested compositor. Capture logs for any failure and
+compare the same operation with HEAD before assigning it to tiling. Restore the
+test output settings before exit; retain scratch evidence until reviewed.
+
+Physical qualification is complete only after results are recorded for the
+available hardware. Mark unavailable multi-display cases pending, not passed.
+Keep tiling opt-in while these checks and renderer limitations remain open.
diff --git a/docs/plans/optional-tiling.md b/docs/plans/optional-tiling.md
new file mode 100644
index 0000000..fbefa66
--- /dev/null
+++ b/docs/plans/optional-tiling.md
@@ -0,0 +1,434 @@
+# Plan: optional tiling and conventional workspaces
+
+Status: stages 1–5 and automated stage 6 validation implemented for review; workspace mode remains opt-in.
+Updated 2026-10-08.
+
+The first milestone provides opt-in floating workspaces, reversible canvas
+transitions, separate shortcut presets and Settings controls. Workspace IDs
+1–32 are supported (1–10 in the default preset). Dialogs and tab groups move
+together; external activation reveals their workspace. Output removal migrates
+workspace ownership to a surviving output without merging membership.
+
+Per-app floating rules and versioned workspace persistence are implemented.
+Manual split controls, reversible grabs and multi-window layout undo are implemented. Canvas
+autosave is preserved while workspace mode is active. See [README](../../README.md)
+for configuration and shortcuts.
+
+Milestone validation: Debug and ReleaseSafe builds, `zig build test`, and
+snapping, shortcut editing, focus/zoom, tabs, initial window state, layout IPC,
+autosave and output-destruction integrations pass. `tests/workspaces.py`
+covers one/two outputs, 1.5× scale, negative origins, dialogs, Settings mode
+selection, workspace protocol activation, camera/window restoration and held
+keys; its optional GTK check verifies actual Xwayland click routing. Workspace
+shortcut editing/disable and hot-unplug variants also pass.
+
+The full protocol suite stops at its second-lock-client assertion; the full
+Xwayland suite stops at an outdated IPC envelope in its server-stop test. Both
+failures were reproduced on a separate HEAD worktree.
+
+Automatic-layout validation adds pure split/constraint/allocation tests and
+headless checks for stable focus, insertion/closure, live minimum/maximum sizes,
+overflow recovery, output rotation, decoration changes, manual placement and
+minimize/maximize/fullscreen reinsertion. Workspace and tab integrations pass,
+including two outputs with negative origins at 1.5× and real GTK/Xwayland tiled
+click delivery. Automatic-layout geometry also passes with GLES at 1.5×.
+Debug, ReleaseSafe and unit tests pass. The broader output-scale suite's
+`BufferNotAttached` failure and Xwayland shutdown's legacy-envelope assertion
+were reproduced in a fresh worktree of HEAD (`a3f4a31`).
+
+Layout-undo coverage includes keyboard/IPC operations, manual snaps, no-op
+operations, live/released grabs, delayed configure replies, updated client
+constraints, dialogs, tab groups and selected-tab closure, placeholder
+replacement, and reconciliation after closing a focused member. Transfers
+restore both layouts, including tiled/floating moves and windows that remain
+maximized or fullscreen, on two outputs with negative origins at 1.5× scale.
+Canvas undo, snapping, shortcut editing, focus/zoom, initial window state,
+layout IPC/autosave and output-destruction integrations also pass. Debug and
+ReleaseSafe builds and all 785 unit tests pass. GLES was not repeated for this change: this environment has no DRM
+render node.
+
+Stage 5 validation: Debug and ReleaseSafe builds and all 789 unit tests pass.
+Workspace integrations pass on one output and on two outputs with negative
+origins at 1.5× scale, including actual GTK/Xwayland clicks. Restart checks cover
+duplicate app IDs launched in reverse title order, tab groups and selection,
+floating overrides and reinsertion, exact split geometry, empty workspace
+preferences, hidden membership, saved canvas state, named saves and delayed
+startup beyond the first autosave tick. The full Settings suite, snapping,
+shortcut editing, focus/zoom, tabs, initial window state, layout IPC/autosave,
+output destruction and window-rule integrations pass. GLES could not run because
+this environment has no DRM render node.
+
+Stage 6 validation: Debug and ReleaseSafe builds and `zig build test` pass.
+The complete workspace suite passes on one output and on two outputs at 1.5×
+with negative origins, including real GTK/Xwayland clicks. New acceptance checks
+cover live output density/origin changes during tile grabs, unchanged split
+topology, real Wayland click delivery, stable configure counts, per-thread idle
+wakeups, workspace IPC/protocol lock guards, unlock restoration and lock-client
+death. Idle samples recorded 0–2 voluntary context switches per thread in 1.2 s
+and no additional configures.
+The GTK routing fixture now honors the requested output count and converts
+pointer positions to output-local coordinates for negative-origin displays.
+
+Hot-unplug/reconnect checks retain the connector name, preserve separate visible
+and hidden workspace membership on the surviving output, assign an empty
+workspace to the returning output and exercise reversible transfers. Shortcut
+inhibition now runs in both modes, including tiling, Alt+Tab, number/wheel
+navigation, pointer grabs and Super+Escape. The placeholder-undo test now waits
+for the neighboring client's split configure before capturing its geometry.
+
+Snapping, shortcut editing, focus/zoom, tabs, initial window state, layout
+IPC/autosave, output destruction/arrangement/scale, security contexts and X11
+size-hint hardening pass. Workspace variants of shortcut editing and tabs pass.
+The protocol suite's expanded Canvas response expectation and Xwayland's old
+stop-server request envelope are updated. The full protocol suite still fails
+at the second lock client; the full/fractional Xwayland suites stop at a stale
+41-pixel titlebar assertion (the compositor reports 35). These failures were
+reproduced in a fresh HEAD worktree (`a3f4a31`). At that validation run, GLES and
+physical-display qualification were pending because no DRM render node was available.
+
+Follow-up qualification (2026-10-08): render nodes are now available. The lock
+client and 41-vs-35 Xwayland titlebar failures were reproduced again against a
+fresh HEAD build. The complete workspace suite passes with NVIDIA GLES on two
+outputs at 1.5× with negative origins and real GTK input. Intel GLES passes
+the full one-output suite, two-output controls/layout/persistence/routing and border
+checks; its two-output idle limit still fails, with repeated wakeups reproduced
+in HEAD canvas mode. Glass GPU tests pass on Intel and fail identically on HEAD
+and the implementation on NVIDIA. Physical-display checks remain pending by
+user choice. See the [qualification record and hardware checklist](optional-tiling-qualification.md)
+for commands, evidence and open checks. Canvas remains the default.
+
+Physical follow-up: the user rebuilt and restarted the installed ReleaseSafe
+compositor. Its running binary hash matches the checkout; IPC confirms GLES2,
+`nested = false`, a physical 2560×1600 panel at 1.5×/60 Hz and Canvas startup.
+Interactive tiling, physical output changes and multi-display checks remain
+pending in the qualification checklist.
+
+The user then confirmed physical tiling, real clicks, pointer rearrangement,
+split resizing and Escape cancellation. Their requested workspace styling adds
+a 1 logical px red active-window outline (including CSD/floating clients) and
+an 8 px default tile gap. Explicit `window_gap` settings still override that
+default; Canvas retains its styling and zero-gap default. The focus colour is
+the `workspace_active_border` theme token. The visual update needs a new physical
+rebuild/restart for user confirmation.
+
+## Agreed direction
+
+Keep the existing pan-and-zoom canvas as the default. Add an optional
+conventional workspace mode with automatic tiling, floating exceptions, and
+manual window placement. Use a Hyprland-style default shortcut preset in
+workspace mode. Returning to canvas mode restores its existing shortcuts.
+
+Workspace mode is a desktop-wide choice. Within that mode, each workspace can
+use automatic tiling or floating placement. Its shortcut preset stays consistent
+when switching between tiled and floating workspaces or focusing a floating
+window.
+
+## Existing foundations
+
+- [snap.zig](../../src/snap.zig) already implements manual half/quarter tiles,
+ edge snapping, previews, and keyboard placement steps.
+- [Toplevel.zig](../../src/Toplevel.zig) owns forced geometry, layout changes,
+ floating restore geometry, and backend-specific configure requests.
+- [World.zig](../../src/World.zig) owns the shared canvas and focus stack.
+ Its toplevel list changes with focus and must not become the tiling order.
+- Current desktop navigation moves the camera between canvas grid positions;
+ it does not switch window membership or visibility. The workspace protocol
+ currently advertises one Canvas workspace.
+- Canvas persistence currently restores by app ID and still needs a versioned
+ workspace format. Workspace undo now owns snapshots of affected split trees
+ and members; canvas undo retains its single-window/camera behavior.
+
+## User-visible behavior
+
+In canvas mode, retain pan, desktop/window zoom, floating placement, and manual
+snapping. In workspace mode, use a fixed camera and normal window scale, with
+one visible workspace per output. New workspaces default to automatic tiling.
+
+Save canvas positions and window zoom before entering workspace mode. Initially
+place existing windows in a workspace on their current output. Returning to
+canvas restores saved state for surviving windows and gives newly opened windows
+sensible floating positions. Clamp restored positions when the output topology
+has changed so windows remain reachable.
+
+Dialogs and transient utilities float by default. Users can toggle any eligible
+window between floating and tiled placement, with per-app rules for exceptions.
+An existing tab group occupies one tile. Explicit manual half/quarter snapping
+removes the window from automatic arrangement; the remaining tiles reflow.
+
+Fullscreen and maximize temporarily override placement and remember the prior
+tile. Minimize removes the window from arrangement while retaining reinsertion
+information. Restore these windows deterministically even if the original
+neighbours have closed.
+
+## Shortcut presets
+
+Use Hyprland's upstream example configuration as the reference for familiar
+bindings, rather than assuming every tiling compositor uses the same defaults.
+The following mappings were checked against the
+[official Hyprland example configuration](https://github.com/hyprwm/Hyprland/blob/main/example/hyprland.lua)
+on 2026-10-08. RediWM should ship a stable preset; upstream changes should not
+silently change existing users' bindings.
+
+| Workspace-mode shortcut | RediWM action |
+| --- | --- |
+| Super+Q | Open the configured terminal |
+| Super+C | Close the focused window |
+| Super+E | Open the configured file manager |
+| Super+R | Open the start menu / launcher |
+| Super+V | Toggle the focused window between tiled and floating |
+| Super+J | Toggle the relevant split direction |
+| Super+arrows | Focus in that direction |
+| Super+1…9, Super+0 | Switch to workspace 1…10 |
+| Super+Shift+1…9, Super+Shift+0 | Move the focused window to workspace 1…10 and follow it |
+| Super+wheel | Cycle existing workspaces |
+| Super+left-drag | Move a floating window or rearrange a tile |
+| Super+right-drag | Resize a floating window or adjust a tiled split |
+
+Use RediWM's configured applications and shell actions for these bindings; no
+Hyprland companion programs are required. Adapt Super+M to RediWM's session/power
+menu instead of its canvas maximize action. Hyprland's example assigns that key
+to its shutdown/exit flow; the shell menu is the proposed RediWM equivalent.
+
+Keep useful RediWM bindings such as Super+F for fullscreen, Super+L for lock,
+Alt+Tab, screenshots, media controls, and Super+Z for undo where they do not
+conflict. Add the following RediWM extensions, clearly labelled as extensions
+rather than Hyprland defaults:
+
+| Additional workspace shortcut | Action |
+| --- | --- |
+| Super+Shift+arrows | Move/swap the focused tile in that direction |
+| Super+Ctrl+arrows | Adjust the relevant split size |
+| Super+Shift+Space | Toggle automatic tiling for the current workspace |
+
+Keep manual snap actions configurable and available through window controls.
+Their canvas shortcuts remain Super+Shift+arrows; workspace mode uses those keys
+for rearrangement. Pseudotiling and special/scratchpad workspaces are deferred,
+so leave Hyprland's corresponding Super+P and Super+S combinations unassigned
+until those features exist.
+
+### Configuration and compatibility
+
+- Select the workspace preset automatically when entering workspace mode, and
+ restore the canvas preset when leaving it. Do not persistently rewrite bindings
+ during a mode change.
+- Keep existing `[keybinds]` configuration behavior for canvas mode. Add a
+ separate workspace override table (proposed spelling: `[keybinds.workspace]`)
+ layered over the workspace preset. This avoids importing canvas depth/pan
+ bindings into the workspace preset accidentally.
+- Explicit workspace bindings, including `noop`, win over preset defaults.
+ Allow users to edit or disable every preset binding through Settings.
+- Show the active mode/preset in shortcut settings and display conflicts there.
+ Highlight changed meanings such as Super+Q, Super+M, arrows, and number keys.
+- Keyboard, pointer modifiers, and wheel actions must all switch together.
+ Finish or cancel current gestures before switching modes; avoid held-key
+ repeats executing an action from the previous mode.
+- Preserve shortcut inhibition, lock handling, keyboard-layout fallback,
+ hardware controls, and the existing shortcut-inhibition escape binding.
+
+## Implementation stages
+
+### 1. Real workspace ownership
+
+Add a workspace manager responsible for stable workspace IDs, membership,
+visibility, output assignment, remembered focus, and an independent tiling order.
+Start with conventional floating workspaces.
+
+Update focus traversal, hit testing, taskbar, switcher, activation/reveal paths,
+and workspace protocol reporting. A hidden workspace must not accept input.
+Switching to a workspace already visible on another output should focus that
+output rather than display the workspace twice. Define deterministic migration
+and focus fallback when an output is disconnected.
+
+Checkpoint: switching and moving windows between floating workspaces works on
+one or multiple outputs, including dialogs and compositor-owned Settings windows.
+
+### 2. Reversible mode switching and shortcut presets
+
+Implement Canvas / Workspaces selection, canvas state capture/restore, the fixed
+workspace camera, and the mode-specific shortcut resolver described above.
+Keep window-depth and canvas-pan actions inactive in workspace mode. Add the
+workspace switching/moving actions and Settings support for editing the preset.
+
+Configuration parsing belongs in `src/config/`; applying mode changes belongs
+in `src/config_runtime/`. Audit `Input.zig` pointer modifier handling as well as
+the keyboard action table. Preserve custom canvas configurations and reload
+behavior.
+
+Checkpoint: repeated mode changes preserve windows and focus, activate the right
+keyboard/mouse preset, and restore canvas geometry and bindings without edits to
+the user's existing shortcut table.
+
+### 3. Automatic layout engine — implemented
+
+The pure `auto_layout.zig` split tree supports insertion/removal, swapping,
+rotation and ratio adjustments. `auto_tiling.zig` coalesces compositor changes
+through an event-loop idle callback and admits eligible members in stable
+workspace insertion order. Windows use a separate arbitrary automatic target
+in the existing forced-geometry path. Focus changes do not rearrange the tree.
+The existing `window_gap` applies to output edges and internal splits; client
+limits include decoration extents. Overflow leaves later members floating and
+retries on membership, constraints or usable-area changes. Bounded clients may
+leave unused space inside their tile. Dialogs and fixed-size clients float.
+
+Stage 4 now supplies manipulation shortcuts and drag insertion previews.
+Explicit manual placement/snapping opts a window out; tiled pointer grabs keep
+it in the split tree. Minimize/maximize/fullscreen suspend a leaf, and tabs share
+one leaf. Stage 5 now supplies multi-window undo.
+
+Original stage requirements:
+
+Implement one recursive split layout in a separate module: leaves represent
+windows or tab groups; internal nodes store direction and split ratio. Support
+insertion, removal, swapping, split rotation, and resizing. Focus changes alone
+must not reorder tiles.
+
+Keep geometry calculation independent of scene mutation. Extend the existing
+compositor-owned geometry path to accept arbitrary tile rectangles rather than
+representing automatic placement as a manual half/quarter tile. Keep layout
+state explicit so focus zoom, drag handling, and other floating-only behavior
+recognize automatic tiles.
+
+Account for usable output area, titlebars, borders, gaps, fractional scale, and
+client size constraints. Define a stable fallback when minimum sizes cannot fit:
+leave a newly inserted window floating, and use a deterministic member order for
+overflow after an output shrinks. Never loop between client configure replies
+and relayout indefinitely.
+
+Recompute only for membership, layout, constraints, or usable-area changes;
+coalesce related changes and send only changed geometry. Add no idle polling.
+
+Checkpoint: opening, closing, and resizing windows gives stable, non-overlapping
+tiles with valid sizes and no focus-dependent rearrangement.
+
+### 4. Manual controls and lifecycle integration — implemented
+
+The workspace preset now assigns Super+V/J, Super+Shift+arrows,
+Super+Ctrl+arrows and Super+Shift+Space. The same tiling actions are editable in
+Settings and available through IPC `tiling_action` under its usual lock,
+modal and sandbox checks. Each workspace retains its own automatic/floating
+choice without changing shortcut presets.
+
+Tile moves stage an insertion preview and apply only on release. Split resizes
+are live and own a tree snapshot; Escape restores it and reconciles current
+membership, so closing a window cannot resurrect a stale member. Output removal,
+mode changes and a grabbed window becoming hidden or fullscreen cancel the grab.
+Cross-output insertion and workspace transfers update both layouts. Floating
+toggles and unmap/remap retain reinsertion hints; tab identity changes rename the
+leaf when possible, remapped tabs rejoin surviving groups, and placeholder
+replacement preserves its member identity.
+Normal floating drags/resizes and canvas snapping remain available.
+
+Split operations use the complete layout snapshots supplied in stage 5.
+Per-workspace choices and ratios now persist in the stage 5 workspace snapshot.
+
+Original stage requirements:
+
+
+Wire keyboard rearrangement, split resizing, automatic-layout toggling, and
+floating toggles into the shared actions used by Settings and IPC. Show an
+insertion preview while dragging a tile. Escape restores its previous layout;
+moving across outputs/workspaces updates both source and destination layouts.
+
+Cover minimize/restore, maximize/fullscreen, client unmap/remap, destruction,
+output removal, tab membership changes, and placeholder-to-client replacement.
+Keep dialogs above their owners and avoid counting hidden tabs as extra tiles.
+Preserve backend geometry conventions and actual Xwayland input routing.
+
+Checkpoint: mouse and keyboard manipulation agree, cancellation is reversible,
+and lifecycle events leave no stale members, empty splits, or unreachable windows.
+
+### 5. Settings, rules, persistence, IPC, and undo
+
+Layout undo is implemented in `layout_undo.zig`, backed by owned snapshots in
+`undo.zig`. It captures only affected workspace trees and their member state,
+including both sides of transfers. Shared keyboard/IPC actions, tile insertion,
+split resizing, manual snapping, floating moves/resizes and explicit IPC
+placement use the same undo slot. No-op operations retain the previous entry;
+Escape discards a tiled gesture, while undo during a live grab ends it first.
+Window IDs and stable insertion identities reconcile closures, tab identity
+changes and placeholder replacement. Restoring uses live constraints and output
+ownership, and preserves current minimize/maximize/fullscreen overrides.
+Snapshots are freed on replacement, cancellation, mode changes, lock and shutdown.
+
+Settings now edits workspace placement, gaps and per-app floating defaults.
+Existing window rules accept a live `floating` property; explicit per-window
+placement overrides stay independent. IPC reports output/visibility, gaps,
+split nodes and window placement, with typed setters under the existing lock,
+modal and sandbox guards.
+
+`config/workspace_layout.zig` owns the bounded version 2 JSON format;
+`workspace_persistence.zig` applies it. Workspace autosave uses its own state
+file, and named saves use the same serializer. Unversioned canvas TOML stays
+readable. Snapshots retain output ownership, workspace choices, split topology,
+ratios, occurrence identities, floating geometry, tab grouping/selection and
+saved canvas state. Startup reads once and consumes each app/backend/title/
+instance match once; reverse launch order and missing members are reconciled.
+Restoration runs after initial placement and before map-time focus, then finishes
+group repair after tab reconciliation. Explicit layout operations protect affected
+workspaces from later split rebuilds, and the finite startup restore window frees
+the loaded snapshot after 37 seconds. Periodic saves preserve the original file
+while matches are pending; explicit saves and shutdown capture current state.
+Atomic writes skip unchanged snapshots.
+
+Expose mode, workspace layout, gaps, shortcut overrides, and per-app floating
+rules. Extend IPC with workspace/layout state and actions through its existing
+lock and sandbox checks.
+
+Version the saved layout format and read older saves. Persist workspace
+membership, split structure, ratios, floating restore geometry, and saved canvas
+state. Match multiple windows from one app explicitly, consume each match once,
+and tolerate missing or ambiguous matches. Coordinate autosave restoration with
+initial window placement so the two cannot fight each other.
+
+Extend undo to snapshot all affected layout state for rearrangements, resizes,
+floating toggles, and transfers, including both workspaces when applicable.
+Destroyed windows must not invalidate undo of surviving members.
+
+Checkpoint: restart and undo restore coherent groups rather than isolated window
+coordinates, and config reload respects explicit binding overrides.
+
+### 6. Validation and rollout — automated checks implemented
+
+The automated acceptance and regression coverage above makes the opt-in feature
+reviewable. Keep Canvas as the shipped default. GLES results and open renderer
+limitations are recorded in the [qualification record](optional-tiling-qualification.md).
+Physical-display checks remain pending; reproducing failures on HEAD does not
+count as passing those checks.
+
+Extend existing suites where practical and add focused tests for workspace
+ownership and layout calculations. Follow [TESTING.md](../../TESTING.md) and the
+applicable directory instructions; use isolated headless sessions and scratch
+state directories.
+
+Acceptance coverage:
+
+- Canvas behavior and manual snapping remain unchanged with the feature off.
+- Hidden workspaces cannot receive focus/input; activation reveals the correct
+ workspace without bypassing lock or shortcut inhibition.
+- Preset selection, collisions, explicit overrides, `noop`, reloads, held keys,
+ pointer modifiers, and return to canvas all behave consistently.
+- Wayland, Xwayland, Settings, dialogs, tabs, placeholders, and remapped windows
+ participate correctly.
+- Minimize, fullscreen, maximize, dragging, cancellation, and window closure
+ preserve layout invariants.
+- Multiple outputs, unplug/reconnect, negative origins, scale changes, and
+ fractional-scale/GLES rendering preserve geometry and real input delivery.
+- Restart, older saves, duplicate app IDs, and multi-window undo are reliable.
+- Idle behavior adds no wakeups and layout changes do not cause configure storms.
+
+For implementation, build Debug and ReleaseSafe, run `zig build test`, and run
+the relevant integrations: snapping, keyboard shortcuts, focus/zoom, tabs,
+initial window state, layout IPC/autosave, output destruction/arrangement,
+workspace protocols, and Xwayland. Compare failures against a HEAD worktree
+before treating them as regressions.
+
+## Delivery boundary
+
+The first reviewable milestone is conventional floating workspaces, reversible
+canvas transitions, and the Hyprland-style shortcut preset. Automatic splits,
+manual controls and multi-window undo now build on that foundation. Workspace
+Settings, per-app floating rules, richer layout IPC and persistence now complete
+that milestone. Keep the feature opt-in throughout development.
+
+Additional layout algorithms, pseudotiling, scratchpads, and full Hyprland
+configuration compatibility are outside this first implementation.
diff --git a/docs/plans/scene-graph.md b/docs/plans/scene-graph.md
index b4007ce..6e26df2 100644
--- a/docs/plans/scene-graph.md
+++ b/docs/plans/scene-graph.md
@@ -1,45 +1,205 @@
-# Proposal: compositor-owned scene graph
+# Plan: compositor-owned scene graph and render pass
-Status: unimplemented, retained from the September 2026 proposal. RediWM still
-uses `wlr_scene`, projection and the glass implementation. This is an optional
-architecture project, not a prerequisite for desktop readiness.
+Status: decided, not started. Updated 2026-10-08. Replaces the September 2026
+proposal.
-## Motivation and scope
+Decision (2026-10-08): clipped, rounded client corners are a hard requirement,
+and the way to get them is an owned render pass. Doing it properly matters more
+than doing it quickly. CPU and RAM are constraints this work must not break,
+not its motivation (see [Resource expectations](#resource-expectations)).
-Evaluate whether an owned scene graph would improve fractional positioning,
-subtree transforms, backdrop effects and clipping of client corners. Those needs
-currently span `src/projection.c`, `src/glass.c` and the two-band window chrome.
-The old line counts, mechanical conversion checklist and delivery estimates no
-longer describe the current tree and have been removed.
+## Why `wlr_scene` cannot do it
-Retain wlroots backends, input/session handling, renderers, allocators, Xwayland
-and protocol implementations. Prefer retaining its surface/subsurface commit
-semantics behind an adapter over reimplementing them. Static linking and binary
-portability are separate packaging decisions, not necessary first steps.
+RediWM draws through `wlr_scene` plus two layers built to work around it:
-## Possible stages
+* **Client corners are square.** `wlr_scene` and the wlroots 0.20 render pass
+ cannot mask a texture. The frame reserves a footer band under the client
+ (`chrome.footerHeight`, at least `ceil(radius)` tall) and draws the bottom
+ arcs there. `Toplevel.probeClientEdge` reads back the client's last buffer
+ row (GL readback, explicit-sync waits) to colour that band. Borders have two
+ paths (`ChromeBuffer` arcs, `Toplevel.syncBorders` straight rects with
+ `side_fills`). Shadows are CPU-rasterized corner/edge buffers.
+* **Integer coordinates.** `src/projection.c` mirrors every source node into
+ a second tree to apply camera zoom, Xwayland `1/N` scale and fractional
+ positioning, with a per-leaf `view_state` cache to keep the sync affordable.
+* **Backdrop effects are a side channel.** `src/glass.c` re-walks the scene
+ (`capture_prefix`) into a private capture buffer per effect, enters its own
+ GL context state per effect and flushes per effect (about 0.35 ms per
+ re-blurred effect, 2026-09 measurement). It is GLES2-only
+ (`wlr_renderer_is_gles2`; otherwise a CSS-style tint).
-1. Measure current projection, glass, scene commit and scanout behavior on a
- fixed workload. Identify an actual benefit before replacing infrastructure.
-2. Prototype typed nodes with continuous logical coordinates, transforms,
- clipping and optional effects, initially presented through wlroots nodes.
-3. Evaluate an owned output-state/render pass only if the prototype justifies
- taking responsibility for damage, buffer age, presentation and scanout.
-4. Move backdrop effects and rounded clipping onto that path, then remove
- obsolete projection/chrome workarounds once equivalent behavior is proven.
+Scene API reach: about 45 distinct `wlr_scene_*` functions, ~260 references,
+scene types in 49 source files. The frame path is `Output.handleFrame` →
+`scene_output.buildState` → `Output.commitFrameState`; screenshots
+(`screenshot/capture.zig`) and IPC capture call `buildState` too.
-Every stage must leave a working compositor. Do not let a temporary second
-scene representation become a permanent new source of geometry truth.
+## Target design
+
+**Retained from wlroots:** backends, `wlr_output`/`wlr_output_state` and
+`Output.commitFrameState`, swapchain and allocator, `wlr_damage_ring`, the
+GLES2 renderer's context, texture import and buffer FBOs, seat/input, Xwayland,
+and every protocol implementation (`wlr_surface`, subsurface, xdg-shell,
+layer-shell, viewporter, presentation, linux-dmabuf, drm-syncobj, screencopy).
+Client surface semantics stay behind an adapter; they are not reimplemented.
+
+**Owned:**
+
+* *Node graph.* Typed nodes (tree, rect, texture/surface, shadow, backdrop
+ effect) with float logical coordinates, translate + uniform scale, opacity,
+ and a clip shape. One source of geometry truth; zoom, `1/N` Xwayland scale
+ and fractional placement are node properties, not a second tree.
+* *Clip groups.* A rounded-rect clip (per-corner radii) applies to a whole
+ subtree: titlebar chrome, client surface and its subsurfaces, footer. It is
+ evaluated in the fragment shader as a signed-distance coverage in device
+ pixels, so AA is right at any scale or zoom. One shape function replaces the
+ skirt, `probeClientEdge`, `side_fills`, the straight-rect border path and the
+ chrome arcs. xdg popups are separate trees and are never clipped by a
+ parent's shape.
+* *Analytic primitives.* Borders and shadows become shader primitives. CPU
+ raster is left for what is really content: title text, icons, buttons.
+* *Output pass.* Per output: acquire swapchain buffer (age), accumulate
+ damage, walk in paint order with opaque-region culling, draw with an owned
+ GLES2 program driven directly on the wlroots context and buffer FBO, as
+ `glass.c` already does (`wlr_gles2_renderer_get_buffer_fbo`,
+ `wlr_gles2_texture_get_attribs`). The wlroots render pass has no custom
+ shader or stencil, so it cannot be used for masked draws.
+* *Backdrop effects in the pass.* An effect samples the framebuffer drawn so
+ far (a region copy), blurs, and composes through its clip shape. No prefix
+ re-render, no separate pass, no per-effect context switch. Culling must keep
+ what a blur reads, and damage under an effect expands to the effect's padded
+ extent (a swapchain buffer's pixels outside the damage are stale).
+* *Distribution of surface feedback.* Frame callbacks, `wl_surface.enter/leave`,
+ preferred scale, presentation feedback, dmabuf feedback tranches,
+ explicit-sync acquire/release, primary output.
+* *Direct scanout* for an opaque fullscreen client with no clip, transform or
+ effect above it (test with `wlr_output_test_state`).
+* *Hit testing and capture of node subsets.* Float hit tests honour the clip
+ shape, so clicks on a transparent rounded corner reach the window below.
+ Capture renders a node subset, replacing the owned adapter around
+ wlroots' leaky scene capture helper.
+
+**Policy defaults (assumed, change in stage 0 if wrong):** radius is
+`border_radius` scaled by chrome density, 0 when maximized or fullscreen
+(the current `Toplevel.cornerRadius`). It applies to server-decorated native
+and Xwayland windows and to `.shell` windows (Settings). Client-side-decorated
+windows are not clipped by the compositor unless a rule asks. The footer
+reservation drops from `max(border, ceil(radius))` to the border width, so the
+radius-tall band returns to the client; every `footerHeight` consumer (snap,
+resize edges, layout, saved layouts, Xwayland, tabs, tests that pin titlebar
+or body heights) needs an audit.
+
+## Stages
+
+Every stage leaves a working compositor. The graph is the only geometry truth;
+a presenter consumes it and holds no geometry of its own. Switching between
+presenters during the migration uses a temporary config key (not an
+environment variable: no test hooks in production), removed in stage 6.
+
+0. **Baseline and inventory (no behaviour change).**
+ * Fixed workload and harness: three windows with glass, a 60 fps damage
+ client, drag and resize, a fullscreen client, zoom steps and
+ scales 1, 1.5 and mixed. Record `cpu_frame`, `projection_cpu`,
+ `glass_cpu`, `scene_commit_cpu`, `gpu_elapsed`, wakeups, RSS and
+ instructions:u; keep golden IPC screenshots of chrome, corners and glass.
+ * Inventory exactly what `wlr_scene_output` does today for the projected
+ tree (frame-done, enter/leave, presentation, dmabuf feedback, scanout,
+ release points, primary output, damage/culling). That table is the
+ checklist for stage 3.
+ * Inventory what wlroots' GLES2 texture shader does that an owned shader
+ must reproduce or consciously drop: external-OES targets, transfer
+ function and primaries, range/encoding, premultiplied blending, filters.
+ * Confirm the policy defaults above and the renderer decision below.
+1. **Pass spike (noninstalled fixture, `test-glass`-style pixel tests).**
+ Draw a 2D and an external-OES client texture through the rounded clip at
+ fractional scale and zoom; analytic border and shadow; blur from a
+ framebuffer copy. Gate: no seams or fringe (extend `window_corners.py`
+ criteria), correct premultiplied edges, measured cost within the stage 0
+ baseline, buffer-age damage correct under an effect. Failing the gate is a
+ result: revise the design before stage 2.
+2. **Typed node model behind the existing presenter.** `projection.c`'s
+ view sync consumes the typed graph (float coordinates, clip, opacity) and
+ rounds for `wlr_scene`. No visible change; existing tests pass unchanged.
+3. **Owned output pass at parity (radius 0).** Everything in the stage 0
+ inventory, plus capture, screenshots, lock coverage and hotplug through the
+ new path. Exit: pixel-equivalent to the legacy presenter within tolerance
+ and cost at or below baseline, including scanout where it applied.
+4. **Clipping and primitives.** Clip groups on frames, analytic borders and
+ shadows, shape-aware hit testing; delete the skirt, `probeClientEdge`,
+ `side_fills`, the dual border path and `edge_sampling.py`; shrink the footer.
+5. **Backdrop effects in the pass.** Delete `glass.c`'s prefix capture,
+ per-effect contexts, dependency hashing and the drag hold; keep glass pixel
+ tests, converted.
+6. **Delete.** `wlr_scene` output rendering, the projection view tree, the
+ legacy presenter and the temporary config key. Update `AGENTS.md`
+ (rendering and damage rules, the two-border-path and skirt notes),
+ `TESTING.md` and the area notes.
+
+The old wlr_scene source tree stays as the surface adapter until a separate,
+later decision; replacing it is not part of this plan.
+
+## Resource expectations
+
+Hypotheses to confirm in stages 0, 1 and 3; the stage 0 baseline defines the
+numbers.
+
+| Area | Expectation |
+|---|---|
+| Idle CPU, wakeups | Unchanged. The pass adds no timers or polling. |
+| Per-frame, no glass overlap | About unchanged; the floor is wlroots/Mesa driver cost (parity with labwc at 60 fps damage in 2026-09). |
+| Glass over damage | Lower: no prefix re-render, context switch or flush per effect. The new cost is one backdrop region copy per effect. |
+| Client edge probe | Gone, with its GL readback and acquire-wait stalls. |
+| Chrome CPU on resize/move | Lower if arcs, borders and shadows stop being CPU rasters; title text still is. |
+| GPU | A mask multiply per client pixel is negligible; the backdrop copy is the real cost. Check `gpu_elapsed`. |
+| Scanout | Preserved for opaque fullscreen clients. |
+| RAM | Not above baseline: per-effect capture/output/intermediate buffers shrink, shadow/skirt buffers go; shader programs and damage rings are tiny. |
## Acceptance requirements
Preserve surface commit ordering, explicit-sync fences, frame callbacks,
-presentation feedback, damage, hit-testing, color transforms, capture isolation,
-output hotplug, and lock coverage. Include popups, IME candidates, subsurfaces,
-fractional/mixed scale and close snapshots.
-
-Compare CPU/GPU frame costs and scanout/plane use against the existing renderer;
-do not assume glass makes scanout irrelevant. Require equivalent pixels and
-capture behavior under isolated tests before migration. The current render
-invariants are in [AGENTS.md](../../AGENTS.md), with test commands in
-[TESTING.md](../../TESTING.md).
+presentation feedback, damage, hit-testing, colour transforms and colour
+descriptions, capture isolation, output hotplug and lock coverage. Include
+popups, IME candidates, subsurfaces, mixed and fractional scale, camera zoom
+steps down to `camera_zoom_min`, Xwayland at `N > 1`, tiles and maximize,
+close snapshots and the Settings shell window.
+
+Corner-specific: client pixels in the clipped corner are transparent (the
+backdrop shows through) with no bright fringe and no seam at any zoom step or
+scale; the same shape clips chrome and client; hit tests follow the shape.
+
+Run through existing suites, extended rather than duplicated: `window_corners`,
+`appearance_chrome`, `decorations`, `kde_decorations`, `capture`,
+`screencast`, `screenshot_regressions`, `explicit_sync`, `presentation_time`,
+`output_scale`, `output_destroy`, `lock_screen`, `layer_lifecycle`,
+`popup_constraint`, `focus_zoom`, `desktop_zoom`, `mini_map*`, `window_snapping`,
+`desktop_damage`, `panel_damage`, `single_pixel`, `wlr_protocols`, the perf
+scripts and `zig build test-glass` / `zig build test`. Compare CPU/GPU frame
+cost and scanout/plane use against the legacy renderer; do not assume glass
+makes scanout irrelevant. The render invariants are in
+[AGENTS.md](../../AGENTS.md) and the commands in [TESTING.md](../../TESTING.md).
+
+## Risks and open decisions
+
+* **Renderer policy.** Masked draws need GLES2 (as glass already does). Open:
+ require GLES2 for the desktop session and run tests on a render node (as
+ `test-glass` already does), or keep a pixman path. Recommended: require
+ GLES2; do not keep a software path alive as a second renderer.
+* **Reimplementing `wlr_scene_output` behaviour** is the main regression risk
+ (frame callbacks, presentation timestamps, dmabuf feedback, enter/leave,
+ release points). The stage 0 table and per-item tests are the mitigation.
+* **Colour management and external textures** must be matched in the owned
+ shader or consciously dropped; decide in stage 0.
+* **Blur with buffer age.** Damage expansion under effects must be exact, or
+ stale pixels appear in the blur.
+* **Binding gaps.** zig-wlroots lacks some needed APIs (damage ring,
+ swapchain, GLES2 attribs); hand-declare them and keep the wlroots 0.20 ABI
+ pin in `build.zig.zon`.
+* **Xwayland coupling.** `scene.restack_xwayland_surfaces = false` and
+ `Toplevel.raise` sync scene and X11 stacking; the graph must keep that
+ ordering contract.
+* **Footer change** alters client geometry; saved layouts and tests that pin
+ titlebar/body sizes (the known 41 vs 35 titlebar assertion) need review.
+* **No second truth.** A temporary presenter or adapter must not grow its own
+ geometry; if it does, stop and fold it into the graph.
+
+Independent of this plan and cheap: batch glass effects into one EGL
+enter/leave and drop the per-effect `glFlush` in `glass.c`.
diff --git a/src/Input.zig b/src/Input.zig
index 40a334f..32dbf2a 100644
--- a/src/Input.zig
+++ b/src/Input.zig
@@ -166,6 +166,7 @@ grab_x: f64 = 0,
grab_y: f64 = 0,
grab_box: wlr.Box = undefined,
move_snap: MoveSnap = .{},
+tiling_grab: ?@import("tiling_grab.zig") = null,
/// The last titlebar press, for double-click-to-maximize.
title_press: ?TitlePress = null,
/// Pointer presses so far: a double-click is two presses in a row.
@@ -227,6 +228,7 @@ pub fn isSuperHeld(input: *Input) bool {
/// The `.super_key` pan trigger: `[input] pan_modifier` held on any keyboards.
pub fn isPanModifierHeld(input: *Input) bool {
+ if (input.server.world.workspaces.active) return false;
return switch (input.server.config.input.pan_modifier) {
.super => input.isSuperHeld(),
.super_alt => input.isDesktopZoomHeld(),
@@ -577,6 +579,11 @@ pub fn setNamedCursor(input: *Input, name: [*:0]const u8) void {
}
pub fn deinit(input: *Input) void {
+ if (input.tiling_grab) |*grab| {
+ if (grab.snapshot) |*tree| tree.deinit(gpa);
+ if (grab.undo_snapshot) |snapshot| snapshot.destroy();
+ }
+ input.tiling_grab = null;
input.window_menu.close();
input.start_drag.link.remove();
if (input.drag_icon_tree) |tree| tree.node.destroy();
@@ -638,9 +645,12 @@ const TitlePress = struct {
};
pub fn startMove(input: *Input, toplevel: *Toplevel) void {
+ if (!@import("workspaces.zig").visible(toplevel)) return;
toplevel.finishZoomAnimation();
toplevel.finishMoveAnimation();
toplevel.finishSizeAnimation();
+ if (@import("tiling_grab.zig").begin(input, toplevel, null, 0x110)) return;
+ toplevel.pending_restore = null;
const snapped = toplevel.layout() != .floating and !toplevel.isFullscreen();
input.move_snap.preview.hide();
input.move_snap = .{
@@ -665,7 +675,7 @@ pub fn startMove(input: *Input, toplevel: *Toplevel) void {
// Snapshot current geometry for undo. Press folding: if a focus change
// already fired on this press, begin() will inherit its focus id.
const geom = toplevel.clientGeometry();
- input.server.undo.begin(.{
+ if (!@import("layout_undo.zig").beginGesture(input.server, toplevel.workspace_id)) input.server.undo.begin(.{
.kind = .move,
.press_seq = input.server.undo.press_seq,
.at_ms = 0,
@@ -690,9 +700,16 @@ fn endMove(input: *Input, apply_snap: bool) void {
return;
};
input.grabbed_toplevel = null;
+ if (apply_snap and input.server.world.workspaces.active) {
+ const point = input.server.world.toLayout(@as(f64, @floatFromInt(toplevel.x)) + @as(f64, @floatFromInt(toplevel.chrome_width)) / 2, @as(f64, @floatFromInt(toplevel.y)) + @as(f64, @floatFromInt(toplevel.chrome_height)) / 2);
+ if (if (target != null) output else @import("Output.zig").atLayout(input.server, point.x, point.y)) |out| {
+ @import("layout_undo.zig").includeDestination(input.server, out.workspace_id);
+ input.server.world.workspaces.placed(toplevel, out);
+ }
+ }
if (apply_snap) if (target) |t| if (output) |out| toplevel.snapTo(out, t, origin);
const geom = toplevel.clientGeometry();
- input.server.undo.commit(Server.undoNowMs(), .{
+ if (!@import("layout_undo.zig").commitGesture(input.server, null)) input.server.undo.commit(Server.undoNowMs(), .{
.window = .{
.id = toplevel.id,
.x = toplevel.x,
@@ -709,7 +726,7 @@ fn endMove(input: *Input, apply_snap: bool) void {
/// keeping the grab at the same fraction of the frame width so the titlebar
/// stays under the pointer.
fn floatGrabbed(input: *Input, toplevel: *Toplevel) void {
- const restore = toplevel.tile_restore orelse toplevel.maximize_restore;
+ const restore = toplevel.tile_restore orelse toplevel.auto_restore orelse toplevel.maximize_restore;
const ws = toplevel.worldScale();
const old_w = @as(f64, @floatFromInt(@max(1, toplevel.chrome_width))) * ws;
const fraction = std.math.clamp(input.grab_x / old_w, 0, 1);
@@ -730,7 +747,7 @@ fn updateSnapTarget(input: *Input, toplevel: *Toplevel) void {
input.move_snap.target = target;
input.move_snap.output = output;
if (found) |f| {
- const rect = snap.targetRect(f.output.usableBox(), f.target, input.server.config.compositor.window_gap);
+ const rect = snap.targetRect(f.output.usableBox(), f.target, input.server.config.compositor.windowGap());
input.move_snap.preview.show(input.server.overlay_tree, rect);
} else {
input.move_snap.preview.hide();
@@ -791,6 +808,8 @@ pub fn startResize(
initiating_device: ?*wlr.InputDevice,
initiating_button: u32,
) void {
+ if (!@import("workspaces.zig").visible(toplevel)) return;
+ if (@import("tiling_grab.zig").begin(input, toplevel, wlr_edges, initiating_button)) return;
const edges = resize.Edges.fromWlr(wlr_edges);
if (edges.isNone()) return;
@@ -808,6 +827,7 @@ pub fn startResize(
// Resizing a tile makes it an ordinary window of the tile's geometry.
const layout_before = toplevel.layout();
+ const layout_gesture = @import("layout_undo.zig").beginGesture(input.server, toplevel.workspace_id);
toplevel.leaveLayout();
input.server.world.focus(toplevel);
toplevel.finishZoomAnimation();
@@ -868,7 +888,7 @@ pub fn startResize(
sess.last_sent_height = client_h;
}
// Snapshot current geometry for undo at the start of the resize.
- input.server.undo.begin(.{
+ if (!layout_gesture) input.server.undo.begin(.{
.kind = .resize,
.press_seq = input.server.undo.press_seq,
.at_ms = 0,
@@ -891,7 +911,7 @@ pub fn finishResize(input: *Input) void {
session.settling = true;
// Commit the resize undo entry now that the final geometry is known.
- input.server.undo.commit(Server.undoNowMs(), .{
+ if (!@import("layout_undo.zig").commitGesture(input.server, .{ .id = toplevel.id, .width = final_size.width, .height = final_size.height })) input.server.undo.commit(Server.undoNowMs(), .{
.window = .{
.id = toplevel.id,
.x = toplevel.x,
@@ -964,6 +984,7 @@ pub fn finishSettlement(input: *Input, generation: u64) void {
}
pub fn clearGrab(input: *Input) void {
+ if (input.tiling_grab != null) input.finishTilingGrab(false);
input.server.world.mini_map.hide();
if (input.resize_session != null) {
input.cancelResize();
@@ -980,6 +1001,7 @@ pub fn clearGrab(input: *Input) void {
}
pub fn startPan(input: *Input, trigger: PanTrigger, device: ?*wlr.InputDevice) void {
+ if (input.server.world.workspaces.active) return;
if (input.server.world.mini_map.dragging) return;
if (input.server.switcher.active()) return;
// Don't start a new pan if this trigger is currently inhibited
@@ -1075,6 +1097,7 @@ fn beginMiddlePanAfterThreshold(session: *PanSession, x: f64, y: f64) bool {
}
pub fn detachOutput(input: *Input, output: *Output) void {
+ if (input.tiling_grab != null) input.finishTilingGrab(false);
if (input.move_snap.output == output) {
input.move_snap.target = null;
input.move_snap.output = null;
@@ -1401,6 +1424,10 @@ pub fn processCursorMotion(input: *Input, time_msec: u32) void {
return;
}
}
+ if (input.tiling_grab != null) {
+ @import("tiling_grab.zig").motion(input);
+ return;
+ }
switch (input.cursor_mode) {
.passthrough => input.passthroughMotion(time_msec),
.move => input.processMove(),
@@ -1842,6 +1869,13 @@ pub fn processButton(
if (input.active_buttons > 0) input.active_buttons -= 1;
}
+ if (input.tiling_grab) |session| {
+ if (state == .released and button == session.button) {
+ input.finishTilingGrab(true);
+ input.processCursorMotion(time_msec);
+ }
+ return;
+ }
if (input.cursor_mode == .resize) {
if (state == .released) {
if (input.resize_session) |session| {
@@ -1856,7 +1890,7 @@ pub fn processButton(
}
// Middle button: start/end pan
- if (button == btn_middle and input.server.config.input.middle_button_pan) {
+ if (button == btn_middle and !input.server.world.workspaces.active and input.server.config.input.middle_button_pan) {
if (state == .pressed) {
if (input.cursor_mode == .passthrough and input.resize_session == null and input.grabbed_toplevel == null) {
const inhibited = if (input.pan_session) |sess|
@@ -2073,7 +2107,7 @@ fn processClientButton(
const toplevel = res.cc.toplevel;
input.server.world.focus(toplevel);
// Alt+drag moves and Alt+right-drag resizes, as over a client.
- const alt = if (input.seat.getKeyboard()) |keyboard| keyboard.getModifiers().alt else false;
+ const alt = if (input.server.world.workspaces.active) input.isSuperHeld() else input.isAltHeld();
if (alt and button == btn_left) {
toplevel.beginMove();
} else if (alt and button == btn_right) {
@@ -2116,6 +2150,16 @@ fn processClientButton(
// clients, nothing Xwayland-specific). Clicking an unfocused window to
// start a drag from it is a completely ordinary gesture, so this isn't a
// narrow edge case.
+ if (input.server.world.workspaces.active and input.isSuperHeld() and hit == .surface and (button == btn_left or button == btn_right)) {
+ const top = hit.surface.toplevel;
+ input.server.world.focus(top);
+ if (button == btn_left) top.beginMove() else {
+ const local = top.frameLocal(input.cursor.x, input.cursor.y);
+ const edges = resize.selectEdgesFromQuadrant(local.x, local.y, 0, 0, top.chrome_width, top.chrome_height);
+ input.startResize(top, edges.toWlr(), device, button);
+ }
+ return;
+ }
if (hit == .surface) input.server.world.focusSurface(hit.surface.toplevel, hit.surface.surface);
_ = input.seat.pointerNotifyButton(time_msec, button, state);
switch (hit) {
@@ -2123,7 +2167,7 @@ fn processClientButton(
const ws = res.toplevel.worldScale() / res.toplevel.surfaceScale();
input.rememberPointerGrab(res.sx, res.sy, ws);
if (input.seat.getKeyboard()) |keyboard| {
- if (keyboard.getModifiers().alt) {
+ if (!input.server.world.workspaces.active and keyboard.getModifiers().alt) {
if (button == btn_left) {
res.toplevel.beginMove();
} else if (button == btn_right) {
@@ -2147,7 +2191,7 @@ fn processClientButton(
}
}
-fn setHover(input: *Input, toplevel: ?*Toplevel, control: ?chrome.ControlKind) void {
+pub fn setHover(input: *Input, toplevel: ?*Toplevel, control: ?chrome.ControlKind) void {
if (input.hovered_toplevel) |previous| {
if (previous != toplevel) previous.applyHover(false, null);
}
@@ -2216,6 +2260,13 @@ pub fn processAxis(
return;
}
}
+ if (input.server.world.workspaces.active and input.isSuperHeld()) {
+ if (orientation == .vertical_scroll) {
+ const steps = input.zoom_scroll.feed(delta_discrete, delta, @intCast(@intFromEnum(source)));
+ if (steps != 0) input.server.world.workspaces.cycle(input.server, steps > 0);
+ }
+ return;
+ }
const scroll_hit = scene_data.hitTest(input.server, input.cursor.x, input.cursor.y);
if (scroll_hit == .taskbar) {
const hit = scroll_hit.taskbar;
@@ -2232,7 +2283,7 @@ pub fn processAxis(
}
}
const desktop_zoom = input.isDesktopZoomHeld();
- const target: ?*Toplevel = if (desktop_zoom) null else switch (scroll_hit) {
+ const target: ?*Toplevel = if (input.server.world.workspaces.active or desktop_zoom) null else switch (scroll_hit) {
.surface => |res| if (input.isAltHeld()) res.toplevel else null,
.chrome => |res| if (input.isAltHeld() or (res.sy >= 0 and res.sy < res.toplevel.titlebarHeight())) res.toplevel else null,
else => null,
@@ -2240,7 +2291,7 @@ pub fn processAxis(
const target_id = if (target) |window| window.id else 0;
if (input.zoom_target_id != target_id) input.zoom_scroll.reset();
input.zoom_target_id = target_id;
- if (target != null or input.isAltHeld()) {
+ if (!input.server.world.workspaces.active and (target != null or input.isAltHeld())) {
if (orientation != .vertical_scroll) return;
if (!input.canZoom()) {
input.zoom_scroll.reset();
@@ -2269,7 +2320,7 @@ pub fn processAxis(
if (input.cursor_mode == .resize or input.cursor_mode == .pan) return;
// Two-finger touchpad motion over empty desktop is a camera pan, matching
// the middle-drag rubber-band/fling model. Mouse wheels stay no-ops here.
- const desktop_finger = source == .finger and (scroll_hit == .none or input.finger_pan);
+ const desktop_finger = !input.server.world.workspaces.active and source == .finger and (scroll_hit == .none or input.finger_pan);
if (desktop_finger and input.cursor_mode == .passthrough and input.resize_session == null) {
if (raw_delta == 0 and raw_delta_discrete == 0) {
if (input.finger_pan) {
@@ -2375,6 +2426,7 @@ fn cursorHoldEnd(listener: *wl.Listener(*wlr.Pointer.event.HoldEnd), event: *wlr
/// Camera changes cannot invalidate an in-flight client or compositor grab.
pub fn canZoom(input: *Input) bool {
+ if (input.server.world.workspaces.active) return false;
if (input.server.world.mini_map.dragging) return false;
if (input.active_buttons != 0 or input.resize_session != null or input.seat.pointerHasGrab()) return false;
if (input.server.world.pinching) return false;
@@ -2390,12 +2442,14 @@ fn clientSurfaceHit(hit: scene_data.Hit) bool {
}
fn compositorOwnsPinch(input: *Input) bool {
+ if (input.server.world.workspaces.active) return false;
if (input.server.locker != null or input.server.polkit_dialog != null or input.server.switcher.active()) return false;
if (input.cursor_mode == .move or input.cursor_mode == .resize or input.resize_session != null) return false;
return !clientSurfaceHit(scene_data.hitTest(input.server, input.cursor.x, input.cursor.y));
}
fn compositorOwnsSwipe(input: *Input, fingers: u32) bool {
+ if (input.server.world.workspaces.active) return false;
if (fingers != 2) return false;
if (input.server.locker != null or input.server.polkit_dialog != null or input.server.switcher.active()) return false;
if (input.cursor_mode != .passthrough or input.resize_session != null) return false;
@@ -2505,7 +2559,16 @@ fn startDrag(listener: *wl.Listener(*wlr.Drag), drag: *wlr.Drag) void {
/// drag was cancelled, and ending the grab then leaves the target, hides the
/// icon and forgets the drag. The button is still held; its release reaches
/// the client under the pointer like any other, so nothing is dropped.
+pub fn finishTilingGrab(input: *Input, commit: bool) void {
+ @import("tiling_grab.zig").finish(input, commit);
+}
+
pub fn cancelDrag(input: *Input) bool {
+ if (input.tiling_grab != null) {
+ input.finishTilingGrab(false);
+ input.processCursorMotion(0);
+ return true;
+ }
const drag = input.seat.drag orelse return false;
if (drag.grab_type != .keyboard_pointer) return false;
if (drag.source) |source| source.destroy();
diff --git a/src/Keyboard.zig b/src/Keyboard.zig
index 8faf7e4..55c77a6 100644
--- a/src/Keyboard.zig
+++ b/src/Keyboard.zig
@@ -15,6 +15,7 @@ const log = std.log.scoped(.keyboard);
const keybinds = @import("config").keybinds;
const ControlCenter = @import("control_center/panel.zig").ControlCenter;
const StartMenu = @import("start_menu/panel.zig").StartMenu;
+const ui_compose = @import("ui").compose;
server: *Server,
link: wl.list.Link = undefined,
@@ -32,12 +33,17 @@ switcher_timer: ?*wl.EventSource = null,
switcher_code: ?u32 = null,
shortcut_consumed: [768]bool = @splat(false),
hardware_consumed: [768]bool = @splat(false),
+mode_consumed: [768]bool = @splat(false),
repeat_timer: ?*wl.EventSource = null,
repeat_code: ?u32 = null,
/// Key repeat for compositor-drawn UI, which has no client to repeat keys
/// itself: the held key and the shell target that took its press.
shell_timer: ?*wl.EventSource = null,
shell_repeat: ?ShellRepeat = null,
+/// Dead keys and Compose sequences for compositor-drawn fields (clients
+/// compose their own), and the shell target a half-typed one belongs to.
+compose: ui_compose.Compose = .{},
+compose_target: ?ShellTarget = null,
caps: bool = false,
client_pressed: [768]bool = @splat(false),
grab_pressed: [768]u64 = @splat(0),
@@ -196,6 +202,16 @@ pub fn enter(server: *Server, surface: *wlr.Surface) void {
}
pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state: wl.Keyboard.KeyState) void {
+ if (event_keycode < keyboard.mode_consumed.len and keyboard.mode_consumed[event_keycode]) {
+ if (state == .pressed) return;
+ keyboard.mode_consumed[event_keycode] = false;
+ if (!keyboard.client_pressed[event_keycode]) {
+ keyboard.shortcut_consumed[event_keycode] = false;
+ keyboard.switcher_consumed[event_keycode] = false;
+ keyboard.hardware_consumed[event_keycode] = false;
+ return;
+ }
+ }
keyboard.noteShellKey(event_keycode, state);
if (keyboard.server.locker != null and @import("input/text_input.zig").isVirtual(keyboard.device)) return;
@import("startup.zig").markFirstInput();
@@ -665,6 +681,7 @@ fn handleDestroy(listener: *wl.Listener(*wlr.InputDevice), _: *wlr.InputDevice)
}
}
+ keyboard.compose.deinit();
gpa.destroy(keyboard);
}
@@ -751,8 +768,47 @@ const ShellTarget = union(enum) {
else => std.meta.activeTag(a) == std.meta.activeTag(b),
};
}
+
+ /// Whether this target is the freeable panel at `panel`'s address.
+ fn isPanel(target: ShellTarget, panel: anytype) bool {
+ return switch (target) {
+ .control_center => |cc| @intFromPtr(cc) == @intFromPtr(panel),
+ .start_menu => |sm| @intFromPtr(sm) == @intFromPtr(panel),
+ .wifi => |popup| @intFromPtr(popup) == @intFromPtr(panel),
+ else => false,
+ };
+ }
};
+/// What a shell press types once dead keys and Compose sequences resolve.
+/// `sym` is the key's own, or none for composed text.
+const Typed = struct { sym: xkb.Keysym, utf8: []const u8, composed: bool };
+
+fn composeLocale(server: *Server) []const u8 {
+ // The setting reaches only the apps we launch; the compositor reads it
+ // itself, and falls back to the session's own environment.
+ if (server.config.region.language.len != 0) return server.config.region.language;
+ return ui_compose.localeFromEnviron(server.environ);
+}
+
+/// Null when the press only advanced a sequence (a dead key, or a key that
+/// cancelled one) and types nothing. Composed text lands in `out`, which the
+/// caller scrubs like the other key scratch: lock and polkit keys are
+/// secrets. A shortcut modifier abandons a half-typed sequence, and so does
+/// a press for another target: a sequence belongs to the panel it began in.
+fn composeShell(keyboard: *Keyboard, target: ShellTarget, sym: xkb.Keysym, mods: wlr.Keyboard.ModifierMask, utf8: []const u8, out: *[64]u8) ?Typed {
+ const plain: Typed = .{ .sym = sym, .utf8 = utf8, .composed = false };
+ if (mods.ctrl or mods.alt or mods.logo) {
+ keyboard.compose.reset();
+ return plain;
+ }
+ if (keyboard.compose_target) |owner| if (!owner.eql(target)) keyboard.compose.reset();
+ keyboard.compose_target = target;
+ const text = keyboard.compose.feed(composeLocale(keyboard.server), @intFromEnum(sym), out) orelse return plain;
+ if (text.len == 0) return null;
+ return .{ .sym = @enumFromInt(0), .utf8 = text, .composed = true };
+}
+
const ShellRepeat = struct { code: u32, target: ShellTarget };
/// The shell target a press would reach now, in `processKey`'s order; null
@@ -801,6 +857,9 @@ fn shellKeyRepeats(keyboard: *Keyboard, event_keycode: u32, target: ShellTarget)
const mods = wlr_keyboard.getModifiers();
if (mods.ctrl or mods.alt or mods.logo) return false;
const sym = xkb_state.keyGetOneSym(keycode);
+ // A dead key types nothing, and the key that completes a sequence types
+ // its letter once, not a stream of the bare letter.
+ if (keyboard.compose.willConsume(@intFromEnum(sym))) return false;
// Lock and polkit keys are secrets: scrub the scratch either way.
var buf: [64]u8 = @splat(0);
defer @import("session/lock.zig").clearKeyScratch(&buf);
@@ -833,8 +892,14 @@ fn deliverShell(keyboard: *Keyboard, target: ShellTarget, event_keycode: u32) vo
var buf: [64]u8 = @splat(0);
defer @import("session/lock.zig").clearKeyScratch(&buf);
const n = xkb_state.keyGetUtf8(keycode, &buf);
- const utf8 = if (n > 0 and n < buf.len) buf[0..@intCast(n)] else "";
- const syms = xkb_state.keyGetSyms(keycode);
+ const raw = if (n > 0 and n < buf.len) buf[0..@intCast(n)] else "";
+ var composed: [64]u8 = @splat(0);
+ defer @import("session/lock.zig").clearKeyScratch(&composed);
+ // The start menu composes in `deliverStartMenu`.
+ const typed = if (target == .start_menu) Typed{ .sym = xkb_state.keyGetOneSym(keycode), .utf8 = raw, .composed = false } else keyboard.composeShell(target, xkb_state.keyGetOneSym(keycode), mods, raw, &composed) orelse return;
+ const utf8 = typed.utf8;
+ const composed_syms = [_]xkb.Keysym{typed.sym};
+ const syms: []const xkb.Keysym = if (typed.composed) &composed_syms else xkb_state.keyGetSyms(keycode);
switch (target) {
.polkit => if (server.polkit_dialog) |dialog| if (syms.len > 0) dialog.key(syms[0], utf8, mods),
.lock => if (server.locker) |lock| if (syms.len > 0) lock.key(syms[0], utf8, mods),
@@ -859,7 +924,7 @@ fn deliverShell(keyboard: *Keyboard, target: ShellTarget, event_keycode: u32) vo
},
.wifi => |popup| if (syms.len > 0) popup.key(syms[0], utf8, mods),
.start_menu => |sm| _ = keyboard.deliverStartMenu(sm, event_keycode, .pressed),
- .desktop => if (server.desktop) |desktop| desktop.key(@intFromEnum(xkb_state.keyGetOneSym(keycode)), utf8),
+ .desktop => if (server.desktop) |desktop| desktop.key(@intFromEnum(typed.sym), utf8),
}
}
@@ -872,8 +937,13 @@ fn deliverStartMenu(keyboard: *Keyboard, sm: *StartMenu, event_keycode: u32, sta
if (syms.len == 0) return false;
var utf8_buf: [64]u8 = undefined;
const utf8_len = xkb_state.keyGetUtf8(keycode, &utf8_buf);
- const utf8: ?[]const u8 = if (utf8_len > 0 and utf8_len < utf8_buf.len) utf8_buf[0..@intCast(utf8_len)] else null;
- return sm.handleKey(syms[0], state, utf8, wlr_keyboard.getModifiers());
+ const raw: []const u8 = if (utf8_len > 0 and utf8_len < utf8_buf.len) utf8_buf[0..@intCast(utf8_len)] else "";
+ const mods = wlr_keyboard.getModifiers();
+ // Only presses compose. A key that merely advanced a sequence is ours:
+ // returning false would hand the dead key to the keys behind the menu.
+ var composed: [64]u8 = undefined;
+ const typed = if (state == .pressed) keyboard.composeShell(.{ .start_menu = sm }, syms[0], mods, raw, &composed) orelse return true else Typed{ .sym = syms[0], .utf8 = raw, .composed = false };
+ return sm.handleKey(typed.sym, state, if (typed.utf8.len > 0) typed.utf8 else null, mods);
}
fn armShellRepeat(keyboard: *Keyboard, event_keycode: u32, target: ShellTarget) void {
@@ -892,14 +962,12 @@ fn armShellRepeat(keyboard: *Keyboard, event_keycode: u32, target: ShellTarget)
pub fn forgetShellTarget(server: *Server, panel: anytype) void {
var it = server.input.keyboards.iterator(.forward);
while (it.next()) |keyboard| {
- const held = keyboard.shell_repeat orelse continue;
- const same = switch (held.target) {
- .control_center => |cc| @intFromPtr(cc) == @intFromPtr(panel),
- .start_menu => |sm| @intFromPtr(sm) == @intFromPtr(panel),
- .wifi => |popup| @intFromPtr(popup) == @intFromPtr(panel),
- else => false,
+ if (keyboard.compose_target) |owner| if (owner.isPanel(panel)) {
+ keyboard.compose.reset();
+ keyboard.compose_target = null;
};
- if (same) keyboard.stopShellRepeat();
+ const held = keyboard.shell_repeat orelse continue;
+ if (held.target.isPanel(panel)) keyboard.stopShellRepeat();
}
}
@@ -937,3 +1005,14 @@ fn repeatShell(keyboard: *Keyboard) c_int {
keyboard.shell_timer.?.timerUpdate(@intCast(@max(1, @divTrunc(1000, @max(1, rate))))) catch keyboard.stopShellRepeat();
return 0;
}
+
+/// End repeats without losing consumed releases when changing desktop modes.
+pub fn cancelModeRepeats(keyboard: *Keyboard) void {
+ const kb = keyboard.device.toKeyboard();
+ for (kb.keycodes[0..kb.num_keycodes]) |code| {
+ if (code < keyboard.mode_consumed.len) keyboard.mode_consumed[code] = true;
+ }
+ keyboard.stopRepeat();
+ keyboard.stopSwitcherRepeat();
+ keyboard.stopShellRepeat();
+}
diff --git a/src/Output.zig b/src/Output.zig
index 1306c4c..b15eb00 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -111,6 +111,7 @@ link: wl.list.Link = undefined,
frame: wl.Listener(*wlr.Output) = .init(handleFrame),
request_state: wl.Listener(*wlr.Output.event.RequestState) = .init(handleRequestState),
+workspace_id: u8 = 0,
destroy: wl.Listener(*wlr.Output) = .init(handleDestroy),
pub fn isLogicallyEnabled(self: *const Output) bool {
@@ -541,6 +542,8 @@ pub fn syncLayout(server: *Server) void {
if (!out.idle_blanked and !out.user_disabled) layer.arrange();
}
recomputeWorldBounds(server);
+ server.world.workspaces.setMode(server, server.config.compositor.desktop_mode == .workspaces);
+ server.world.workspaces.syncOutputs(server);
if (server.desktop) |desktop| desktop.syncLayout();
if (server.output_management) |om| om.publish();
server.input.touch.remap();
@@ -1496,6 +1499,7 @@ fn handleDestroy(listener: *wl.Listener(*wlr.Output), _: *wlr.Output) void {
// fromWlr/atLayout cannot hand out a freed Output.
output.wlr_output.data = null;
if (server.desktop) |desktop| desktop.outputRemoved(output);
+ server.world.workspaces.forgetOutput(output);
gpa.destroy(output);
server.input.refreshOutputScales();
syncLayout(server);
diff --git a/src/Server.zig b/src/Server.zig
index cb398ee..4826840 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -845,6 +845,8 @@ pub fn getSystemd(server: *Server) !*@import("systemd.zig").Client {
}
pub fn deinit(server: *Server) void {
+ server.undo.clear();
+ server.undo.applying = true;
// terminate saved the layout before leaving the event loop. Only paths
// such as restart_shell, which stop the display directly, need to save it
// here. In both cases save before tearing down Xwayland or native clients.
@@ -1229,7 +1231,7 @@ fn updateTaskbarFullscreenVisibility(server: *Server) void {
// write keeps the bar in lockstep with the resize instead of flashing
// on top for a frame.
const fullscreen_output: ?*Output = if (focused) |t|
- (if (t.fullscreen) t.currentOutput() else null)
+ (if (t.fullscreen and @import("workspaces.zig").visible(t)) t.currentOutput() else null)
else
null;
diff --git a/src/Switcher.zig b/src/Switcher.zig
index b1d8f34..481e9bd 100644
--- a/src/Switcher.zig
+++ b/src/Switcher.zig
@@ -98,7 +98,7 @@ fn open(self: *Self, server: *Server) !void {
self.background = try self.makeNode(&bg.base, self.width, height);
var it = server.world.toplevels.iterator(.forward);
while (it.next()) |tl| {
- if (!tl.isMapped() or tl.tab_hidden) continue;
+ if (!tl.isMapped() or tl.tab_hidden or !@import("workspaces.zig").visible(tl)) continue;
const image = try PanelBuffer.create(card_w, card_h, self.scale);
defer image.base.drop();
r = Renderer.init(image.pixels, image.width, image.height, self.scale);
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index bbe7a2d..6413e83 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -815,7 +815,7 @@ fn reconcile(bar: *Taskbar, now_ms: i64) bool {
defer visible.deinit(gpa);
var it = bar.server.world.toplevels.iterator(.forward);
while (it.next()) |toplevel| {
- if (toplevel.tab_hidden or (toplevel.live_rules.skip_taskbar orelse false)) continue;
+ if (!@import("workspaces.zig").visible(toplevel) or (bar.server.world.workspaces.active and toplevel.currentOutput() != Output.fromWlr(bar.wlr_output)) or toplevel.tab_hidden or (toplevel.live_rules.skip_taskbar orelse false)) continue;
visible.append(gpa, toplevel) catch break;
}
std.mem.sort(*Toplevel, visible.items, {}, taskbarOrderLessThan);
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index 8e62b39..2fa7084 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -158,6 +158,10 @@ frame_data: scene_data.SceneData = undefined,
chrome_data: scene_data.SceneData = undefined,
id: u64 = 0,
+workspace_id: u8 = 0,
+workspace_order: u64 = 0,
+workspace_generation: u64 = 0,
+canvas_state: ?@import("workspaces.zig").CanvasWindow = null,
// Hidden tabs stay mapped; this is independent of client minimization.
tab_group: u64 = 0,
tab_identity: []const u8 = "",
@@ -268,8 +272,17 @@ maximize_restore: ?RestoreGeometry = null,
fullscreen_restore: ?RestoreGeometry = null,
maximize_target: ?RestoreGeometry = null,
fullscreen_target: ?RestoreGeometry = null,
-// Half/quarter-screen tile (snap.zig). Like maximize, the compositor owns the
-// geometry; `tile_restore` is the floating geometry to return to.
+// Automatic rectangles are independent of manual half/quarter tiles.
+// Explicit floating placement opts a member out; overflow can retry later.
+auto_target: ?RestoreGeometry = null,
+auto_restore: ?RestoreGeometry = null,
+auto_float: bool = false,
+auto_float_override: ?bool = null,
+auto_seen: ?@import("auto_tiling.zig").State = null,
+auto_reinsert: ?@import("auto_layout.zig").Placement = null,
+tab_resume_group: u64 = 0,
+tab_resume_restore: ?RestoreGeometry = null,
+// Manual half/quarter tile and the floating geometry to return to.
tile: ?tiling.Tile = null,
tile_target: ?RestoreGeometry = null,
tile_restore: ?RestoreGeometry = null,
@@ -285,12 +298,7 @@ reconnect_maximized: bool = false,
reconnect_fullscreen: bool = false,
reconnect_tile: ?tiling.Tile = null,
-pub const RestoreGeometry = struct {
- x: i32,
- y: i32,
- width: i32,
- height: i32,
-};
+pub const RestoreGeometry = @import("undo.zig").Geometry;
const ChromeNodes = struct {
frame_tree: *wlr.SceneTree,
@@ -486,7 +494,7 @@ fn handleDelayTimeout(toplevel: *Toplevel) c_int {
ph.delay_timer = null;
}
if (!ph.matched and !ph.cancelled and toplevel.in_world) {
- toplevel.frame_tree.node.setEnabled(true);
+ toplevel.frame_tree.node.setEnabled(@import("window_tabs.zig").visible(toplevel));
toplevel.server.scheduleFrames();
}
return 0;
@@ -648,6 +656,8 @@ pub fn createPlaceholder(
server.world.toplevels.prepend(toplevel);
toplevel.in_world = true;
+ toplevel.server.world.workspaces.mapped(toplevel);
+ if (server.layout_autosave) |autosave| autosave.finishMapped(toplevel);
server.world.focus(toplevel);
server.refreshTaskbars();
@@ -668,7 +678,7 @@ pub fn createPlaceholder(
_ = t.timerUpdate(@intCast(delay_ms)) catch {};
}
} else {
- toplevel.frame_tree.node.setEnabled(true);
+ toplevel.frame_tree.node.setEnabled(@import("window_tabs.zig").visible(toplevel));
}
toplevel.backend.placeholder.timeout_timer = server.wl_server.getEventLoop().addTimer(
@@ -1087,6 +1097,10 @@ pub fn raise(toplevel: *Toplevel) void {
fn syncXwaylandStack(toplevel: *Toplevel) void {
if (toplevel.backend != .xwayland or toplevel.backend_gone) return;
+ if (!@import("workspaces.zig").visible(toplevel)) {
+ toplevel.backend.xwayland.xsurface.restack(null, .below);
+ return;
+ }
// Use the nearest managed X11 sibling above us. This also covers an
// initially unfocused window placed below a focused Wayland window.
if (toplevel.frame_tree.node.parent) |parent| {
@@ -1101,7 +1115,7 @@ fn syncXwaylandStack(toplevel: *Toplevel) void {
const data = scene_data.SceneData.fromNode(node) orelse continue;
if (data.role != .toplevel) continue;
const other = data.role.toplevel;
- if (!other.in_world or other.minimized or other.backend_gone or other.backend != .xwayland) continue;
+ if (!other.in_world or other.minimized or !@import("workspaces.zig").visible(other) or other.backend_gone or other.backend != .xwayland) continue;
toplevel.backend.xwayland.xsurface.restack(other.backend.xwayland.xsurface, .below);
return;
}
@@ -1137,6 +1151,7 @@ pub fn setActivated(toplevel: *Toplevel, activated: bool) void {
/// Publishes state, title, output and parent changes to wlr foreign-toplevel
/// clients; unchanged values send nothing.
pub fn syncForeign(toplevel: *Toplevel) void {
+ @import("auto_tiling.zig").observe(toplevel);
if (toplevel.wlr_foreign) |handle| handle.sync();
}
@@ -1304,6 +1319,10 @@ pub fn setPosition(toplevel: *Toplevel, x: i32, y: i32) void {
/// are refit directly because their geometry is owned by the target output.
pub fn moveToOutput(toplevel: *Toplevel, output: *Output) bool {
if (!toplevel.in_world or !output.isAvailable()) return false;
+ if (toplevel.server.world.workspaces.active) {
+ toplevel.server.world.workspaces.moveTo(toplevel, output.workspace_id);
+ return true;
+ }
if (toplevel.isMaximized()) {
toplevel.setMaximizedOn(output);
return true;
@@ -1450,8 +1469,8 @@ fn commitPosition(toplevel: *Toplevel, x: i32, y: i32, update_scene: bool) void
adapter.configure(
xscale.surfacePosition((x + toplevel.borderWidth()), n),
xscale.surfacePosition((y + toplevel.titlebarHeight()), n),
- geom.width,
- geom.height,
+ if (toplevel.auto_target != null and !toplevel.maximized and !toplevel.fullscreen) xscale.surfaceLength(toplevel.auto_target.?.width, n) else geom.width,
+ if (toplevel.auto_target != null and !toplevel.maximized and !toplevel.fullscreen) xscale.surfaceLength(toplevel.auto_target.?.height, n) else geom.height,
);
}
},
@@ -1848,6 +1867,14 @@ pub fn borderWidth(toplevel: *const Toplevel) i32 {
return if (toplevel.hasServerDecorations()) chrome.frame_border else 0;
}
+fn hasWorkspaceFocusBorder(toplevel: *const Toplevel) bool {
+ return toplevel.server.world.workspaces.active and toplevel.activated and !toplevel.isFullscreen();
+}
+
+fn borderColor(toplevel: *const Toplevel) col.Premul {
+ return chrome.windowBorderColor(toplevel.last_painted_hover, toplevel.hasWorkspaceFocusBorder());
+}
+
pub fn footerHeight(toplevel: *const Toplevel) i32 {
if (!toplevel.hasServerDecorations()) return 0;
return chrome.footerHeight(toplevel.cornerRadius());
@@ -1874,6 +1901,7 @@ pub fn zoom(toplevel: *const Toplevel) f64 {
/// Client units to presented world units, including the temporary focus boost.
/// The saved frame position, client size and zoom_index remain unchanged.
pub fn worldScale(toplevel: *const Toplevel) f64 {
+ if (toplevel.server.world.workspaces.active) return 1;
return @import("camera.zig").boostedScale(toplevel.zoom_scale, toplevel.server.world.camera.zoom(), toplevel.zoom_boost_value);
}
@@ -1914,6 +1942,7 @@ fn takeZoomBoost(toplevel: *Toplevel) void {
}
fn cameraFocusOpacity(toplevel: *const Toplevel) f32 {
+ if (toplevel.server.world.workspaces.active) return 1;
if (toplevel.server.config.compositor.focus_zoom != .camera or toplevel.layout() != .floating or toplevel.isFullscreen()) return 1;
// Windows passed by the camera fade away, and stop accepting input once
// invisible. Reversing the zoom reveals the same retained scene again.
@@ -1966,6 +1995,7 @@ pub fn tickZoom(toplevel: *Toplevel, now_ms: i64) bool {
}
pub fn setZoom(toplevel: *Toplevel, index: usize, lx: f64, ly: f64) void {
+ if (toplevel.server.world.workspaces.active) return;
toplevel.takeZoomBoost();
const next = @min(index, @import("camera.zig").zoom_levels.len - 1);
if (next == toplevel.zoom_index and toplevel.zoom_scale == @as(f64, @floatFromInt(@import("camera.zig").zoom_levels[next])) / 100) return;
@@ -1999,6 +2029,7 @@ pub fn setZoom(toplevel: *Toplevel, index: usize, lx: f64, ly: f64) void {
}
pub fn setZoomAnimated(toplevel: *Toplevel, index: usize, lx: f64, ly: f64) void {
+ if (toplevel.server.world.workspaces.active) return;
toplevel.takeZoomBoost();
const next = @min(index, @import("camera.zig").zoom_levels.len - 1);
const target_scale = @as(f64, @floatFromInt(@import("camera.zig").zoom_levels[next])) / 100;
@@ -2092,6 +2123,11 @@ pub fn handleSurfaceCommit(toplevel: *Toplevel) void {
toplevel.syncChrome(true, true, nowMs()) catch |err| {
log.err("handleCommit: could not update window decoration: {}", .{err});
};
+ if (toplevel.in_world) if (toplevel.server.layout_autosave) |autosave| {
+ autosave.mapped(toplevel);
+ autosave.finishMapped(toplevel);
+ };
+ @import("auto_tiling.zig").observe(toplevel);
toplevel.server.window_tabs.reconcile(toplevel);
if (toplevel.tab_hidden) {
if (@import("window_tabs.zig").active(toplevel.server, toplevel.tab_group)) |active_tab| active_tab.syncChrome(false, false, nowMs()) catch {};
@@ -2134,6 +2170,13 @@ pub fn handleMapped(toplevel: *Toplevel) void {
if (maybe_ph) |ph_top| {
if (ph_top.in_world and ph_top.backend == .placeholder and !ph_top.backend.placeholder.cancelled) {
inherited_placeholder = ph_top;
+ toplevel.workspace_id = ph_top.workspace_id;
+ toplevel.workspace_order = ph_top.workspace_order;
+ toplevel.workspace_generation = ph_top.workspace_generation;
+ toplevel.canvas_state = ph_top.canvas_state;
+ toplevel.auto_float = ph_top.auto_float;
+ toplevel.auto_restore = ph_top.auto_restore;
+ toplevel.auto_reinsert = ph_top.auto_reinsert;
const ph = &ph_top.backend.placeholder;
ph.matched = true;
ph_token = ph.token;
@@ -2179,11 +2222,16 @@ pub fn handleMapped(toplevel: *Toplevel) void {
}
}
- const want_focus = if (inherited_placeholder != null) ph_had_focus else (toplevel.open_rules.focus orelse true);
+ toplevel.server.world.workspaces.mapped(toplevel);
+ const want_focus = (if (inherited_placeholder != null) ph_had_focus else (toplevel.open_rules.focus orelse true)) and @import("workspaces.zig").visible(toplevel);
if (want_focus) {
toplevel.needs_attention = false;
toplevel.server.world.toplevels.prepend(toplevel);
toplevel.in_world = true;
+ toplevel.server.world.workspaces.mapped(toplevel);
+ const undo_applying = toplevel.server.undo.applying;
+ if (inherited_placeholder != null and toplevel.server.world.workspaces.active) toplevel.server.undo.applying = true;
+ defer toplevel.server.undo.applying = undo_applying;
toplevel.server.world.focus(toplevel);
} else {
toplevel.needs_attention = true;
@@ -2195,6 +2243,7 @@ pub fn handleMapped(toplevel: *Toplevel) void {
toplevel.server.world.toplevels.prepend(toplevel);
}
toplevel.in_world = true;
+ toplevel.server.world.workspaces.mapped(toplevel);
toplevel.setActivated(false);
@import("config_runtime/apply.zig").applyWindowOpacity(toplevel.server);
toplevel.server.refreshTaskbars();
@@ -2221,6 +2270,7 @@ pub fn handleMapped(toplevel: *Toplevel) void {
}
if (inherited_placeholder) |ph_top| {
+ @import("layout_undo.zig").replaced(toplevel.server, ph_top.id, toplevel.id);
if (toplevel.server.ipc) |ipc| {
events.onLaunchMatched(ipc, ph_desktop_id, toplevel.id, ph_pid);
}
@@ -2250,6 +2300,7 @@ pub fn handleMapped(toplevel: *Toplevel) void {
}
toplevel.server.window_tabs.mapped(toplevel);
toplevel.server.window_tabs.mappedToken(toplevel);
+ if (toplevel.server.layout_autosave) |autosave| autosave.finishMapped(toplevel);
toplevel.syncChrome(false, false, nowMs()) catch {};
toplevel.frame_tree.node.setEnabled(@import("window_tabs.zig").visible(toplevel));
// A newly focused app must not open behind the camera's current depth.
@@ -2264,14 +2315,20 @@ pub fn handleUnmapped(toplevel: *Toplevel) void {
toplevel.finishMoveAnimation();
toplevel.server.switcher.cancel();
if (!toplevel.in_world) return;
+ const undo_applying = toplevel.server.undo.applying;
+ toplevel.server.undo.applying = true;
+ defer toplevel.server.undo.applying = undo_applying;
const was_focused = toplevel.server.world.toplevels.first() == toplevel;
const was_tab = toplevel.tab_group != 0;
+ @import("auto_tiling.zig").unmapped(toplevel);
+ @import("window_tabs.zig").rememberUnmap(toplevel);
toplevel.server.window_tabs.remove(toplevel, false);
+ toplevel.auto_target = null;
toplevel.in_world = false;
toplevel.needs_attention = false;
toplevel.detachInput();
toplevel.resetEdgeSample();
- const keep_scene = if (was_tab) false else toplevel.beginCloseAnimation();
+ const keep_scene = if (was_tab or !@import("workspaces.zig").visible(toplevel)) false else toplevel.beginCloseAnimation();
if (!keep_scene) {
toplevel.clearChromeCache();
toplevel.frame_tree.node.setEnabled(false);
@@ -2314,6 +2371,7 @@ pub fn handleUnmapped(toplevel: *Toplevel) void {
toplevel.wlr_foreign = null;
}
toplevel.link.remove();
+ toplevel.server.world.workspaces.tiler.schedule(toplevel.server);
toplevel.server.refreshTaskbars();
// A dismissed transient dialog returns focus to the window it was
// opened from, rather than leaving the seat with no keyboard focus at
@@ -2323,6 +2381,7 @@ pub fn handleUnmapped(toplevel: *Toplevel) void {
if (owner_toplevel.in_world) toplevel.server.world.focus(owner_toplevel);
}
}
+ if (was_focused and toplevel.server.world.workspaces.active) @import("workspaces.zig").focusFallback(toplevel.server, toplevel.workspace_id);
if (toplevel.server.ipc) |ipc| {
events.onWindowClosed(ipc, toplevel.id);
ipc.wait_mgr.checkAll();
@@ -2374,6 +2433,7 @@ pub fn destroyNow(toplevel: *Toplevel) void {
if (toplevel.in_world) {
toplevel.in_world = false;
toplevel.link.remove();
+ toplevel.server.world.workspaces.tiler.schedule(toplevel.server);
toplevel.server.refreshTaskbars();
if (toplevel.server.ipc) |ipc| {
events.onWindowClosed(ipc, toplevel.id);
@@ -2692,6 +2752,7 @@ fn applyEdgeSample(toplevel: *Toplevel) void {
/// color/size, so already-open windows must pick it up immediately, same as
/// border/titlebar colors already do.
pub fn refreshTheme(toplevel: *Toplevel) void {
+ defer @import("auto_tiling.zig").observe(toplevel);
const height_changed = if (toplevel.last_titlebar) |memo| memo.chrome_height != theme.global.chrome_height else false;
switch (toplevel.backend) {
.placeholder => |*ph| col.setRect(ph.body_rect, col.Straight.fromRgba(theme.global.window_bg).premultiply()),
@@ -2777,7 +2838,7 @@ pub fn syncChrome(toplevel: *Toplevel, sample_edge: bool, rebuild_shadow: bool,
toplevel.titlebar_buffer.node.setEnabled(decorated);
toplevel.footer_buffer.node.setEnabled(decorated);
for (toplevel.side_fills) |rect| rect.node.setEnabled(decorated);
- for (toplevel.border_rects) |rect| rect.node.setEnabled(decorated);
+ for (toplevel.border_rects) |rect| rect.node.setEnabled(decorated or toplevel.hasWorkspaceFocusBorder());
if (!decorated) {
toplevel.resetEdgeSample();
toplevel.releaseIcon();
@@ -2796,6 +2857,7 @@ pub fn syncChrome(toplevel: *Toplevel, sample_edge: bool, rebuild_shadow: bool,
toplevel.hover_anim.cancel(0);
toplevel.resetChip();
toplevel.last_painted_hover = 0;
+ toplevel.syncBorders(animated.w, animated.h);
return;
}
@@ -2824,6 +2886,7 @@ pub fn syncChrome(toplevel: *Toplevel, sample_edge: bool, rebuild_shadow: bool,
.tabs = toplevel.tabStrip(&tab_storage),
.radius = radius,
.active = toplevel.activated,
+ .workspace_focus = toplevel.hasWorkspaceFocusBorder(),
.maximized = toplevel.isMaximized(),
.density = toplevel.chromeDensity(),
.title = window_title,
@@ -3003,12 +3066,26 @@ fn syncResizeGrab(toplevel: *Toplevel, width: i32, height: i32) void {
}
fn syncBorders(toplevel: *Toplevel, width: i32, height: i32) void {
+ const color = toplevel.borderColor();
+ for (toplevel.border_rects) |rect| col.setRect(rect, color);
+ if (!toplevel.hasServerDecorations()) {
+ // Outline CSD frames outside their content. Client geometry and input
+ // coordinates stay unchanged, and the content remains above the stroke.
+ const edge = chrome.frame_border;
+ toplevel.border_rects[0].node.setPosition(-edge, -edge);
+ toplevel.border_rects[0].setSize(width + 2 * edge, edge);
+ toplevel.border_rects[1].node.setPosition(-edge, 0);
+ toplevel.border_rects[1].setSize(edge, height);
+ toplevel.border_rects[2].node.setPosition(width, 0);
+ toplevel.border_rects[2].setSize(edge, height);
+ toplevel.border_rects[3].node.setPosition(-edge, height);
+ toplevel.border_rects[3].setSize(width + 2 * edge, edge);
+ return;
+ }
const inset: i32 = if (toplevel.isMaximized())
0
else
@intFromFloat(@ceil(toplevel.cornerRadius()));
- const color = chrome.borderColor(toplevel.last_painted_hover);
- for (toplevel.border_rects) |rect| col.setRect(rect, color);
// Only back the client-height gap: overlapping the retained bands would
// apply the translucent chrome twice at the joins.
@@ -3061,7 +3138,7 @@ pub fn applyOpacity(toplevel: *Toplevel, now_ms: i64) void {
buffer.setOpacity(value.*);
}
}.iter, &opacity);
- const color = chrome.borderColor(toplevel.last_painted_hover).scale(opacity);
+ const color = toplevel.borderColor().scale(opacity);
for (toplevel.border_rects) |rect| col.setRect(rect, color);
for (toplevel.side_fills) |rect| col.setRect(rect, chrome.fillColor().scale(opacity));
glass.Effect.configure(toplevel.glass_effect, toplevel.cornerRadius(), opacity);
@@ -3221,6 +3298,7 @@ pub fn minimize(toplevel: *Toplevel) void {
}
if (toplevel.tab_group != 0) @import("window_tabs.zig").refreshVisibility(server);
+ if (server.world.workspaces.active) @import("workspaces.zig").focusFallback(server, toplevel.workspace_id);
// Must run last: content_tree stays alive and rendering-ready while
// minimized (only the frame is hidden), so a window-capture source
// over it wouldn't otherwise notice — unlike a real close, nothing
@@ -3240,7 +3318,7 @@ pub fn restore(toplevel: *Toplevel) void {
defer if (toplevel.tab_group != 0) @import("window_tabs.zig").refreshVisibility(toplevel.server);
if (!toplevel.minimized or !toplevel.in_world) return;
toplevel.minimized = false;
- toplevel.frame_tree.node.setEnabled(true);
+ toplevel.frame_tree.node.setEnabled(@import("window_tabs.zig").visible(toplevel));
switch (toplevel.backend) {
.xwayland => |*adapter| adapter.xsurface.setMinimized(false),
.xdg, .placeholder, .shell => {},
@@ -3266,6 +3344,25 @@ pub fn rememberGeometry(toplevel: *const Toplevel) RestoreGeometry {
};
}
+/// Immediate floating placement, with no deferred restore that can undo a drag.
+pub fn restoreGeometryNow(toplevel: *Toplevel, saved: RestoreGeometry) void {
+ toplevel.pending_restore = null;
+ toplevel.finishSizeAnimation();
+ var x = saved.x;
+ var y = saved.y;
+ if (@import("workspaces.zig").outputFor(toplevel)) |output| {
+ // A restore may have been captured before transfer or hot-unplug.
+ // Keep its titlebar on the workspace's current output.
+ const usable = output.usableBox();
+ const width = saved.width +| (2 * toplevel.borderWidth());
+ const height = saved.height +| toplevel.titlebarHeight() +| toplevel.footerHeight();
+ x = std.math.clamp(x, usable.x, usable.x + @max(0, usable.width - width));
+ y = std.math.clamp(y, usable.y, usable.y + @max(0, usable.height - height));
+ }
+ toplevel.setPosition(x, y);
+ _ = toplevel.requestSize(saved.width, saved.height);
+}
+
pub fn restoreGeometry(toplevel: *Toplevel, saved: RestoreGeometry) void {
toplevel.pending_restore = saved;
_ = toplevel.requestSizeAnimated(saved.width, saved.height);
@@ -3274,13 +3371,21 @@ pub fn restoreGeometry(toplevel: *Toplevel, saved: RestoreGeometry) void {
}
pub fn forcedGeometry(toplevel: *const Toplevel) ?RestoreGeometry {
- return toplevel.fullscreen_target orelse toplevel.maximize_target orelse toplevel.tile_target orelse toplevel.pending_restore;
+ return toplevel.fullscreen_target orelse toplevel.maximize_target orelse toplevel.tile_target orelse toplevel.auto_target orelse toplevel.pending_restore;
}
fn applyForcedGeometry(toplevel: *Toplevel) c_int {
const forced = toplevel.forcedGeometry() orelse return 0;
- _ = toplevel.requestSizeAnimated(forced.width, forced.height);
- toplevel.setPositionAnimated(forced.x, forced.y);
+ if (toplevel.auto_target != null and !toplevel.maximized and !toplevel.fullscreen) {
+ // Automatic frames must not inherit a size-animation endpoint computed
+ // with the old maximized/fullscreen decorations before the xdg ack.
+ toplevel.finishSizeAnimation();
+ _ = toplevel.requestSize(forced.width, forced.height);
+ toplevel.setPosition(forced.x, forced.y);
+ } else {
+ _ = toplevel.requestSizeAnimated(forced.width, forced.height);
+ toplevel.setPositionAnimated(forced.x, forced.y);
+ }
toplevel.pending_restore = null;
return 0;
}
@@ -3301,7 +3406,7 @@ fn scheduleForcedGeometry(toplevel: *Toplevel) void {
// under it. The compositor owns the position as well as the requested client
// size, so it also owns and restores both values on un-maximize.
pub fn toggleMaximize(toplevel: *Toplevel) void {
- toplevel.setMaximized(!toplevel.isMaximized());
+ toplevel.setMaximized(!toplevel.maximized);
}
pub fn currentIdentity(toplevel: *Toplevel) window_rules.WindowIdentity {
@@ -3350,6 +3455,7 @@ pub fn resolveTargetOutput(toplevel: *const Toplevel) ?*Output {
/// layout). Used to decide which output's taskbar a fullscreen window
/// should suppress.
pub fn currentOutput(toplevel: *const Toplevel) ?*Output {
+ if (@import("workspaces.zig").outputFor(toplevel)) |output| return output;
const center = toplevel.frameWorld(@floatFromInt(@divTrunc(toplevel.chrome_width, 2)), @floatFromInt(@divTrunc(toplevel.chrome_height, 2)));
const layout_center = toplevel.server.world.toLayout(center.x, center.y);
return Output.atLayout(toplevel.server, layout_center.x, layout_center.y) orelse toplevel.resolveTargetOutput();
@@ -3624,12 +3730,13 @@ pub fn setMaximized(toplevel: *Toplevel, maximizing: bool) void {
pub fn layout(toplevel: *const Toplevel) tiling.Layout {
if (toplevel.maximized) return .maximized;
if (toplevel.tile) |tile| return .{ .tiled = tile };
+ if (toplevel.auto_target != null) return .automatic;
return .floating;
}
/// The geometry to return to when leaving maximize or a tile.
fn floatingGeometry(toplevel: *const Toplevel) RestoreGeometry {
- return toplevel.tile_restore orelse toplevel.rememberGeometry();
+ return toplevel.tile_restore orelse toplevel.auto_restore orelse toplevel.rememberGeometry();
}
pub fn setTiled(toplevel: *Toplevel, tile: tiling.Tile) void {
@@ -3646,7 +3753,7 @@ pub fn setTiledOn(toplevel: *Toplevel, output: *Output, tile: tiling.Tile) void
const usable = output.usableBox();
if (usable.width <= 0 or usable.height <= 0) return;
- const rect = tiling.tileRect(usable, tile, toplevel.server.config.compositor.window_gap);
+ const rect = tiling.tileRect(usable, tile, toplevel.server.config.compositor.windowGap());
// cornerRadius() still reads maximized until an xdg client acks leaving it.
const footer = if (toplevel.hasServerDecorations()) chrome.footerHeight(chrome.frameRadius() * toplevel.chromeDensity()) else 0;
const scale = toplevel.zoom();
@@ -3663,6 +3770,7 @@ pub fn setTiledOn(toplevel: *Toplevel, output: *Output, tile: tiling.Tile) void
} else if (toplevel.tile_restore == null) {
toplevel.tile_restore = toplevel.rememberGeometry();
}
+ @import("auto_tiling.zig").setFloating(toplevel, true);
toplevel.tile = tile;
toplevel.tile_target = .{ .x = wx, .y = wy, .width = width, .height = height };
toplevel.sendTiled(tiling.tiledEdges(tile));
@@ -3672,8 +3780,61 @@ pub fn setTiledOn(toplevel: *Toplevel, output: *Output, tile: tiling.Tile) void
toplevel.notifyLayoutChanged();
}
+/// Arbitrary automatic frame rectangle. Only changed targets configure a client;
+/// replies to an earlier configure never trigger another layout pass.
+pub fn setAutoTile(toplevel: *Toplevel, rect: wlr.Box) void {
+ if (!toplevel.in_world or toplevel.fullscreen or toplevel.maximized) return;
+ const footer = if (toplevel.hasServerDecorations()) chrome.footerHeight(chrome.frameRadius() * toplevel.chromeDensity()) else 0;
+ const target: RestoreGeometry = .{
+ .x = rect.x,
+ .y = rect.y,
+ .width = @max(1, rect.width - 2 * toplevel.borderWidth()),
+ .height = @max(1, rect.height - toplevel.titlebarHeight() - footer),
+ };
+ toplevel.finishSizeAnimation();
+ if (toplevel.auto_target) |previous| if (std.meta.eql(previous, target)) return;
+ if (toplevel.auto_restore == null) toplevel.auto_restore = toplevel.rememberGeometry();
+ const was_tiled = toplevel.auto_target != null;
+ toplevel.auto_target = target;
+ toplevel.pending_restore = null;
+ toplevel.clearZoomBoost();
+ if (!was_tiled) toplevel.sendTiled(.{ .top = true, .bottom = true, .left = true, .right = true });
+ const moved = toplevel.x != target.x or toplevel.y != target.y;
+ // X11 sends position and size together: commitPosition uses auto_target,
+ // never the old client buffer size, and already configures a moved window.
+ toplevel.setPosition(target.x, target.y);
+ if (toplevel.backend != .xwayland or !moved) _ = toplevel.requestSize(target.width, target.height);
+ toplevel.notifyLayoutChanged();
+}
+
+pub fn clearAutoTile(toplevel: *Toplevel, restore_floating: bool) void {
+ if (toplevel.auto_target == null) return;
+ const saved = toplevel.auto_restore;
+ toplevel.auto_target = null;
+ toplevel.auto_restore = null;
+ if (toplevel.tile == null) toplevel.sendTiled(.{});
+ if (restore_floating and !toplevel.fullscreen and !toplevel.maximized) {
+ if (saved) |geom| {
+ var floating = geom;
+ const constraints = toplevel.sizeConstraints();
+ floating.width = @max(floating.width, @max(1, constraints.min_width));
+ floating.height = @max(floating.height, @max(1, constraints.min_height));
+ if (constraints.max_width > 0) floating.width = @min(floating.width, constraints.max_width);
+ if (constraints.max_height > 0) floating.height = @min(floating.height, constraints.max_height);
+ toplevel.restoreGeometryNow(floating);
+ }
+ }
+ toplevel.notifyLayoutChanged();
+}
+
/// Return a tiled window to its floating geometry.
pub fn untile(toplevel: *Toplevel) void {
+ if (toplevel.auto_target != null) {
+ const saved = toplevel.auto_restore;
+ @import("auto_tiling.zig").setFloating(toplevel, true);
+ if (saved) |geom| toplevel.restoreGeometry(geom);
+ return;
+ }
if (toplevel.tile == null) return;
const saved = toplevel.tile_restore;
toplevel.dropTile();
@@ -3684,6 +3845,7 @@ pub fn untile(toplevel: *Toplevel) void {
/// Leave maximize or a tile without moving; the caller places the window
/// (a drag carrying it off, an interactive resize, undo).
pub fn leaveLayout(toplevel: *Toplevel) void {
+ @import("auto_tiling.zig").setFloating(toplevel, true);
if (!toplevel.maximized and !toplevel.isMaximized() and toplevel.tile == null) return;
toplevel.clearMaximized();
toplevel.dropTile();
@@ -3697,6 +3859,11 @@ pub fn applyLayout(toplevel: *Toplevel, target: tiling.Layout) void {
.floating => if (toplevel.maximized) toplevel.setMaximized(false) else toplevel.untile(),
.maximized => toplevel.setMaximized(true),
.tiled => |tile| toplevel.setTiled(tile),
+ .automatic => {
+ toplevel.clearMaximized();
+ toplevel.dropTile();
+ @import("auto_tiling.zig").setFloating(toplevel, false);
+ },
}
}
@@ -3751,13 +3918,14 @@ fn notifyLayoutChanged(toplevel: *Toplevel) void {
}
pub fn setFullscreen(toplevel: *Toplevel, fullscreen: bool) void {
- if (toplevel.isFullscreen() != fullscreen) {
+ if (toplevel.fullscreen != fullscreen) {
toplevel.toggleFullscreen();
}
}
pub fn toggleFullscreen(toplevel: *Toplevel) void {
- const next = !toplevel.isFullscreen();
+ // Use compositor intent: a second toggle may precede the client ack.
+ const next = !toplevel.fullscreen;
if (!next) {
toplevel.fullscreen = false;
switch (toplevel.backend) {
@@ -3815,6 +3983,11 @@ pub fn handleIdentityChanged(toplevel: *Toplevel) void {
toplevel.syncChrome(true, true, nowMs()) catch {};
}
+ if (toplevel.in_world) if (toplevel.server.layout_autosave) |autosave| {
+ autosave.mapped(toplevel);
+ autosave.finishMapped(toplevel);
+ };
+ @import("auto_tiling.zig").observe(toplevel);
toplevel.server.window_tabs.reconcile(toplevel);
if (toplevel.tab_hidden) {
if (@import("window_tabs.zig").active(toplevel.server, toplevel.tab_group)) |active_tab| active_tab.syncChrome(false, false, nowMs()) catch {};
diff --git a/src/World.zig b/src/World.zig
index 00b1023..1799a43 100644
--- a/src/World.zig
+++ b/src/World.zig
@@ -24,6 +24,7 @@ projection: *Projection,
toplevels: wl.list.Head(Toplevel, .link) = undefined,
/// Unmapped windows whose close animation still owns a scene tree.
closing: wl.list.Head(Toplevel, .closing_link) = undefined,
+workspaces: @import("workspaces.zig") = .{},
camera: camera_mod.Camera = .{},
bounds: camera_mod.Bounds = .{},
mini_map: @import("mini_map.zig") = .{},
@@ -91,6 +92,9 @@ pub fn focusSurface(world: *World, toplevel: *Toplevel, surface: ?*wlr.Surface)
if (world.server.locker != null or world.server.polkit_dialog != null) return;
// Only windows in the stack can be raised; the reorder below needs the link.
if (!toplevel.in_world) return;
+ world.workspaces.reveal(toplevel);
+ if (!@import("workspaces.zig").visible(toplevel)) return;
+ world.workspaces.rememberFocus(toplevel);
world.server.window_tabs.focusMember(toplevel);
var boosted = world.toplevels.iterator(.forward);
while (boosted.next()) |previous| {
@@ -184,7 +188,7 @@ pub fn focusSurface(world: *World, toplevel: *Toplevel, surface: ?*wlr.Surface)
fn raiseTransientChildren(world: *World, owner: *Toplevel) void {
var it = world.toplevels.iterator(.forward);
while (it.next()) |candidate| {
- if (candidate.in_world and !candidate.minimized and candidate.owner() == owner) {
+ if (candidate.in_world and @import("workspaces.zig").visible(candidate) and !candidate.minimized and candidate.owner() == owner) {
candidate.raise();
}
}
@@ -194,7 +198,7 @@ pub fn cycleFocus(world: *World) void {
if (world.toplevels.length() < 2) return;
var it = world.toplevels.iterator(.reverse);
const toplevel = while (it.next()) |candidate| {
- if (!candidate.tab_hidden) break candidate;
+ if (!candidate.tab_hidden and @import("workspaces.zig").visible(candidate)) break candidate;
} else return;
if (toplevel == world.toplevels.first()) return;
if (toplevel.minimized) {
@@ -212,7 +216,7 @@ pub fn cycleFocusPrev(world: *World) void {
const current = world.toplevels.first() orelse return;
var it = world.toplevels.iterator(.forward);
const toplevel = while (it.next()) |candidate| {
- if (candidate != current and !candidate.tab_hidden) break candidate;
+ if (candidate != current and !candidate.tab_hidden and @import("workspaces.zig").visible(candidate)) break candidate;
} else return;
current.link.remove();
world.toplevels.append(current);
@@ -230,6 +234,7 @@ pub fn cycleFocusPrev(world: *World) void {
/// after leaving the taskbar. Also called from input events so a quick release
/// and re-press between frames cannot retain the previous preview.
pub fn peekTarget(world: *World) ?*Toplevel {
+ if (world.workspaces.active) return null;
const input = &world.server.input;
var held = false;
var keyboards = input.keyboards.iterator(.forward);
@@ -327,6 +332,7 @@ pub fn initBounds(world: *World, layout_x: i32, layout_y: i32, layout_w: i32, la
/// Project the world without changing source nodes or client geometry.
pub fn applyCamera(world: *World) void {
+ if (world.workspaces.active) world.camera = .{ .focus_zoom = 1 };
if (!world.allowsOverscroll()) {
world.camera.clamp(world.bounds);
}
@@ -393,6 +399,8 @@ pub fn isWindowVisible(world: *World, toplevel: *Toplevel, output: *@import("Out
/// Reveal `toplevel` on `output` if it is currently offscreen.
pub fn revealIfOffscreen(world: *World, toplevel: *Toplevel, output: *@import("Output.zig")) void {
+ world.workspaces.reveal(toplevel);
+ if (world.workspaces.active) return;
if (world.windowFocusOffset(toplevel, output, world.camera, toplevel.worldScale(), false)) |offset| {
world.springPan(offset.x, offset.y, .camera_reveal);
}
@@ -406,6 +414,8 @@ fn windowFocusOffset(world: *World, toplevel: *Toplevel, output: *@import("Outpu
/// Explicit navigation (Alt+Tab, directional focus and taskbar activation).
/// Plain pointer focus does not change the zoom beneath the pointer.
pub fn navigateTo(world: *World, toplevel: *Toplevel, output: *@import("Output.zig")) void {
+ world.workspaces.reveal(toplevel);
+ if (world.workspaces.active) return;
if (!toplevel.in_world or toplevel.minimized) return;
const mode = world.server.config.compositor.focus_zoom;
const floating = toplevel.layout() == .floating and !toplevel.isFullscreen();
@@ -441,6 +451,7 @@ pub fn refreshFocusZoom(world: *World) void {
/// layout, so a cursor-based lookup can return a wrapper that has already been
/// freed.
pub fn ensureInBounds(world: *World, wx: i32, wy: i32, w: i32, h: i32) void {
+ if (world.workspaces.active) return;
const ux: i32 = @intFromFloat(@round(world.bounds.origin_x));
const uy: i32 = @intFromFloat(@round(world.bounds.origin_y));
const uw: i32 = @intFromFloat(@round(world.bounds.width));
@@ -461,6 +472,7 @@ pub fn reveal(
}
pub fn deinit(world: *World) void {
+ world.workspaces.tiler.deinit();
world.mini_map.deinit();
Projection.destroy(world.projection);
}
@@ -652,6 +664,7 @@ pub fn resetCamera(world: *World) void {
}
pub fn springPan(world: *World, x: f64, y: f64, target: anim.Target) void {
+ if (world.workspaces.active) return;
world.pan_target = target;
world.mini_map.show(world.server, world.server.input.cursor.x, world.server.input.cursor.y);
if (world.pinching) world.endPinch(false);
@@ -678,6 +691,7 @@ pub fn springPan(world: *World, x: f64, y: f64, target: anim.Target) void {
}
pub fn beginPan(world: *World) void {
+ if (world.workspaces.active) return;
world.mini_map.show(world.server, world.server.input.cursor.x, world.server.input.cursor.y);
if (world.pinching) world.endPinch(false);
world.zoom_keeps_anchor = false;
@@ -692,6 +706,7 @@ pub fn beginPan(world: *World) void {
}
pub fn panBy(world: *World, dx: f64, dy: f64) void {
+ if (world.workspaces.active) return;
if (!world.panning) world.beginPan();
_ = camera_mod.applyMotionRubber(&world.camera, dx, dy, world.bounds, &world.pan_raw_x, &world.pan_raw_y);
world.applyCamera();
diff --git a/src/Xwayland.zig b/src/Xwayland.zig
index bb1fab1..b9a0250 100644
--- a/src/Xwayland.zig
+++ b/src/Xwayland.zig
@@ -176,6 +176,9 @@ fn handleNewSurface(listener: *wl.Listener(*wlr.XwaylandSurface), xsurface: *wlr
fn handleReady(listener: *wl.Listener(void)) void {
const xwayland: *Xwayland = @fieldParentPtr("on_ready", listener);
xwayland.ready = true;
+ // wlroots' xwm_destroy clears the seat when a lazy Xwayland exits idle,
+ // and the restarted xwm never gets it back: no X11 clipboard or DnD.
+ if (xwayland.wlr_xwayland.seat == null) xwayland.wlr_xwayland.setSeat(xwayland.server.input.seat);
xwayland.applyCursor();
if (xwayland.native_scaling) {
xwayland.applyScaleHints();
diff --git a/src/auto_layout.zig b/src/auto_layout.zig
new file mode 100644
index 0000000..9e981b6
--- /dev/null
+++ b/src/auto_layout.zig
@@ -0,0 +1,454 @@
+//! Recursive split geometry, independent of compositor objects and focus order.
+//! Members arrive in stable insertion order. Suspended leaves retain their split;
+//! overflow is admitted oldest-first and retried only when the caller changes state.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+pub const Box = struct { x: i32, y: i32, width: i32, height: i32 };
+pub const Key = struct { id: u64, group: bool = false };
+pub const Member = struct {
+ key: Key,
+ order: u64 = 0,
+ active: bool = true,
+ min_width: i32 = 1,
+ min_height: i32 = 1,
+ max_width: i32 = 0,
+ max_height: i32 = 0,
+};
+pub const Axis = enum { horizontal, vertical };
+pub const Direction = enum { left, right, up, down };
+pub const Placement = struct { anchor: Key, axis: Axis, ratio: f64 = 0.5, before: bool = false };
+pub const Split = struct { axis: Axis, ratio: f64, span: i32 };
+const Size = struct { width: i32 = 0, height: i32 = 0 };
+pub const Node = struct {
+ member: ?Member = null,
+ children: ?struct { a: *Node, b: *Node } = null,
+ axis: Axis = .horizontal,
+ ratio: f64 = 0.5,
+ enabled: bool = false,
+ rect: ?Box = null,
+ split: ?Split = null,
+
+ fn destroy(node: *Node, allocator: Allocator) void {
+ if (node.children) |c| {
+ c.a.destroy(allocator);
+ c.b.destroy(allocator);
+ }
+ allocator.destroy(node);
+ }
+ fn find(node: *Node, key: Key) ?*Node {
+ if (node.member) |m| return if (std.meta.eql(m.key, key)) node else null;
+ const c = node.children.?;
+ return c.a.find(key) orelse c.b.find(key);
+ }
+ fn parent(node: *Node, key: Key) ?*Node {
+ const c = node.children orelse return null;
+ for ([_]*Node{ c.a, c.b }) |child| {
+ if (child.member) |m| if (std.meta.eql(m.key, key)) return node;
+ }
+ return c.a.parent(key) orelse c.b.parent(key);
+ }
+ fn clone(node: *const Node, allocator: Allocator) Allocator.Error!*Node {
+ const copy = try allocator.create(Node);
+ errdefer allocator.destroy(copy);
+ copy.* = node.*;
+ if (node.children) |c| {
+ const a = try c.a.clone(allocator);
+ errdefer a.destroy(allocator);
+ copy.children = .{ .a = a, .b = try c.b.clone(allocator) };
+ }
+ return copy;
+ }
+ fn firstKey(node: *Node) Key {
+ if (node.member) |m| return m.key;
+ const c = node.children.?;
+ return if (c.a.minimum(0).width > 0 or c.b.minimum(0).width == 0) c.a.firstKey() else c.b.firstKey();
+ }
+ fn splitFor(node: *Node, key: Key, axis: ?Axis) ?*Node {
+ const c = node.children orelse return null;
+ const child = if (c.a.find(key) != null) c.a else if (c.b.find(key) != null) c.b else return null;
+ if (child.splitFor(key, axis)) |found| return found;
+ if (node.split != null and (axis == null or node.axis == axis.?)) return node;
+ return null;
+ }
+ fn collect(node: *Node, allocator: Allocator, members: *std.ArrayList(Member)) Allocator.Error!void {
+ if (node.member) |m| return members.append(allocator, m);
+ const c = node.children.?;
+ try c.a.collect(allocator, members);
+ try c.b.collect(allocator, members);
+ }
+ fn minimum(node: *const Node, gap: i32) Size {
+ if (node.member) |m| return if (node.enabled) .{ .width = @max(1, m.min_width), .height = @max(1, m.min_height) } else .{};
+ const c = node.children.?;
+ const a = c.a.minimum(gap);
+ const b = c.b.minimum(gap);
+ if (a.width == 0) return b;
+ if (b.width == 0) return a;
+ return switch (node.axis) {
+ .horizontal => .{ .width = a.width +| b.width +| gap, .height = @max(a.height, b.height) },
+ .vertical => .{ .width = @max(a.width, b.width), .height = a.height +| b.height +| gap },
+ };
+ }
+ fn place(node: *Node, box: Box, gap: i32) void {
+ node.rect = null;
+ node.split = null;
+ if (node.member) |m| {
+ if (!node.enabled) return;
+ var rect = box;
+ if (m.max_width > 0) rect.width = @min(rect.width, @max(m.min_width, m.max_width));
+ if (m.max_height > 0) rect.height = @min(rect.height, @max(m.min_height, m.max_height));
+ node.rect = rect;
+ return;
+ }
+ const c = node.children.?;
+ const a = c.a.minimum(gap);
+ const b = c.b.minimum(gap);
+ if (a.width == 0 or b.width == 0) {
+ c.a.place(box, gap);
+ c.b.place(box, gap);
+ return;
+ }
+ var first = box;
+ var second = box;
+ switch (node.axis) {
+ .horizontal => {
+ const available = box.width - gap;
+ first.width = std.math.clamp(@as(i32, @intFromFloat(@round(@as(f64, @floatFromInt(available)) * node.ratio))), a.width, available - b.width);
+ second.x += first.width + gap;
+ second.width = available - first.width;
+ },
+ .vertical => {
+ const available = box.height - gap;
+ first.height = std.math.clamp(@as(i32, @intFromFloat(@round(@as(f64, @floatFromInt(available)) * node.ratio))), a.height, available - b.height);
+ second.y += first.height + gap;
+ second.height = available - first.height;
+ },
+ }
+ const span = if (node.axis == .horizontal) box.width - gap else box.height - gap;
+ node.split = .{ .axis = node.axis, .span = span, .ratio = @as(f64, @floatFromInt(if (node.axis == .horizontal) first.width else first.height)) / @as(f64, @floatFromInt(span)) };
+ c.a.place(first, gap);
+ c.b.place(second, gap);
+ }
+};
+
+pub const Tree = struct {
+ root: ?*Node = null,
+
+ pub fn deinit(tree: *Tree, allocator: Allocator) void {
+ if (tree.root) |node| node.destroy(allocator);
+ tree.* = .{};
+ }
+ pub fn contains(tree: *const Tree, key: Key) bool {
+ return if (tree.root) |node| node.find(key) != null else false;
+ }
+ pub fn rectangle(tree: *const Tree, key: Key) ?Box {
+ const node = (tree.root orelse return null).find(key) orelse return null;
+ return node.rect;
+ }
+ pub fn insert(tree: *Tree, allocator: Allocator, member: Member, beside: ?Key, axis: Axis) !void {
+ if (tree.contains(member.key)) return;
+ const leaf = try allocator.create(Node);
+ errdefer allocator.destroy(leaf);
+ leaf.* = .{ .member = member };
+ const root = tree.root orelse {
+ tree.root = leaf;
+ return;
+ };
+ var anchor = if (beside) |key| root.find(key) orelse root else root;
+ while (anchor.children) |c| anchor = c.b;
+ const previous = try allocator.create(Node);
+ previous.* = anchor.*;
+ anchor.* = .{ .children = .{ .a = previous, .b = leaf }, .axis = axis };
+ }
+ pub fn clone(tree: *const Tree, allocator: Allocator) !Tree {
+ return .{ .root = if (tree.root) |root| try root.clone(allocator) else null };
+ }
+ /// Compare placement, ignoring cached geometry and live client constraints.
+ pub fn eql(tree: *const Tree, other: *const Tree) bool {
+ return eqlNode(tree.root, other.root);
+ }
+ fn eqlNode(a: ?*const Node, b: ?*const Node) bool {
+ const first = a orelse return b == null;
+ const second = b orelse return false;
+ if (first.member) |member| {
+ return if (second.member) |other| std.meta.eql(member.key, other.key) else false;
+ }
+ if (second.member != null or first.axis != second.axis or first.ratio != second.ratio) return false;
+ const ac = first.children.?;
+ const bc = second.children.?;
+ return eqlNode(ac.a, bc.a) and eqlNode(ac.b, bc.b);
+ }
+ pub fn getMember(tree: *const Tree, key: Key) ?Member {
+ return ((tree.root orelse return null).find(key) orelse return null).member;
+ }
+ pub fn rename(tree: *Tree, old: Key, new: Key) void {
+ if (tree.contains(new)) return;
+ const node = (tree.root orelse return).find(old) orelse return;
+ node.member.?.key = new;
+ }
+ pub fn placement(tree: *const Tree, key: Key) ?Placement {
+ const parent = (tree.root orelse return null).parent(key) orelse return null;
+ const c = parent.children.?;
+ const before = c.a.find(key) != null;
+ return .{ .anchor = (if (before) c.b else c.a).firstKey(), .axis = parent.axis, .ratio = parent.ratio, .before = before };
+ }
+ pub fn insertAt(tree: *Tree, allocator: Allocator, value: Member, at: Placement) !void {
+ if (tree.contains(value.key)) return;
+ try tree.insert(allocator, value, at.anchor, at.axis);
+ const node = (tree.root orelse return).parent(value.key) orelse return;
+ node.ratio = std.math.clamp(at.ratio, 0.05, 0.95);
+ if (at.before) std.mem.swap(*Node, &node.children.?.a, &node.children.?.b);
+ }
+ pub fn splitFor(tree: *const Tree, key: Key, axis: ?Axis) ?Split {
+ return ((tree.root orelse return null).splitFor(key, axis) orelse return null).split;
+ }
+ pub fn setRatio(tree: *Tree, key: Key, axis: Axis, ratio: f64) void {
+ if (!std.math.isFinite(ratio)) return;
+ const node = (tree.root orelse return).splitFor(key, axis) orelse return;
+ node.ratio = std.math.clamp(ratio, 0.05, 0.95);
+ }
+ /// Used by drag previews on a private copy; admission order stays independent
+ /// of split traversal and survives swaps and subtree moves.
+ pub fn arrangeExisting(tree: *Tree, allocator: Allocator, usable: Box, gap: u32) !void {
+ const root = tree.root orelse return;
+ var members: std.ArrayList(Member) = .empty;
+ defer members.deinit(allocator);
+ try root.collect(allocator, &members);
+ std.mem.sort(Member, members.items, {}, struct {
+ fn less(_: void, a: Member, b: Member) bool {
+ return if (a.order != b.order) a.order < b.order else a.key.id < b.key.id;
+ }
+ }.less);
+ tree.arrange(members.items, usable, gap);
+ }
+ pub fn neighbor(tree: *const Tree, key: Key, direction: Direction) ?Key {
+ const source = tree.rectangle(key) orelse return null;
+ var result: ?Key = null;
+ var score: f64 = std.math.inf(f64);
+ neighborNode(tree.root orelse return null, key, source, direction, &result, &score);
+ return result;
+ }
+ fn neighborNode(node: *Node, key: Key, source: Box, direction: Direction, result: *?Key, best: *f64) void {
+ if (node.children) |c| {
+ neighborNode(c.a, key, source, direction, result, best);
+ neighborNode(c.b, key, source, direction, result, best);
+ return;
+ }
+ const m = node.member.?;
+ if (std.meta.eql(m.key, key)) return;
+ const box = node.rect orelse return;
+ const dx = @as(f64, @floatFromInt(box.x - source.x)) + @as(f64, @floatFromInt(box.width - source.width)) / 2;
+ const dy = @as(f64, @floatFromInt(box.y - source.y)) + @as(f64, @floatFromInt(box.height - source.height)) / 2;
+ const along = switch (direction) {
+ .left => -dx,
+ .right => dx,
+ .up => -dy,
+ .down => dy,
+ };
+ if (along <= 0) return;
+ const across = if (direction == .left or direction == .right) dy else dx;
+ const score = along * along + 4 * across * across;
+ if (score < best.*) {
+ best.* = score;
+ result.* = m.key;
+ }
+ }
+ pub fn remove(tree: *Tree, allocator: Allocator, key: Key) void {
+ tree.root = removeNode(tree.root, allocator, key);
+ }
+ fn removeNode(maybe_node: ?*Node, allocator: Allocator, key: Key) ?*Node {
+ const node = maybe_node orelse return null;
+ if (node.member) |m| {
+ if (!std.meta.eql(m.key, key)) return node;
+ allocator.destroy(node);
+ return null;
+ }
+ const c = node.children.?;
+ const a = removeNode(c.a, allocator, key);
+ const b = removeNode(c.b, allocator, key);
+ if (a != null and b != null) {
+ node.children = .{ .a = a.?, .b = b.? };
+ return node;
+ }
+ allocator.destroy(node);
+ return a orelse b;
+ }
+ pub fn swap(tree: *Tree, a: Key, b: Key) void {
+ const root = tree.root orelse return;
+ const one = root.find(a) orelse return;
+ const two = root.find(b) orelse return;
+ std.mem.swap(?Member, &one.member, &two.member);
+ }
+ pub fn rotate(tree: *Tree, key: Key) void {
+ const node = (tree.root orelse return).splitFor(key, null) orelse return;
+ node.axis = if (node.axis == .horizontal) .vertical else .horizontal;
+ }
+ pub fn resize(tree: *Tree, key: Key, delta: f64) void {
+ if (!std.math.isFinite(delta)) return;
+ const node = (tree.root orelse return).parent(key) orelse return;
+ node.ratio = std.math.clamp(node.ratio + delta, 0.05, 0.95);
+ }
+ fn missing(node: *Node, members: []const Member) ?Key {
+ if (node.member) |m| {
+ for (members) |candidate| if (std.meta.eql(m.key, candidate.key)) return null;
+ return m.key;
+ }
+ const c = node.children.?;
+ return missing(c.a, members) orelse missing(c.b, members);
+ }
+ /// Membership synchronization is transactional per insertion on allocation failure.
+ pub fn sync(tree: *Tree, allocator: Allocator, members: []const Member, usable: Box, requested_gap: u32) !void {
+ while (tree.root) |root| {
+ const key = missing(root, members) orelse break;
+ tree.remove(allocator, key);
+ }
+ if (tree.root) |root| {
+ for (members) |member| {
+ if (root.find(member.key)) |node| node.member = member;
+ }
+ }
+ tree.arrange(members, usable, requested_gap);
+ var beside: ?Key = null;
+ for (members) |member| {
+ if (!tree.contains(member.key)) {
+ var rect = usable;
+ if (beside) |key| rect = tree.rectangle(key) orelse usable;
+ try tree.insert(allocator, member, beside, if (rect.width >= rect.height) .horizontal else .vertical);
+ tree.arrange(members, usable, requested_gap);
+ }
+ if (tree.rectangle(member.key) != null) beside = member.key;
+ }
+ }
+ pub fn arrange(tree: *Tree, members: []const Member, usable: Box, requested_gap: u32) void {
+ const root = tree.root orelse return;
+ const gap: i32 = @intCast(@min(requested_gap, @as(u32, @intCast(@max(0, @divTrunc(@min(usable.width, usable.height) - 1, 2))))));
+ const box: Box = .{ .x = usable.x + gap, .y = usable.y + gap, .width = @max(0, usable.width - 2 * gap), .height = @max(0, usable.height - 2 * gap) };
+ disable(root);
+ for (members) |member| {
+ const node = root.find(member.key) orelse continue;
+ node.enabled = member.active;
+ const size = root.minimum(gap);
+ if (size.width > box.width or size.height > box.height) node.enabled = false;
+ }
+ root.place(box, gap);
+ }
+ fn disable(node: *Node) void {
+ node.enabled = false;
+ if (node.children) |c| {
+ disable(c.a);
+ disable(c.b);
+ }
+ }
+};
+
+const testing = std.testing;
+const screen: Box = .{ .x = -1280, .y = -120, .width = 1281, .height = 673 };
+test "stable splits, gaps, suspension, overflow and recovery" {
+ var tree: Tree = .{};
+ defer tree.deinit(testing.allocator);
+ var members = [_]Member{ .{ .key = .{ .id = 1 }, .min_width = 200 }, .{ .key = .{ .id = 2 }, .min_width = 200 }, .{ .key = .{ .id = 3 }, .min_width = 200 } };
+ try tree.sync(testing.allocator, &members, screen, 8);
+ const first = tree.rectangle(members[0].key).?;
+ const second = tree.rectangle(members[1].key).?;
+ const third = tree.rectangle(members[2].key).?;
+ try testing.expectEqual(first.x + first.width + 8, second.x);
+ try testing.expectEqual(second.y + second.height + 8, third.y);
+ try testing.expectEqual(screen.x + screen.width - 8, third.x + third.width);
+ try tree.sync(testing.allocator, &members, screen, 8);
+ try testing.expectEqual(first, tree.rectangle(members[0].key).?);
+ members[1].active = false;
+ try tree.sync(testing.allocator, &members, screen, 8);
+ try testing.expectEqual(first, tree.rectangle(members[0].key).?);
+ try testing.expectEqual(@as(?Box, null), tree.rectangle(members[1].key));
+ members[1].active = true;
+ members[2].min_width = 1200;
+ try tree.sync(testing.allocator, &members, screen, 8);
+ try testing.expectEqual(@as(?Box, null), tree.rectangle(members[2].key));
+ members[2].min_width = 200;
+ try tree.sync(testing.allocator, &members, screen, 8);
+ try testing.expectEqual(third, tree.rectangle(members[2].key).?);
+ try tree.sync(testing.allocator, members[0..1], screen, 8);
+ try testing.expectEqual(screen.width - 16, tree.rectangle(members[0].key).?.width);
+}
+
+test "rotation, resizing, swapping and bounded clients" {
+ var tree: Tree = .{};
+ defer tree.deinit(testing.allocator);
+ const members = [_]Member{ .{ .key = .{ .id = 1 } }, .{ .key = .{ .id = 2 }, .max_width = 300 } };
+ try tree.sync(testing.allocator, &members, screen, 8);
+ try testing.expectEqual(@as(i32, 300), tree.rectangle(members[1].key).?.width);
+ tree.swap(members[0].key, members[1].key);
+ tree.arrange(&members, screen, 8);
+ try testing.expect(tree.rectangle(members[1].key).?.x < tree.rectangle(members[0].key).?.x);
+ tree.rotate(members[0].key);
+ tree.resize(members[0].key, 0.2);
+ tree.arrange(&members, screen, 8);
+ try testing.expect(tree.rectangle(members[1].key).?.height > tree.rectangle(members[0].key).?.height);
+ tree.remove(testing.allocator, members[0].key);
+ tree.arrange(members[1..], screen, 8);
+ try testing.expect(!tree.contains(members[0].key));
+}
+
+test "insertion allocation failures preserve the original leaf" {
+ const Case = struct {
+ fn run(allocator: Allocator) !void {
+ var tree: Tree = .{};
+ defer tree.deinit(allocator);
+ const one: Member = .{ .key = .{ .id = 1 } };
+ try tree.insert(allocator, one, null, .horizontal);
+ tree.insert(allocator, .{ .key = .{ .id = 2 } }, one.key, .vertical) catch |err| {
+ try testing.expect(tree.contains(one.key));
+ return err;
+ };
+ }
+ };
+ try testing.checkAllAllocationFailures(testing.allocator, Case.run, .{});
+}
+
+test "directional controls, reinsertion and cancellation preserve surviving members" {
+ var tree: Tree = .{};
+ defer tree.deinit(testing.allocator);
+ const members = [_]Member{ .{ .key = .{ .id = 1 }, .order = 1 }, .{ .key = .{ .id = 2 }, .order = 2 }, .{ .key = .{ .id = 3 }, .order = 3 } };
+ try tree.sync(testing.allocator, &members, screen, 8);
+ const before = tree.rectangle(members[2].key).?;
+ const at = tree.placement(members[2].key).?;
+ tree.remove(testing.allocator, members[2].key);
+ try tree.insertAt(testing.allocator, members[2], at);
+ tree.arrange(&members, screen, 8);
+ try testing.expectEqual(before, tree.rectangle(members[2].key).?);
+ try testing.expectEqual(members[1].key, tree.neighbor(members[2].key, .up).?);
+ var saved = try tree.clone(testing.allocator);
+ defer saved.deinit(testing.allocator);
+ try testing.expect(tree.eql(&saved));
+ // Re-raster geometry alone is not a user layout change.
+ try saved.arrangeExisting(testing.allocator, .{ .x = -100, .y = 20, .width = 1100, .height = 720 }, 12);
+ try testing.expect(tree.eql(&saved));
+ const split = tree.splitFor(members[2].key, .horizontal).?;
+ tree.setRatio(members[2].key, split.axis, 0.8);
+ try testing.expect(!tree.eql(&saved));
+ tree.arrange(&members, screen, 8);
+ try testing.expect(tree.rectangle(members[2].key).?.width < before.width);
+ // A snapshot contains keys, not client pointers. Closing a neighbor while
+ // resizing and then cancelling prunes the closed leaf safely.
+ try saved.sync(testing.allocator, members[1..], screen, 8);
+ try testing.expect(!saved.contains(members[0].key));
+ try testing.expectEqual(before.height, saved.rectangle(members[2].key).?.height);
+ saved.rename(members[2].key, .{ .id = 42, .group = true });
+ try testing.expect(saved.contains(.{ .id = 42, .group = true }));
+}
+
+test "snapshot allocation failures leave a live layout intact" {
+ const Case = struct {
+ fn run(allocator: Allocator) !void {
+ var tree: Tree = .{};
+ defer tree.deinit(allocator);
+ try tree.insert(allocator, .{ .key = .{ .id = 1 } }, null, .horizontal);
+ try tree.insert(allocator, .{ .key = .{ .id = 2 } }, null, .vertical);
+ var copy = tree.clone(allocator) catch |err| {
+ try testing.expect(tree.contains(.{ .id = 1 }) and tree.contains(.{ .id = 2 }));
+ return err;
+ };
+ defer copy.deinit(allocator);
+ }
+ };
+ try testing.checkAllAllocationFailures(testing.allocator, Case.run, .{});
+}
diff --git a/src/auto_tiling.zig b/src/auto_tiling.zig
new file mode 100644
index 0000000..1fa14c5
--- /dev/null
+++ b/src/auto_tiling.zig
@@ -0,0 +1,362 @@
+//! Event-driven bridge from workspace membership to pure split geometry.
+const std = @import("std");
+const wl = @import("wayland").server.wl;
+const Server = @import("Server.zig");
+const Top = @import("Toplevel.zig");
+const layout = @import("auto_layout.zig");
+const gpa = @import("main.zig").gpa;
+
+pub const State = struct {
+ workspace: u8,
+ group: u64,
+ constraints: @import("resize.zig").SizeConstraints,
+ horizontal: i32,
+ vertical: i32,
+ excluded: bool,
+ suspended: bool,
+ hidden: bool,
+};
+
+pub fn isFloating(top: *const Top) bool {
+ if (top.auto_float_override) |value| return value;
+ if (top.auto_float) return true;
+ if (top.live_rules.floating) |value| return value;
+ for (top.server.config.compositor.floating_apps) |pattern| {
+ if (@import("config").window_rules.matchGlob(pattern, top.appId())) return true;
+ }
+ return false;
+}
+
+fn state(top: *Top) State {
+ const c = top.sizeConstraints();
+ const fixed = c.min_width > 0 and c.min_height > 0 and c.min_width == c.max_width and c.min_height == c.max_height;
+ return .{
+ .workspace = top.workspace_id,
+ .group = top.tab_group,
+ .constraints = c,
+ .horizontal = 2 * top.borderWidth(),
+ // Fullscreen/maximize decoration suppression must not alter the saved tile.
+ .vertical = top.titlebarHeight() + if (top.hasServerDecorations()) @import("chrome.zig").footerHeight(@import("chrome.zig").frameRadius() * top.chromeDensity()) else @as(i32, 0),
+ .excluded = isFloating(top) or top.tile != null or top.currentIdentity().dialog or fixed,
+ .suspended = top.minimized or top.fullscreen or top.maximized,
+ .hidden = top.tab_hidden,
+ };
+}
+
+pub fn observe(top: *Top) void {
+ if (!top.in_world or !top.server.world.workspaces.active) return;
+ const next = state(top);
+ if ((next.suspended or next.excluded or next.hidden) and top.server.input.tiling_grab != null and top.server.input.grabbed_toplevel == top)
+ top.server.input.finishTilingGrab(false);
+ if (top.auto_seen) |previous| if (std.meta.eql(next, previous)) return;
+ if (top.auto_seen) |previous| {
+ if (previous.group != next.group and previous.workspace == next.workspace and next.workspace != 0) {
+ const old: layout.Key = if (previous.group != 0) .{ .id = previous.group, .group = true } else .{ .id = top.workspace_order };
+ var shared = false;
+ var it = top.server.world.toplevels.iterator(.forward);
+ while (it.next()) |other| if (other != top and std.meta.eql(key(other), old)) {
+ shared = true;
+ break;
+ };
+ if (!shared) top.server.world.workspaces.tiler.trees[next.workspace - 1].rename(old, key(top));
+ }
+ }
+ top.auto_seen = next;
+ top.server.world.workspaces.tiler.schedule(top.server);
+}
+
+pub fn key(top: *Top) layout.Key {
+ return if (top.tab_group != 0) .{ .id = top.tab_group, .group = true } else .{ .id = top.workspace_order };
+}
+
+/// Manual placement opts the whole tab group out until explicitly rejoined.
+pub fn setFloating(top: *Top, floating: bool) void {
+ if (!top.server.world.workspaces.active) return;
+ var it = top.server.world.toplevels.iterator(.forward);
+ while (it.next()) |member| {
+ if (member != top and (top.tab_group == 0 or member.tab_group != top.tab_group)) continue;
+ if (floating and member.auto_target != null and member.workspace_id != 0)
+ member.auto_reinsert = top.server.world.workspaces.tiler.trees[member.workspace_id - 1].placement(key(member));
+ member.auto_float = floating;
+ member.auto_float_override = floating;
+ if (floating) member.clearAutoTile(false);
+ observe(member);
+ }
+ top.auto_float = floating;
+ top.auto_float_override = floating;
+ top.server.world.workspaces.tiler.schedule(top.server);
+}
+
+pub fn unmapped(top: *Top) void {
+ if (!top.server.world.workspaces.active or top.workspace_id == 0) return;
+ if (!top.auto_float) top.auto_reinsert = top.server.world.workspaces.tiler.trees[top.workspace_id - 1].placement(key(top));
+ top.auto_seen = null;
+}
+
+pub const Manager = struct {
+ trees: [@import("workspaces.zig").count]layout.Tree = @splat(.{}),
+ idle: ?*wl.EventSource = null,
+ applying: bool = false,
+
+ pub fn deinit(self: *Manager) void {
+ if (self.idle) |source| source.remove();
+ self.idle = null;
+ for (&self.trees) |*tree| tree.deinit(gpa);
+ }
+ pub fn schedule(self: *Manager, server: *Server) void {
+ if (!server.world.workspaces.active or self.applying or self.idle != null) return;
+ self.idle = server.wl_server.getEventLoop().addIdle(*Server, flush, server) catch null;
+ }
+ /// Resolve pending membership before a user operation takes a snapshot.
+ pub fn flushNow(self: *Manager, server: *Server) void {
+ if (self.applying or !server.world.workspaces.active) return;
+ if (self.idle) |source| source.remove();
+ flush(server);
+ }
+ fn flush(server: *Server) void {
+ const self = &server.world.workspaces.tiler;
+ self.idle = null;
+ if (!server.world.workspaces.active) return;
+ self.applying = true;
+ defer self.applying = false;
+ self.reflow(server) catch |err| {
+ std.log.warn("automatic layout: {s}", .{@errorName(err)});
+ return;
+ };
+ @import("tiling_grab.zig").refreshPreview(&server.input);
+ }
+ fn reflow(self: *Manager, server: *Server) !void {
+ var tops: std.ArrayList(*Top) = .empty;
+ defer tops.deinit(gpa);
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| try tops.append(gpa, top);
+ std.mem.sort(*Top, tops.items, {}, struct {
+ fn less(_: void, a: *Top, b: *Top) bool {
+ return a.workspace_order < b.workspace_order;
+ }
+ }.less);
+ var members: std.ArrayList(layout.Member) = .empty;
+ defer members.deinit(gpa);
+ for (&self.trees, 0..) |*tree, index| {
+ members.clearRetainingCapacity();
+ const output = server.world.workspaces.slots[index].output;
+ for (tops.items) |top| {
+ if (top.workspace_id != index + 1) continue;
+ const s = state(top);
+ const k = key(top);
+ var m: layout.Member = .{
+ .key = k,
+ .order = top.workspace_order,
+ .active = server.world.workspaces.slots[index].automatic and !s.excluded and !s.suspended and !s.hidden,
+ .min_width = @max(1, s.constraints.min_width) +| s.horizontal,
+ .min_height = @max(1, s.constraints.min_height) +| s.vertical,
+ .max_width = if (s.constraints.max_width > 0) s.constraints.max_width +| s.horizontal else 0,
+ .max_height = if (s.constraints.max_height > 0) s.constraints.max_height +| s.vertical else 0,
+ };
+ if (s.constraints.control_min_width > s.constraints.min_width and
+ (s.constraints.max_width == 0 or s.constraints.control_min_width <= s.constraints.max_width))
+ m.min_width = s.constraints.control_min_width +| s.horizontal;
+ // A group occupies one leaf. Inactive tabs contribute constraints
+ // so selecting a tab cannot shuffle neighbouring tiles.
+ var found = false;
+ for (members.items) |*existing| {
+ if (!std.meta.eql(existing.key, k)) continue;
+ existing.active = existing.active or m.active;
+ existing.order = @min(existing.order, m.order);
+ existing.min_width = @max(existing.min_width, m.min_width);
+ existing.min_height = @max(existing.min_height, m.min_height);
+ existing.max_width = boundedMin(existing.max_width, m.max_width);
+ existing.max_height = boundedMin(existing.max_height, m.max_height);
+ found = true;
+ break;
+ }
+ if (!found and !s.excluded) try members.append(gpa, m);
+ }
+ for (members.items) |*member| {
+ // Conflicting limits in a tab group have no valid shared tile.
+ // Keep the group floating instead of violating a client's max.
+ if ((member.max_width > 0 and member.min_width > member.max_width) or
+ (member.max_height > 0 and member.min_height > member.max_height)) member.active = false;
+ }
+ const box = if (output) |out| out.usableBox() else @import("wlroots").Box{ .x = 0, .y = 0, .width = 0, .height = 0 };
+ for (tops.items) |top| {
+ if (top.workspace_id != index + 1 or tree.contains(key(top))) continue;
+ const at = top.auto_reinsert orelse continue;
+ if (!tree.contains(at.anchor)) continue;
+ for (members.items) |m| if (std.meta.eql(m.key, key(top))) {
+ try tree.insertAt(gpa, m, at);
+ top.auto_reinsert = null;
+ break;
+ };
+ }
+ try tree.sync(gpa, members.items, .{ .x = box.x, .y = box.y, .width = box.width, .height = box.height }, server.config.compositor.windowGap());
+ for (tops.items) |top| {
+ if (top.workspace_id != index + 1) continue;
+ const s = state(top);
+ if (!s.excluded and !s.suspended and !s.hidden) {
+ if (tree.rectangle(key(top))) |rect| {
+ top.setAutoTile(.{ .x = rect.x, .y = rect.y, .width = rect.width, .height = rect.height });
+ } else top.clearAutoTile(true);
+ } else if (s.excluded) top.clearAutoTile(true);
+ top.auto_seen = state(top);
+ }
+ }
+ }
+};
+
+fn boundedMin(a: i32, b: i32) i32 {
+ return if (a == 0) b else if (b == 0) a else @min(a, b);
+}
+
+pub fn execute(server: *Server, target: ?*Top, action: @import("config").keybinds.TilingAction) void {
+ if (!server.world.workspaces.active or server.locker != null or server.polkit_dialog != null) return;
+ if (server.input.tiling_grab != null) server.input.finishTilingGrab(false);
+ const manager = &server.world.workspaces.tiler;
+ manager.flushNow(server);
+ if (action == .toggle_workspace_tiling) {
+ const id = if (target) |top| top.workspace_id else (server.getDefaultOutput() orelse return).workspace_id;
+ if (id == 0) return;
+ var transaction = @import("layout_undo.zig").Transaction.begin(server, &.{id});
+ defer transaction.finish();
+ const slot = &server.world.workspaces.slots[id - 1];
+ slot.automatic = !slot.automatic;
+ if (server.input.open_control_center) |cc| cc.refresh();
+ manager.schedule(server);
+ return;
+ }
+ const top = target orelse return;
+ if (!top.in_world or top.workspace_id == 0 or top.minimized or top.fullscreen or top.maximized or top.tab_hidden) return;
+ if (!@import("workspaces.zig").visible(top)) return;
+ var transaction = @import("layout_undo.zig").Transaction.begin(server, &.{top.workspace_id});
+ defer transaction.finish();
+ const tree = &manager.trees[top.workspace_id - 1];
+ if (action == .toggle_floating) {
+ // Dialogs and fixed-size utilities are floating exceptions, not tiles.
+ const c = top.sizeConstraints();
+ if (top.currentIdentity().dialog or (c.min_width > 0 and c.min_height > 0 and c.min_width == c.max_width and c.min_height == c.max_height)) return;
+ const floating = !isFloating(top) and top.tile == null;
+ const saved = top.auto_restore;
+ if (!floating) top.leaveLayout();
+ setFloating(top, floating);
+ if (floating) if (saved) |geometry| top.restoreGeometryNow(geometry);
+ } else {
+ if (top.auto_target == null or !server.world.workspaces.slots[top.workspace_id - 1].automatic) return;
+ switch (action) {
+ .toggle_split => {
+ if (tree.splitFor(key(top), null) == null) return;
+ tree.rotate(key(top));
+ },
+ .swap_left, .swap_right, .swap_up, .swap_down => {
+ const direction: layout.Direction = switch (action) {
+ .swap_left => .left,
+ .swap_right => .right,
+ .swap_up => .up,
+ else => .down,
+ };
+ const other = tree.neighbor(key(top), direction) orelse return;
+ tree.swap(key(top), other);
+ },
+ .resize_split_left, .resize_split_right, .resize_split_up, .resize_split_down => {
+ const horizontal = action == .resize_split_left or action == .resize_split_right;
+ const split = tree.splitFor(key(top), if (horizontal) .horizontal else .vertical) orelse return;
+ const delta: f64 = if (action == .resize_split_left or action == .resize_split_up) -32 else 32;
+ tree.setRatio(key(top), split.axis, split.ratio + delta / @as(f64, @floatFromInt(split.span)));
+ },
+ else => unreachable,
+ }
+ }
+ manager.schedule(server);
+}
+
+pub const Drop = struct {
+ workspace: u8,
+ anchor: ?layout.Key = null,
+ axis: layout.Axis = .horizontal,
+ before: bool = false,
+};
+pub const PreparedDrop = struct { tree: ?layout.Tree, rect: @import("wlroots").Box };
+
+pub fn dropAt(top: *Top, x: f64, y: f64) ?Drop {
+ const server = top.server;
+ const output = @import("Output.zig").atLayout(server, x, y) orelse return null;
+ const id = output.workspace_id;
+ if (id == 0) return null;
+ if (!server.world.workspaces.slots[id - 1].automatic) return .{ .workspace = id };
+ if (id == top.workspace_id) if (server.world.workspaces.tiler.trees[id - 1].rectangle(key(top))) |box| {
+ if (x >= @as(f64, @floatFromInt(box.x)) and y >= @as(f64, @floatFromInt(box.y)) and
+ x < @as(f64, @floatFromInt(box.x + box.width)) and y < @as(f64, @floatFromInt(box.y + box.height))) return null;
+ };
+ var nearest: ?*Top = null;
+ var distance: f64 = std.math.inf(f64);
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |candidate| {
+ if (candidate.workspace_id != id or candidate.tab_hidden or candidate.minimized or candidate.maximized or candidate.fullscreen or candidate.auto_target == null) continue;
+ if (std.meta.eql(key(candidate), key(top))) continue;
+ const box = server.world.workspaces.tiler.trees[id - 1].rectangle(key(candidate)) orelse continue;
+ const dx = @max(0, @max(@as(f64, @floatFromInt(box.x)) - x, x - @as(f64, @floatFromInt(box.x + box.width))));
+ const dy = @max(0, @max(@as(f64, @floatFromInt(box.y)) - y, y - @as(f64, @floatFromInt(box.y + box.height))));
+ const d = dx * dx + dy * dy;
+ if (d < distance or (d == distance and nearest != null and candidate.workspace_order < nearest.?.workspace_order)) {
+ nearest = candidate;
+ distance = d;
+ }
+ }
+ const other = nearest orelse return if (id != top.workspace_id) .{ .workspace = id } else null;
+ const box = server.world.workspaces.tiler.trees[id - 1].rectangle(key(other)).?;
+ const dx = (x - @as(f64, @floatFromInt(box.x))) / @as(f64, @floatFromInt(@max(1, box.width))) - 0.5;
+ const dy = (y - @as(f64, @floatFromInt(box.y))) / @as(f64, @floatFromInt(@max(1, box.height))) - 0.5;
+ const horizontal = @abs(dx) >= @abs(dy);
+ return .{ .workspace = id, .anchor = key(other), .axis = if (horizontal) .horizontal else .vertical, .before = if (horizontal) dx < 0 else dy < 0 };
+}
+
+pub fn prepareDrop(top: *Top, drop: Drop) !?PreparedDrop {
+ const server = top.server;
+ const slot = &server.world.workspaces.slots[drop.workspace - 1];
+ const output = slot.output orelse return null;
+ const usable = output.usableBox();
+ if (!slot.automatic) {
+ const saved = top.auto_restore orelse top.rememberGeometry();
+ const width = saved.width + 2 * top.borderWidth();
+ const height = saved.height + top.titlebarHeight() + top.footerHeight();
+ return .{ .tree = null, .rect = .{
+ .x = std.math.clamp(@as(i32, @intFromFloat(server.input.cursor.x)) - @divTrunc(width, 2), usable.x, usable.x + @max(0, usable.width - width)),
+ .y = std.math.clamp(@as(i32, @intFromFloat(server.input.cursor.y)) - @divTrunc(top.titlebarHeight(), 2), usable.y, usable.y + @max(0, usable.height - height)),
+ .width = width,
+ .height = height,
+ } };
+ }
+ const source = &server.world.workspaces.tiler.trees[top.workspace_id - 1];
+ const value = source.getMember(key(top)) orelse return null;
+ var copy = try server.world.workspaces.tiler.trees[drop.workspace - 1].clone(gpa);
+ var keep = false;
+ defer if (!keep) copy.deinit(gpa);
+ copy.remove(gpa, value.key);
+ if (drop.anchor) |anchor| {
+ if (!copy.contains(anchor)) return null;
+ try copy.insertAt(gpa, value, .{ .anchor = anchor, .axis = drop.axis, .before = drop.before });
+ } else try copy.insert(gpa, value, null, .horizontal);
+ try copy.arrangeExisting(gpa, .{ .x = usable.x, .y = usable.y, .width = usable.width, .height = usable.height }, server.config.compositor.windowGap());
+ const rect = copy.rectangle(value.key) orelse return null;
+ // Refuse an insertion that would evict any of the target's current tiles.
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |other| {
+ if (other.workspace_id != drop.workspace or other.auto_target == null or other.minimized or other.fullscreen or other.maximized or other.tab_hidden) continue;
+ if (copy.rectangle(key(other)) == null) return null;
+ }
+ keep = true;
+ return .{ .tree = copy, .rect = .{ .x = rect.x, .y = rect.y, .width = rect.width, .height = rect.height } };
+}
+
+pub fn commitDrop(top: *Top, drop: Drop, prepared: *PreparedDrop) void {
+ const server = top.server;
+ var transaction = @import("layout_undo.zig").Transaction.begin(server, &.{ top.workspace_id, drop.workspace });
+ defer transaction.finish();
+ if (prepared.tree) |tree| {
+ const target = &server.world.workspaces.tiler.trees[drop.workspace - 1];
+ target.deinit(gpa);
+ target.* = tree;
+ prepared.tree = null;
+ }
+ if (drop.workspace != top.workspace_id) server.world.workspaces.moveTo(top, drop.workspace);
+ server.world.workspaces.tiler.schedule(server);
+}
diff --git a/src/chrome.zig b/src/chrome.zig
index b78c89c..0b05ad7 100644
--- a/src/chrome.zig
+++ b/src/chrome.zig
@@ -252,6 +252,7 @@ pub const ChromeState = struct {
tabs: @import("chrome_tabs.zig").Strip = .{},
radius: f32,
active: bool = false,
+ workspace_focus: bool = false,
maximized: bool = false,
density: f32 = 1,
title: []const u8 = "",
@@ -291,6 +292,8 @@ pub const TitlebarMemo = struct {
radius: f32,
density: f32 = 1,
active: bool = false,
+ workspace_focus: bool = false,
+ workspace_active_border: [4]f32 = @splat(0),
// wlroots strdup's the title on set_title, so pointer equality implies
// content equality without owning a copy of the string.
title_ptr: ?[*:0]const u8,
@@ -324,6 +327,8 @@ pub const TitlebarMemo = struct {
.radius = state.radius,
.density = state.density,
.active = state.active,
+ .workspace_focus = state.workspace_focus,
+ .workspace_active_border = t.workspace_active_border,
.title_ptr = title_ptr,
.tabs_hash = @import("chrome_tabs.zig").hash(state.tabs),
.scale = state.scale,
@@ -358,12 +363,13 @@ pub const TitlebarMemo = struct {
}
/// Whether `ChromeBuffer.createUpdated` can derive `b` from the buffer
- /// painted for `a`: only hover, the hovered control, title or weight differ.
+ /// painted for `a`: only hover, focus, the hovered control, title or weight differ.
pub fn reusableFor(a: TitlebarMemo, b: TitlebarMemo) bool {
var normalized = a;
normalized.title_ptr = b.title_ptr;
normalized.tabs_hash = b.tabs_hash;
normalized.active = b.active;
+ normalized.workspace_focus = b.workspace_focus;
return normalized.stableEql(b);
}
@@ -373,13 +379,14 @@ pub const TitlebarMemo = struct {
if (a.height != b.height) return false;
if (a.radius != b.radius or a.density != b.density) return false;
if (a.active != b.active) return false;
+ if (a.workspace_focus != b.workspace_focus) return false;
if (a.title_ptr != b.title_ptr or a.tabs_hash != b.tabs_hash) return false;
if (a.scale != b.scale) return false;
if (a.hover != b.hover) return false;
if (a.chip_pos != b.chip_pos or a.chip_alpha != b.chip_alpha) return false;
if (a.maximized != b.maximized) return false;
if (!iconEql(a.icon, b.icon)) return false;
- inline for (.{ "glass", "border", "border_soft", "fg", "dim", "border_hover", "surface_hover", "danger", "close_fg" }) |field| {
+ inline for (.{ "glass", "border", "border_soft", "fg", "dim", "border_hover", "surface_hover", "danger", "close_fg", "workspace_active_border" }) |field| {
if (!rgbaEql(@field(a, field), @field(b, field))) return false;
}
return a.close_hover_alpha == b.close_hover_alpha and a.title_size == b.title_size and a.chrome_height == b.chrome_height and a.chrome_control_gap == b.chrome_control_gap and a.chrome_round_buttons == b.chrome_round_buttons;
@@ -396,6 +403,8 @@ pub const FooterMemo = struct {
skirt_fill: ?[4]f32,
scale: f32,
hover: f32,
+ workspace_focus: bool = false,
+ workspace_active_border: [4]f32 = @splat(0),
glass: [4]f32,
border: [4]f32,
border_hover: [4]f32,
@@ -410,6 +419,8 @@ pub const FooterMemo = struct {
.skirt_fill = state.skirt_fill,
.scale = state.scale,
.hover = state.hover,
+ .workspace_focus = state.workspace_focus,
+ .workspace_active_border = t.workspace_active_border,
.glass = t.window_bg,
.border = t.window_border,
.border_hover = t.window_border_hover,
@@ -419,6 +430,7 @@ pub const FooterMemo = struct {
pub fn stableEql(a: FooterMemo, b: FooterMemo) bool {
var normalized = a;
normalized.hover = b.hover;
+ normalized.workspace_focus = b.workspace_focus;
return normalized.eql(b);
}
@@ -429,7 +441,8 @@ pub const FooterMemo = struct {
if (!optionalRgbaEql(a.skirt_fill, b.skirt_fill)) return false;
if (a.scale != b.scale) return false;
if (a.hover != b.hover) return false;
- inline for (.{ "glass", "border", "border_hover" }) |field| {
+ if (a.workspace_focus != b.workspace_focus) return false;
+ inline for (.{ "glass", "border", "border_hover", "workspace_active_border" }) |field| {
if (!rgbaEql(@field(a, field), @field(b, field))) return false;
}
return true;
@@ -564,10 +577,10 @@ pub const ChromeBuffer = struct {
frame.state = state;
frame.base.init(&impl, frame.width, frame.height);
const corners: i32 = @min(frame.logical_width, @as(i32, @intFromFloat(@ceil(state.radius))) + 1);
- const border_changed = previous.state.hover != state.hover;
+ const border_changed = previous.state.hover != state.hover or previous.state.workspace_focus != state.workspace_focus;
if (state.tabs.tabs.len > 0 and frame.band == .titlebar) {
const tabs = @import("chrome_tabs.zig");
- if (previous.tabs_layout_hash == tabs.layoutHash(state.tabs) and
+ if (!border_changed and previous.tabs_layout_hash == tabs.layoutHash(state.tabs) and
previous.state.hover == state.hover and previous.state.chip_pos == state.chip_pos and previous.state.chip_alpha == state.chip_alpha and previous.state.maximized == state.maximized)
{
const geom = tabs.geometry(frame.logical_width, state.density, state.tabs);
@@ -690,7 +703,7 @@ pub const ChromeBuffer = struct {
const icon_left: f32 = @floatFromInt(m.length(title_inset));
const icon_top: f32 = @floatFromInt(@divTrunc(m.titlebarHeight() - m.iconSize(), 2));
// Hover gently brightens the same border used by the straight edges.
- const edge_color = borderFill(frame.state.hover);
+ const edge_color = windowBorderFill(frame.state.hover, frame.state.workspace_focus);
// The titlebar uses the window tint. The
// skirt continues the client, so it takes the client's own edge colour.
const base = switch (frame.band) {
@@ -1273,6 +1286,14 @@ pub fn borderColor(hover: f32) col.Premul {
return borderFill(hover).straight().premultiply();
}
+fn windowBorderFill(hover: f32, workspace_focus: bool) Color {
+ return if (workspace_focus) Color.fromRgba(theme.global.workspace_active_border) else borderFill(hover);
+}
+
+pub fn windowBorderColor(hover: f32, workspace_focus: bool) col.Premul {
+ return windowBorderFill(hover, workspace_focus).straight().premultiply();
+}
+
/// Chrome backing beneath the border, shared by the header and client sides.
pub fn fillColor() col.Premul {
return Color.chrome().straight().premultiply();
@@ -1859,6 +1880,7 @@ test "cached chrome updates exactly match complete rasters across hover controls
state.chip_alpha = if (control == null) 0.35 else 1;
state.title = titles[step % titles.len];
state.active = step % 2 == 0;
+ state.workspace_focus = step % 3 == 0;
step += 1;
const expected = try ChromeBuffer.create(width, 350, band, state);
defer expected.base.drop();
diff --git a/src/config/default.zig b/src/config/default.zig
index e27630f..9e656c0 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -106,6 +106,10 @@ pub const source =
\\env = "none" # none | fcitx | ibus; daemon uses [[autostart]]
\\
\\[compositor]
+ \\# Optional automatically tiled workspaces; canvas remains the default.
+ \\# Workspace shortcuts are overridden separately in [keybinds.workspace].
+ \\desktop_mode = "canvas"
+ \\floating_apps = [] # app ID glob patterns that float in workspaces
\\# Allow fullscreen clients to request asynchronous presentation (may tear).
\\allow_tearing = false
\\# Only windows launched with the chrome + join that window’s tabs.
@@ -128,7 +132,8 @@ pub const source =
\\camera_zoom_min = 0.25
\\camera_zoom_max = 1.0
\\focus_zoom = "boost" # Window switching: keep, boost, or camera
- \\window_gap = 0 # px around and between snapped windows
+ \\# Default tile gap: 0 px in canvas, 8 px in workspaces. Uncomment to override.
+ \\# window_gap = 8 # px around and between tiled windows
\\snap_to_edges = true # drag a window to a screen edge to tile or maximize it
\\dodge_file_drags = true # a file manager slides aside while you drag a file out of it
\\switcher_opacity = 1.0 # 0.0-1.0, background only; previews stay opaque
diff --git a/src/config/keybinds.zig b/src/config/keybinds.zig
index 770aeec..2f3338d 100644
--- a/src/config/keybinds.zig
+++ b/src/config/keybinds.zig
@@ -17,8 +17,26 @@ const xkb = @import("xkbcommon");
const log = std.log.scoped(.config);
+pub const TilingAction = enum { toggle_floating, toggle_split, toggle_workspace_tiling, swap_left, swap_right, swap_up, swap_down, resize_split_left, resize_split_right, resize_split_up, resize_split_down };
+
pub const Action = union(enum) {
+ toggle_floating,
+ toggle_split,
+ toggle_workspace_tiling,
+ swap_left,
+ swap_right,
+ swap_up,
+ swap_down,
+ resize_split_left,
+ resize_split_right,
+ resize_split_up,
+ resize_split_down,
noop,
+ workspace: u8,
+ move_to_workspace: u8,
+ workspace_next,
+ workspace_prev,
+ toggle_power_menu,
volume_up,
volume_down,
volume_mute,
diff --git a/src/config/keymap.zig b/src/config/keymap.zig
index 7a172f4..59204dc 100644
--- a/src/config/keymap.zig
+++ b/src/config/keymap.zig
@@ -30,10 +30,24 @@ pub fn bindingSyms(config: anytype, state: *xkb.State, key: xkb.Keycode, mods: a
const active = state.keyGetSyms(key);
for (active) |sym| if (config.lookupKeybind(mods, sym) != null) return active;
const layout = state.keyGetLayout(key);
- if (layout == 0 or layout == std.math.maxInt(u32)) return active;
+ if (layout == std.math.maxInt(u32)) return active;
const level = state.keyGetLevel(key, layout);
if (level == std.math.maxInt(u32)) return active;
- return state.getKeymap().keyGetSymsByLevel(key, 0, level);
+ const shifted_fallback = state.getKeymap().keyGetSymsByLevel(key, 0, level);
+ if (layout != 0) for (shifted_fallback) |sym| {
+ if (config.lookupKeybind(mods, sym) != null) return shifted_fallback;
+ };
+ // Shift+number bindings name the number row, although XKB emits !/@/….
+ // Prefer an explicit shifted-symbol binding; then try the unshifted key
+ // while retaining the full modifier mask. Text still uses active XKB state.
+ if (mods.shift) {
+ const base = state.getKeymap().keyGetSymsByLevel(key, layout, 0);
+ for (base) |sym| if (config.lookupKeybind(mods, sym) != null) return base;
+ const fallback = state.getKeymap().keyGetSymsByLevel(key, 0, 0);
+ for (fallback) |sym| if (config.lookupKeybind(mods, sym) != null) return fallback;
+ }
+ if (layout == 0) return active;
+ return shifted_fallback;
}
pub fn namesEqual(a: anytype, b: @TypeOf(a)) bool {
diff --git a/src/config/loader.zig b/src/config/loader.zig
index fd87fab..7e29469 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -117,7 +117,11 @@ pub const RegionConfig = struct {
pub const TaskbarItems = @import("taskbar_items.zig").Config;
+pub const DesktopMode = enum { canvas, workspaces };
+
pub const CompositorConfig = struct {
+ desktop_mode: DesktopMode = .canvas,
+ floating_apps: []const []const u8 = &.{},
default_file_manager: []const u8 = "",
default_terminal: []const u8 = "",
taskbar_items: TaskbarItems = .{},
@@ -143,8 +147,8 @@ pub const CompositorConfig = struct {
camera_zoom_max: f32 = 1.0,
/// How explicit window switching brings a small window into focus.
focus_zoom: types.FocusZoom = .boost,
- /// Space around and between half/quarter tiles (snap.tileRect).
- window_gap: u32 = 0,
+ /// Explicit space around/between tiles. Unset uses the active mode's default.
+ window_gap: ?u32 = null,
/// Dragging a window to an open screen edge tiles or maximizes it.
snap_to_edges: bool = true,
/// A file manager slides aside while a file is dragged out of it; see
@@ -175,6 +179,10 @@ pub const CompositorConfig = struct {
/// Lock before the system sleeps, however sleep was requested; logind
/// waits until the lock is on screen (`session/power.zig`).
lock_on_suspend: bool = true,
+
+ pub fn windowGap(self: CompositorConfig) u32 {
+ return self.window_gap orelse if (self.desktop_mode == .workspaces) 8 else 0;
+ }
};
pub const LidAction = types.LidAction;
@@ -271,6 +279,8 @@ pub const Config = struct {
ipc: IpcConfig = .{},
outputs: []OutputConfig = &.{},
keybinds: []Keybind = &.{},
+ workspace_keybinds: []Keybind = &.{},
+ workspace_lookup: std.AutoHashMapUnmanaged(u64, usize) = .empty,
lookup: std.AutoHashMapUnmanaged(u64, usize) = .empty,
autostart: [][]const u8 = &.{},
window_rules: []WindowRule = &.{},
@@ -287,9 +297,14 @@ pub const Config = struct {
}
pub fn lookupKeybind(self: *const Config, mods: anytype, sym: xkb.Keysym) ?Action {
+ if (self.compositor.desktop_mode == .workspaces) return keybinds.lookupKey(self.workspace_keybinds, self.workspace_lookup, mods, sym);
return keybinds.lookupKey(self.keybinds, self.lookup, mods, sym);
}
+ pub fn activeKeybinds(self: *const Config) []Keybind {
+ return if (self.compositor.desktop_mode == .workspaces) self.workspace_keybinds else self.keybinds;
+ }
+
pub fn sandboxAllowGroups(self: *const Config, app_id: ?[]const u8, engine: ?[]const u8) sandbox_allow.GroupSet {
if (app_id == null) return sandbox_allow.GroupSet.initEmpty();
var set = sandbox_allow.GroupSet.initEmpty();
@@ -309,6 +324,7 @@ pub fn default(allocator: Allocator) !Config {
errdefer cfg.deinit();
cfg.keyboard_keymap = try @import("keymap.zig").compile(allocator, cfg.input);
try applyDefaultKeybinds(&cfg);
+ try applyWorkspaceKeybinds(&cfg, .empty);
return cfg;
}
@@ -454,6 +470,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config
var seen_frame_radius = false;
var autostart_list: std.ArrayListUnmanaged([]const u8) = .empty;
var bind_list: std.ArrayListUnmanaged(Keybind) = .empty;
+ var workspace_binds: std.ArrayListUnmanaged(Keybind) = .empty;
var outputs_list: std.ArrayListUnmanaged(OutputConfig) = .empty;
var current_output: OutputConfig = .{};
var have_current_output = false;
@@ -591,7 +608,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config
fail(path, line_no, "invalid night_light field '{s}': {s}", .{ key, @errorName(err) });
return error.InvalidConfig;
},
- .keybinds => {
+ .keybinds, .workspace_keybinds => {
const spec = keybinds.parseKeybind(key) catch {
fail(path, line_no, "invalid keybind '{s}'", .{key});
return error.InvalidConfig;
@@ -604,7 +621,8 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config
fail(path, line_no, "invalid action '{s}'", .{action_str});
return error.InvalidConfig;
};
- bind_list.append(cfg.arena.allocator(), .{
+ const list = if (section == .workspace_keybinds) &workspace_binds else &bind_list;
+ list.append(cfg.arena.allocator(), .{
.modifiers = spec.modifiers,
.sym = spec.sym,
.action = action,
@@ -686,6 +704,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config
} else {
try applyDefaultKeybinds(&cfg);
}
+ try applyWorkspaceKeybinds(&cfg, workspace_binds);
cfg.autostart = autostart_list.items;
cfg.outputs = outputs_list.items;
var have_primary = false;
@@ -721,6 +740,7 @@ const Section = union(enum) {
autostart,
outputs,
keybinds,
+ workspace_keybinds,
polkit,
idle,
window_rules,
@@ -793,6 +813,7 @@ fn parseSection(line: []const u8) !Section {
}
const close = std.mem.indexOfScalar(u8, line, ']') orelse return error.InvalidConfig;
const name = line[1..close];
+ if (std.mem.eql(u8, name, "keybinds.workspace")) return .workspace_keybinds;
// Array tables and internal tags are deliberately not accepted here.
inline for (.{ .theme, .taskbar_theme, .input, .input_method, .compositor, .region, .keybinds, .polkit, .idle, .night_light, .notifications, .desktop, .ipc, .animations }) |tag| {
if (std.mem.eql(u8, name, @tagName(tag))) return tag;
@@ -843,6 +864,24 @@ fn parseKeybindsOnly(allocator: Allocator, bytes: []const u8) ![]Keybind {
return list.items;
}
+fn applyWorkspaceKeybinds(cfg: *Config, overrides: std.ArrayListUnmanaged(Keybind)) !void {
+ const a = cfg.arena.allocator();
+ var list = overrides;
+ const defaults = try parseKeybindsOnly(a, @import("workspace_defaults.zig").source);
+ const canvas = try parseKeybindsOnly(a, default_file.source);
+ for ([_][]Keybind{ defaults, canvas }, 0..) |binds, source| for (binds) |bind| {
+ if (source == 1 and !keybinds.isHardwareAction(bind.action) and bind.action != .restore_shortcuts) continue;
+ const key = keybinds.pack(bind.modifiers, bind.sym);
+ const overridden = for (list.items) |custom| {
+ if (keybinds.pack(custom.modifiers, custom.sym) == key) break true;
+ } else false;
+ if (!overridden) try list.append(a, bind);
+ };
+ cfg.workspace_keybinds = list.items;
+ cfg.workspace_lookup = .empty;
+ for (list.items, 0..) |bind, i| try cfg.workspace_lookup.put(a, keybinds.pack(bind.modifiers, bind.sym), i);
+}
+
fn rebuildLookup(cfg: *Config) !void {
cfg.lookup = .empty;
const a = cfg.arena.allocator();
@@ -943,6 +982,8 @@ const region_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(RegionConfig),
};
const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(CompositorConfig), FieldRule, null) = .{
+ .desktop_mode = .enumeration,
+ .floating_apps = .json_string_list,
.taskbar_items = .taskbar_items,
.taskbar_position = .enumeration,
.window_tab_apps = .json_string_list,
@@ -1661,6 +1702,12 @@ test "config field parsing preserves ranges and derived zoom state" {
}
var c = CompositorConfig{};
+ try std.testing.expectEqual(@as(u32, 0), c.windowGap());
+ c.desktop_mode = .workspaces;
+ try std.testing.expectEqual(@as(u32, 8), c.windowGap());
+ try applyCompositorKey(&c, a, "window_gap", "0");
+ try std.testing.expectEqual(@as(u32, 0), c.windowGap());
+ c.desktop_mode = .canvas;
inline for (.{
.{ "canvas_width", "1", "100000", "0", "100001" },
.{ "canvas_height", "1", "100000", "0", "100001" },
@@ -1668,9 +1715,9 @@ test "config field parsing preserves ranges and derived zoom state" {
.{ "border_radius", "0", "128", "129", "130" },
}) |fixture| {
try applyCompositorKey(&c, a, fixture[0], fixture[1]);
- try std.testing.expectEqual(try std.fmt.parseInt(u32, fixture[1], 10), @field(c, fixture[0]));
+ try std.testing.expectEqual(@as(@TypeOf(@field(c, fixture[0])), try std.fmt.parseInt(u32, fixture[1], 10)), @field(c, fixture[0]));
try applyCompositorKey(&c, a, fixture[0], fixture[2]);
- try std.testing.expectEqual(try std.fmt.parseInt(u32, fixture[2], 10), @field(c, fixture[0]));
+ try std.testing.expectEqual(@as(@TypeOf(@field(c, fixture[0])), try std.fmt.parseInt(u32, fixture[2], 10)), @field(c, fixture[0]));
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, fixture[0], fixture[3]));
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, fixture[0], fixture[4]));
}
@@ -2173,3 +2220,29 @@ test "mini map defaults and validated configuration" {
try std.testing.expectError(error.InvalidConfig, parse(a, "[compositor]\n" ++ line ++ "\n", "invalid"));
}
}
+
+test "workspace preset is independent, overrides include noop, and mode preserves canvas bindings" {
+ var cfg = try parse(std.testing.allocator, "[keybinds]\n\"Super+q\" = \"spawn custom-canvas\"\n" ++
+ "[keybinds.workspace]\n\"Super+c\" = \"noop\"\n\"Super+F12\" = \"workspace 8\"\n", "test");
+ defer cfg.deinit();
+ const q = try keybinds.parseKeybind("Super+q");
+ const c = try keybinds.parseKeybind("Super+c");
+ const two = try keybinds.parseKeybind("Super+2");
+ try std.testing.expectEqualStrings("custom-canvas", cfg.lookupKeybind(q.modifiers, q.sym).?.spawn);
+ cfg.compositor.desktop_mode = .workspaces;
+ try std.testing.expectEqualStrings("default-terminal", cfg.lookupKeybind(q.modifiers, q.sym).?.spawn);
+ try std.testing.expectEqual(Action.noop, cfg.lookupKeybind(c.modifiers, c.sym).?);
+ try std.testing.expectEqual(@as(u8, 2), cfg.lookupKeybind(two.modifiers, two.sym).?.workspace);
+ const v = try keybinds.parseKeybind("Super+v");
+ const rotate = try keybinds.parseKeybind("Super+j");
+ const swap = try keybinds.parseKeybind("Super+Shift+Right");
+ const split = try keybinds.parseKeybind("Super+Ctrl+Right");
+ try std.testing.expectEqual(Action.toggle_floating, cfg.lookupKeybind(v.modifiers, v.sym).?);
+ try std.testing.expectEqual(Action.toggle_split, cfg.lookupKeybind(rotate.modifiers, rotate.sym).?);
+ try std.testing.expectEqual(Action.swap_right, cfg.lookupKeybind(swap.modifiers, swap.sym).?);
+ try std.testing.expectEqual(Action.resize_split_right, cfg.lookupKeybind(split.modifiers, split.sym).?);
+ cfg.compositor.desktop_mode = .canvas;
+ try std.testing.expectEqual(@as(?Action, null), cfg.lookupKeybind(v.modifiers, v.sym));
+ try std.testing.expectEqualStrings("custom-canvas", cfg.lookupKeybind(q.modifiers, q.sym).?.spawn);
+ try std.testing.expectEqual(@as(?Action, null), cfg.lookupKeybind(two.modifiers, two.sym));
+}
diff --git a/src/config/mod.zig b/src/config/mod.zig
index 0d9f4a4..6f54b47 100644
--- a/src/config/mod.zig
+++ b/src/config/mod.zig
@@ -16,6 +16,7 @@ pub const setting_save = @import("setting_save.zig");
pub const shortcut_save = @import("shortcut_save.zig");
pub const taskbar_items = @import("taskbar_items.zig");
pub const types = @import("types.zig");
+pub const workspace_layout = @import("workspace_layout.zig");
pub const window_rules = @import("window_rules.zig");
test {
diff --git a/src/config/setting_save.zig b/src/config/setting_save.zig
index 9b5fe98..eee6507 100644
--- a/src/config/setting_save.zig
+++ b/src/config/setting_save.zig
@@ -10,7 +10,9 @@ pub fn saveInput(allocator: std.mem.Allocator, io: Io, path: []const u8, comptim
}
pub fn saveCompositor(allocator: std.mem.Allocator, io: Io, path: []const u8, comptime key: []const u8, value: @FieldType(loader.CompositorConfig, key)) !void {
- try save(allocator, io, path, "compositor", key, value);
+ if (@typeInfo(@TypeOf(value)) == .optional) {
+ try save(allocator, io, path, "compositor", key, value orelse return error.InvalidValue);
+ } else try save(allocator, io, path, "compositor", key, value);
}
pub fn saveRegion(allocator: std.mem.Allocator, io: Io, path: []const u8, comptime key: []const u8, value: @FieldType(loader.RegionConfig, key)) !void {
@@ -200,7 +202,7 @@ test "compositor dark_mode saves beside other compositor keys and matching key n
var cfg = try loader.parse(a, updated, "test");
defer cfg.deinit();
try std.testing.expect(cfg.compositor.dark_mode);
- try std.testing.expectEqual(@as(u32, 12), cfg.compositor.window_gap);
+ try std.testing.expectEqual(@as(u32, 12), cfg.compositor.windowGap());
try std.testing.expect(!cfg.input.tap_drag);
try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, updated, "dark_mode"));
try std.testing.expect(std.mem.indexOf(u8, updated, "# apps") != null);
@@ -245,7 +247,7 @@ test "taskbar item order and visibility save without changing other settings" {
var cfg = try loader.parse(a, updated, "test");
defer cfg.deinit();
try std.testing.expectEqualDeep(items, cfg.compositor.taskbar_items);
- try std.testing.expectEqual(@as(u32, 12), cfg.compositor.window_gap);
+ try std.testing.expectEqual(@as(u32, 12), cfg.compositor.windowGap());
try std.testing.expect(std.mem.indexOf(u8, updated, "# keep") != null);
}
@@ -264,7 +266,7 @@ test "animations settings save and preserve other settings" {
try std.testing.expect(!cfg.animations.enabled);
try std.testing.expectEqual(@as(f32, 1.5), cfg.animations.speed);
try std.testing.expectEqual(anim.ReducedMotion.on, cfg.animations.reduced_motion);
- try std.testing.expectEqual(@as(u32, 8), cfg.compositor.window_gap);
+ try std.testing.expectEqual(@as(u32, 8), cfg.compositor.windowGap());
}
test "window switching modes persist without replacing unrelated configuration" {
@@ -277,7 +279,7 @@ test "window switching modes persist without replacing unrelated configuration"
var cfg = try loader.parse(allocator, updated, "test");
defer cfg.deinit();
try std.testing.expectEqual(mode, cfg.compositor.focus_zoom);
- try std.testing.expectEqual(@as(u32, 12), cfg.compositor.window_gap);
+ try std.testing.expectEqual(@as(u32, 12), cfg.compositor.windowGap());
try std.testing.expect(std.mem.indexOf(u8, updated, "# switching") != null);
}
try std.testing.expectError(error.InvalidConfig, loader.parse(allocator, "[compositor]\nfocus_zoom = \"unknown\"\n", "test"));
diff --git a/src/config/shortcut_save.zig b/src/config/shortcut_save.zig
index d82366a..25e3bca 100644
--- a/src/config/shortcut_save.zig
+++ b/src/config/shortcut_save.zig
@@ -13,7 +13,13 @@ pub fn format(a: std.mem.Allocator, bind: keys.Keybind) ![]const u8 {
}
pub fn patch(a: std.mem.Allocator, original: []const u8, binds: []const keys.Keybind, index: usize, replacement: keys.Keybind) ![]u8 {
+ return patchMode(a, original, binds, index, replacement, .canvas);
+}
+
+pub fn patchMode(a: std.mem.Allocator, original: []const u8, binds: []const keys.Keybind, index: usize, replacement: keys.Keybind, mode: loader.DesktopMode) ![]u8 {
+ const section = if (mode == .workspaces) "[keybinds.workspace]" else "[keybinds]";
var defaults = try loader.parse(a, "[keybinds]\n", "shortcut-defaults");
+ defaults.compositor.desktop_mode = mode;
defer defaults.deinit();
var out: std.Io.Writer.Allocating = .init(a);
errdefer out.deinit();
@@ -22,7 +28,7 @@ pub fn patch(a: std.mem.Allocator, original: []const u8, binds: []const keys.Key
while (lines.next()) |line| {
const trimmed = std.mem.trim(u8, line, " \t\r");
if (std.mem.startsWith(u8, trimmed, "[")) {
- in_section = std.mem.eql(u8, @import("ui").theme.stripComment(trimmed), "[keybinds]");
+ in_section = std.mem.eql(u8, @import("ui").theme.stripComment(trimmed), section);
if (in_section) continue;
}
if (in_section and trimmed.len > 0 and trimmed[0] != '#') {
@@ -34,11 +40,11 @@ pub fn patch(a: std.mem.Allocator, original: []const u8, binds: []const keys.Key
}
try out.writer.print("{s}\n", .{line});
}
- try out.writer.writeAll("\n[keybinds]\n");
+ try out.writer.print("\n{s}\n", .{section});
for (binds, 0..) |old, i| {
if (i != index and keys.pack(old.modifiers, old.sym) == keys.pack(replacement.modifiers, replacement.sym)) continue;
const bind = if (i == index) replacement else old;
- if (bind.action == .noop and !isInherited(defaults.keybinds, bind)) continue;
+ if (mode == .canvas and bind.action == .noop and !isInherited(defaults.activeKeybinds(), bind)) continue;
const key = try format(a, bind);
defer a.free(key);
// Match the loader: quoted action contents are literal, without unescaping.
@@ -52,7 +58,7 @@ pub fn patch(a: std.mem.Allocator, original: []const u8, binds: []const keys.Key
try out.writer.print("\"{s}\" = \"{s}\"\n", .{ key, keys.describeAction(bind.action, action_buf) });
}
const old = binds[index];
- if (isInherited(defaults.keybinds, old) and keys.pack(old.modifiers, old.sym) != keys.pack(replacement.modifiers, replacement.sym)) {
+ if (isInherited(defaults.activeKeybinds(), old) and keys.pack(old.modifiers, old.sym) != keys.pack(replacement.modifiers, replacement.sym)) {
const key = try format(a, old);
defer a.free(key);
try out.writer.print("\"{s}\" = \"noop\"\n", .{key});
@@ -68,16 +74,21 @@ fn isInherited(defaults: []const keys.Keybind, bind: keys.Keybind) bool {
}
pub fn save(a: std.mem.Allocator, io: std.Io, path: []const u8, binds: []const keys.Keybind, index: usize, replacement: keys.Keybind) !void {
+ return saveMode(a, io, path, binds, index, replacement, .canvas);
+}
+
+pub fn saveMode(a: std.mem.Allocator, io: std.Io, path: []const u8, binds: []const keys.Keybind, index: usize, replacement: keys.Keybind, mode: loader.DesktopMode) !void {
if (path.len == 0) return error.NoConfigPath;
const original = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20));
defer a.free(original);
var old = try loader.parse(a, original, path);
defer old.deinit();
- if (old.keybinds.len != binds.len) return error.ConfigChanged;
- for (old.keybinds, binds) |x, y| {
+ old.compositor.desktop_mode = mode;
+ if (old.activeKeybinds().len != binds.len) return error.ConfigChanged;
+ for (old.activeKeybinds(), binds) |x, y| {
if (keys.pack(x.modifiers, x.sym) != keys.pack(y.modifiers, y.sym) or !keys.actionEql(x.action, y.action)) return error.ConfigChanged;
}
- const result = try patch(a, original, binds, index, replacement);
+ const result = try patchMode(a, original, binds, index, replacement, mode);
defer a.free(result);
var checked = try loader.parse(a, result, path);
defer checked.deinit();
@@ -138,3 +149,20 @@ test "moving Files restores ordinary keys and removes obsolete non-inherited noo
try std.testing.expectEqual(@as(?keys.Action, null), parsed.lookupKeybind(plain.modifiers, plain.sym));
try std.testing.expectEqual(@as(?keys.Action, null), parsed.lookupKeybind(cfg.keybinds[0].modifiers, cfg.keybinds[0].sym));
}
+
+test "editing workspace defaults preserves canvas bindings and masks the previous key" {
+ const a = std.testing.allocator;
+ const original = "[compositor]\ndesktop_mode = \"workspaces\"\n[keybinds]\n\"Super+q\" = \"close_window\"\n";
+ var cfg = try loader.parse(a, original, "test");
+ defer cfg.deinit();
+ const binds = cfg.activeKeybinds();
+ const key = try keys.parseKeybind("Super+F12");
+ const updated = try patchMode(a, original, binds, 0, .{ .sym = key.sym, .modifiers = key.modifiers, .action = binds[0].action }, .workspaces);
+ defer a.free(updated);
+ var parsed = try loader.parse(a, updated, "test");
+ defer parsed.deinit();
+ try std.testing.expectEqual(keys.Action.noop, parsed.lookupKeybind(binds[0].modifiers, binds[0].sym).?);
+ try std.testing.expectEqualStrings("default-terminal", parsed.lookupKeybind(key.modifiers, key.sym).?.spawn);
+ parsed.compositor.desktop_mode = .canvas;
+ try std.testing.expectEqual(keys.Action.close_window, parsed.lookupKeybind(binds[0].modifiers, binds[0].sym).?);
+}
diff --git a/src/config/window_rules.zig b/src/config/window_rules.zig
index d88e882..6c6b6af 100644
--- a/src/config/window_rules.zig
+++ b/src/config/window_rules.zig
@@ -67,6 +67,7 @@ pub const WindowRule = struct {
opacity: ?f32 = null,
decorations: ?DecorationMode = null,
skip_taskbar: ?bool = null,
+ floating: ?bool = null,
pub fn hasProperties(self: WindowRule) bool {
return self.output != null or
@@ -81,7 +82,7 @@ pub const WindowRule = struct {
self.depth != null or
self.opacity != null or
self.decorations != null or
- self.skip_taskbar != null;
+ self.skip_taskbar != null or self.floating != null;
}
pub fn hasMatchers(self: WindowRule) bool {
@@ -123,6 +124,7 @@ pub const Resolved = struct {
opacity: ?f32 = null,
decorations: ?DecorationMode = null,
skip_taskbar: ?bool = null,
+ floating: ?bool = null,
matched_rules: std.StaticBitSet(max_rules) = std.StaticBitSet(max_rules).initEmpty(),
};
@@ -192,12 +194,14 @@ pub const LiveRules = struct {
opacity: ?f32 = null,
decorations: ?DecorationMode = null,
skip_taskbar: ?bool = null,
+ floating: ?bool = null,
pub fn fromResolved(resolved: Resolved) LiveRules {
return .{
.opacity = resolved.opacity,
.decorations = resolved.decorations,
.skip_taskbar = resolved.skip_taskbar,
+ .floating = resolved.floating,
};
}
};
@@ -326,6 +330,7 @@ pub fn resolve(rules: []const WindowRule, id: WindowIdentity) Resolved {
if (rule.opacity != null) res.opacity = rule.opacity;
if (rule.decorations != null) res.decorations = rule.decorations;
if (rule.skip_taskbar != null) res.skip_taskbar = rule.skip_taskbar;
+ if (rule.floating != null) res.floating = rule.floating;
}
// Across rules, fullscreen wins over maximized if fullscreen is true.
@@ -456,6 +461,8 @@ pub fn applyRuleKey(rule: *WindowRule, allocator: Allocator, key: []const u8, va
} else if (std.mem.eql(u8, key, "decorations")) {
const str = try theme_mod.unquote(value);
rule.decorations = try DecorationMode.parse(str);
+ } else if (std.mem.eql(u8, key, "floating")) {
+ rule.floating = try parseBool(value);
} else if (std.mem.eql(u8, key, "skip_taskbar")) {
rule.skip_taskbar = try parseBool(value);
} else {
@@ -661,3 +668,14 @@ test "open rules snapshot survives config deinit" {
try std.testing.expectEqual(@as(?bool, true), open_snapshot.center);
try std.testing.expectEqual(@as(?f32, null), live_snapshot.opacity);
}
+
+test "floating rules follow matcher specificity and last matching value" {
+ const rules: []const WindowRule = &.{ .{ .app_id = &.{"tool*"}, .floating = true }, .{ .title = &.{"Main"}, .floating = false } };
+ try std.testing.expect(resolve(rules, .{ .app_id = "tool", .title = "Utility" }).floating.?);
+ try std.testing.expect(!resolve(rules, .{ .app_id = "tool", .title = "Main" }).floating.?);
+ try std.testing.expect(LiveRules.fromResolved(resolve(rules, .{ .app_id = "tool" })).floating.?);
+ var rule: WindowRule = .{};
+ try applyRuleKey(&rule, std.testing.allocator, "floating", "false");
+ try std.testing.expect(rule.hasProperties());
+ try std.testing.expectError(error.InvalidValue, applyRuleKey(&rule, std.testing.allocator, "floating", "1"));
+}
diff --git a/src/config/workspace_defaults.zig b/src/config/workspace_defaults.zig
new file mode 100644
index 0000000..3fe3083
--- /dev/null
+++ b/src/config/workspace_defaults.zig
@@ -0,0 +1,56 @@
+// Stable workspace preset; canvas bindings remain independent.
+pub const source =
+ \\[keybinds]
+ \\"Super+q" = "spawn default-terminal"
+ \\"Super+c" = "close_window"
+ \\"Super+e" = "spawn default-file-manager"
+ \\"Super+r" = "toggle_start_menu"
+ \\"Super+m" = "toggle_power_menu"
+ \\"Super+f" = "toggle_fullscreen"
+ \\"Super+l" = "lock_screen"
+ \\"Super+z" = "undo"
+ \\"Ctrl+Shift+s" = "screenshot_region"
+ \\"Ctrl+Tab" = "focus_next"
+ \\"Ctrl+Shift+Tab" = "focus_prev"
+ \\"Alt+Tab" = "focus_next"
+ \\"Alt+Shift+Tab" = "focus_prev"
+ \\"Ctrl+Alt+Tab" = "focus_next"
+ \\"Ctrl+Alt+Shift+Tab" = "focus_prev"
+ \\"Print" = "screenshot_output"
+ \\"Super+Print" = "screenshot_output"
+ \\"Super+Left" = "focus_left"
+ \\"Super+Right" = "focus_right"
+ \\"Super+Up" = "focus_up"
+ \\"Super+Down" = "focus_down"
+ \\"Super+1" = "workspace 1"
+ \\"Super+Shift+1" = "move_to_workspace 1"
+ \\"Super+2" = "workspace 2"
+ \\"Super+Shift+2" = "move_to_workspace 2"
+ \\"Super+3" = "workspace 3"
+ \\"Super+Shift+3" = "move_to_workspace 3"
+ \\"Super+4" = "workspace 4"
+ \\"Super+Shift+4" = "move_to_workspace 4"
+ \\"Super+5" = "workspace 5"
+ \\"Super+Shift+5" = "move_to_workspace 5"
+ \\"Super+6" = "workspace 6"
+ \\"Super+Shift+6" = "move_to_workspace 6"
+ \\"Super+7" = "workspace 7"
+ \\"Super+Shift+7" = "move_to_workspace 7"
+ \\"Super+8" = "workspace 8"
+ \\"Super+Shift+8" = "move_to_workspace 8"
+ \\"Super+9" = "workspace 9"
+ \\"Super+Shift+9" = "move_to_workspace 9"
+ \\"Super+0" = "workspace 10"
+ \\"Super+Shift+0" = "move_to_workspace 10"
+ \\"Super+v" = "toggle_floating"
+ \\"Super+j" = "toggle_split"
+ \\"Super+Shift+space" = "toggle_workspace_tiling"
+ \\"Super+Shift+Left" = "swap_left"
+ \\"Super+Shift+Right" = "swap_right"
+ \\"Super+Shift+Up" = "swap_up"
+ \\"Super+Shift+Down" = "swap_down"
+ \\"Super+Ctrl+Left" = "resize_split_left"
+ \\"Super+Ctrl+Right" = "resize_split_right"
+ \\"Super+Ctrl+Up" = "resize_split_up"
+ \\"Super+Ctrl+Down" = "resize_split_down"
+;
diff --git a/src/config/workspace_layout.zig b/src/config/workspace_layout.zig
new file mode 100644
index 0000000..fc6e8a8
--- /dev/null
+++ b/src/config/workspace_layout.zig
@@ -0,0 +1,172 @@
+//! Versioned, bounded workspace snapshots. No compositor or scene dependencies.
+const std = @import("std");
+pub const Geometry = struct { x: i32, y: i32, width: i32, height: i32 };
+pub const Canvas = struct {
+ geometry: Geometry,
+ zoom_index: usize = 0,
+ maximized: bool = false,
+ tile: ?[]const u8 = null,
+ fullscreen: bool = false,
+ maximize_restore: ?Geometry = null,
+ tile_restore: ?Geometry = null,
+ fullscreen_restore: ?Geometry = null,
+};
+pub const Reinsert = struct {
+ anchor: u64,
+ group: bool = false,
+ axis: enum { horizontal, vertical } = .horizontal,
+ ratio: f64 = 0.5,
+ before: bool = false,
+};
+pub const Window = struct {
+ app_id: []const u8,
+ title: []const u8 = "",
+ backend: []const u8 = "xdg",
+ instance: []const u8 = "",
+ ordinal: usize = 0,
+ workspace: u8,
+ order: u64,
+ group: u64 = 0,
+ tab_active: bool = true,
+ floating: bool = false,
+ floating_override: ?bool = null,
+ reinsert: ?Reinsert = null,
+ geometry: Geometry,
+ auto_restore: ?Geometry = null,
+ maximize_restore: ?Geometry = null,
+ fullscreen_restore: ?Geometry = null,
+ tile: ?[]const u8 = null,
+ tile_restore: ?Geometry = null,
+ maximized: bool = false,
+ fullscreen: bool = false,
+ minimized: bool = false,
+ canvas: ?Canvas = null,
+};
+/// Preorder binary tree. A leaf stores a stable insertion or tab-group ID.
+pub const Node = struct {
+ id: ?u64 = null,
+ group: bool = false,
+ axis: enum { horizontal, vertical } = .horizontal,
+ ratio: f64 = 0.5,
+};
+pub const Workspace = struct {
+ id: u8,
+ automatic: bool = true,
+ output: []const u8 = "",
+ visible: bool = false,
+ focus_order: ?u64 = null,
+ nodes: []const Node = &.{},
+};
+pub const Camera = struct { offset_x: f64 = 0, offset_y: f64 = 0, zoom_index: usize = 0 };
+pub const Bounds = struct { max_x: f64 = 0, max_y: f64 = 0, origin_x: f64 = 0, origin_y: f64 = 0, width: f64 = 0, height: f64 = 0 };
+pub const Saved = struct {
+ version: u32 = 2,
+ camera: Camera = .{},
+ bounds: Bounds = .{},
+ workspaces: []const Workspace,
+ windows: []const Window,
+};
+pub fn parse(a: std.mem.Allocator, bytes: []const u8) !std.json.Parsed(Saved) {
+ const parsed = try std.json.parseFromSlice(Saved, a, bytes, .{ .allocate = .alloc_always });
+ errdefer parsed.deinit();
+ const s = parsed.value;
+ if (s.version != 2) return error.UnsupportedLayoutVersion;
+ if (s.workspaces.len > 32 or s.windows.len > 4096) return error.InvalidLayout;
+ if (!std.math.isFinite(s.camera.offset_x) or !std.math.isFinite(s.camera.offset_y)) return error.InvalidLayout;
+ inline for (std.meta.fields(Bounds)) |f| if (!std.math.isFinite(@field(s.bounds, f.name))) return error.InvalidLayout;
+ var seen: [32]bool = @splat(false);
+ for (s.workspaces) |w| {
+ if (w.id == 0 or w.id > 32 or seen[w.id - 1] or w.nodes.len > 8191) return error.InvalidLayout;
+ seen[w.id - 1] = true;
+ for (w.nodes, 0..) |node, index| if (node.id) |id| {
+ for (w.nodes[0..index]) |prior| if (prior.id == id and prior.group == node.group) return error.InvalidLayout;
+ };
+ var cursor: usize = 0;
+ if (w.nodes.len > 0) try validateTree(w.nodes, &cursor, 0);
+ if (cursor != w.nodes.len) return error.InvalidLayout;
+ }
+ for (s.windows, 0..) |w, i| {
+ if (w.workspace == 0 or w.workspace > 32 or !seen[w.workspace - 1] or w.order == 0 or w.order == std.math.maxInt(u64) or !validGeometry(w.geometry)) return error.InvalidLayout;
+ if (w.app_id.len > 4096 or w.title.len > 16384) return error.InvalidLayout;
+ for (s.windows[0..i]) |previous| if (previous.order == w.order) return error.InvalidLayout;
+ if (w.reinsert) |r| if (r.anchor == 0 or !std.math.isFinite(r.ratio) or r.ratio < 0.05 or r.ratio > 0.95) return error.InvalidLayout;
+ if (w.auto_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ if (w.maximize_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ if (w.fullscreen_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ if (w.tile_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ if (w.canvas) |c| {
+ if (!validGeometry(c.geometry)) return error.InvalidLayout;
+ if (c.maximize_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ if (c.tile_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ if (c.fullscreen_restore) |g| if (!validGeometry(g)) return error.InvalidLayout;
+ }
+ }
+ return parsed;
+}
+fn validGeometry(g: Geometry) bool {
+ return g.width > 0 and g.height > 0 and g.width <= 65536 and g.height <= 65536 and @abs(@as(i64, g.x)) < (1 << 28) and @abs(@as(i64, g.y)) < (1 << 28);
+}
+fn validateTree(nodes: []const Node, cursor: *usize, depth: usize) !void {
+ if (cursor.* >= nodes.len or depth > 128) return error.InvalidLayout;
+ const node = nodes[cursor.*];
+ cursor.* += 1;
+ if (node.id) |id| {
+ if (id == 0) return error.InvalidLayout;
+ return;
+ }
+ if (!std.math.isFinite(node.ratio) or node.ratio < 0.05 or node.ratio > 0.95) return error.InvalidLayout;
+ try validateTree(nodes, cursor, depth + 1);
+ try validateTree(nodes, cursor, depth + 1);
+}
+
+test "workspace saves reject unsupported versions and malformed trees" {
+ const a = std.testing.allocator;
+ try std.testing.expectError(error.UnsupportedLayoutVersion, parse(a, "{\"version\":3,\"workspaces\":[],\"windows\":[]}"));
+ try std.testing.expectError(error.InvalidLayout, parse(a, "{\"workspaces\":[{\"id\":1,\"nodes\":[{}]}],\"windows\":[]}"));
+ var valid = try parse(a, "{\"workspaces\":[{\"id\":2,\"nodes\":[{}, {\"id\":1}, {\"id\":2}]}],\"windows\":[]}");
+ defer valid.deinit();
+ try std.testing.expectEqual(@as(usize, 3), valid.value.workspaces[0].nodes.len);
+}
+
+pub const LegacyWindow = struct {
+ app_id: []const u8 = "",
+ x: i32 = 0,
+ y: i32 = 0,
+ zoom_index: usize = 0,
+};
+/// Unversioned canvas TOML from earlier releases. Retain its coordinate/zoom
+/// semantics; old width/height described chrome rather than client geometry.
+pub fn parseLegacy(a: std.mem.Allocator, bytes: []const u8) ![]const LegacyWindow {
+ var list: std.ArrayList(LegacyWindow) = .empty;
+ errdefer list.deinit(a);
+ var current: LegacyWindow = .{};
+ var have = false;
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (std.mem.eql(u8, line, "[[window]]")) {
+ if (have) try list.append(a, current);
+ current = .{};
+ have = false;
+ continue;
+ }
+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
+ const key = std.mem.trim(u8, line[0..eq], " \t");
+ const value = std.mem.trim(u8, line[eq + 1 ..], " \t");
+ if (std.mem.eql(u8, key, "app_id")) {
+ const unquoted = try @import("ui").theme.unquote(value);
+ current.app_id = try a.dupe(u8, unquoted);
+ have = true;
+ } else if (std.mem.eql(u8, key, "x")) current.x = try std.fmt.parseInt(i32, value, 10) else if (std.mem.eql(u8, key, "y")) current.y = try std.fmt.parseInt(i32, value, 10) else if (std.mem.eql(u8, key, "zoom_index")) current.zoom_index = try std.fmt.parseInt(usize, value, 10);
+ }
+ if (have) try list.append(a, current);
+ return list.toOwnedSlice(a);
+}
+
+test "legacy layout keeps separate occurrences of an app" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const rows = try parseLegacy(arena.allocator(), "[[window]]\napp_id = \"app\"\nx = 10\n[[window]]\napp_id = \"app\"\nx = 20\n");
+ try std.testing.expectEqual(@as(usize, 2), rows.len);
+ try std.testing.expectEqual(@as(i32, 20), rows[1].x);
+}
diff --git a/src/config_runtime/actions.zig b/src/config_runtime/actions.zig
index f7f26f8..5c2fab5 100644
--- a/src/config_runtime/actions.zig
+++ b/src/config_runtime/actions.zig
@@ -14,8 +14,20 @@ const gpa = @import("../main.zig").gpa;
pub fn executeAction(server: *Server, action: Action) void {
if (server.locker != null and !keybinds.isHardwareAction(action)) return;
+ if (server.world.workspaces.active) switch (action) {
+ .set_depth, .zoom_in, .zoom_out, .zoom_reset, .camera_zoom_in, .camera_zoom_out, .camera_zoom_reset, .pan_left, .pan_right, .pan_up, .pan_down => return,
+ else => {},
+ };
switch (action) {
+ .toggle_floating, .toggle_split, .toggle_workspace_tiling, .swap_left, .swap_right, .swap_up, .swap_down, .resize_split_left, .resize_split_right, .resize_split_up, .resize_split_down => @import("../auto_tiling.zig").execute(server, focusedToplevel(server), std.meta.stringToEnum(keybinds.TilingAction, @tagName(action)).?),
.noop => {},
+ .workspace => |id| server.world.workspaces.switchTo(server, id),
+ .move_to_workspace => |id| if (focusedToplevel(server)) |top| server.world.workspaces.moveTo(top, id),
+ .workspace_next => server.world.workspaces.cycle(server, true),
+ .workspace_prev => server.world.workspaces.cycle(server, false),
+ .toggle_power_menu => if (server.getDefaultOutput()) |output| {
+ if (output.power_menu != null) output.closePowerMenu() else output.openPowerMenu();
+ },
.volume_up, .volume_down, .volume_mute, .mic_mute, .brightness_up, .brightness_down => @import("../hardware_keys.zig").execute(server, action),
.power_profile_cycle => if (server.power_profiles) |pp| pp.cycle(),
.spawn => |cmd| launchPreferred(server, cmd),
@@ -63,12 +75,18 @@ pub fn executeAction(server: *Server, action: Action) void {
}
pub fn focusedToplevel(server: *Server) ?*Toplevel {
+ if (server.world.workspaces.active) return @import("../ipc/handlers.zig").findFocusedToplevel(server);
return @import("../ipc/handlers.zig").findFocusedToplevel(server) orelse server.world.toplevels.first();
}
fn tileFocused(server: *Server, dir: snap.Direction) void {
const toplevel = focusedToplevel(server) orelse return;
if (!toplevel.in_world or toplevel.minimized) return;
+ var transaction: ?@import("../layout_undo.zig").Transaction = if (server.world.workspaces.active)
+ @import("../layout_undo.zig").Transaction.begin(server, &.{toplevel.workspace_id})
+ else
+ null;
+ defer if (transaction) |*change| change.finish();
const before = toplevel.layout();
const geom = toplevel.clientGeometry();
const window: @import("../undo.zig").WindowState = .{
@@ -223,7 +241,7 @@ fn focusDirection(server: *Server, dir: Dir) void {
var best_score: i64 = std.math.maxInt(i64);
var it = server.world.toplevels.iterator(.forward);
while (it.next()) |t| {
- if (t == focused or t.minimized or t.tab_hidden) continue;
+ if (!@import("../workspaces.zig").visible(t) or t == focused or t.minimized or t.tab_hidden) continue;
const tx = t.x + @divTrunc(t.chrome_width, 2);
const ty = t.y + @divTrunc(t.chrome_height, 2);
const dx = tx - fx;
@@ -305,6 +323,7 @@ pub fn saveLayoutToPathIfChanged(server: *Server, path: []const u8, last_hash: *
}
fn writeLayout(server: *Server, path: []const u8, last_hash: ?*?u64) !void {
+ if (server.world.workspaces.active) return @import("../workspace_persistence.zig").save(server, path, last_hash);
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(gpa);
var it = server.world.toplevels.iterator(.forward);
@@ -350,59 +369,80 @@ fn restoreLayout(server: *Server, name: []const u8) void {
/// (session/layout_autosave.zig) — the latter just picks a different path
/// and tolerates a missing file (nothing to recover) silently.
pub fn restoreLayoutFromPath(server: *Server, path: []const u8) !void {
- const bytes = try IoDir.cwd().readFileAlloc(server.io, path, gpa, .limited(1 << 20));
- defer gpa.free(bytes);
-
- var app_id: []const u8 = "";
- var x: i32 = 0;
- var y: i32 = 0;
- var zoom_index: usize = 0;
- var have = false;
- var lines = std.mem.splitScalar(u8, bytes, '\n');
- while (lines.next()) |raw| {
- const line = std.mem.trim(u8, raw, " \t\r");
- if (std.mem.eql(u8, line, "[[window]]")) {
- if (have) applySavedWindow(server, app_id, x, y, zoom_index);
- have = false;
- app_id = "";
- x = 0;
- y = 0;
- zoom_index = 0;
- continue;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const bytes = try IoDir.cwd().readFileAlloc(server.io, path, a, .limited(1 << 20));
+ const trimmed = std.mem.trimStart(u8, bytes, " \t\r\n");
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ defer server.undo.applying = applying;
+ if (std.mem.startsWith(u8, trimmed, "{")) {
+ if (server.world.workspaces.active) {
+ var restore = try @import("../workspace_persistence.zig").Restore.fromBytes(bytes);
+ defer restore.deinit();
+ var it = server.world.toplevels.iterator(.reverse);
+ while (it.next()) |top| restore.apply(server, top);
+ it = server.world.toplevels.iterator(.reverse);
+ while (it.next()) |top| restore.finish(server, top);
+ if (server.layout_autosave) |autosave| for (restore.parsed.value.workspaces) |workspace| autosave.touch(&.{workspace.id});
+ } else {
+ const saved = try @import("config").workspace_layout.parse(a, bytes);
+ var used: std.AutoHashMapUnmanaged(u64, void) = .empty;
+ for (saved.value.windows) |window| {
+ const top = matchSavedWindow(server, window.app_id, &used, a) orelse continue;
+ const c = window.canvas orelse continue;
+ top.restoreGeometryNow(.{ .x = c.geometry.x, .y = c.geometry.y, .width = c.geometry.width, .height = c.geometry.height });
+ top.setZoomOrigin(@min(c.zoom_index, camera_mod.zoom_levels.len - 1));
+ }
}
- const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
- const key = std.mem.trim(u8, line[0..eq], " \t");
- const value = std.mem.trim(u8, line[eq + 1 ..], " \t");
- if (std.mem.eql(u8, key, "app_id")) {
- if (value.len >= 2 and value[0] == '"') app_id = value[1 .. value.len - 1];
- have = true;
- } else if (std.mem.eql(u8, key, "x")) {
- x = std.fmt.parseInt(i32, value, 10) catch 0;
- } else if (std.mem.eql(u8, key, "y")) {
- y = std.fmt.parseInt(i32, value, 10) catch 0;
- } else if (std.mem.eql(u8, key, "zoom_index")) {
- zoom_index = std.fmt.parseInt(usize, value, 10) catch 0;
+ return;
+ }
+ const rows = try @import("config").workspace_layout.parseLegacy(a, bytes);
+ var used: std.AutoHashMapUnmanaged(u64, void) = .empty;
+ for (rows) |row| {
+ const top = matchSavedWindow(server, row.app_id, &used, a) orelse continue;
+ const zoom_index = @min(row.zoom_index, camera_mod.zoom_levels.len - 1);
+ if (server.world.workspaces.active) {
+ // Older canvas saves update the return-to-canvas state, never the
+ // fixed workspace camera or the current automatic rectangles.
+ var canvas = top.canvas_state orelse @import("../workspaces.zig").CanvasWindow{
+ .geometry = top.rememberGeometry(),
+ .zoom_index = 0,
+ .layout = .floating,
+ .fullscreen = false,
+ .maximize_restore = null,
+ .tile_restore = null,
+ .fullscreen_restore = null,
+ };
+ canvas.geometry.x = row.x;
+ canvas.geometry.y = row.y;
+ canvas.zoom_index = zoom_index;
+ top.canvas_state = canvas;
+ } else {
+ top.setPosition(row.x, row.y);
+ top.setZoom(zoom_index, server.input.cursor.x, server.input.cursor.y);
}
}
- if (have) applySavedWindow(server, app_id, x, y, zoom_index);
}
-
-fn applySavedWindow(server: *Server, app_id: []const u8, x: i32, y: i32, zoom_index: usize) void {
- var it = server.world.toplevels.iterator(.forward);
- while (it.next()) |t| {
- const id = t.appId();
- if (t.tab_hidden or !std.mem.eql(u8, id, app_id)) continue;
- // restore_layout is not a user gesture; suppress undo recording.
- server.undo.applying = true;
- defer server.undo.applying = false;
- t.setPosition(x, y);
- const max_index = camera_mod.zoom_levels.len - 1;
- t.setZoom(@min(zoom_index, max_index), server.input.cursor.x, server.input.cursor.y);
- return;
+fn matchSavedWindow(server: *Server, app_id: []const u8, used: *std.AutoHashMapUnmanaged(u64, void), a: std.mem.Allocator) ?*Toplevel {
+ var it = server.world.toplevels.iterator(.reverse);
+ while (it.next()) |top| {
+ if (top.tab_hidden or used.contains(top.id) or !std.mem.eql(u8, top.appId(), app_id)) continue;
+ used.put(a, top.id, {}) catch return null;
+ return top;
}
+ return null;
}
fn executeUndo(server: *Server) void {
+ if (server.input.tiling_grab != null) server.input.finishTilingGrab(true);
+ const resizing = if (server.input.resize_session) |session| @as(?@import("../layout_undo.zig").Resize, .{
+ .id = session.toplevel.id,
+ .width = session.latest_desired_size.width,
+ .height = session.latest_desired_size.height,
+ }) else null;
+ _ = @import("../layout_undo.zig").commitGesture(server, resizing);
const now_ms = Server.undoNowMs();
// Commit any in-flight gesture so a late event cannot clobber the restored state.
if (server.undo.pending) |pending| {
@@ -427,19 +467,32 @@ fn executeUndo(server: *Server) void {
.zoom_index = server.world.camera.zoom_index,
.focus_zoom = server.world.camera.focus_zoom,
} },
- .focus => .none,
+ .focus, .workspace_layout => .none,
};
server.undo.commit(now_ms, live);
}
+ if (server.world.workspaces.active) {
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ @import("../workspaces.zig").cancelGestures(server);
+ server.undo.applying = applying;
+ }
+
const change = server.undo.slot orelse return;
server.undo.slot = null;
+ defer change.deinit();
// Guard: setters in setPosition / setZoom / focusSurface must not record
// while we are applying an undo.
server.undo.applying = true;
defer server.undo.applying = false;
+ if (change.snapshot) |snapshot| {
+ @import("../layout_undo.zig").apply(server, snapshot);
+ return;
+ }
+
// 1. Camera
if (change.camera) |cam| {
server.world.panning = false;
@@ -475,7 +528,7 @@ fn executeUndo(server: *Server) void {
toplevel.leaveLayout();
toplevel.restoreGeometry(.{ .x = win.x, .y = win.y, .width = win.width, .height = win.height });
},
- .maximized, .tiled => toplevel.applyLayout(win.layout),
+ .maximized, .tiled, .automatic => toplevel.applyLayout(win.layout),
}
} else if (change.kind == .resize) {
toplevel.restoreGeometry(.{ .x = win.x, .y = win.y, .width = win.width, .height = win.height });
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 6da8d27..f671728 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -23,7 +23,9 @@ const themeEql = loader.themeEql;
const wheelAccel = loader.wheelAccel;
pub const applyInactiveOpacity = applyWindowOpacity;
pub fn applyDiff(server: *Server, old: Config, new: Config) void {
+ server.world.workspaces.setMode(server, new.compositor.desktop_mode == .workspaces);
server.window_tabs.reconfigure(server);
+ if (old.compositor.window_gap != new.compositor.window_gap) server.world.workspaces.tiler.schedule(server);
if (!std.meta.eql(old.region, new.region)) applyRegion(server);
if (!std.mem.eql(u8, old.compositor.default_file_manager, new.compositor.default_file_manager) or
!std.mem.eql(u8, old.compositor.default_terminal, new.compositor.default_terminal))
@@ -100,6 +102,7 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
server.scheduleFrames();
if (server.input.open_control_center) |cc| cc.refresh();
}
+ server.world.workspaces.tiler.schedule(server);
var any_taskbar_changed = false;
var it = server.world.toplevels.iterator(.forward);
while (it.next()) |toplevel| {
@@ -108,6 +111,7 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
const resolved = window_rules.resolve(new.window_rules, toplevel.currentIdentity());
toplevel.live_rules = window_rules.LiveRules.fromResolved(resolved);
toplevel.matched_rules = resolved.matched_rules;
+ @import("../auto_tiling.zig").observe(toplevel);
if (toplevel.live_rules.decorations != prev_rules.decorations) {
if (toplevel.decoration) |d| d.applyMode();
diff --git a/src/config_runtime/workspace_controls.zig b/src/config_runtime/workspace_controls.zig
new file mode 100644
index 0000000..cb558c4
--- /dev/null
+++ b/src/config_runtime/workspace_controls.zig
@@ -0,0 +1,43 @@
+//! Shared Settings/IPC setters. Save before applying, so a failed write leaves
+//! the live configuration unchanged.
+const std = @import("std");
+const Server = @import("../Server.zig");
+const config = @import("config");
+const gpa = @import("../main.zig").gpa;
+pub fn mode(server: *Server, value: config.loader.DesktopMode, persist: bool) !void {
+ if (persist) try config.setting_save.saveCompositor(gpa, server.io, server.config.path, "desktop_mode", value);
+ server.config.compositor.desktop_mode = value;
+ server.world.workspaces.setMode(server, value == .workspaces);
+}
+pub fn gap(server: *Server, value: u32, persist: bool) !void {
+ if (value > 512) return error.InvalidGap;
+ if (persist) try config.setting_save.saveCompositor(gpa, server.io, server.config.path, "window_gap", value);
+ server.config.compositor.window_gap = value;
+ server.world.workspaces.tiler.schedule(server);
+ if (server.input.open_control_center) |cc| cc.refresh();
+}
+pub fn floatingApps(server: *Server, values: []const []const u8, persist: bool) !void {
+ const a = server.config.arena.allocator();
+ const owned = try a.alloc([]const u8, values.len);
+ for (values, owned) |value, *dest| dest.* = try a.dupe(u8, value);
+ if (persist) try config.setting_save.saveCompositor(gpa, server.io, server.config.path, "floating_apps", values);
+ server.config.compositor.floating_apps = owned;
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| @import("../auto_tiling.zig").observe(top);
+ server.world.workspaces.tiler.schedule(server);
+ if (server.input.open_control_center) |cc| cc.refresh();
+}
+pub fn automatic(server: *Server, id: u8, value: bool) void {
+ if (id == 0 or id > 32 or !server.world.workspaces.active) return;
+ var transaction = @import("../layout_undo.zig").Transaction.begin(server, &.{id});
+ defer transaction.finish();
+ const slot = &server.world.workspaces.slots[id - 1];
+ if (!slot.exists) {
+ slot.exists = true;
+ slot.output = server.getDefaultOutput();
+ if (slot.output) |out| slot.box = out.usableBox();
+ }
+ slot.automatic = value;
+ server.world.workspaces.tiler.schedule(server);
+ if (server.input.open_control_center) |cc| cc.refresh();
+}
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index 5594871..995c328 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -325,7 +325,7 @@ pub const ControlCenter = struct {
pub fn hasKeyboardFocus(cc: *const ControlCenter) bool {
if (!cc.focused) return false;
const toplevel = cc.toplevel;
- if (!toplevel.in_world or toplevel.minimized) return false;
+ if (!toplevel.in_world or toplevel.minimized or !@import("../workspaces.zig").visible(toplevel)) return false;
if (cc.server.world.toplevels.first() != toplevel) return false;
if (cc.server.input.seat.keyboard_state.focused_surface != null) return false;
if (cc.server.desktop) |desktop| if (desktop.keyboard_focused) return false;
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 4ff6b35..5c09d3a 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -584,7 +584,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
out.inactive_opacity_group_children = .{ inactive_opacity_header, inactive_opacity_slider };
const inactive_opacity_row: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.inactive_opacity_group_children };
- const gap_val: f32 = @floatFromInt(@min(out.cc.server.config.compositor.window_gap, max_window_gap));
+ const gap_val: f32 = @floatFromInt(@min(out.cc.server.config.compositor.windowGap(), max_window_gap));
const window_gap_row = pxGroup(out, px_window_gap, "Snapped window gap", gap_val, 0, max_window_gap, 1, &onWindowGapChanged);
out.taskbar_position_children = .{
@@ -1301,7 +1301,7 @@ fn onWindowGapChanged(owner: ?*anyopaque, _: usize, value: f32) void {
const s = section(owner);
const server = section(owner).cc.server;
const gap: u32 = @intFromFloat(std.math.clamp(@round(value), 0.0, max_window_gap));
- if (gap == server.config.compositor.window_gap) return;
+ if (gap == server.config.compositor.windowGap()) return;
server.config.compositor.window_gap = gap;
const formatted = std.fmt.bufPrint(&s.px[px_window_gap].value_buf, "{d}px", .{gap}) catch "?";
s.px[px_window_gap].header_children[1].kind.text.content = formatted;
@@ -1318,6 +1318,7 @@ fn onWindowGapChanged(owner: ?*anyopaque, _: usize, value: f32) void {
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "window_gap", gap) catch |err| {
std.log.warn("could not save window_gap: {}", .{err});
};
+ server.world.workspaces.tiler.schedule(server);
}
fn onTaskbarPositionChanged(owner: ?*anyopaque, _: usize, index: usize) void {
diff --git a/src/control_center/sections/desktop.zig b/src/control_center/sections/desktop.zig
index 731cb98..1570fb7 100644
--- a/src/control_center/sections/desktop.zig
+++ b/src/control_center/sections/desktop.zig
@@ -27,6 +27,8 @@ pub const Section = struct {
arena: std.heap.ArenaAllocator = .init(gpa),
root: W = undefined,
message: []const u8 = "",
+ selected_workspace: u8 = 0,
+ floating_choices: []const []const u8 = &.{},
};
fn text(value: []const u8, size: f32, dim: bool) W {
@@ -102,7 +104,10 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
}
row.* = .{ .kind = .container, .direction = .row, .justify = .center, .gap = gap, .width = .{ .percent = 1 }, .height = .{ .fixed = cell_size }, .children = cells };
}
- const grid: W = .{ .kind = .container, .direction = .column, .justify = .center, .gap = gap, .width = .{ .percent = 1 }, .height = .{ .fixed = 220 }, .children = grid_rows };
+ // The grid is exactly as tall as its rows: a single row stays one strip
+ // instead of floating in a padded box.
+ const grid_height = cell_size * @as(f32, @floatFromInt(rows)) + gap * @as(f32, @floatFromInt(rows -| 1));
+ const grid: W = .{ .kind = .container, .direction = .column, .justify = .center, .gap = gap, .width = .{ .percent = 1 }, .height = .{ .fixed = grid_height }, .children = grid_rows };
const preview = try card(a, &.{ text("Canvas Preview", 16, false), text("Your desktop panning area.", 12, true), grid, text("Highlighted: bottom-left screen", 12, true) });
const controls = try card(a, &.{
text("Canvas Size", 16, false),
@@ -146,7 +151,14 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
});
fixed_row.justify = .space_between;
fixed_row.@"align" = .center;
+ const mode_card = try card(a, &.{
+ text("Desktop mode", 14, false),
+ .{ .name = "desktop_mode", .kind = .{ .segmented = .{ .labels = &.{ "Canvas", "Workspaces" }, .selected = @intFromEnum(cfg.desktop_mode), .owner = cc, .on_change = modeChanged } }, .width = .{ .percent = 1 } },
+ text(if (cfg.desktop_mode == .workspaces) "Automatic tiles with a fixed view and Hyprland-style shortcuts. Drag tiles to rearrange; Super+V toggles floating." else "Pan and zoom the canvas. Switching back restores your canvas positions and zoom.", 12, true),
+ });
+ if (cfg.desktop_mode == .workspaces) return workspaceTree(s, cc, a, mode_card);
var root = try container(a, .column, &.{
+ mode_card,
body,
switching,
mini_map,
@@ -249,3 +261,108 @@ fn change(owner: ?*anyopaque, id: usize) void {
@import("../../Output.zig").recomputeWorldBounds(cc.server);
cc.refresh();
}
+
+fn modeChanged(owner: ?*anyopaque, _: usize, index: usize) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));
+ if (index > 1) return;
+ const mode: @import("config").loader.DesktopMode = @enumFromInt(index);
+ @import("../../config_runtime/workspace_controls.zig").mode(cc.server, mode, true) catch {
+ cc.desktop.message = "Could not save desktop mode.";
+ cc.refresh();
+ };
+}
+
+const gaps = [_]u32{ 0, 4, 8, 12, 16, 24, 32 };
+const gap_labels = [_][]const u8{ "0 px", "4 px", "8 px", "12 px", "16 px", "24 px", "32 px" };
+fn workspaceTree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator, mode_card: W) !W {
+ const manager = &cc.server.world.workspaces;
+ const id = if (s.selected_workspace > 0) s.selected_workspace else if (cc.server.getDefaultOutput()) |out| @max(1, out.workspace_id) else 1;
+ s.selected_workspace = id;
+ const labels = try a.alloc([]const u8, 32);
+ for (labels, 0..) |*label, i| label.* = try std.fmt.allocPrint(a, "Workspace {d}", .{i + 1});
+ const slot = manager.slots[id - 1];
+ const workspace_card = try card(a, &.{
+ text("Workspace layout", 16, false),
+ try mapSelect(cc, a, "Workspace", "workspace_select", labels, id - 1, false, workspaceSelected),
+ try mapSelect(cc, a, "Placement", "workspace_layout", &.{ "Automatic tiling", "Floating" }, if (slot.automatic) 0 else 1, false, layoutChanged),
+ text(if (slot.output) |out| try std.fmt.allocPrint(a, "Output: {s}", .{std.mem.span(out.wlr_output.name)}) else "Assigned to the current output when first used.", 12, true),
+ text("Layouts and split sizes are saved for your next session.", 12, true),
+ });
+ var gap_index: usize = 0;
+ const value = cc.server.config.compositor.windowGap();
+ for (gaps, 0..) |candidate, i| if (@abs(@as(i64, candidate) - value) < @abs(@as(i64, gaps[gap_index]) - value)) {
+ gap_index = i;
+ };
+ const spacing = try card(a, &.{
+ text("Window spacing", 16, false),
+ try mapSelect(cc, a, try std.fmt.allocPrint(a, "Gap ({d} px)", .{value}), "workspace_gap", &gap_labels, gap_index, false, gapChanged),
+ text("Applies to output edges and the space between automatic tiles.", 12, true),
+ });
+ var choices: std.ArrayList([]const u8) = .empty;
+ for (cc.server.config.compositor.floating_apps) |app| try choices.append(a, try a.dupe(u8, app));
+ cc.server.window_tabs.loadKnown(cc.server);
+ var it = cc.server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| _ = cc.server.window_tabs.remember(top.appId());
+ for (cc.server.window_tabs.known.items) |app| {
+ var found = false;
+ for (choices.items) |existing| if (std.mem.eql(u8, app, existing)) {
+ found = true;
+ break;
+ };
+ if (!found) try choices.append(a, try a.dupe(u8, app));
+ }
+ s.floating_choices = choices.items;
+ const list = ui.widgets.checkbox_list;
+ const items = try a.alloc(list.Item, choices.items.len);
+ for (choices.items, items, 0..) |app, *item, i| {
+ var checked = false;
+ for (cc.server.config.compositor.floating_apps) |enabled| if (std.mem.eql(u8, enabled, app)) {
+ checked = true;
+ break;
+ };
+ item.* = .{ .id = i, .name = try std.fmt.allocPrint(a, "floating_app:{s}", .{app}), .label = app, .checked = checked };
+ }
+ const rules = try card(a, &.{
+ text("Floating apps", 16, false),
+ text("Checked apps open floating. Super+V can override placement for a window. Dialogs and fixed-size windows float automatically.", 12, true),
+ try list.build(a, items, cc, floatingChanged, .{}),
+ text("Open an app to add it here. Advanced title, backend and glob matches use [[window_rules]] floating in your config.", 12, true),
+ });
+ return container(a, .column, &.{ mode_card, workspace_card, spacing, rules, text(s.message, 12, true) });
+}
+fn workspaceSelected(owner: ?*anyopaque, _: usize, index: usize) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));
+ if (index >= 32) return;
+ cc.desktop.selected_workspace = @intCast(index + 1);
+ cc.refresh();
+}
+fn layoutChanged(owner: ?*anyopaque, _: usize, index: usize) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));
+ if (index > 1) return;
+ @import("../../config_runtime/workspace_controls.zig").automatic(cc.server, cc.desktop.selected_workspace, index == 0);
+}
+fn gapChanged(owner: ?*anyopaque, _: usize, index: usize) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));
+ if (index >= gaps.len) return;
+ @import("../../config_runtime/workspace_controls.zig").gap(cc.server, gaps[index], true) catch {
+ cc.desktop.message = "Could not save window spacing.";
+ cc.refresh();
+ };
+}
+fn floatingChanged(owner: ?*anyopaque, index: usize, checked: bool) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));
+ if (index >= cc.desktop.floating_choices.len) return;
+ const selected = cc.desktop.floating_choices[index];
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var apps: std.ArrayList([]const u8) = .empty;
+ for (cc.server.config.compositor.floating_apps) |app| if (!std.mem.eql(u8, selected, app)) {
+ apps.append(a, app) catch return;
+ };
+ if (checked) apps.append(a, selected) catch return;
+ @import("../../config_runtime/workspace_controls.zig").floatingApps(cc.server, apps.items, true) catch {
+ cc.desktop.message = "Could not save floating apps.";
+ cc.refresh();
+ };
+}
diff --git a/src/control_center/sections/shortcuts.zig b/src/control_center/sections/shortcuts.zig
index 49688e1..581e27f 100644
--- a/src/control_center/sections/shortcuts.zig
+++ b/src/control_center/sections/shortcuts.zig
@@ -59,17 +59,17 @@ pub const Section = struct {
else => {},
}
const index = s.editing orelse return;
- if (index >= cc.server.config.keybinds.len) {
+ if (index >= cc.server.config.activeKeybinds().len) {
s.cancel();
return;
}
s.held_keycode = keycode;
s.held_sym = sym;
s.held_mods = @bitCast(keys.relevantMods(mods));
- const candidate: keys.Keybind = .{ .sym = keys.normalizeSym(sym), .modifiers = keys.relevantMods(mods), .action = cc.server.config.keybinds[index].action };
+ const candidate: keys.Keybind = .{ .sym = keys.normalizeSym(sym), .modifiers = keys.relevantMods(mods), .action = cc.server.config.activeKeybinds()[index].action };
s.message = "";
s.candidate = candidate;
- for (cc.server.config.keybinds, 0..) |bind, i| {
+ for (cc.server.config.activeKeybinds(), 0..) |bind, i| {
if (i != index and bind.action != .noop and keys.pack(bind.modifiers, bind.sym) == keys.pack(candidate.modifiers, candidate.sym)) {
s.candidate = null;
s.message = "Shortcut already in use. Try another.";
@@ -84,7 +84,7 @@ pub const Section = struct {
s.pending_save = false;
const candidate = s.candidate orelse return;
const index = s.editing orelse return;
- saving.save(gpa, cc.server.io, cc.server.config.path, cc.server.config.keybinds, index, candidate) catch {
+ saving.saveMode(gpa, cc.server.io, cc.server.config.path, cc.server.config.activeKeybinds(), index, candidate, cc.server.config.compositor.desktop_mode) catch {
s.message = "Could not save. Check the configuration file and try again.";
cc.refresh();
return;
@@ -97,7 +97,7 @@ pub const Section = struct {
fn group(action: keys.Action) usize {
return switch (action) {
- .close_window, .toggle_fullscreen, .toggle_maximize, .tile_left, .tile_right, .tile_up, .tile_down => 0,
+ .toggle_floating, .toggle_split, .toggle_workspace_tiling, .swap_left, .swap_right, .swap_up, .swap_down, .resize_split_left, .resize_split_right, .resize_split_up, .resize_split_down, .close_window, .toggle_fullscreen, .toggle_maximize, .tile_left, .tile_right, .tile_up, .tile_down => 0,
.set_depth, .zoom_in, .zoom_out, .zoom_reset, .camera_zoom_in, .camera_zoom_out, .camera_zoom_reset, .pan_left, .pan_right, .pan_up, .pan_down, .focus_next, .focus_prev, .focus_left, .focus_right, .focus_up, .focus_down, .save_layout, .restore_layout, .undo => 1,
.spawn, .toggle_start_menu => 2,
.screenshot_region, .screenshot_output => 3,
@@ -130,11 +130,15 @@ fn buildGroups(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !voi
// Config reloads can replace string payloads and reorder bindings. Retain
// only the key identity; cancel if that row no longer denotes the same key.
if (s.editing) |i| {
- if (i >= cc.server.config.keybinds.len or keys.pack(cc.server.config.keybinds[i].modifiers, cc.server.config.keybinds[i].sym) != keys.pack(s.original.?.modifiers, s.original.?.sym)) s.cancel();
- if (s.candidate) |*c| c.action = cc.server.config.keybinds[i].action;
+ if (i >= cc.server.config.activeKeybinds().len or keys.pack(cc.server.config.activeKeybinds()[i].modifiers, cc.server.config.activeKeybinds()[i].sym) != keys.pack(s.original.?.modifiers, s.original.?.sym)) s.cancel();
+ if (s.candidate) |*c| c.action = cc.server.config.activeKeybinds()[i].action;
}
for (&s.groups, 0..) |*card, g| {
var rows: std.ArrayList(W) = .empty;
+ if (g == 0) {
+ try rows.append(a, text(if (cc.server.world.workspaces.active) "Workspaces · Hyprland-style preset" else "Canvas · RediWM preset", false));
+ if (cc.server.world.workspaces.active) try rows.append(a, text("Super+Q opens Terminal; Super+M opens Power. Arrows focus; numbers switch workspaces.", true));
+ }
try rows.append(a, .{ .kind = .{ .row = .{ .owner = cc, .id = g, .on_click = collapse } }, .height = .{ .fixed = 40 }, .width = .{ .percent = 1 }, .padding = ui.layout.Edges.xy(12, 0), .gap = 12, .@"align" = .center, .children = try children(a, &.{
.{ .kind = .{ .icon = .{ .id = icons[g], .color = t.window_fg } }, .width = .{ .fixed = 20 }, .height = .{ .fixed = 20 } },
blk: {
@@ -144,8 +148,8 @@ fn buildGroups(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !voi
},
.{ .kind = .{ .icon = .{ .id = if (s.collapsed[g]) .chevron_up else .chevron_down, .color = t.window_dim } }, .width = .{ .fixed = 16 }, .height = .{ .fixed = 16 } },
}) });
- if (!s.collapsed[g]) for (cc.server.config.keybinds, 0..) |bind, i| {
- if (bind.action == .noop or group(bind.action) != g) continue;
+ if (!s.collapsed[g]) for (cc.server.config.activeKeybinds(), 0..) |bind, i| {
+ if (group(bind.action) != g) continue;
const editing = s.editing == i;
const raw = @tagName(bind.action);
const title = try a.dupe(u8, if (bind.action == .toggle_start_menu) "Toggle Launcher" else raw);
@@ -191,6 +195,11 @@ fn buildGroups(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !voi
var edit_btn = button(cc, i, "Edit shortcut", .edit, edit);
edit_btn.name = "edit";
try controls.append(a, edit_btn);
+ if (bind.action != .noop) {
+ var disable = button(cc, i, "Disable shortcut", .close, disableClicked);
+ disable.name = "disable";
+ try controls.append(a, disable);
+ }
}
try rows.append(a, .{ .kind = .{ .rect = .{ .color = t.window_divider } }, .height = .{ .fixed = 1 }, .width = .{ .percent = 1 } });
try rows.append(a, .{ .kind = .container, .direction = .row, .height = .{ .fixed = 60 }, .width = .{ .percent = 1 }, .padding = ui.layout.Edges.xy(12, 0), .gap = 8, .@"align" = .center, .children = controls.items });
@@ -205,7 +214,7 @@ fn edit(p: ?*anyopaque, i: usize) void {
const cc = owner(p);
cc.shortcuts.cancel();
cc.shortcuts.editing = i;
- cc.shortcuts.original = cc.server.config.keybinds[i];
+ cc.shortcuts.original = cc.server.config.activeKeybinds()[i];
cc.refresh();
}
fn collapse(p: ?*anyopaque, i: usize) void {
@@ -225,6 +234,23 @@ fn confirmClicked(p: ?*anyopaque, _: usize) void {
fn descriptionFor(action: keys.Action, buf: []u8) []const u8 {
return switch (action) {
+ .toggle_floating => "Toggle the focused window between floating and automatic tiling.",
+ .toggle_split => "Rotate the nearest tiled split.",
+ .toggle_workspace_tiling => "Toggle automatic tiling for the current workspace.",
+ .swap_left => "Swap the focused tile left.",
+ .swap_right => "Swap the focused tile right.",
+ .swap_up => "Swap the focused tile up.",
+ .swap_down => "Swap the focused tile down.",
+ .resize_split_left => "Move the relevant split divider left.",
+ .resize_split_right => "Move the relevant split divider right.",
+ .resize_split_up => "Move the relevant split divider up.",
+ .resize_split_down => "Move the relevant split divider down.",
+ .workspace => |n| std.fmt.bufPrint(buf, "Switch to workspace {d}.", .{n}) catch "Switch workspace.",
+ .move_to_workspace => |n| std.fmt.bufPrint(buf, "Move the window to workspace {d} and follow it.", .{n}) catch "Move to workspace.",
+ .workspace_next => "Cycle to the next existing workspace.",
+ .workspace_prev => "Cycle to the previous existing workspace.",
+ .toggle_power_menu => "Open the session and power menu.",
+ .noop => "Disabled shortcut.",
.toggle_fullscreen => "Enter or leave fullscreen.",
.toggle_maximize => "Maximize or restore the focused window.",
.tile_left => "Snap the focused window to the left half.",
@@ -267,3 +293,12 @@ fn descriptionFor(action: keys.Action, buf: []u8) []const u8 {
else => "",
};
}
+
+fn disableClicked(p: ?*anyopaque, i: usize) void {
+ const cc = owner(p);
+ const bind = cc.server.config.activeKeybinds()[i];
+ cc.shortcuts.editing = i;
+ cc.shortcuts.original = bind;
+ cc.shortcuts.candidate = .{ .sym = bind.sym, .modifiers = bind.modifiers, .action = .noop };
+ cc.shortcuts.pending_save = true;
+}
diff --git a/src/editor/compose.zig b/src/editor/compose.zig
deleted file mode 100644
index 345f52c..0000000
--- a/src/editor/compose.zig
+++ /dev/null
@@ -1,42 +0,0 @@
-const std = @import("std");
-const c = @cImport({
- @cInclude("xkbcommon/xkbcommon-compose.h");
-});
-pub const Compose = struct {
- table: ?*c.xkb_compose_table = null,
- state: ?*c.xkb_compose_state = null,
- pub fn init(environ: std.process.Environ) Compose {
- const context = c.xkb_context_new(c.XKB_CONTEXT_NO_FLAGS) orelse return .{};
- defer c.xkb_context_unref(context);
- const locale = environ.getPosix("LC_ALL") orelse environ.getPosix("LC_CTYPE") orelse environ.getPosix("LANG") orelse "C.UTF-8";
- const z = std.heap.c_allocator.dupeZ(u8, locale) catch return .{};
- defer std.heap.c_allocator.free(z);
- const table = c.xkb_compose_table_new_from_locale(context, z, c.XKB_COMPOSE_COMPILE_NO_FLAGS) orelse return .{};
- return .{ .table = table, .state = c.xkb_compose_state_new(table, c.XKB_COMPOSE_STATE_NO_FLAGS) };
- }
- pub fn deinit(self: *Compose) void {
- if (self.state) |s| c.xkb_compose_state_unref(s);
- if (self.table) |t| c.xkb_compose_table_unref(t);
- }
- pub fn reset(self: *Compose) void {
- if (self.state) |s| c.xkb_compose_state_reset(s);
- }
- /// null lets the ordinary XKB key through; empty text means composition is pending.
- pub fn feed(self: *Compose, sym: u32, buf: []u8) ?[]const u8 {
- const state = self.state orelse return null;
- _ = c.xkb_compose_state_feed(state, sym);
- switch (c.xkb_compose_state_get_status(state)) {
- c.XKB_COMPOSE_COMPOSING => return "",
- c.XKB_COMPOSE_COMPOSED => {
- const n = c.xkb_compose_state_get_utf8(state, buf.ptr, buf.len);
- c.xkb_compose_state_reset(state);
- return buf[0..@intCast(std.math.clamp(n, 0, @as(c_int, @intCast(buf.len - 1))))];
- },
- c.XKB_COMPOSE_CANCELLED => {
- c.xkb_compose_state_reset(state);
- return "";
- },
- else => return null,
- }
- }
-};
diff --git a/src/editor/main.zig b/src/editor/main.zig
index b6fa62f..2f1a5ef 100644
--- a/src/editor/main.zig
+++ b/src/editor/main.zig
@@ -72,7 +72,9 @@ pub const Client = struct {
caret_state: ?app_mod.App.CaretState = null,
clipboard: @import("clipboard.zig").Clipboard = undefined,
ime: @import("ime.zig").Ime = undefined,
- compose: @import("compose.zig").Compose = .{},
+ compose: @import("ui").compose.Compose = .{},
+ /// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).
+ locale: []const u8 = "",
pub fn registryEvent(registry: *wl.Registry, event: wl.Registry.Event, self: *Client) void {
switch (event) {
@@ -465,7 +467,7 @@ pub const Client = struct {
const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
if (!self.app.ctrl and !self.app.alt and !self.app.menu_open) {
var composed: [128]u8 = undefined;
- if (self.compose.feed(sym, &composed)) |value| {
+ if (self.compose.feed(self.locale, sym, &composed)) |value| {
if (value.len > 0) self.app.pasteText(value);
return;
}
@@ -474,6 +476,7 @@ pub const Client = struct {
}
fn appRepeats(self: *Client, key: u32) bool {
+ if (self.compose.consumed) return false;
const state = self.xkb_state orelse return false;
var buf: [64]u8 = undefined;
const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
@@ -785,7 +788,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
for (paths) |path| self.app.open(path);
self.ime = .{ .app = &self.app };
defer self.ime.deinit();
- self.compose = @import("compose.zig").Compose.init(init.minimal.environ);
+ self.locale = @import("ui").compose.localeFromEnviron(init.minimal.environ);
defer self.compose.deinit();
self.clipboard = .{ .app = &self.app };
defer self.clipboard.deinit();
diff --git a/src/extra_protocols.c b/src/extra_protocols.c
index 567bde8..6f86fb1 100644
--- a/src/extra_protocols.c
+++ b/src/extra_protocols.c
@@ -4,6 +4,7 @@
#define WLR_PRIVATE private
#include "extra_protocols.h"
#include <stdlib.h>
+#include <stdio.h>
#include <string.h>
#include <wlr/backend/drm.h>
#include <wlr/render/wlr_renderer.h>
@@ -25,6 +26,11 @@ struct rediwm_protocols {
struct wlr_tearing_control_manager_v1 *tearing;
struct wlr_drm_lease_v1_manager *lease;
struct wlr_ext_workspace_group_handle_v1 *group;
+ struct wlr_ext_workspace_manager_v1 *workspaces;
+ struct wlr_ext_workspace_handle_v1 *canvas, *workspace[32];
+ struct wl_listener workspace_commit;
+ void (*activate_workspace)(void *, unsigned);
+ bool workspace_mode;
struct wl_listener tag, description, lease_request, layout_add;
struct wl_list outputs;
struct wlr_scene *scene; // set once the scene follows the color manager
@@ -86,11 +92,13 @@ struct workspace_output {
struct wl_listener destroy;
struct rediwm_protocols *protocols;
struct wlr_output *output;
+ struct wlr_ext_workspace_group_handle_v1 *group;
};
static void output_removed(struct wl_listener *listener, void *data) {
(void)data;
struct workspace_output *o = wl_container_of(listener, o, destroy);
- wlr_ext_workspace_group_handle_v1_output_leave(o->protocols->group, o->output);
+ if (o->group) wlr_ext_workspace_group_handle_v1_destroy(o->group);
+ if (o->protocols->group) wlr_ext_workspace_group_handle_v1_output_leave(o->protocols->group, o->output);
wl_list_remove(&o->destroy.link); wl_list_remove(&o->link); free(o);
}
static void output_added(struct wl_listener *listener, void *data) {
@@ -102,7 +110,73 @@ static void output_added(struct wl_listener *listener, void *data) {
o->destroy.notify = output_removed;
wl_signal_add(&lo->events.destroy, &o->destroy);
wl_list_insert(&p->outputs, &o->link);
- wlr_ext_workspace_group_handle_v1_output_enter(p->group, lo->output);
+ if (!p->workspace_mode && p->group) wlr_ext_workspace_group_handle_v1_output_enter(p->group, lo->output);
+}
+static void workspace_commit(struct wl_listener *listener, void *data) {
+ struct rediwm_protocols *p = wl_container_of(listener, p, workspace_commit);
+ if (p->blocked(p->data) || !p->activate_workspace) return;
+ struct wlr_ext_workspace_v1_commit_event *event = data;
+ struct wlr_ext_workspace_v1_request *request;
+ wl_list_for_each(request, event->requests, link) {
+ if (request->type != WLR_EXT_WORKSPACE_V1_REQUEST_ACTIVATE || !request->activate.workspace) continue;
+ for (unsigned i = 0; i < 32; i++) if (request->activate.workspace == p->workspace[i]) {
+ p->activate_workspace(p->data, i + 1);
+ break;
+ }
+ }
+}
+void rediwm_workspace_mode(struct rediwm_protocols *p, bool enabled, void (*activate)(void *, unsigned)) {
+ if (!p) return;
+ p->activate_workspace = activate;
+ if (p->workspace_mode == enabled) return;
+ p->workspace_mode = enabled;
+ struct workspace_output *o;
+ if (enabled) {
+ if (p->canvas) wlr_ext_workspace_handle_v1_destroy(p->canvas);
+ p->canvas = NULL;
+ if (p->group) wlr_ext_workspace_group_handle_v1_destroy(p->group);
+ p->group = NULL;
+ } else {
+ p->group = wlr_ext_workspace_group_handle_v1_create(p->workspaces, 0);
+ for (unsigned i = 0; i < 32; i++) {
+ if (p->workspace[i]) wlr_ext_workspace_handle_v1_destroy(p->workspace[i]);
+ p->workspace[i] = NULL;
+ }
+ wl_list_for_each(o, &p->outputs, link) {
+ if (o->group) wlr_ext_workspace_group_handle_v1_destroy(o->group);
+ o->group = NULL;
+ if (p->group) wlr_ext_workspace_group_handle_v1_output_enter(p->group, o->output);
+ }
+ p->canvas = wlr_ext_workspace_handle_v1_create(p->workspaces, "rediwm-canvas", 0);
+ if (p->canvas) {
+ wlr_ext_workspace_handle_v1_set_group(p->canvas, p->group);
+ wlr_ext_workspace_handle_v1_set_name(p->canvas, "Canvas");
+ wlr_ext_workspace_handle_v1_set_active(p->canvas, true);
+ }
+ }
+}
+void rediwm_workspace_update(struct rediwm_protocols *p, unsigned id, const char *name, struct wlr_output *output, bool active) {
+ if (!p || id == 0 || id > 32 || !p->workspace_mode) return;
+ struct wlr_ext_workspace_handle_v1 **slot = &p->workspace[id - 1];
+ if (!*slot) {
+ char identifier[40];
+ snprintf(identifier, sizeof(identifier), "rediwm-workspace-%u", id);
+ *slot = wlr_ext_workspace_handle_v1_create(p->workspaces, identifier, EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ACTIVATE);
+ if (!*slot) return;
+ wlr_ext_workspace_handle_v1_set_name(*slot, name);
+ }
+ struct wlr_ext_workspace_group_handle_v1 *group = NULL;
+ struct workspace_output *o;
+ wl_list_for_each(o, &p->outputs, link) if (o->output == output) {
+ if (!o->group) {
+ o->group = wlr_ext_workspace_group_handle_v1_create(p->workspaces, 0);
+ if (o->group) wlr_ext_workspace_group_handle_v1_output_enter(o->group, output);
+ }
+ group = o->group;
+ break;
+ }
+ wlr_ext_workspace_handle_v1_set_group(*slot, group);
+ wlr_ext_workspace_handle_v1_set_active(*slot, active);
}
static void lease_requested(struct wl_listener *listener, void *data) {
struct rediwm_protocols *p = wl_container_of(listener, p, lease_request);
@@ -161,6 +235,7 @@ void rediwm_protocols_destroy(struct rediwm_protocols *p) {
wl_list_init(&p->scene->private.color_manager_v1_destroy.link);
p->scene->color_manager_v1 = NULL;
}
+ wl_list_remove(&p->workspace_commit.link);
free(p);
}
struct rediwm_protocols *rediwm_protocols_create(struct wl_display *display,
@@ -170,6 +245,7 @@ struct rediwm_protocols *rediwm_protocols_create(struct wl_display *display,
struct rediwm_protocols *p = calloc(1, sizeof(*p));
if (!p) return NULL;
p->data = data; p->blocked = blocked; p->changed = changed;
+ wl_list_init(&p->workspace_commit.link);
wl_list_init(&p->outputs); wl_list_init(&p->tag.link); wl_list_init(&p->description.link);
wl_list_init(&p->lease_request.link); wl_list_init(&p->layout_add.link);
p->content = wlr_content_type_manager_v1_create(display, 1);
@@ -194,9 +270,13 @@ struct rediwm_protocols *rediwm_protocols_create(struct wl_display *display,
p->scene = scene;
struct wlr_ext_workspace_manager_v1 *workspaces = wlr_ext_workspace_manager_v1_create(display, 1);
if (!workspaces) goto fail;
+ p->workspaces = workspaces;
+ p->workspace_commit.notify = workspace_commit;
+ wl_signal_add(&workspaces->events.commit, &p->workspace_commit);
p->group = wlr_ext_workspace_group_handle_v1_create(workspaces, 0);
struct wlr_ext_workspace_handle_v1 *canvas = wlr_ext_workspace_handle_v1_create(workspaces, "rediwm-canvas", 0);
if (!p->group || !canvas) goto fail;
+ p->canvas = canvas;
wlr_ext_workspace_handle_v1_set_group(canvas, p->group);
wlr_ext_workspace_handle_v1_set_name(canvas, "Canvas");
wlr_ext_workspace_handle_v1_set_active(canvas, true);
diff --git a/src/extra_protocols.zig b/src/extra_protocols.zig
index c634847..baf4ba3 100644
--- a/src/extra_protocols.zig
+++ b/src/extra_protocols.zig
@@ -29,3 +29,19 @@ pub fn tag(surface: ?*wlr.Surface, description: bool) ?[]const u8 {
pub fn content(server: *Server, surface: ?*wlr.Surface) ?[]const u8 {
return if (rediwm_protocols_content(server.extra_protocols, surface)) |s| std.mem.span(s) else null;
}
+
+extern fn rediwm_workspace_mode(?*Protocols, bool, *const fn (*Server, c_uint) callconv(.c) void) void;
+extern fn rediwm_workspace_update(?*Protocols, c_uint, [*:0]const u8, ?*wlr.Output, bool) void;
+fn activateWorkspace(server: *Server, id: c_uint) callconv(.c) void {
+ if (id <= @import("workspaces.zig").count) server.world.workspaces.switchTo(server, @intCast(id));
+}
+pub fn syncWorkspaces(server: *Server) void {
+ const manager = &server.world.workspaces;
+ rediwm_workspace_mode(server.extra_protocols, manager.active, activateWorkspace);
+ if (!manager.active) return;
+ for (manager.slots, 0..) |slot, index| {
+ if (!slot.exists) continue;
+ const output = slot.output;
+ rediwm_workspace_update(server.extra_protocols, @intCast(index + 1), @import("workspaces.zig").names[index], if (output) |o| o.wlr_output else null, if (output) |o| o.workspace_id == index + 1 else false);
+ }
+}
diff --git a/src/files/app.zig b/src/files/app.zig
index 3d03c1c..3d45df3 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -1753,7 +1753,7 @@ pub const App = struct {
}
self.h = @max(self.h, self.footerHeight() + 300);
self.focus = if (options.mode == .save) .filename else .file_view;
- self.filename.select_all = true;
+ self.filename.selectStem();
self.updateTitle();
}
@@ -1853,7 +1853,7 @@ pub const App = struct {
index = (index + (if (self.shift) order.len - 1 else 1)) % order.len;
self.focus = order[index];
if (self.focus == .chooser_choice) self.chooser_choice_index = index - 4;
- if (self.focus == .filename) self.filename.select_all = true;
+ if (self.focus == .filename) self.filename.selectStem();
if (self.focus == .location_bar and self.search_visible) {
self.search_visible = false;
self.search.text.clearRetainingCapacity();
diff --git a/src/files/editor.zig b/src/files/editor.zig
index edd25da..4a62177 100644
--- a/src/files/editor.zig
+++ b/src/files/editor.zig
@@ -25,6 +25,20 @@ pub const Editor = struct {
self.select_all = false;
}
}
+ /// Length of `name` without its extension (`.tar.gz` counts as one), so
+ /// typing over the selection renames the file and keeps its type. A
+ /// dotfile or a name without an extension is all stem.
+ pub fn stemLength(name: []const u8) usize {
+ var end = name.len - std.fs.path.extension(name).len;
+ if (end > 4 and std.ascii.eqlIgnoreCase(name[end - 4 .. end], ".tar")) end -= 4;
+ return end;
+ }
+ /// Selects the stem of the text.
+ pub fn selectStem(self: *Editor) void {
+ self.select_all = false;
+ self.anchor = 0;
+ self.cursor = stemLength(self.text.items);
+ }
pub fn set(self: *Editor, a: std.mem.Allocator, value: []const u8) !void {
try self.text.ensureTotalCapacity(a, value.len);
self.text.clearRetainingCapacity();
@@ -117,3 +131,13 @@ test "UTF-8 selection, words, deletion and shortcut isolation" {
e.key(a, c.XKB_KEY_c, "c", true, false, false);
try std.testing.expectEqualStrings("αβ", e.text.items);
}
+
+test "stem selection keeps the extension" {
+ try std.testing.expectEqual(@as(usize, 5), Editor.stemLength("photo.png"));
+ try std.testing.expectEqual(@as(usize, 7), Editor.stemLength("archive.tar.gz"));
+ try std.testing.expectEqual(@as(usize, 7), Editor.stemLength("archive.TAR"));
+ try std.testing.expectEqual(@as(usize, 7), Editor.stemLength(".bashrc"));
+ try std.testing.expectEqual(@as(usize, 4), Editor.stemLength("name"));
+ try std.testing.expectEqual(@as(usize, 0), Editor.stemLength(""));
+ try std.testing.expectEqual(@as(usize, 4), Editor.stemLength(".tar"));
+}
diff --git a/src/files/main.zig b/src/files/main.zig
index 4120527..74293eb 100644
--- a/src/files/main.zig
+++ b/src/files/main.zig
@@ -121,6 +121,9 @@ pub const Client = struct {
xkb_context: ?*c.xkb_context = null,
xkb_state: ?*c.xkb_state = null,
key_repeat: key_repeat.KeyRepeat = .{},
+ compose: @import("ui").compose.Compose = .{},
+ /// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).
+ locale: []const u8 = "",
app: app_mod.App,
pub fn registryEvent(registry: *wl.Registry, event: wl.Registry.Event, self: *Client) void {
@@ -545,10 +548,20 @@ pub const Client = struct {
const sym = c.xkb_state_key_get_one_sym(state, key + 8);
var buf: [64]u8 = undefined;
const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
+ // Dead keys have no text of their own: sequences resolve here, and a
+ // shortcut modifier abandons a half-typed one.
+ if (!self.app.ctrl and !self.app.alt) {
+ var composed: [64]u8 = undefined;
+ if (self.compose.feed(self.locale, sym, &composed)) |text| {
+ if (text.len > 0) self.app.handleKey(0, text);
+ return;
+ }
+ } else self.compose.reset();
self.app.handleKey(sym, buf[0..@intCast(std.math.clamp(n, 0, 63))]);
}
fn appRepeats(self: *Client, key: u32) bool {
+ if (self.compose.consumed) return false;
const state = self.xkb_state orelse return false;
var buf: [64]u8 = undefined;
const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
@@ -568,6 +581,7 @@ pub const Client = struct {
.enter => self.app.refreshPins(),
.leave => {
self.key_repeat.stop();
+ self.compose.reset();
self.app.menu = null;
self.app.ctrl = false;
self.app.shift = false;
@@ -1266,7 +1280,9 @@ pub fn run(init: std.process.Init, target_dir: []const u8, selected_file: ?[]con
var self = Client{
.display = display,
.app = app,
+ .locale = @import("ui").compose.localeFromEnviron(init.minimal.environ),
};
+ defer self.compose.deinit();
defer self.app.deinit();
if (chooser) |options| try self.app.configureChooser(options);
if (selected_file) |path| self.app.selectOnLoad(path);
diff --git a/src/icon_cache.zig b/src/icon_cache.zig
index 5c89447..4e473bc 100644
--- a/src/icon_cache.zig
+++ b/src/icon_cache.zig
@@ -44,6 +44,7 @@ extern fn g_error_free(err: *GError) void;
// `pub`: icon_service.zig frees rasters it evicts with this same allocator,
// since that's what actually produced the pixel buffers below.
pub const gpa = std.heap.c_allocator;
+const ui = @import("ui");
const png = @import("png.zig");
const icon_theme = @import("icon_theme.zig");
@@ -88,7 +89,7 @@ pub fn get(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32)
// dangling pointer the moment icon_service frees an evicted raster.
pub fn lookup(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32) !?Entry {
if (std.mem.eql(u8, icon_name, "builtin:redi-logo")) {
- const bytes = @embedFile("assets/redi-logo.svg");
+ const bytes = ui.shell_icons.redi_logo;
var err: ?*GError = null;
const handle = rsvg_handle_new_from_data(bytes.ptr, bytes.len, &err) orelse {
if (err) |e| g_error_free(e);
diff --git a/src/images/app.zig b/src/images/app.zig
index d343963..196f267 100644
--- a/src/images/app.zig
+++ b/src/images/app.zig
@@ -38,6 +38,8 @@ pub const App = struct {
w: i32 = 1080,
h: i32 = 720,
scale: i32 = 1,
+ /// Fractional device pixels per logical pixel; `scale` is its ceiling.
+ density: f64 = 1,
dirty: bool = true,
title_changed: bool = true,
title: [1024:0]u8 = @splat(0),
@@ -365,7 +367,7 @@ pub const App = struct {
},
.actual => {
self.view.fitting = false;
- self.view.zoom = 1 / @as(f64, @floatFromInt(self.scale));
+ self.view.zoom = 1 / self.density;
self.clamp();
},
}
@@ -1123,7 +1125,7 @@ pub const App = struct {
}
if (self.stripBar()) |bar| shell_ui.drawScrollbar(cr, scrollbar.look(bar, self.strip_appearance, ui_theme.global.scrollbar_width, ui_theme.shellPalette()));
var status: [160]u8 = undefined;
- const text = if (self.image) |im| std.fmt.bufPrint(&status, "{d} × {d} · {d:.0}% · {d} / {d}", .{ im.w, im.h, self.view.scale(box, @floatFromInt(im.w), @floatFromInt(im.h)) * @as(f64, @floatFromInt(self.scale)) * 100, self.position() + 1, self.count() }) catch "" else "Space / Esc to close · Arrow keys to browse";
+ const text = if (self.image) |im| std.fmt.bufPrint(&status, "{d} × {d} · {d:.0}% · {d} / {d}", .{ im.w, im.h, self.view.scale(box, @floatFromInt(im.w), @floatFromInt(im.h)) * self.density * 100, self.position() + 1, self.count() }) catch "" else "Space / Esc to close · Arrow keys to browse";
setSource(cr, t.window_fg);
drawText(cr, text, (@as(f64, @floatFromInt(self.w)) - measureText(cr, text, shell_ui.statusSize(), false)) / 2, @floatFromInt(self.h - 3), shell_ui.statusSize(), false);
if (self.dialog != .none) self.drawDialog(cr);
diff --git a/src/images/main.zig b/src/images/main.zig
index 4777b77..9edd222 100644
--- a/src/images/main.zig
+++ b/src/images/main.zig
@@ -27,6 +27,21 @@ const OutputInfo = struct {
logical: ?*zxdg.OutputV1 = null,
logical_width: i32 = 0,
logical_height: i32 = 0,
+ mode_width: i32 = 0,
+ mode_height: i32 = 0,
+
+ /// Physical pixels per logical pixel. `wl_output.scale` is the integer
+ /// ceiling, so a 1.5 output reads as 2; the mode and the logical size
+ /// give the real factor. Anything outside (scale - 1, scale] (a rotated
+ /// or nested output) falls back to the integer.
+ fn density(self: OutputInfo) f64 {
+ const whole: f64 = @floatFromInt(self.scale);
+ const logical = @max(self.logical_width, self.logical_height);
+ const mode = @max(self.mode_width, self.mode_height);
+ if (logical <= 0 or mode <= 0) return whole;
+ const real = @as(f64, @floatFromInt(mode)) / @as(f64, @floatFromInt(logical));
+ return if (real > whole - 1 and real <= whole + 0.01) real else whole;
+ }
};
pub const Client = struct {
@@ -37,6 +52,7 @@ pub const Client = struct {
outputs: std.ArrayList(*OutputInfo) = .empty,
entered_outputs: std.ArrayList(*OutputInfo) = .empty,
scale: i32 = 1,
+ density: f64 = 1,
seat: ?*wl.Seat = null,
pointer: ?*wl.Pointer = null,
keyboard: ?*wl.Keyboard = null,
@@ -67,6 +83,9 @@ pub const Client = struct {
xkb_context: ?*c.xkb_context = null,
xkb_state: ?*c.xkb_state = null,
key_repeat: key_repeat.KeyRepeat = .{},
+ compose: @import("ui").compose.Compose = .{},
+ /// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).
+ locale: []const u8 = "",
app: app_mod.App,
pub fn registryEvent(registry: *wl.Registry, event: wl.Registry.Event, self: *Client) void {
@@ -173,13 +192,22 @@ pub const Client = struct {
if (event == .logical_size) {
info.logical_width = event.logical_size.width;
info.logical_height = event.logical_size.height;
+ info.client.recomputeScale();
}
}
fn outputEvent(_: *wl.Output, event: wl.Output.Event, info: *OutputInfo) void {
- if (event == .scale) {
- info.scale = std.math.clamp(event.scale.factor, 1, 4);
- info.client.recomputeScale();
+ switch (event) {
+ .scale => |ev| {
+ info.scale = std.math.clamp(ev.factor, 1, 4);
+ info.client.recomputeScale();
+ },
+ .mode => |ev| if (ev.flags.current) {
+ info.mode_width = ev.width;
+ info.mode_height = ev.height;
+ info.client.recomputeScale();
+ },
+ else => {},
}
}
@@ -189,10 +217,16 @@ pub const Client = struct {
// wl_surface.enter is received.
fn recomputeScale(self: *Client) void {
var new_scale: i32 = 1;
- for (self.entered_outputs.items) |info| new_scale = @max(new_scale, info.scale);
- if (new_scale != self.scale) {
+ var new_density: f64 = 1;
+ for (self.entered_outputs.items) |info| {
+ new_scale = @max(new_scale, info.scale);
+ new_density = @max(new_density, info.density());
+ }
+ if (new_scale != self.scale or new_density != self.density) {
self.scale = new_scale;
+ self.density = new_density;
self.app.scale = new_scale;
+ self.app.density = new_density;
self.app.dirty = true;
}
}
@@ -443,10 +477,20 @@ pub const Client = struct {
const sym = c.xkb_state_key_get_one_sym(state, key + 8);
var buf: [64]u8 = undefined;
const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
+ // Dead keys have no text of their own: sequences resolve here, and a
+ // shortcut modifier abandons a half-typed one.
+ if (!self.app.ctrl and !self.app.alt) {
+ var composed: [64]u8 = undefined;
+ if (self.compose.feed(self.locale, sym, &composed)) |text| {
+ if (text.len > 0) self.app.handleKey(0, text);
+ return;
+ }
+ } else self.compose.reset();
self.app.handleKey(sym, buf[0..@intCast(std.math.clamp(n, 0, 63))]);
}
fn appRepeats(self: *Client, key: u32) bool {
+ if (self.compose.consumed) return false;
const state = self.xkb_state orelse return false;
var buf: [64]u8 = undefined;
const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
@@ -465,6 +509,7 @@ pub const Client = struct {
switch (event) {
.leave => {
self.key_repeat.stop();
+ self.compose.reset();
self.app.cancelDrag();
self.app.ctrl = false;
self.app.shift = false;
@@ -714,7 +759,8 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, selected: usize,
}
const display = try wl.Display.connect(null);
defer display.disconnect();
- var self = Client{ .display = display, .app = try app_mod.App.init(paths, selected), .return_focus = return_focus };
+ var self = Client{ .display = display, .app = try app_mod.App.init(paths, selected), .return_focus = return_focus, .locale = @import("ui").compose.localeFromEnviron(init.minimal.environ) };
+ defer self.compose.deinit();
self.app.io = init.io;
defer self.app.deinit();
defer for (self.buffers) |slot| {
diff --git a/src/ipc/commands.zig b/src/ipc/commands.zig
index 5cfc22d..a21fadb 100644
--- a/src/ipc/commands.zig
+++ b/src/ipc/commands.zig
@@ -46,6 +46,19 @@ pub const CommandSpec = struct {
// Canonical v1 names and internal parameter-parser routes.
pub const specs = [_]CommandSpec{
+ .{ .id = .set_desktop_mode, .kind = .action, .description = "Set Canvas or Workspaces mode", .params_schema = "{\"mode\":\"canvas\" | \"workspaces\", \"persist\"?:boolean}", .description_order = 101 },
+ .{ .id = .set_workspace_layout, .kind = .action, .description = "Set a workspace to automatic tiling or floating", .params_schema = "{\"workspace\":number, \"automatic\":boolean}", .description_order = 102 },
+ .{ .id = .switch_workspace, .kind = .action, .description = "Activate a workspace", .params_schema = "{\"workspace\":number}", .description_order = 103 },
+ .{ .id = .move_to_workspace, .kind = .action, .description = "Move a window and its dialogs or tabs to a workspace and follow", .params_schema = "{\"id\":number, \"workspace\":number}", .description_order = 104 },
+ .{ .id = .set_window_gap, .kind = .action, .description = "Set the gap at workspace edges and between tiles", .params_schema = "{\"gap\":number, \"persist\"?:boolean}", .description_order = 105 },
+ .{ .id = .set_floating_apps, .kind = .action, .description = "Set app ID glob patterns that float by default", .params_schema = "{\"apps\":string[], \"persist\"?:boolean}", .description_order = 106 },
+ .{
+ .id = .tiling_action,
+ .kind = .action,
+ .description = "Toggle floating/workspace tiling, rotate, swap or resize an automatic split",
+ .params_schema = "{\"action\": \"toggle_floating\" | \"toggle_workspace_tiling\" | \"toggle_split\" | \"swap_left\" | \"swap_right\" | \"swap_up\" | \"swap_down\" | \"resize_split_left\" | \"resize_split_right\" | \"resize_split_up\" | \"resize_split_down\", \"id\"?: number}",
+ .description_order = 100,
+ },
.{
.id = .version,
.kind = .query,
diff --git a/src/ipc/events.zig b/src/ipc/events.zig
index 000fa96..2206b92 100644
--- a/src/ipc/events.zig
+++ b/src/ipc/events.zig
@@ -129,11 +129,13 @@ pub fn sendSnapshot(ipc: *ipc_server_mod.Server, client: *ipc_server_mod.Client)
const focused_id: ?u64 = if (handlers.findFocusedToplevel(compositor)) |t| t.id else null;
+ const workspaces = try compositor.world.workspaces.data(compositor, ipc.allocator);
+ defer if (compositor.world.workspaces.active) ipc.allocator.free(workspaces);
const snap: protocol.StateSnapshot = .{
.seq = ipc.seq,
.windows = wins.items,
.outputs = outs.items,
- .workspaces = &.{.{ .id = 1, .name = "Canvas", .is_focused = true }},
+ .workspaces = workspaces,
.focused_window_id = focused_id,
.session_id = ipc.session_id,
.time_ms = anim.nowMs(),
diff --git a/src/ipc/handlers.zig b/src/ipc/handlers.zig
index 0195f02..08a280d 100644
--- a/src/ipc/handlers.zig
+++ b/src/ipc/handlers.zig
@@ -115,7 +115,7 @@ pub fn handleRequest(
}
},
.workspaces => {
- return .{ .ok = .{ .workspaces = &.{.{ .id = 1, .name = "Canvas", .is_focused = true }} } };
+ return .{ .ok = .{ .workspaces = try server.world.workspaces.data(server, allocator) } };
},
.event_stream => {
return .{ .ok = .handled };
@@ -146,7 +146,7 @@ pub fn handleRequest(
.camera = makeCameraData(server),
.focused_window_id = focused_id,
.shell = makeShellStateData(server),
- .workspaces = &.{.{ .id = 1, .name = "Canvas", .is_focused = true }},
+ .workspaces = try server.world.workspaces.data(server, allocator),
} } };
},
.get_window_debug => |p| {
@@ -208,7 +208,7 @@ pub fn handleRequest(
.maximized = toplevel.isMaximized(),
.fullscreen = toplevel.isFullscreen(),
.is_resizing = toplevel.isResizing(),
- .zoom_percent = @import("../camera.zig").zoom_levels[toplevel.zoom_index],
+ .zoom_percent = if (server.world.workspaces.active) 100 else @import("../camera.zig").zoom_levels[toplevel.zoom_index],
.effective_zoom = toplevel.zoom(),
.zoom_boosted = toplevel.zoom_boost.to != 0,
.source_box = .{ .x = src_box.x, .y = src_box.y, .width = src_box.width, .height = src_box.height },
@@ -724,7 +724,7 @@ fn handleAction(
const msg = try std.fmt.allocPrint(allocator, "UnknownWindow: {d}", .{p.id});
return .{ .err = msg };
};
- if (toplevel.isResizing() or (server.input.cursor_mode == .move and server.input.grabbed_toplevel == toplevel)) return .{ .err = "Busy" };
+ if (toplevel.isResizing() or ((server.input.cursor_mode == .move or server.input.tiling_grab != null) and server.input.grabbed_toplevel == toplevel)) return .{ .err = "Busy" };
if (p.output) |name| {
const target_output = findOutputByName(server, name) orelse {
@@ -732,6 +732,11 @@ fn handleAction(
return .{ .err = msg };
};
if (!target_output.isAvailable()) return .{ .err = "OutputUnavailable" };
+ var transaction: ?@import("../layout_undo.zig").Transaction = if (server.world.workspaces.active)
+ @import("../layout_undo.zig").Transaction.begin(server, &.{ toplevel.workspace_id, target_output.workspace_id })
+ else
+ null;
+ defer if (transaction) |*change| change.finish();
const old_x = toplevel.x;
const old_y = toplevel.y;
if (!toplevel.moveToOutput(target_output)) return .{ .err = "WindowUnavailable" };
@@ -746,7 +751,21 @@ fn handleAction(
child.setPosition(child.x + dx, child.y + dy);
}
} else {
+ var transaction: ?@import("../layout_undo.zig").Transaction = if (server.world.workspaces.active)
+ @import("../layout_undo.zig").Transaction.begin(server, &.{toplevel.workspace_id})
+ else
+ null;
+ defer if (transaction) |*change| change.finish();
+ const floating = toplevel.auto_restore;
+ @import("../auto_tiling.zig").setFloating(toplevel, true);
toplevel.setPosition(p.x, p.y);
+ if (floating) |saved| {
+ // This explicit placement is final; a delayed restore must
+ // not move it back after a subsequent interactive drag.
+ toplevel.pending_restore = null;
+ toplevel.finishSizeAnimation();
+ _ = toplevel.requestSize(saved.width, saved.height);
+ }
}
toplevel.syncChrome(false, false, Toplevel.nowMs()) catch {};
return .{ .ok = .handled };
@@ -1273,6 +1292,41 @@ fn handleAction(
},
// Phase 4 targeted actions
+ .set_desktop_mode => |p| {
+ @import("../config_runtime/workspace_controls.zig").mode(server, p.mode, p.persist) catch |err| return .{ .err = @errorName(err) };
+ return .{ .ok = .handled };
+ },
+ .set_window_gap => |p| {
+ @import("../config_runtime/workspace_controls.zig").gap(server, p.gap, p.persist) catch |err| return .{ .err = @errorName(err) };
+ return .{ .ok = .handled };
+ },
+ .set_floating_apps => |p| {
+ @import("../config_runtime/workspace_controls.zig").floatingApps(server, p.apps, p.persist) catch |err| return .{ .err = @errorName(err) };
+ return .{ .ok = .handled };
+ },
+ .set_workspace_layout => |p| {
+ if (!server.world.workspaces.active) return .{ .err = "WorkspaceModeRequired" };
+ @import("../config_runtime/workspace_controls.zig").automatic(server, p.workspace, p.automatic);
+ return .{ .ok = .handled };
+ },
+ .switch_workspace => |p| {
+ if (!server.world.workspaces.active) return .{ .err = "WorkspaceModeRequired" };
+ server.world.workspaces.switchTo(server, p.workspace);
+ return .{ .ok = .handled };
+ },
+ .move_to_workspace => |p| {
+ if (!server.world.workspaces.active) return .{ .err = "WorkspaceModeRequired" };
+ const top = findToplevelById(server, p.id) orelse return .{ .err = "UnknownWindow" };
+ server.world.workspaces.moveTo(top, p.workspace);
+ return .{ .ok = .handled };
+ },
+ .tiling_action => |p| {
+ if (!server.world.workspaces.active) return .{ .err = "WorkspaceModeRequired" };
+ const top = if (p.id) |id| findToplevelById(server, id) orelse return .{ .err = "UnknownWindow" } else findFocusedToplevel(server);
+ if (top) |target| if (!target.in_world or !@import("../workspaces.zig").visible(target)) return .{ .err = "WindowNotVisible" };
+ @import("../auto_tiling.zig").execute(server, top, p.action);
+ return .{ .ok = .handled };
+ },
.maximize_window => |p| {
const toplevel = findToplevelById(server, p.id) orelse return .{ .err = "UnknownWindow" };
toplevel.setMaximized(true);
@@ -1287,9 +1341,9 @@ fn handleAction(
const toplevel = findToplevelById(server, p.id) orelse return .{ .err = "UnknownWindow" };
if (toplevel.minimized) {
toplevel.restore();
- } else if (toplevel.isMaximized()) {
+ } else if (toplevel.maximized) {
toplevel.setMaximized(false);
- } else if (toplevel.isFullscreen()) {
+ } else if (toplevel.fullscreen) {
toplevel.setFullscreen(false);
}
return .{ .ok = .handled };
@@ -1297,7 +1351,7 @@ fn handleAction(
.fullscreen_window => |p| {
const toplevel = findToplevelById(server, p.id) orelse return .{ .err = "UnknownWindow" };
_ = p.output;
- toplevel.setFullscreen(!toplevel.isFullscreen());
+ toplevel.toggleFullscreen();
return .{ .ok = .handled };
},
.stop_xwayland => {
@@ -1308,6 +1362,14 @@ fn handleAction(
.set_window_size => |p| {
const toplevel = findToplevelById(server, p.id) orelse return .{ .err = "UnknownWindow" };
if (p.width <= 0 or p.height <= 0) return .{ .err = "InvalidCoordinates" };
+ if (server.input.tiling_grab != null) server.input.finishTilingGrab(false);
+ var transaction: ?@import("../layout_undo.zig").Transaction = if (server.world.workspaces.active)
+ @import("../layout_undo.zig").Transaction.begin(server, &.{toplevel.workspace_id})
+ else
+ null;
+ defer if (transaction) |*change| change.finish();
+ if (transaction) |*change| change.resized = .{ .id = toplevel.id, .width = p.width, .height = p.height };
+ if (toplevel.auto_target != null) toplevel.leaveLayout();
_ = toplevel.requestSizeAnimated(p.width, p.height);
return .{ .ok = .handled };
},
@@ -1641,6 +1703,7 @@ fn getWindowRules(server: *Server, id: u64, allocator: std.mem.Allocator) !proto
.effective_opacity = effective_opacity,
.decorations = dec_str,
.skip_taskbar = toplevel.live_rules.skip_taskbar,
+ .floating = toplevel.live_rules.floating,
},
.resolved_before_app_id = toplevel.resolved_before_app_id,
} } };
@@ -1690,6 +1753,7 @@ fn matchWindowRules(server: *Server, params: protocol.MatchWindowRulesParams, al
.effective_opacity = null,
.decorations = dec_str,
.skip_taskbar = live_r.skip_taskbar,
+ .floating = live_r.floating,
},
} } };
}
@@ -2739,7 +2803,10 @@ pub fn makeWindowData(server: *Server, toplevel: *Toplevel) protocol.WindowData
.tab_group = if (toplevel.tab_group != 0) toplevel.tab_group else null,
.tab_active = !toplevel.tab_hidden,
.is_maximized = toplevel.isMaximized(),
- .workspace_id = 1,
+ .workspace_order = toplevel.workspace_order,
+ .placement = if (toplevel.fullscreen) "fullscreen" else if (toplevel.maximized) "maximized" else if (toplevel.tile != null) "manual" else if (toplevel.auto_target != null) "automatic" else "floating",
+ .floating_override = toplevel.auto_float_override,
+ .workspace_id = if (server.world.workspaces.active) toplevel.workspace_id else 1,
.tag = @import("../extra_protocols.zig").tag(toplevel.surface(), false),
.description = @import("../extra_protocols.zig").tag(toplevel.surface(), true),
.content_type = @import("../extra_protocols.zig").content(server, toplevel.surface()),
@@ -2747,7 +2814,7 @@ pub fn makeWindowData(server: *Server, toplevel: *Toplevel) protocol.WindowData
.y = toplevel.y,
.width = toplevel.logicalWidth(),
.height = toplevel.logicalHeight(),
- .zoom_percent = @import("../camera.zig").zoom_levels[toplevel.zoom_index],
+ .zoom_percent = if (server.world.workspaces.active) 100 else @import("../camera.zig").zoom_levels[toplevel.zoom_index],
.backend = toplevel.backendName(),
.x11_class = toplevel.x11Class(),
.x11_instance = toplevel.x11Instance(),
@@ -2867,7 +2934,10 @@ pub fn findToplevelById(server: *Server, id: u64) ?*Toplevel {
}
pub fn findFocusedToplevel(server: *Server) ?*Toplevel {
- if (server.input.seat.keyboard_state.focused_surface) |surface| return Toplevel.fromSurface(server, surface);
+ if (server.input.seat.keyboard_state.focused_surface) |surface| {
+ const top = Toplevel.fromSurface(server, surface) orelse return null;
+ return if (@import("../workspaces.zig").visible(top)) top else null;
+ }
// The settings window is focused without a wl_surface.
if (server.input.open_control_center) |cc| if (cc.hasKeyboardFocus()) return cc.toplevel;
return null;
diff --git a/src/ipc/protocol.zig b/src/ipc/protocol.zig
index 7a9ed1b..e0d7ac6 100644
--- a/src/ipc/protocol.zig
+++ b/src/ipc/protocol.zig
@@ -73,6 +73,9 @@ pub const WindowData = struct {
is_minimized: bool,
is_maximized: bool,
workspace_id: ?u64 = null,
+ workspace_order: u64 = 0,
+ placement: []const u8 = "floating",
+ floating_override: ?bool = null,
x: i32,
y: i32,
width: i32,
@@ -107,6 +110,12 @@ pub const WindowData = struct {
try jws.write(self.is_minimized);
try jws.objectField("is_maximized");
try jws.write(self.is_maximized);
+ try jws.objectField("workspace_order");
+ try jws.write(self.workspace_order);
+ try jws.objectField("placement");
+ try jws.write(self.placement);
+ try jws.objectField("floating_override");
+ try jws.write(self.floating_override);
try jws.objectField("workspace_id");
try jws.write(self.workspace_id);
try jws.objectField("x");
@@ -166,6 +175,11 @@ pub const OutputData = struct {
};
pub const WorkspaceData = struct {
+ is_visible: bool = true,
+ output: ?[]const u8 = null,
+ automatic: bool = false,
+ window_gap: u32 = 0,
+ nodes: []const @import("config").workspace_layout.Node = &.{},
id: u64,
name: ?[]const u8 = null,
is_focused: bool = false,
@@ -365,6 +379,7 @@ pub const OpenRulesData = struct {
};
pub const LiveRulesData = struct {
+ floating: ?bool = null,
opacity: ?f32 = null,
effective_opacity: ?f32 = null,
decorations: ?[]const u8 = null,
@@ -1033,6 +1048,13 @@ pub const Action = union(enum) {
advance_idle_time: struct { seconds: u32 },
// Phase 4 targeted actions
+ set_desktop_mode: struct { mode: @import("config").loader.DesktopMode, persist: bool = true },
+ set_workspace_layout: struct { workspace: u8, automatic: bool },
+ switch_workspace: struct { workspace: u8 },
+ move_to_workspace: struct { id: u64, workspace: u8 },
+ set_window_gap: struct { gap: u32, persist: bool = true },
+ set_floating_apps: struct { apps: []const []const u8, persist: bool = true },
+ tiling_action: struct { action: @import("config").keybinds.TilingAction, id: ?u64 = null },
maximize_window: struct { id: u64 },
minimize_window: struct { id: u64 },
restore_window: struct { id: u64 },
@@ -2305,6 +2327,50 @@ fn parseActionParams(allocator: std.mem.Allocator, command_tag: commands.RouteTa
}
return .{ .set_night_light_clock = .{ .unix_seconds = sec } };
},
+ .set_desktop_mode => {
+ const p = params orelse return error.InvalidRequest;
+ const mode = p.get("mode") orelse return error.InvalidRequest;
+ if (mode != .string) return error.InvalidRequest;
+ return .{ .set_desktop_mode = .{ .mode = std.meta.stringToEnum(@import("config").loader.DesktopMode, mode.string) orelse return error.InvalidRequest, .persist = try persistParam(p) } };
+ },
+ .switch_workspace, .move_to_workspace, .set_workspace_layout => {
+ const p = params orelse return error.InvalidRequest;
+ const id = try parseU32(p.get("workspace") orelse return error.InvalidRequest);
+ if (id == 0 or id > 32) return error.InvalidRequest;
+ switch (command_tag) {
+ .switch_workspace => return .{ .switch_workspace = .{ .workspace = @intCast(id) } },
+ .move_to_workspace => return .{ .move_to_workspace = .{ .id = try parseU64(p.get("id") orelse return error.InvalidRequest), .workspace = @intCast(id) } },
+ else => {
+ const automatic = p.get("automatic") orelse return error.InvalidRequest;
+ if (automatic != .bool) return error.InvalidRequest;
+ return .{ .set_workspace_layout = .{ .workspace = @intCast(id), .automatic = automatic.bool } };
+ },
+ }
+ },
+ .set_window_gap => {
+ const p = params orelse return error.InvalidRequest;
+ const gap = try parseU32(p.get("gap") orelse return error.InvalidRequest);
+ if (gap > 512) return error.InvalidRequest;
+ return .{ .set_window_gap = .{ .gap = gap, .persist = try persistParam(p) } };
+ },
+ .set_floating_apps => {
+ const p = params orelse return error.InvalidRequest;
+ const values = p.get("apps") orelse return error.InvalidRequest;
+ if (values != .array or values.array.items.len > 256) return error.InvalidRequest;
+ const apps = try allocator.alloc([]const u8, values.array.items.len);
+ for (values.array.items, apps) |value, *dest| {
+ if (value != .string or value.string.len == 0 or value.string.len > 512) return error.InvalidRequest;
+ dest.* = try allocator.dupe(u8, value.string);
+ }
+ return .{ .set_floating_apps = .{ .apps = apps, .persist = try persistParam(p) } };
+ },
+ .tiling_action => {
+ const p = params orelse return error.InvalidRequest;
+ const action = p.get("action") orelse return error.InvalidRequest;
+ if (action != .string) return error.InvalidRequest;
+ const tag = std.meta.stringToEnum(@import("config").keybinds.TilingAction, action.string) orelse return error.InvalidRequest;
+ return .{ .tiling_action = .{ .action = tag, .id = if (p.get("id")) |id| try parseOptU64(id) else null } };
+ },
.maximize_window => {
const p = params orelse return error.InvalidRequest;
const id_v = p.get("id") orelse p.get("window_id") orelse return error.InvalidRequest;
@@ -2858,6 +2924,8 @@ fn stringifyLiveRules(live: LiveRulesData, writer: anytype) !void {
if (live.effective_opacity) |eo| try writer.print("{d}", .{eo}) else try writer.writeAll("null");
try writer.writeAll(",\"decorations\":");
if (live.decorations) |d| try writer.print("{f}", .{std.json.fmt(d, .{})}) else try writer.writeAll("null");
+ try writer.writeAll(",\"floating\":");
+ if (live.floating) |value| try writer.print("{}", .{value}) else try writer.writeAll("null");
try writer.writeAll(",\"skip_taskbar\":");
if (live.skip_taskbar) |st| try writer.print("{}", .{st}) else try writer.writeAll("null");
try writer.writeByte('}');
diff --git a/src/ipc_serializers.jsonl b/src/ipc_serializers.jsonl
index 59f7714..be84c16 100644
--- a/src/ipc_serializers.jsonl
+++ b/src/ipc_serializers.jsonl
@@ -18,14 +18,14 @@
{"Ok":{"Capabilities":["text \"quoted\"\n\\"]}}
{"Ok":{"DescribeIPC":{"protocol_version":"text \"quoted\"\n\\","build_version":"text \"quoted\"\n\\","backend":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","commands":[{"name":"text \"quoted\"\n\\","kind":"text \"quoted\"\n\\","description":"text \"quoted\"\n\\","params_schema":"text \"quoted\"\n\\","units":null}],"unavailable_reasons":["text \"quoted\"\n\\"]}}}
{"Ok":{"DescribeIPC":{"protocol_version":"text \"quoted\"\n\\","build_version":"text \"quoted\"\n\\","backend":"text \"quoted\"\n\\","renderer":"text \"quoted\"\n\\","commands":[{"name":"text \"quoted\"\n\\","kind":"text \"quoted\"\n\\","description":"text \"quoted\"\n\\","params_schema":"text \"quoted\"\n\\","units":"text \"quoted\"\n\\"}],"unavailable_reasons":["text \"quoted\"\n\\"]}}}
-{"Ok":{"Windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false}]}}
-{"Ok":{"Windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true}]}}
+{"Ok":{"Windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false,"workspace_order":0,"placement":"text \"quoted\"\n\\","floating_override":null}]}}
+{"Ok":{"Windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}]}}
{"Ok":{"Outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false}]}}
{"Ok":{"Outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true}]}}
{"Ok":{"FocusedWindow":null}}
-{"Ok":{"FocusedWindow":{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true}}}
-{"Ok":{"Workspaces":[{"id":0,"name":null,"is_focused":false}]}}
-{"Ok":{"Workspaces":[{"id":7,"name":"text \"quoted\"\n\\","is_focused":true}]}}
+{"Ok":{"FocusedWindow":{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}}}
+{"Ok":{"Workspaces":[{"id":0,"name":null,"is_focused":false,"is_visible":false,"output":null,"automatic":false,"window_gap":0,"nodes":[{"id":null,"group":false,"axis":"horizontal","ratio":0}]}]}}
+{"Ok":{"Workspaces":[{"id":7,"name":"text \"quoted\"\n\\","is_focused":true,"is_visible":true,"output":"text \"quoted\"\n\\","automatic":true,"window_gap":7,"nodes":[{"id":7,"group":true,"axis":"horizontal","ratio":1.23456}]}]}}
{"Ok":{"Screenshot":{"width":0,"height":0,"format":"text \"quoted\"\n\\","data":null,"path":null,"output_name":"text \"quoted\"\n\\","capture_mode":"text \"quoted\"\n\\","frame_seq":0}}}
{"Ok":{"Screenshot":{"width":7,"height":7,"format":"text \"quoted\"\n\\","data":"text \"quoted\"\n\\","path":"text \"quoted\"\n\\","output_name":"text \"quoted\"\n\\","capture_mode":"text \"quoted\"\n\\","frame_seq":7,"crop_applied":{"x":7,"y":7,"width":7,"height":7}}}}
{"Ok":{"Camera":{"x":0,"y":0,"max_x":0,"max_y":0,"zoom_percent":0}}}
@@ -34,8 +34,8 @@
{"Ok":{"AudioState":{"master_volume":1.23456,"master_muted":true,"default_sink":"text \"quoted\"\n\\","streams":[{"index":7,"name":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","pid":7,"volume":1.23456,"muted":true}]}}}
{"Ok":{"PanelStats":{"paints":0,"allocated_bytes":0,"reused_bytes":0,"paint_ns":0}}}
{"Ok":{"PanelStats":{"paints":7,"allocated_bytes":7,"reused_bytes":7,"paint_ns":7}}}
-{"Ok":{"State":{"seq":0,"session_id":"text \"quoted\"\n\\","focused_window_id":null,"windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false}],"outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false}],"camera":{"x":0,"y":0,"max_x":0,"max_y":0,"zoom_percent":0},"shell":{"start_menu":null,"control_center":null,"power_menu":null,"taskbar_count":0,"polkit_dialog":null},"workspaces":[{"id":0,"name":null,"is_focused":false}]}}}
-{"Ok":{"State":{"seq":7,"session_id":"text \"quoted\"\n\\","focused_window_id":7,"windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true}],"outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true}],"camera":{"x":7,"y":7,"max_x":7,"max_y":7,"zoom_percent":7},"shell":{"start_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"control_center":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"power_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"taskbar_count":7,"polkit_dialog":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7}},"workspaces":[{"id":7,"name":"text \"quoted\"\n\\","is_focused":true}]}}}
+{"Ok":{"State":{"seq":0,"session_id":"text \"quoted\"\n\\","focused_window_id":null,"windows":[{"id":0,"title":null,"app_id":null,"sandbox":null,"pid":null,"is_focused":false,"is_minimized":false,"is_maximized":false,"workspace_id":null,"x":0,"y":0,"width":0,"height":0,"zoom_percent":0,"backend":"text \"quoted\"\n\\","x11_class":null,"x11_instance":null,"is_urgent":false,"workspace_order":0,"placement":"text \"quoted\"\n\\","floating_override":null}],"outputs":[{"name":"text \"quoted\"\n\\","make":null,"model":null,"enabled":false,"x":0,"y":0,"logical_width":0,"logical_height":0,"buffer_width":0,"buffer_height":0,"transform":"text \"quoted\"\n\\","bottom_exclusion":0,"scale":0,"refresh_hz":0,"is_focused":false}],"camera":{"x":0,"y":0,"max_x":0,"max_y":0,"zoom_percent":0},"shell":{"start_menu":null,"control_center":null,"power_menu":null,"taskbar_count":0,"polkit_dialog":null},"workspaces":[{"id":0,"name":null,"is_focused":false,"is_visible":false,"output":null,"automatic":false,"window_gap":0,"nodes":[{"id":null,"group":false,"axis":"horizontal","ratio":0}]}]}}}
+{"Ok":{"State":{"seq":7,"session_id":"text \"quoted\"\n\\","focused_window_id":7,"windows":[{"id":7,"title":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","sandbox":{"engine":"text \"quoted\"\n\\","app_id":"text \"quoted\"\n\\","instance_id":"text \"quoted\"\n\\"},"pid":7,"is_focused":true,"is_minimized":true,"is_maximized":true,"workspace_id":7,"x":7,"y":7,"width":7,"height":7,"zoom_percent":7,"backend":"text \"quoted\"\n\\","x11_class":"text \"quoted\"\n\\","x11_instance":"text \"quoted\"\n\\","is_urgent":true,"workspace_order":7,"placement":"text \"quoted\"\n\\","floating_override":true}],"outputs":[{"name":"text \"quoted\"\n\\","make":"text \"quoted\"\n\\","model":"text \"quoted\"\n\\","enabled":true,"x":7,"y":7,"logical_width":7,"logical_height":7,"buffer_width":7,"buffer_height":7,"transform":"text \"quoted\"\n\\","bottom_exclusion":7,"scale":1.23456,"refresh_hz":1.23456,"is_focused":true}],"camera":{"x":7,"y":7,"max_x":7,"max_y":7,"zoom_percent":7},"shell":{"start_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"control_center":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"power_menu":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7},"taskbar_count":7,"polkit_dialog":{"state":"text \"quoted\"\n\\","progress":1.23456,"is_settled":true,"box":{"x":7,"y":7,"width":7,"height":7},"search_text":"text \"quoted\"\n\\","category":"text \"quoted\"\n\\","selected_index":7,"result_count":7}},"workspaces":[{"id":7,"name":"text \"quoted\"\n\\","is_focused":true,"is_visible":true,"output":"text \"quoted\"\n\\","automatic":true,"window_gap":7,"nodes":[{"id":7,"group":true,"axis":"horizontal","ratio":1.23456}]}]}}}
{"Ok":{"WaitFor":{"condition":"text \"quoted\"\n\\","elapsed_ms":0,"state":null}}}
{"Ok":{"WaitFor":{"condition":"text \"quoted\"\n\\","elapsed_ms":7,"state":"text \"quoted\"\n\\"}}}
{"Ok":{"WaitForFrame":{"output":"text \"quoted\"\n\\","frame_seq":0,"elapsed_ms":0}}}
@@ -68,10 +68,10 @@
{"Ok":{"IdleState":{"enabled":true,"state":"text \"quoted\"\n\\","blank_after_seconds":7,"suspend_after_seconds":7,"idle_ms":7,"is_inhibited":true,"inhibitor_count":7,"suspend_request_count":7,"inhibitors":[{"surface_ptr":7,"window_id":7,"app_id":"text \"quoted\"\n\\","title":"text \"quoted\"\n\\","is_active":true,"reason":"text \"quoted\"\n\\"}]}}}
{"Ok":{"CaptureState":{"supported":false,"active_sessions":0,"sessions":[{"output":null,"window_id":null}],"last_failure":null,"indicator":null}}}
{"Ok":{"CaptureState":{"supported":true,"active_sessions":7,"sessions":[{"output":"text \"quoted\"\n\\","window_id":7}],"last_failure":"text \"quoted\"\n\\","indicator":{"output":"text \"quoted\"\n\\","box":{"x":7,"y":7,"width":7,"height":7}}}}}
-{"Ok":{"WindowRules":{"window_id":0,"matched_rules":[0],"open":{"output":null,"x":null,"y":null,"center":null,"width":null,"height":null,"maximized":null,"fullscreen":null,"focus":null,"depth":null},"live":{"opacity":null,"effective_opacity":null,"decorations":null,"skip_taskbar":null},"resolved_before_app_id":false}}}
-{"Ok":{"WindowRules":{"window_id":7,"matched_rules":[7],"open":{"output":"text \"quoted\"\n\\","x":7,"y":7,"center":true,"width":7,"height":7,"maximized":true,"fullscreen":true,"focus":true,"depth":7},"live":{"opacity":1.23456,"effective_opacity":1.23456,"decorations":"text \"quoted\"\n\\","skip_taskbar":true},"resolved_before_app_id":true}}}
-{"Ok":{"MatchWindowRules":{"matched_rules":[0],"open":{"output":null,"x":null,"y":null,"center":null,"width":null,"height":null,"maximized":null,"fullscreen":null,"focus":null,"depth":null},"live":{"opacity":null,"effective_opacity":null,"decorations":null,"skip_taskbar":null}}}}
-{"Ok":{"MatchWindowRules":{"matched_rules":[7],"open":{"output":"text \"quoted\"\n\\","x":7,"y":7,"center":true,"width":7,"height":7,"maximized":true,"fullscreen":true,"focus":true,"depth":7},"live":{"opacity":1.23456,"effective_opacity":1.23456,"decorations":"text \"quoted\"\n\\","skip_taskbar":true}}}}
+{"Ok":{"WindowRules":{"window_id":0,"matched_rules":[0],"open":{"output":null,"x":null,"y":null,"center":null,"width":null,"height":null,"maximized":null,"fullscreen":null,"focus":null,"depth":null},"live":{"opacity":null,"effective_opacity":null,"decorations":null,"skip_taskbar":null,"floating":null},"resolved_before_app_id":false}}}
+{"Ok":{"WindowRules":{"window_id":7,"matched_rules":[7],"open":{"output":"text \"quoted\"\n\\","x":7,"y":7,"center":true,"width":7,"height":7,"maximized":true,"fullscreen":true,"focus":true,"depth":7},"live":{"opacity":1.23456,"effective_opacity":1.23456,"decorations":"text \"quoted\"\n\\","skip_taskbar":true,"floating":true},"resolved_before_app_id":true}}}
+{"Ok":{"MatchWindowRules":{"matched_rules":[0],"open":{"output":null,"x":null,"y":null,"center":null,"width":null,"height":null,"maximized":null,"fullscreen":null,"focus":null,"depth":null},"live":{"opacity":null,"effective_opacity":null,"decorations":null,"skip_taskbar":null,"floating":null}}}}
+{"Ok":{"MatchWindowRules":{"matched_rules":[7],"open":{"output":"text \"quoted\"\n\\","x":7,"y":7,"center":true,"width":7,"height":7,"maximized":true,"fullscreen":true,"focus":true,"depth":7},"live":{"opacity":1.23456,"effective_opacity":1.23456,"decorations":"text \"quoted\"\n\\","skip_taskbar":true,"floating":true}}}}
{"Ok":{"NightLight":{"enabled":false,"schedule":"text \"quoted\"\n\\","phase":"off","temperature":0,"next_change_unix":null,"clock_overridden":false,"outputs":[{"name":"text \"quoted\"\n\\","gamma_size":0,"night_light":false,"gamma":0,"temperature":0,"status":"neutral"}]}}}
{"Ok":{"NightLight":{"enabled":true,"schedule":"text \"quoted\"\n\\","phase":"off","temperature":7,"next_change_unix":7,"clock_overridden":true,"outputs":[{"name":"text \"quoted\"\n\\","gamma_size":7,"night_light":true,"gamma":1.2345600128173828,"temperature":7,"status":"neutral"}]}}}
{"Ok":{"Notifications":{"toasts":[{"id":0,"app_name":"text \"quoted\"\n\\","summary":"text \"quoted\"\n\\","body":"text \"quoted\"\n\\","app_icon":"text \"quoted\"\n\\","urgency":0,"resident":false,"transient":false,"expire_at_ms":null,"paused":false,"closing":false}],"history":[{"id":0,"app_name":"text \"quoted\"\n\\","summary":"text \"quoted\"\n\\","body":"text \"quoted\"\n\\","app_icon":"text \"quoted\"\n\\","urgency":0,"time_ms":0,"closed":false,"close_reason":null}],"dnd":false}}}
diff --git a/src/ipc_tests.zig b/src/ipc_tests.zig
index 8dffcbb..32ef04d 100644
--- a/src/ipc_tests.zig
+++ b/src/ipc_tests.zig
@@ -877,15 +877,15 @@ test "every v1 command parses" {
\\"text":"hi","volume":0.7,"index":1,"muted":false,"ms":null,
\\"condition":"menu_opened","timeout_ms":42,"seconds":2,"enabled":true,
\\"blank_after_seconds":600,"suspend_after_seconds":0,"desktop_id":"example.desktop",
- \\"action_key":"default","phase":"begin","scale":1.2,"rotation":0,
+ \\"action":"toggle_split","action_key":"default","phase":"begin","scale":1.2,"rotation":0,
\\"fingers":2,"cancelled":false,"layout":"next","path":"start_menu/settings","at":0.5,
- \\"service":"alpha.service","mode":"on","event":"bell","color":"#aabbcc"}
+ \\"service":"alpha.service","mode":"on","event":"bell","color":"#aabbcc","workspace":2,"automatic":true,"gap":12,"apps":["utility*"]}
;
inline for (protocol.commands.specs) |s| {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
- const input = try std.fmt.allocPrint(a, "{{\"version\":1,\"command\":\"{s}\",\"params\":{s}}}", .{ comptime s.wire(), params });
+ const input = try std.fmt.allocPrint(a, "{{\"version\":1,\"command\":\"{s}\",\"params\":{s}}}", .{ comptime s.wire(), if (s.id == .set_desktop_mode) "{\"mode\":\"workspaces\"}" else params });
const request = try protocol.parseRequest(a, input);
try std.testing.expectEqualStrings(@tagName(s.id), requestCommandName(request));
}
@@ -984,3 +984,36 @@ test "v1 rejects legacy envelopes names versions and ambiguous fields" {
} else |_| {}
}
}
+
+test "tiling IPC accepts only the shared tiling actions" {
+ const a = std.testing.allocator;
+ const request = try protocol.parseRequest(a, "{\"version\":1,\"command\":\"tiling_action\",\"params\":{\"action\":\"toggle_floating\",\"id\":7}}");
+ try std.testing.expectEqual(@as(?u64, 7), request.action.tiling_action.id);
+ try std.testing.expect(request.action.tiling_action.action == .toggle_floating);
+ inline for (.{
+ "{\"action\":\"spawn\"}",
+ "{\"action\":\"toggle_split\",\"id\":-1}",
+ "{\"action\":42}",
+ "{}",
+ }) |params| {
+ try std.testing.expectError(error.InvalidRequest, protocol.parseRequest(a, "{\"version\":1,\"command\":\"tiling_action\",\"params\":" ++ params ++ "}"));
+ }
+}
+
+test "workspace controls validate IDs, spacing, patterns and mode" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const cases = .{
+ .{ "switch_workspace", "{\"workspace\":0}" },
+ .{ "move_to_workspace", "{\"id\":7,\"workspace\":33}" },
+ .{ "set_workspace_layout", "{\"workspace\":2,\"automatic\":1}" },
+ .{ "set_window_gap", "{\"gap\":513}" },
+ .{ "set_floating_apps", "{\"apps\":[true]}" },
+ .{ "set_desktop_mode", "{\"mode\":\"unknown\"}" },
+ };
+ inline for (cases) |item| {
+ const input = "{\"version\":1,\"command\":\"" ++ item[0] ++ "\",\"params\":" ++ item[1] ++ "}";
+ try std.testing.expectError(error.InvalidRequest, protocol.parseRequest(a, input));
+ }
+}
diff --git a/src/layout_undo.zig b/src/layout_undo.zig
new file mode 100644
index 0000000..d2a079a
--- /dev/null
+++ b/src/layout_undo.zig
@@ -0,0 +1,272 @@
+//! Compositor bridge for owned workspace undo snapshots. Trees retain stable
+//! identities; apply reconciles against current clients, constraints and outputs.
+const std = @import("std");
+const Server = @import("Server.zig");
+const Top = @import("Toplevel.zig");
+const workspaces = @import("workspaces.zig");
+const tiling = @import("auto_tiling.zig");
+const undo = @import("undo.zig");
+const gpa = @import("main.zig").gpa;
+pub const Snapshot = undo.LayoutSnapshot;
+
+pub fn capture(server: *Server, ids: []const u8) ?*Snapshot {
+ if (server.undo.applying or !server.world.workspaces.active) return null;
+ if (server.undo.pending) |pending| if (pending.snapshot != null) return null;
+ server.world.workspaces.tiler.flushNow(server);
+ return captureOwned(server, ids) catch |err| {
+ // An operation without a snapshot must not leave older geometry undo.
+ server.undo.clear();
+ std.log.warn("layout undo snapshot: {s}", .{@errorName(err)});
+ return null;
+ };
+}
+
+fn captureOwned(server: *Server, ids: []const u8) !*Snapshot {
+ const snapshot = try gpa.create(Snapshot);
+ snapshot.* = .{ .allocator = gpa, .generation = server.world.workspaces.generation };
+ errdefer snapshot.destroy();
+ if (@import("ipc/handlers.zig").findFocusedToplevel(server)) |top| snapshot.focus = top.id;
+ // A pointer press can focus before the grab starts. Fold that focus into
+ // the layout operation, just as the existing floating gesture undo does.
+ if (server.undo.slot) |previous| {
+ if (previous.kind == .focus and previous.press_seq == server.undo.press_seq) snapshot.focus = previous.focus;
+ }
+ var affected: [workspaces.count]bool = @splat(false);
+ for (ids) |id| {
+ if (id == 0 or id > workspaces.count or affected[id - 1]) continue;
+ affected[id - 1] = true;
+ const slot = &server.world.workspaces.slots[id - 1];
+ var tree = try server.world.workspaces.tiler.trees[id - 1].clone(gpa);
+ errdefer tree.deinit(gpa);
+ try snapshot.workspaces.append(gpa, .{ .id = id, .automatic = slot.automatic, .tree = tree });
+ }
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| {
+ if (top.workspace_id == 0 or !affected[top.workspace_id - 1]) continue;
+ try snapshot.windows.append(gpa, .{
+ .id = top.id,
+ .order = top.workspace_order,
+ .key = tiling.key(top),
+ .workspace = top.workspace_id,
+ .floating = top.auto_float,
+ .floating_override = top.auto_float_override,
+ .geometry = geometry(top),
+ .layout = top.layout(),
+ .auto_restore = top.auto_restore,
+ .tile_restore = top.tile_restore,
+ .reinsert = top.auto_reinsert,
+ });
+ }
+ return snapshot;
+}
+
+fn geometry(top: *Top) undo.Geometry {
+ return top.pending_restore orelse top.forcedGeometry() orelse top.rememberGeometry();
+}
+
+/// A floating move can cross outputs only at release. Add the destination's
+/// pre-transfer layout then, retaining the source snapshot from pointer press.
+pub fn includeDestination(server: *Server, id: u8) void {
+ const pending = server.undo.pending orelse return;
+ const snapshot = pending.snapshot orelse return;
+ for (snapshot.workspaces.items) |workspace| if (workspace.id == id) return;
+ includeOwned(server, snapshot, id) catch |err| {
+ std.log.warn("layout undo destination: {s}", .{@errorName(err)});
+ server.undo.clear();
+ };
+}
+
+fn includeOwned(server: *Server, snapshot: *Snapshot, id: u8) !void {
+ const extra = try captureOwned(server, &.{id});
+ defer extra.destroy();
+ try snapshot.workspaces.ensureUnusedCapacity(gpa, extra.workspaces.items.len);
+ try snapshot.windows.ensureUnusedCapacity(gpa, extra.windows.items.len);
+ for (extra.workspaces.items) |*workspace| {
+ snapshot.workspaces.appendAssumeCapacity(workspace.*);
+ workspace.tree = .{};
+ }
+ snapshot.windows.appendSliceAssumeCapacity(extra.windows.items);
+}
+
+pub fn beginGesture(server: *Server, id: u8) bool {
+ if (!server.world.workspaces.active) return false;
+ // On allocation failure, keep workspace gestures out of the legacy
+ // single-window path, which cannot restore a changed group layout.
+ const snapshot = capture(server, &.{id}) orelse return true;
+ server.undo.begin(.{ .kind = .workspace_layout, .press_seq = server.undo.press_seq, .at_ms = 0, .focus = snapshot.focus, .snapshot = snapshot });
+ return true;
+}
+
+pub const Resize = struct { id: u64, width: i32, height: i32 };
+
+pub fn commitGesture(server: *Server, resized: ?Resize) bool {
+ const pending = server.undo.pending orelse return false;
+ const snapshot = pending.snapshot orelse return false;
+ server.undo.pending = null;
+ recordWithResize(server, snapshot, resized);
+ return true;
+}
+
+fn find(server: *Server, saved: Snapshot.Window) ?*Top {
+ if (server.findToplevelById(saved.id)) |top| return top;
+ // Placeholder replacement hands its insertion identity to the real client.
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| if (top.workspace_order == saved.order) return top;
+ return null;
+}
+
+pub fn replaced(server: *Server, old: u64, new: u64) void {
+ const entries = [_]?*undo.Change{
+ if (server.undo.slot) |*entry| entry else null,
+ if (server.undo.pending) |*entry| entry else null,
+ };
+ for (entries) |maybe_entry| {
+ const entry = maybe_entry orelse continue;
+ const snapshot = entry.snapshot orelse continue;
+ if (entry.focus == old) entry.focus = new;
+ if (snapshot.focus == old) snapshot.focus = new;
+ for (snapshot.windows.items) |*window| if (window.id == old) {
+ window.id = new;
+ };
+ }
+}
+
+fn changed(server: *Server, snapshot: *Snapshot) bool {
+ for (snapshot.workspaces.items) |*saved| {
+ const slot = &server.world.workspaces.slots[saved.id - 1];
+ if (slot.automatic != saved.automatic or !saved.tree.eql(&server.world.workspaces.tiler.trees[saved.id - 1])) return true;
+ }
+ for (snapshot.windows.items) |saved| {
+ const top = find(server, saved) orelse continue;
+ if (top.workspace_id != saved.workspace or top.auto_float != saved.floating or top.auto_float_override != saved.floating_override or !top.layout().eql(saved.layout)) return true;
+ if (saved.layout == .floating and !top.minimized and !top.fullscreen and !std.meta.eql(geometry(top), saved.geometry)) return true;
+ }
+ return false;
+}
+
+/// Takes ownership. No-op gestures leave the previous undo entry intact.
+pub fn record(server: *Server, snapshot: ?*Snapshot) void {
+ recordWithResize(server, snapshot, null);
+}
+
+fn recordWithResize(server: *Server, snapshot: ?*Snapshot, resized: ?Resize) void {
+ const saved = snapshot orelse return;
+ // Configure replies may arrive after release. Compare the requested final
+ // client size rather than discarding a real resize against its old buffer.
+ const size_changed = blk: {
+ const size = resized orelse break :blk false;
+ for (saved.windows.items) |window| if (window.id == size.id) {
+ break :blk window.geometry.width != size.width or window.geometry.height != size.height;
+ };
+ break :blk false;
+ };
+ if (!server.world.workspaces.active or saved.generation != server.world.workspaces.generation or (!size_changed and !changed(server, saved))) {
+ saved.destroy();
+ return;
+ }
+ const now = Server.undoNowMs();
+ if (server.layout_autosave) |autosave| for (saved.workspaces.items) |workspace| autosave.touch(&.{workspace.id});
+ server.undo.record(.{ .kind = .workspace_layout, .press_seq = server.undo.press_seq, .at_ms = now, .focus = saved.focus, .snapshot = saved }, now);
+}
+
+/// Suppress nested single-window/focus entries until the operation has finished.
+pub const Transaction = struct {
+ server: *Server,
+ snapshot: ?*Snapshot,
+ applying: bool,
+ resized: ?Resize = null,
+
+ pub fn begin(server: *Server, ids: []const u8) Transaction {
+ const snapshot = capture(server, ids);
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ return .{ .server = server, .snapshot = snapshot, .applying = applying };
+ }
+ pub fn finish(self: *Transaction) void {
+ self.server.undo.applying = self.applying;
+ recordWithResize(self.server, self.snapshot, self.resized);
+ self.snapshot = null;
+ }
+};
+
+/// Takes the trees out of the snapshot. No saved pointer is ever dereferenced;
+/// absent clients disappear in reflow and new clients keep their insertion order.
+pub fn apply(server: *Server, snapshot: *Snapshot) void {
+ const manager = &server.world.workspaces;
+ if (!manager.active or manager.generation != snapshot.generation) return;
+ workspaces.cancelGestures(server);
+ for (snapshot.workspaces.items) |*saved| {
+ const slot = &manager.slots[saved.id - 1];
+ slot.automatic = saved.automatic;
+ for (snapshot.windows.items) |window| {
+ if (window.workspace != saved.id) continue;
+ if (find(server, window)) |top| saved.tree.rename(window.key, tiling.key(top));
+ }
+ const tree = &manager.tiler.trees[saved.id - 1];
+ tree.deinit(gpa);
+ tree.* = saved.tree;
+ saved.tree = .{};
+ }
+ for (snapshot.windows.items) |saved| {
+ const top = find(server, saved) orelse continue;
+ top.finishMoveAnimation();
+ top.clearAutoTile(false);
+ top.workspace_id = saved.workspace;
+ top.auto_float = saved.floating;
+ top.auto_float_override = saved.floating_override;
+ top.auto_restore = saved.auto_restore;
+ top.auto_reinsert = saved.reinsert;
+ top.auto_seen = null;
+ // Forced layouts still belong to the workspace's current output after
+ // undoing a transfer or after output migration.
+ if (workspaces.outputFor(top)) |output| {
+ if (top.fullscreen) top.setFullscreenOn(output) else if (top.maximized) top.setMaximizedOn(output);
+ }
+ // Lifecycle overrides remain live: undo does not unminimize or leave
+ // fullscreen/maximize merely because another tile was rearranged.
+ if (!top.minimized and !top.fullscreen and !top.maximized and saved.layout != .maximized) {
+ if (saved.layout == .tiled) {
+ if (workspaces.outputFor(top)) |output| top.setTiledOn(output, saved.layout.tiled);
+ } else top.applyLayout(saved.layout);
+ top.auto_float = saved.floating;
+ top.auto_float_override = saved.floating_override; // leaveLayout opts out internally
+ top.auto_restore = saved.auto_restore;
+ if (saved.layout == .floating) {
+ var floating = saved.geometry;
+ const limits = top.sizeConstraints();
+ floating.width = @max(floating.width, @max(1, limits.min_width));
+ floating.height = @max(floating.height, @max(1, limits.min_height));
+ if (limits.max_width > 0) floating.width = @min(floating.width, limits.max_width);
+ if (limits.max_height > 0) floating.height = @min(floating.height, limits.max_height);
+ top.restoreGeometryNow(floating);
+ }
+ }
+ top.tile_restore = saved.tile_restore;
+ }
+ // Tabs or dialogs opened after capture follow their surviving group/owner.
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| {
+ if (top.parentWindow()) |owner| top.workspace_id = owner.workspace_id;
+ if (top.tab_group == 0) continue;
+ for (snapshot.windows.items) |saved| {
+ const member = find(server, saved) orelse continue;
+ if (member.tab_group == top.tab_group) {
+ top.workspace_id = member.workspace_id;
+ top.auto_float = member.auto_float;
+ top.auto_float_override = member.auto_float_override;
+ break;
+ }
+ }
+ }
+ manager.tiler.flushNow(server);
+ manager.refresh(server);
+ if (server.input.open_control_center) |cc| cc.refresh();
+ if (snapshot.focus) |id| if (server.findToplevelById(id)) |top| {
+ if (!top.minimized and !top.tab_hidden) {
+ manager.reveal(top);
+ server.world.focus(top);
+ return;
+ }
+ };
+ workspaces.focusFallback(server, null);
+}
diff --git a/src/mini_map.zig b/src/mini_map.zig
index d96b944..7090fbe 100644
--- a/src/mini_map.zig
+++ b/src/mini_map.zig
@@ -42,7 +42,6 @@ const Outline = struct {
const Cache = struct { map: geo.Map, bounds: @import("camera.zig").Bounds, columns: u32, rows: u32, scale: f32, bg: [4]f32, fg: [4]f32, bg_opacity: f32 = 0.91, grid_alpha: f32 = 0.065, border_alpha: f32 = 0.12, radius: f32 = 4 };
const MarkerCache = struct { width: i32, height: i32, scale: f32, accent: [4]f32, fill_alpha: f32 = 0.12, border_alpha: f32 = 0.85, radius: f32 = 4 };
-
fn blocked(server: *Server) bool {
if (server.tray) |tray| if (tray.menu_item != 0) return true;
return server.greeter_mode or server.locker != null or server.polkit_dialog != null or
@@ -52,7 +51,7 @@ fn blocked(server: *Server) bool {
}
pub fn show(self: *Self, server: *Server, x: f64, y: f64) void {
- if (!server.config.compositor.mini_map_enabled or blocked(server)) return;
+ if (server.world.workspaces.active or !server.config.compositor.mini_map_enabled or blocked(server)) return;
self.server = server;
if (self.dragging) return;
const output = Output.atLayout(server, x, y) orelse server.getDefaultOutput() orelse return;
@@ -188,7 +187,7 @@ pub fn release(self: *Self) void {
pub fn tick(self: *Self, output: *Output, now: i64) bool {
if (!self.visible or self.output != output) return false;
const server = self.server.?;
- if (blocked(server) or !server.config.compositor.mini_map_enabled or !output.isAvailable() or output.idle_blanked) {
+ if (blocked(server) or server.world.workspaces.active or !server.config.compositor.mini_map_enabled or !output.isAvailable() or output.idle_blanked) {
self.hide();
return false;
}
diff --git a/src/pdf/main.zig b/src/pdf/main.zig
index 4422398..f8e56f3 100644
--- a/src/pdf/main.zig
+++ b/src/pdf/main.zig
@@ -67,6 +67,9 @@ pub const Client = struct {
xkb_context: ?*c.api.xkb_context = null,
xkb_state: ?*c.api.xkb_state = null,
key_repeat: key_repeat.KeyRepeat = .{},
+ compose: @import("ui").compose.Compose = .{},
+ /// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).
+ locale: []const u8 = "",
/// Socket to the unsandboxed print helper, or -1 without one.
print_fd: c_int = -1,
app: app_mod.App,
@@ -402,10 +405,20 @@ pub const Client = struct {
const sym = c.api.xkb_state_key_get_one_sym(state, key + 8);
var buf: [64]u8 = undefined;
const n = c.api.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
+ // Dead keys have no text of their own: sequences resolve here, and a
+ // shortcut modifier abandons a half-typed one.
+ if (!self.app.ctrl and !self.app.alt) {
+ var composed: [64]u8 = undefined;
+ if (self.compose.feed(self.locale, sym, &composed)) |text| {
+ if (text.len > 0) self.app.handleKey(0, text);
+ return;
+ }
+ } else self.compose.reset();
self.app.handleKey(sym, buf[0..@intCast(std.math.clamp(n, 0, 63))]);
}
fn appRepeats(self: *Client, key: u32) bool {
+ if (self.compose.consumed) return false;
const state = self.xkb_state orelse return false;
var buf: [64]u8 = undefined;
const n = c.api.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
@@ -422,6 +435,7 @@ pub const Client = struct {
switch (event) {
.leave => {
self.key_repeat.stop();
+ self.compose.reset();
self.app.cancelDrag();
self.app.ctrl = false;
self.app.shift = false;
@@ -799,6 +813,11 @@ pub fn run(init: std.process.Init.Minimal) !void {
shell_text.warmGlyphs(font, shell_ui.textSize(), 1, "") catch {};
}
+ // The Compose table for dead keys is a file read; the first dead key
+ // would come after the sandbox closed the filesystem.
+ const locale = @import("ui").compose.localeFromEnviron(init.environ);
+ @import("ui").compose.preload(locale);
+
const display = try @import("connection.zig").connect();
defer display.disconnect();
if (c.rediwm_pdf_sandbox_enter(document_fd, display.getFd(), print_fd) != 0) {
@@ -810,7 +829,9 @@ pub fn run(init: std.process.Init.Minimal) !void {
.display = display,
.print_fd = print_fd,
.app = try app_mod.App.init(initial_path, document_fd),
+ .locale = locale,
};
+ defer self.compose.deinit();
defer self.closePrint();
defer self.app.deinit();
defer for (self.buffers) |slot| {
diff --git a/src/polkit/README.md b/src/polkit/README.md
index 823de1f..85ffd1a 100644
--- a/src/polkit/README.md
+++ b/src/polkit/README.md
@@ -114,7 +114,7 @@ copy/cut/paste, IME, or widget-tree exposure for responses.
Tab/Shift+Tab navigate input, Cancel, Authenticate and action id. Enter submits,
Escape cancels, arrows/Home/End move within the response, and Ctrl+U clears it.
Selecting the action id and pressing Ctrl+C copies only that public identifier.
-The identity is resolved through NSS and the lock icon comes from `icons/lock.svg`.
+The identity is resolved through NSS and the lock icon comes from `assets/icons/lock.svg`.
Helper info/errors remain visible across the following prompt. The UI displays
Attempt N of 3 and clears the field before each retry.
diff --git a/src/session/layout_autosave.zig b/src/session/layout_autosave.zig
index b5b9e80..0f1ce07 100644
--- a/src/session/layout_autosave.zig
+++ b/src/session/layout_autosave.zig
@@ -37,6 +37,8 @@ pub const Autosave = struct {
restore_attempt: usize = 0,
/// Hash of the layout this process last wrote; unchanged ticks skip I/O.
last_saved_hash: ?u64 = null,
+ workspace_hash: ?u64 = null,
+ workspace_restore: ?@import("../workspace_persistence.zig").Restore = null,
pub fn create(server: *Server) !*Autosave {
const self = try gpa.create(Autosave);
@@ -51,12 +53,21 @@ pub const Autosave = struct {
self.restore_timer = try loop.addTimer(*Autosave, onRestoreTimer, self);
try self.restore_timer.?.timerUpdate(restore_delays_ms[0]);
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ if (workspacePath(arena.allocator(), server)) |path| {
+ self.workspace_restore = @import("../workspace_persistence.zig").Restore.load(server, path) catch |err| blk: {
+ if (err != error.FileNotFound) log.warn("workspace restore: {s}", .{@errorName(err)});
+ break :blk null;
+ };
+ }
return self;
}
pub fn deinit(self: *Autosave) void {
if (self.save_timer) |t| t.remove();
if (self.restore_timer) |t| t.remove();
+ if (self.workspace_restore) |*restore| restore.deinit();
gpa.destroy(self);
}
@@ -66,6 +77,13 @@ pub const Autosave = struct {
pub fn saveNow(self: *Autosave) void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
+ if (self.server.world.workspaces.active) {
+ if (workspacePath(arena.allocator(), self.server)) |path|
+ @import("../workspace_persistence.zig").save(self.server, path, &self.workspace_hash) catch |err| {
+ log.warn("workspace autosave: {s}", .{@errorName(err)});
+ };
+ return;
+ }
if (autosavePath(arena.allocator(), self.server)) |path| {
actions.saveLayoutToPathIfChanged(self.server, path, &self.last_saved_hash) catch |err| {
log.warn("autosave: {}", .{err});
@@ -73,24 +91,52 @@ pub const Autosave = struct {
}
}
+ pub fn mapped(self: *Autosave, top: *@import("../Toplevel.zig")) void {
+ if (self.restore_attempt >= restore_delays_ms.len) return;
+ if (self.workspace_restore) |*restore| restore.apply(self.server, top);
+ }
+ pub fn finishMapped(self: *Autosave, top: *@import("../Toplevel.zig")) void {
+ if (self.restore_attempt >= restore_delays_ms.len or !self.server.world.workspaces.active) return;
+ if (self.workspace_restore) |*restore| restore.finish(self.server, top);
+ }
+ pub fn cancelWorkspaceRestore(self: *Autosave) void {
+ if (self.workspace_restore) |*restore| restore.deinit();
+ self.workspace_restore = null;
+ }
+ pub fn navigation(self: *Autosave) void {
+ if (self.workspace_restore) |*restore| if (!restore.initialized) {
+ restore.restore_output_selection = false;
+ };
+ }
+ pub fn touch(self: *Autosave, ids: []const u8) void {
+ if (self.workspace_restore) |*restore| for (ids) |id| {
+ if (id > 0 and id <= 32) restore.touched[id - 1] = true;
+ };
+ }
+
fn onSaveTimer(self: *Autosave) c_int {
- self.saveNow();
+ // Keep the original snapshot on disk while slow startup clients can
+ // still claim it. Explicit saves and shutdown retain saveNow semantics.
+ const pending = self.server.world.workspaces.active and
+ (if (self.workspace_restore) |*restore| restore.pending() else false);
+ if (!pending) self.saveNow();
self.save_timer.?.timerUpdate(autosave_interval_ms) catch {};
return 0;
}
fn onRestoreTimer(self: *Autosave) c_int {
+ if (self.workspace_restore) |*restore| restore.prepare(self.server);
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
if (autosavePath(arena.allocator(), self.server)) |path| {
- actions.restoreLayoutFromPath(self.server, path) catch |err| {
+ if (!self.server.world.workspaces.active) actions.restoreLayoutFromPath(self.server, path) catch |err| {
if (err != error.FileNotFound) log.warn("autosave restore: {}", .{err});
};
}
self.restore_attempt += 1;
if (self.restore_attempt < restore_delays_ms.len) {
self.restore_timer.?.timerUpdate(restore_delays_ms[self.restore_attempt]) catch {};
- }
+ } else self.cancelWorkspaceRestore();
return 0;
}
};
@@ -99,3 +145,8 @@ fn autosavePath(allocator: std.mem.Allocator, server: *Server) ?[]const u8 {
const dir = (window_sizes.resolveStateDir(allocator, server.environ) catch return null) orelse return null;
return std.fmt.allocPrint(allocator, "{s}/autosave-layout.toml", .{dir}) catch null;
}
+
+fn workspacePath(a: std.mem.Allocator, server: *Server) ?[]const u8 {
+ const dir = (window_sizes.resolveStateDir(a, server.environ) catch return null) orelse return null;
+ return std.fmt.allocPrint(a, "{s}/workspace-layout.json", .{dir}) catch null;
+}
diff --git a/src/session/lock.zig b/src/session/lock.zig
index 2f3848c..a441326 100644
--- a/src/session/lock.zig
+++ b/src/session/lock.zig
@@ -137,6 +137,7 @@ pub const Lock = struct {
if (server.polkit) |agent| agent.pauseForLock();
// Clear undo state on lock: restoring spatial state across a screen
// lock session would be confusing (different user context).
+ if (server.input.tiling_grab != null) server.input.finishTilingGrab(false);
server.undo.clear();
var keyboards = server.input.keyboards.iterator(.forward);
while (keyboards.next()) |keyboard| keyboard.cancelHardware();
@@ -1196,6 +1197,7 @@ test "lock authentication failure stays locked and success releases lock state"
.suspended = true,
};
server.polkit = &agent;
+ server.undo = .{};
server.wl_server = display;
server.outputs.init();
server.world.toplevels.init();
diff --git a/src/snap.zig b/src/snap.zig
index 3133367..99b9f82 100644
--- a/src/snap.zig
+++ b/src/snap.zig
@@ -22,6 +22,7 @@ pub const Layout = union(enum) {
floating,
maximized,
tiled: Tile,
+ automatic,
pub fn eql(a: Layout, b: Layout) bool {
return std.meta.eql(a, b);
@@ -140,7 +141,7 @@ pub const Direction = enum { left, right, up, down };
/// join quarters back into halves.
pub fn step(layout: Layout, dir: Direction) Layout {
return switch (layout) {
- .floating => switch (dir) {
+ .floating, .automatic => switch (dir) {
.left => .{ .tiled = .left },
.right => .{ .tiled = .right },
.up => .maximized,
diff --git a/src/tiling_grab.zig b/src/tiling_grab.zig
new file mode 100644
index 0000000..434c438
--- /dev/null
+++ b/src/tiling_grab.zig
@@ -0,0 +1,138 @@
+//! Tile moves are staged until release. Split resizes are live, with an owned
+//! tree snapshot for cancellation; gestures retain IDs, never borrowed nodes.
+const std = @import("std");
+const Input = @import("Input.zig");
+const Top = @import("Toplevel.zig");
+const layout = @import("auto_layout.zig");
+const tiling = @import("auto_tiling.zig");
+const gpa = @import("main.zig").gpa;
+const wlr = @import("wlroots");
+const Self = @This();
+
+id: u64,
+workspace: u8,
+kind: enum { move, resize },
+button: u32,
+start_x: f64,
+start_y: f64,
+last_x: f64,
+last_y: f64,
+moved: bool = false,
+horizontal: ?layout.Split = null,
+vertical: ?layout.Split = null,
+snapshot: ?layout.Tree = null,
+undo_snapshot: ?*@import("layout_undo.zig").Snapshot = null,
+drop: ?tiling.Drop = null,
+
+pub fn begin(input: *Input, top: *Top, edges: ?wlr.Edges, button: u32) bool {
+ if (!input.server.world.workspaces.active or top.auto_target == null or top.minimized or top.fullscreen or top.maximized) return false;
+ if (input.tiling_grab != null) input.finishTilingGrab(false);
+ if (input.resize_session != null) input.cancelResize();
+ input.server.world.workspaces.tiler.flushNow(input.server);
+ if (top.auto_target == null) return false;
+ const tree = &input.server.world.workspaces.tiler.trees[top.workspace_id - 1];
+ var session: Self = .{ .id = top.id, .workspace = top.workspace_id, .kind = if (edges != null) .resize else .move, .button = button, .start_x = input.cursor.x, .start_y = input.cursor.y, .last_x = input.cursor.x, .last_y = input.cursor.y };
+ if (edges) |e| {
+ if (e.left or e.right) session.horizontal = tree.splitFor(tiling.key(top), .horizontal);
+ if (e.top or e.bottom) session.vertical = tree.splitFor(tiling.key(top), .vertical);
+ if (session.horizontal == null and session.vertical == null) return true;
+ session.snapshot = tree.clone(gpa) catch return true;
+ session.undo_snapshot = @import("layout_undo.zig").capture(input.server, &.{top.workspace_id});
+ }
+ top.pending_restore = null;
+ input.tiling_grab = session;
+ input.grabbed_toplevel = top;
+ input.cursor_mode = if (edges != null) .resize else .move;
+ input.move_snap.preview.hide();
+ input.setHover(null, null);
+ input.seat.pointerClearFocus();
+ input.pointer_constraints.sync();
+ input.setNamedCursor(if (edges == null) "grabbing" else if (session.horizontal != null and session.vertical != null) "se-resize" else if (session.horizontal != null) "e-resize" else "s-resize");
+ return true;
+}
+
+pub fn motion(input: *Input) void {
+ const session = &(input.tiling_grab orelse return);
+ if (input.cursor.x == session.last_x and input.cursor.y == session.last_y) return;
+ session.last_x = input.cursor.x;
+ session.last_y = input.cursor.y;
+ const top = input.server.findToplevelById(session.id) orelse {
+ input.finishTilingGrab(false);
+ return;
+ };
+ const dx = input.cursor.x - session.start_x;
+ const dy = input.cursor.y - session.start_y;
+ if (!session.moved and @abs(dx) < @import("snap.zig").unsnap_px and @abs(dy) < @import("snap.zig").unsnap_px) return;
+ session.moved = true;
+ input.title_press = null;
+ if (session.kind == .resize) {
+ const tree = &input.server.world.workspaces.tiler.trees[session.workspace - 1];
+ if (session.horizontal) |split| tree.setRatio(tiling.key(top), .horizontal, split.ratio + dx / @as(f64, @floatFromInt(split.span)));
+ if (session.vertical) |split| tree.setRatio(tiling.key(top), .vertical, split.ratio + dy / @as(f64, @floatFromInt(split.span)));
+ input.server.world.workspaces.tiler.schedule(input.server);
+ return;
+ }
+ updatePreview(input, session, top, false);
+}
+
+/// Membership/constraint changes can move a target even if the pointer is still.
+pub fn refreshPreview(input: *Input) void {
+ const session = &(input.tiling_grab orelse return);
+ if (session.kind != .move or !session.moved) return;
+ const top = input.server.findToplevelById(session.id) orelse return;
+ updatePreview(input, session, top, true);
+}
+
+fn updatePreview(input: *Input, session: *Self, top: *Top, force: bool) void {
+ const drop = tiling.dropAt(top, input.cursor.x, input.cursor.y);
+ if (!force and std.meta.eql(drop, session.drop) and (drop == null or input.server.world.workspaces.slots[drop.?.workspace - 1].automatic)) return;
+ session.drop = drop;
+ input.move_snap.preview.hide();
+ const target = drop orelse return;
+ var prepared = (tiling.prepareDrop(top, target) catch return) orelse return;
+ defer if (prepared.tree) |*tree| tree.deinit(gpa);
+ input.move_snap.preview.show(input.server.overlay_tree, prepared.rect);
+ input.server.scheduleFrames();
+}
+
+pub fn finish(input: *Input, commit: bool) void {
+ var session = input.tiling_grab orelse return;
+ input.tiling_grab = null;
+ input.cursor_mode = .passthrough;
+ input.grabbed_toplevel = null;
+ input.move_snap.preview.hide();
+ defer {
+ if (session.snapshot) |*tree| tree.deinit(gpa);
+ if (session.undo_snapshot) |snapshot| snapshot.destroy();
+ input.setDefaultCursor();
+ input.pointer_constraints.sync();
+ input.server.scheduleFrames();
+ }
+ if (!commit) {
+ if (session.snapshot) |tree| {
+ const current = &input.server.world.workspaces.tiler.trees[session.workspace - 1];
+ current.deinit(gpa);
+ current.* = tree;
+ session.snapshot = null;
+ // Reconcile live membership: a closed window must never reappear.
+ input.server.world.workspaces.tiler.schedule(input.server);
+ }
+ return;
+ }
+ if (!session.moved) return;
+ if (session.kind == .resize) {
+ @import("layout_undo.zig").record(input.server, session.undo_snapshot);
+ session.undo_snapshot = null;
+ return;
+ }
+ const top = input.server.findToplevelById(session.id) orelse return;
+ const drop = tiling.dropAt(top, input.cursor.x, input.cursor.y) orelse return;
+ var prepared = (tiling.prepareDrop(top, drop) catch return) orelse return;
+ defer if (prepared.tree) |*tree| tree.deinit(gpa);
+ const floating = !input.server.world.workspaces.slots[drop.workspace - 1].automatic;
+ tiling.commitDrop(top, drop, &prepared);
+ if (floating) {
+ top.clearAutoTile(true);
+ top.setPosition(prepared.rect.x, prepared.rect.y);
+ }
+}
diff --git a/src/ui/compose.zig b/src/ui/compose.zig
new file mode 100644
index 0000000..08ccba4
--- /dev/null
+++ b/src/ui/compose.zig
@@ -0,0 +1,289 @@
+//! Dead keys and Compose sequences for text fields that read raw xkb keys.
+//!
+//! `xkb_state_key_get_utf8` returns nothing for a dead key, so a field that
+//! only asks it for text drops the accent: ´ then a never becomes á. Every
+//! compositor-drawn field and every app client feeds its key presses here
+//! first. A press that starts or continues a sequence is `consumed` (typed
+//! text arrives when the sequence completes); anything else is `null` and
+//! takes the ordinary path.
+//!
+//! The table comes from the user's language, not from `C`: ´ then c is ç in
+//! `pt_BR` and ć elsewhere. It is built lazily, so a session that never
+//! presses a dead key never loads one, and one table is shared by every
+//! `Compose` in the process.
+const std = @import("std");
+const c = @cImport({
+ @cInclude("xkbcommon/xkbcommon-compose.h");
+});
+
+/// Longest normalized locale name kept (`ll_CC.UTF-8` plus slack).
+const max_locale = 48;
+/// Used for an unset or unusable locale; its table has the ordinary dead-key
+/// sequences.
+const fallback_locale = "C.UTF-8";
+
+/// XKB_KEY_dead_grave through XKB_KEY_dead_longsolidusoverlay, and Multi_key.
+const dead_first: u32 = 0xfe50;
+const dead_last: u32 = 0xfe93;
+const multi_key: u32 = 0xff20;
+
+/// Whether `sym` can begin a sequence, so a press of it must not be typed.
+pub fn startsSequence(sym: u32) bool {
+ return (sym >= dead_first and sym <= dead_last) or sym == multi_key;
+}
+
+/// `ll_CC.utf8@modifier` as `ll_CC.UTF-8`. xkbcommon finds a Compose file by
+/// locale name: a name without an encoding (`pt_BR`) maps to the ISO 8859-1
+/// file, which does not parse as UTF-8, and a modifier is not part of the
+/// name. The text we produce is always UTF-8.
+pub fn normalizeLocale(out: *[max_locale]u8, raw: []const u8) []const u8 {
+ const suffix = ".UTF-8";
+ var name = raw;
+ if (std.mem.indexOfScalar(u8, name, '@')) |at| name = name[0..at];
+ if (std.mem.indexOfScalar(u8, name, '.')) |dot| name = name[0..dot];
+ if (name.len == 0 or std.mem.eql(u8, name, "C") or std.mem.eql(u8, name, "POSIX") or name.len + suffix.len > out.len) return fallback_locale;
+ @memcpy(out[0..name.len], name);
+ @memcpy(out[name.len..][0..suffix.len], suffix);
+ return out[0 .. name.len + suffix.len];
+}
+
+/// The locale for LC_CTYPE, in POSIX precedence; empty when none is set.
+pub fn localeFromEnviron(environ: std.process.Environ) []const u8 {
+ inline for (.{ "LC_ALL", "LC_CTYPE", "LANG" }) |name| {
+ if (environ.getPosix(name)) |value| if (value.len != 0) return value;
+ }
+ return "";
+}
+
+// Main thread only. States hold their own reference to the table they were
+// made from, so replacing the cached table never invalidates a pending one.
+var cache: struct {
+ key: [max_locale]u8 = undefined,
+ key_len: usize = 0,
+ table: ?*c.xkb_compose_table = null,
+ loaded: bool = false,
+} = .{};
+
+fn load(locale: []const u8) ?*c.xkb_compose_table {
+ const context = c.xkb_context_new(c.XKB_CONTEXT_NO_FLAGS) orelse return null;
+ defer c.xkb_context_unref(context);
+ var name: [max_locale + 1]u8 = undefined;
+ @memcpy(name[0..locale.len], locale);
+ name[locale.len] = 0;
+ return c.xkb_compose_table_new_from_locale(context, @ptrCast(&name), c.XKB_COMPOSE_COMPILE_NO_FLAGS);
+}
+
+/// The table for a normalized `locale`, loaded on first use. A locale with no
+/// Compose file falls back to `C.UTF-8`; the answer is cached either way so a
+/// bad name is not retried (and logged by xkbcommon) on every press.
+fn table(locale: []const u8) ?*c.xkb_compose_table {
+ if (cache.loaded and std.mem.eql(u8, cache.key[0..cache.key_len], locale)) return cache.table;
+ if (cache.table) |old| c.xkb_compose_table_unref(old);
+ cache.table = load(locale) orelse if (std.mem.eql(u8, locale, fallback_locale)) null else load(fallback_locale);
+ @memcpy(cache.key[0..locale.len], locale);
+ cache.key_len = locale.len;
+ cache.loaded = true;
+ return cache.table;
+}
+
+/// Loads the table for `locale` now. For a process that is about to lose its
+/// filesystem (the PDF viewer's sandbox): the first dead key would otherwise
+/// find nothing to read.
+pub fn preload(locale: []const u8) void {
+ var buf: [max_locale]u8 = undefined;
+ _ = table(normalizeLocale(&buf, locale));
+}
+
+/// Drops the shared table; for shutdown and tests.
+pub fn flushTable() void {
+ if (cache.table) |old| c.xkb_compose_table_unref(old);
+ cache = .{};
+}
+
+pub const Compose = struct {
+ state: ?*c.xkb_compose_state = null,
+ locale: [max_locale]u8 = undefined,
+ locale_len: usize = 0,
+ /// The last `feed` returned text or swallowed the key. Callers that ask
+ /// whether a press may repeat after delivering it read this.
+ consumed: bool = false,
+
+ pub fn deinit(self: *Compose) void {
+ if (self.state) |state| c.xkb_compose_state_unref(state);
+ self.state = null;
+ self.consumed = false;
+ }
+
+ /// Forgets a half-typed sequence (focus moved, a shortcut modifier went
+ /// down, the field closed).
+ pub fn reset(self: *Compose) void {
+ if (self.state) |state| c.xkb_compose_state_reset(state);
+ self.consumed = false;
+ }
+
+ /// A dead key or Compose key is down and the next key completes it.
+ pub fn pending(self: *const Compose) bool {
+ const state = self.state orelse return false;
+ return c.xkb_compose_state_get_status(state) == c.XKB_COMPOSE_COMPOSING;
+ }
+
+ /// Whether the next press of `sym` will be taken by a sequence. Callers
+ /// that decide on key repeat before delivering the press ask this.
+ pub fn willConsume(self: *const Compose, sym: u32) bool {
+ return startsSequence(sym) or self.pending();
+ }
+
+ /// One key press. Null: not part of a sequence, type it as usual. Empty:
+ /// a sequence is pending (or was cancelled by this key); type nothing.
+ /// Otherwise the composed text, in `buf` (at least 8 bytes). Call it only
+ /// for presses without Ctrl, Alt or Super, and `reset` when those go down.
+ /// `locale` is the user's language (`LANG`-style); an unusable one falls
+ /// back to `C.UTF-8`.
+ pub fn feed(self: *Compose, locale: []const u8, sym: u32, buf: []u8) ?[]const u8 {
+ if (!self.willConsume(sym)) {
+ self.consumed = false;
+ return null;
+ }
+ const result = self.advance(locale, sym, buf);
+ self.consumed = result != null;
+ return result;
+ }
+
+ fn advance(self: *Compose, locale: []const u8, sym: u32, buf: []u8) ?[]const u8 {
+ var name_buf: [max_locale]u8 = undefined;
+ const name = normalizeLocale(&name_buf, locale);
+ if (self.state != null and !std.mem.eql(u8, self.locale[0..self.locale_len], name)) self.deinit();
+ const state = self.state orelse blk: {
+ const fresh = c.xkb_compose_state_new(table(name) orelse return null, c.XKB_COMPOSE_STATE_NO_FLAGS) orelse return null;
+ @memcpy(self.locale[0..name.len], name);
+ self.locale_len = name.len;
+ self.state = fresh;
+ break :blk fresh;
+ };
+ _ = c.xkb_compose_state_feed(state, sym);
+ switch (c.xkb_compose_state_get_status(state)) {
+ c.XKB_COMPOSE_COMPOSING => return "",
+ c.XKB_COMPOSE_COMPOSED => {
+ const n = c.xkb_compose_state_get_utf8(state, buf.ptr, buf.len);
+ c.xkb_compose_state_reset(state);
+ return buf[0..@min(@as(usize, @intCast(@max(n, 0))), buf.len -| 1)];
+ },
+ c.XKB_COMPOSE_CANCELLED => {
+ c.xkb_compose_state_reset(state);
+ return "";
+ },
+ else => return null,
+ }
+ }
+};
+
+const dead_acute: u32 = 0xfe51;
+const dead_tilde: u32 = 0xfe53;
+
+fn needTable(compose: *Compose, locale: []const u8) !void {
+ var scratch: [16]u8 = undefined;
+ // A machine without X11 locale data has no table; nothing to test then.
+ if (compose.feed(locale, dead_acute, &scratch) == null) return error.SkipZigTest;
+ compose.reset();
+}
+
+test "dead keys and the Compose key start sequences, ordinary keys do not" {
+ try std.testing.expect(startsSequence(dead_acute));
+ try std.testing.expect(startsSequence(dead_first));
+ try std.testing.expect(startsSequence(dead_last));
+ try std.testing.expect(startsSequence(multi_key));
+ try std.testing.expect(!startsSequence('a'));
+ try std.testing.expect(!startsSequence(dead_first - 1));
+ try std.testing.expect(!startsSequence(dead_last + 1));
+}
+
+test "locale names get a UTF-8 encoding and lose their modifier" {
+ var buf: [max_locale]u8 = undefined;
+ try std.testing.expectEqualStrings("pt_BR.UTF-8", normalizeLocale(&buf, "pt_BR.utf8"));
+ try std.testing.expectEqualStrings("pt_BR.UTF-8", normalizeLocale(&buf, "pt_BR"));
+ try std.testing.expectEqualStrings("es_MX.UTF-8", normalizeLocale(&buf, "es_MX.ISO-8859-1@euro"));
+ try std.testing.expectEqualStrings("de.UTF-8", normalizeLocale(&buf, "de@x"));
+ try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, ""));
+ try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "C"));
+ try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "POSIX"));
+ try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "C.UTF-8"));
+ try std.testing.expectEqualStrings(fallback_locale, normalizeLocale(&buf, "x" ** 60));
+}
+
+test "ordinary keys pass through without loading a table" {
+ flushTable();
+ var compose: Compose = .{};
+ defer compose.deinit();
+ var buf: [16]u8 = undefined;
+ try std.testing.expect(compose.feed("pt_BR.utf8", 'a', &buf) == null);
+ try std.testing.expect(!compose.consumed);
+ try std.testing.expect(compose.state == null);
+ try std.testing.expect(!cache.loaded);
+}
+
+test "a dead key then a letter composes the accented letter" {
+ var compose: Compose = .{};
+ defer compose.deinit();
+ try needTable(&compose, "C.UTF-8");
+ var buf: [16]u8 = undefined;
+ try std.testing.expectEqualStrings("", compose.feed("C.UTF-8", dead_acute, &buf).?);
+ try std.testing.expect(compose.pending());
+ try std.testing.expect(compose.consumed);
+ try std.testing.expect(compose.willConsume('a'));
+ try std.testing.expectEqualStrings("á", compose.feed("C.UTF-8", 'a', &buf).?);
+ try std.testing.expect(!compose.pending());
+ try std.testing.expect(compose.consumed);
+ try std.testing.expect(compose.feed("C.UTF-8", 'a', &buf) == null);
+ try std.testing.expect(!compose.consumed);
+ try std.testing.expectEqualStrings("", compose.feed("C.UTF-8", dead_tilde, &buf).?);
+ try std.testing.expectEqualStrings("ã", compose.feed("C.UTF-8", 'a', &buf).?);
+}
+
+test "a key that does not fit the sequence cancels it" {
+ var compose: Compose = .{};
+ defer compose.deinit();
+ try needTable(&compose, "C.UTF-8");
+ var buf: [16]u8 = undefined;
+ try std.testing.expectEqualStrings("", compose.feed("C.UTF-8", dead_acute, &buf).?);
+ try std.testing.expectEqualStrings("", compose.feed("C.UTF-8", 'x', &buf).?);
+ try std.testing.expect(!compose.pending());
+ try std.testing.expect(compose.feed("C.UTF-8", 'x', &buf) == null);
+}
+
+test "reset forgets a pending dead key" {
+ var compose: Compose = .{};
+ defer compose.deinit();
+ try needTable(&compose, "C.UTF-8");
+ var buf: [16]u8 = undefined;
+ _ = compose.feed("C.UTF-8", dead_acute, &buf);
+ try std.testing.expect(compose.pending());
+ compose.reset();
+ try std.testing.expect(!compose.pending());
+ try std.testing.expect(compose.feed("C.UTF-8", 'a', &buf) == null);
+}
+
+test "acute then c follows the language: ç in Portuguese, ć otherwise" {
+ var compose: Compose = .{};
+ defer compose.deinit();
+ try needTable(&compose, "pt_BR.utf8");
+ var buf: [16]u8 = undefined;
+ _ = compose.feed("pt_BR.utf8", dead_acute, &buf);
+ const portuguese = compose.feed("pt_BR.utf8", 'c', &buf).?;
+ // Without the pt_BR Compose file the fallback table answers; only the
+ // real one can be checked.
+ if (std.mem.eql(u8, portuguese, "ć")) return error.SkipZigTest;
+ try std.testing.expectEqualStrings("ç", portuguese);
+ // The same state, told another language, switches table.
+ _ = compose.feed("es_MX.utf8", dead_acute, &buf);
+ try std.testing.expectEqualStrings("ć", compose.feed("es_MX.utf8", 'c', &buf).?);
+}
+
+test "an unknown locale falls back instead of failing" {
+ flushTable();
+ var compose: Compose = .{};
+ defer compose.deinit();
+ var buf: [16]u8 = undefined;
+ const first = compose.feed("xx_XX.utf8", dead_acute, &buf) orelse return error.SkipZigTest;
+ try std.testing.expectEqualStrings("", first);
+ try std.testing.expectEqualStrings("á", compose.feed("xx_XX.utf8", 'a', &buf).?);
+}
diff --git a/src/ui/mod.zig b/src/ui/mod.zig
index dc74d9a..a605918 100644
--- a/src/ui/mod.zig
+++ b/src/ui/mod.zig
@@ -31,6 +31,7 @@ pub const widgets = struct {
pub const anim = @import("anim.zig");
pub const cairo = @import("cairo.zig");
pub const client_cursor = @import("client_cursor.zig");
+pub const compose = @import("compose.zig");
pub const context_menu = @import("context_menu.zig");
pub const font_fallback = @import("font_fallback.zig");
pub const hover_glide = @import("hover_glide.zig");
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index 474cef4..ad1a849 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -5,6 +5,9 @@ const IconId = @import("layout.zig").IconId;
const c = @cImport({
@cInclude("cairo.h");
});
+/// The start-button logo; not an `IconId` glyph because it keeps its own colours.
+pub const redi_logo = @embedFile("redi-logo");
+
const Handle = opaque {};
const GError = opaque {};
const Rectangle = extern struct { x: f64 = 0, y: f64 = 0, width: f64, height: f64 };
diff --git a/src/ui/theme.zig b/src/ui/theme.zig
index 4ceae0d..105ba26 100644
--- a/src/ui/theme.zig
+++ b/src/ui/theme.zig
@@ -42,6 +42,8 @@ pub const Theme = struct {
window_dim: [4]f32 = .{ 214.0 / 255.0, 214.0 / 255.0, 214.0 / 255.0, 1 }, // #d6d6d6
window_border: [4]f32 = .{ 1, 1, 1, 0.09 },
window_border_hover: [4]f32 = .{ 1, 1, 1, 0.13 },
+ /// Active window outline in opt-in workspace mode (#ed1b2e).
+ workspace_active_border: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 1 },
window_divider: [4]f32 = .{ 1, 1, 1, 0.045 },
window_close_hover: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 1 },
// App windows (Files, Images, PDF). All their text is `window_fg`
diff --git a/src/ui_tests.zig b/src/ui_tests.zig
index 45161f3..afec3b4 100644
--- a/src/ui_tests.zig
+++ b/src/ui_tests.zig
@@ -1,6 +1,7 @@
// Compositor integration/unit-test root. Shared modules have separate test
// targets in build.zig; their roots cannot import compositor code.
test {
+ _ = @import("auto_layout.zig");
_ = @import("desktop/app.zig");
_ = @import("desktop/config.zig");
_ = @import("desktop/dnd.zig");
diff --git a/src/undo.zig b/src/undo.zig
index 419d1dd..724f6ac 100644
--- a/src/undo.zig
+++ b/src/undo.zig
@@ -1,9 +1,48 @@
// Global undo state for spatial operations (Super + Z).
-// Pure logic over plain structs — no compositor dependency. See plan-undo.md.
+// Plain window state and owned split snapshots; no compositor dependency.
const std = @import("std");
const Layout = @import("snap.zig").Layout;
-pub const Kind = enum { move, resize, window_zoom, pan, camera_zoom, focus };
+pub const Kind = enum { move, resize, window_zoom, pan, camera_zoom, focus, workspace_layout };
+
+pub const Geometry = struct { x: i32, y: i32, width: i32, height: i32 };
+
+/// Owned, pointer-free window identities and independent copies of affected
+/// split trees. The compositor reconciles these with live membership on apply.
+pub const LayoutSnapshot = struct {
+ allocator: std.mem.Allocator,
+ generation: u64,
+ focus: ?u64 = null,
+ workspaces: std.ArrayList(Workspace) = .empty,
+ windows: std.ArrayList(Window) = .empty,
+
+ pub const Workspace = struct {
+ id: u8,
+ automatic: bool,
+ tree: @import("auto_layout.zig").Tree,
+ };
+ pub const Window = struct {
+ id: u64,
+ order: u64,
+ key: @import("auto_layout.zig").Key,
+ workspace: u8,
+ floating: bool,
+ floating_override: ?bool,
+ geometry: Geometry,
+ layout: Layout,
+ auto_restore: ?Geometry,
+ tile_restore: ?Geometry,
+ reinsert: ?@import("auto_layout.zig").Placement,
+ };
+
+ pub fn destroy(self: *LayoutSnapshot) void {
+ const allocator = self.allocator;
+ for (self.workspaces.items) |*workspace| workspace.tree.deinit(allocator);
+ self.workspaces.deinit(allocator);
+ self.windows.deinit(allocator);
+ allocator.destroy(self);
+ }
+};
pub const WindowState = struct {
id: u64,
@@ -36,6 +75,11 @@ pub const Change = struct {
focus: ?u64 = null, // window id that held keyboard focus before this change
window: ?WindowState = null,
camera: ?CameraState = null,
+ snapshot: ?*LayoutSnapshot = null,
+
+ pub fn deinit(change: Change) void {
+ if (change.snapshot) |snapshot| snapshot.destroy();
+ }
};
pub const Undo = struct {
@@ -56,11 +100,13 @@ pub const Undo = struct {
/// folds into one undo entry. `pending` is never clobbered when already
/// set (a focus change inside an active gesture cannot displace it).
pub fn begin(undo: *Undo, change: Change) void {
- if (undo.applying) return;
- if (undo.pending != null) return; // gesture already in flight
+ if (undo.applying or undo.pending != null) {
+ change.deinit();
+ return;
+ }
var c = change;
if (undo.slot) |prev| {
- if (prev.press_seq == change.press_seq) {
+ if (change.snapshot == null and prev.press_seq == change.press_seq) {
// Same press: inherit the previously recorded focus id so the
// drag and the focus change it caused form one undo entry.
c.focus = prev.focus;
@@ -128,11 +174,14 @@ pub const Undo = struct {
/// Discrete operations (focus, zoom steps) begin and commit in one call.
pub fn record(undo: *Undo, change: Change, now_ms: i64) void {
- if (undo.applying) return;
+ if (undo.applying) {
+ change.deinit();
+ return;
+ }
if (change.kind == .focus and change.focus == null) return;
var c = change;
if (undo.slot) |prev| {
- if (prev.press_seq == change.press_seq) {
+ if (change.snapshot == null and prev.press_seq == change.press_seq) {
c.focus = prev.focus;
}
}
@@ -141,6 +190,7 @@ pub const Undo = struct {
/// Drop the in-flight gesture without recording it (e.g. cancelResize).
pub fn drop(undo: *Undo) void {
+ if (undo.pending) |pending| pending.deinit();
undo.pending = null;
}
@@ -160,12 +210,14 @@ pub const Undo = struct {
const same_camera = prev.camera != null and change.camera != null and prev.window == null and change.window == null;
if (same_window or same_camera) {
prev.at_ms = now_ms;
+ change.deinit();
return;
}
}
}
var c = change;
c.at_ms = now_ms;
+ if (undo.slot) |previous| previous.deinit();
undo.slot = c;
}
@@ -175,8 +227,9 @@ pub const Undo = struct {
/// Clear the slot and pending gesture (e.g. on lock / unlock).
pub fn clear(undo: *Undo) void {
+ if (undo.slot) |slot| slot.deinit();
undo.slot = null;
- undo.pending = null;
+ undo.drop();
}
};
@@ -306,3 +359,37 @@ test "commitPending commits an in-flight gesture" {
try std.testing.expect(u.pending == null);
try std.testing.expect(u.slot != null);
}
+
+test "owned layout snapshots are freed on replacement, cancel, clear and suppression" {
+ const Case = struct {
+ fn snapshot(allocator: std.mem.Allocator) !*LayoutSnapshot {
+ const value = try allocator.create(LayoutSnapshot);
+ value.* = .{ .allocator = allocator, .generation = 1 };
+ errdefer value.destroy();
+ var tree: @import("auto_layout.zig").Tree = .{};
+ errdefer tree.deinit(allocator);
+ try tree.insert(allocator, .{ .key = .{ .id = 1 } }, null, .horizontal);
+ try tree.insert(allocator, .{ .key = .{ .id = 2 } }, null, .vertical);
+ try value.workspaces.append(allocator, .{ .id = 1, .automatic = true, .tree = tree });
+ return value;
+ }
+ fn run(allocator: std.mem.Allocator) !void {
+ var u: Undo = .{};
+ defer u.clear();
+ u.record(.{ .kind = .workspace_layout, .press_seq = 1, .at_ms = 0, .snapshot = try snapshot(allocator) }, 0);
+ u.record(.{ .kind = .workspace_layout, .press_seq = 1, .at_ms = 1, .snapshot = try snapshot(allocator) }, 1);
+ u.record(.{ .kind = .focus, .press_seq = 2, .at_ms = 2, .focus = 3 }, 2);
+ try std.testing.expect(u.slot.?.snapshot == null);
+ u.begin(.{ .kind = .workspace_layout, .press_seq = 3, .at_ms = 3, .snapshot = try snapshot(allocator) });
+ // A second begin is consumed even though a gesture is in flight.
+ u.begin(.{ .kind = .workspace_layout, .press_seq = 4, .at_ms = 4, .snapshot = try snapshot(allocator) });
+ u.drop();
+ u.applying = true;
+ u.record(.{ .kind = .workspace_layout, .press_seq = 5, .at_ms = 5, .snapshot = try snapshot(allocator) }, 5);
+ u.applying = false;
+ u.record(.{ .kind = .workspace_layout, .press_seq = 6, .at_ms = 6, .snapshot = try snapshot(allocator) }, 6);
+ u.clear();
+ }
+ };
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{});
+}
diff --git a/src/window_tabs.zig b/src/window_tabs.zig
index 6c79179..764b795 100644
--- a/src/window_tabs.zig
+++ b/src/window_tabs.zig
@@ -211,6 +211,10 @@ fn copyGeometry(from: *Top, to: *Top) void {
to.maximized = from.maximized;
to.maximize_restore = from.maximize_restore;
to.maximize_target = from.maximize_target;
+ to.auto_float = from.auto_float;
+ to.auto_float_override = from.auto_float_override;
+ to.auto_restore = from.auto_restore;
+ to.auto_target = from.auto_target;
to.tile = from.tile;
to.tile_target = from.tile_target;
to.tile_restore = from.tile_restore;
@@ -227,7 +231,7 @@ fn copyGeometry(from: *Top, to: *Top) void {
},
else => {},
}
- to.sendTiled(if (from.tile) |tile| @import("snap.zig").tiledEdges(tile) else .{});
+ to.sendTiled(if (from.tile) |tile| @import("snap.zig").tiledEdges(tile) else if (from.auto_target != null) .{ .top = true, .bottom = true, .left = true, .right = true } else .{});
const geom = from.forcedGeometry() orelse from.rememberGeometry();
to.setPosition(geom.x, geom.y);
_ = to.requestSize(geom.width, geom.height);
@@ -237,7 +241,7 @@ pub fn visible(top: *Top) bool {
var next: ?*Top = top;
var depth: usize = 0;
while (next) |t| : (depth += 1) {
- if (depth == 32 or t.tab_hidden or t.minimized) return false;
+ if (depth == 32 or t.tab_hidden or t.minimized or !@import("workspaces.zig").visible(t)) return false;
next = t.parentWindow();
}
return true;
@@ -401,6 +405,7 @@ fn attach(self: *Self, index: usize, top: *Top) bool {
top.tab_restore = top.rememberGeometry();
top.tab_identity = source.tab_identity;
top.tab_group = p.group;
+ top.workspace_id = source.workspace_id;
top.tab_hidden = true;
self.select(top);
self.finish(index, true);
@@ -408,7 +413,32 @@ fn attach(self: *Self, index: usize, top: *Top) bool {
return true;
}
+/// Unmap is reversible. Keep only a group ID; no client or scene pointer may
+/// survive the group's other members closing while this window is withdrawn.
+pub fn rememberUnmap(top: *Top) void {
+ top.tab_resume_group = top.tab_group;
+ top.tab_resume_restore = top.tab_restore;
+}
+
+fn resumeMember(self: *Self, top: *Top) void {
+ const group = top.tab_resume_group;
+ const floating = top.tab_resume_restore;
+ top.tab_resume_group = 0;
+ top.tab_resume_restore = null;
+ if (group == 0 or !eligible(top) or !enabled(top.server, top.appId())) return;
+ const source = active(top.server, group) orelse return;
+ if (!std.mem.eql(u8, identity(top.appId()), identity(source.appId()))) return;
+ top.tab_group = group;
+ top.tab_identity = source.tab_identity;
+ top.tab_restore = floating;
+ top.workspace_id = source.workspace_id;
+ top.tab_hidden = true;
+ if (top.server.world.toplevels.first() == top) self.select(top) else copyGeometry(source, top);
+ publish(top);
+}
+
pub fn mapped(self: *Self, top: *Top) void {
+ self.resumeMember(top);
self.reconcile(top);
const pid = top.clientPid() orelse return;
for (self.pending.items, 0..) |p, i| {
diff --git a/src/workspace_persistence.zig b/src/workspace_persistence.zig
new file mode 100644
index 0000000..6315cb9
--- /dev/null
+++ b/src/workspace_persistence.zig
@@ -0,0 +1,314 @@
+//! Runtime bridge for the config module's versioned workspace format.
+const std = @import("std");
+const Server = @import("Server.zig");
+const Top = @import("Toplevel.zig");
+const format = @import("config").workspace_layout;
+const layout = @import("auto_layout.zig");
+const gpa = @import("main.zig").gpa;
+
+fn geometry(g: Top.RestoreGeometry) format.Geometry {
+ return .{ .x = g.x, .y = g.y, .width = g.width, .height = g.height };
+}
+fn liveGeometry(g: format.Geometry) Top.RestoreGeometry {
+ return .{ .x = g.x, .y = g.y, .width = g.width, .height = g.height };
+}
+fn optional(g: ?Top.RestoreGeometry) ?format.Geometry {
+ return if (g) |v| geometry(v) else null;
+}
+fn liveOptional(g: ?format.Geometry) ?Top.RestoreGeometry {
+ return if (g) |v| liveGeometry(v) else null;
+}
+pub fn nodes(a: std.mem.Allocator, list: *std.ArrayList(format.Node), node: *const layout.Node) !void {
+ try list.append(a, .{ .id = if (node.member) |m| m.key.id else null, .group = if (node.member) |m| m.key.group else false, .axis = @enumFromInt(@intFromEnum(node.axis)), .ratio = node.ratio });
+ if (node.children) |c| {
+ try nodes(a, list, c.a);
+ try nodes(a, list, c.b);
+ }
+}
+pub fn save(server: *Server, path: []const u8, last_hash: ?*?u64) !void {
+ if (server.greeter_mode or !server.world.workspaces.active) return;
+ server.world.workspaces.tiler.flushNow(server);
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var windows: std.ArrayList(format.Window) = .empty;
+ var tops: std.ArrayList(*Top) = .empty;
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| if (top.workspace_id > 0 and top.backend != .placeholder) {
+ try tops.append(a, top);
+ };
+ std.mem.sort(*Top, tops.items, {}, struct {
+ fn less(_: void, x: *Top, y: *Top) bool {
+ return x.workspace_order < y.workspace_order;
+ }
+ }.less);
+ for (tops.items, 0..) |top, index| {
+ var ordinal: usize = 0;
+ for (tops.items[0..index]) |previous| if (std.mem.eql(u8, top.appId(), previous.appId()) and std.mem.eql(u8, top.backendName(), previous.backendName())) {
+ ordinal += 1;
+ };
+ try windows.append(a, .{
+ .app_id = top.appId(),
+ .title = top.title(),
+ .backend = top.backendName(),
+ .instance = top.x11Instance() orelse "",
+ .ordinal = ordinal,
+ .workspace = top.workspace_id,
+ .order = top.workspace_order,
+ .group = top.tab_group,
+ .tab_active = !top.tab_hidden,
+ .floating = top.auto_float,
+ .floating_override = top.auto_float_override,
+ .reinsert = if (top.auto_reinsert) |at| .{ .anchor = at.anchor.id, .group = at.anchor.group, .axis = @enumFromInt(@intFromEnum(at.axis)), .ratio = at.ratio, .before = at.before } else null,
+ .geometry = geometry(top.auto_restore orelse top.tile_restore orelse top.maximize_restore orelse top.fullscreen_restore orelse top.rememberGeometry()),
+ .auto_restore = optional(top.auto_restore),
+ .maximize_restore = optional(top.maximize_restore),
+ .fullscreen_restore = optional(top.fullscreen_restore),
+ .tile = if (top.tile) |tile| @tagName(tile) else null,
+ .tile_restore = optional(top.tile_restore),
+ .maximized = top.maximized,
+ .fullscreen = top.fullscreen,
+ .minimized = top.minimized,
+ .canvas = if (top.canvas_state) |c| .{ .geometry = geometry(c.geometry), .zoom_index = c.zoom_index, .maximized = c.layout == .maximized, .tile = if (c.layout == .tiled) @tagName(c.layout.tiled) else null, .fullscreen = c.fullscreen, .maximize_restore = optional(c.maximize_restore), .tile_restore = optional(c.tile_restore), .fullscreen_restore = optional(c.fullscreen_restore) } else null,
+ });
+ }
+ var workspaces: std.ArrayList(format.Workspace) = .empty;
+ const manager = &server.world.workspaces;
+ for (manager.slots, 0..) |slot, index| if (slot.exists) {
+ var flat: std.ArrayList(format.Node) = .empty;
+ if (manager.tiler.trees[index].root) |root| try nodes(a, &flat, root);
+ const focused = if (slot.focus) |id| server.findToplevelById(id) else null;
+ try workspaces.append(a, .{ .id = @intCast(index + 1), .automatic = slot.automatic, .nodes = flat.items, .output = if (slot.output) |out| std.mem.span(out.wlr_output.name) else "", .visible = if (slot.output) |out| out.workspace_id == index + 1 else false, .focus_order = if (focused) |top| top.workspace_order else null });
+ };
+ const saved: format.Saved = .{ .windows = windows.items, .workspaces = workspaces.items, .camera = .{ .offset_x = manager.saved_camera.offset_x, .offset_y = manager.saved_camera.offset_y, .zoom_index = manager.saved_camera.zoom_index }, .bounds = .{ .max_x = manager.saved_bounds.max_x, .max_y = manager.saved_bounds.max_y, .origin_x = manager.saved_bounds.origin_x, .origin_y = manager.saved_bounds.origin_y, .width = manager.saved_bounds.width, .height = manager.saved_bounds.height } };
+ const bytes = try std.json.Stringify.valueAlloc(a, saved, .{});
+ const hash = std.hash.Wyhash.hash(0, bytes);
+ if (last_hash) |last| if (last.* == hash) return;
+ if (std.fs.path.dirname(path)) |dir| try std.Io.Dir.cwd().createDirPath(server.io, dir);
+ const temporary = try std.fmt.allocPrint(a, "{s}.tmp", .{path});
+ const file = try std.Io.Dir.cwd().createFile(server.io, temporary, .{ .permissions = .fromMode(0o600) });
+ defer file.close(server.io);
+ defer std.Io.Dir.cwd().deleteFile(server.io, temporary) catch {};
+ try file.writeStreamingAll(server.io, bytes);
+ try file.sync(server.io);
+ try std.Io.Dir.rename(.cwd(), temporary, .cwd(), path, server.io);
+ if (last_hash) |last| last.* = hash;
+}
+
+pub const Restore = struct {
+ parsed: std.json.Parsed(format.Saved),
+ matches: []?u64,
+ finished: []bool,
+ initialized: bool = false,
+ restore_output_selection: bool = true,
+ touched: [32]bool = @splat(false),
+ pub fn load(server: *Server, path: []const u8) !Restore {
+ const bytes = try std.Io.Dir.cwd().readFileAlloc(server.io, path, gpa, .limited(1 << 20));
+ defer gpa.free(bytes);
+ return fromBytes(bytes);
+ }
+ pub fn fromBytes(bytes: []const u8) !Restore {
+ const parsed = try format.parse(gpa, bytes);
+ errdefer parsed.deinit();
+ const matches = try gpa.alloc(?u64, parsed.value.windows.len);
+ errdefer gpa.free(matches);
+ @memset(matches, null);
+ const finished = try gpa.alloc(bool, matches.len);
+ @memset(finished, false);
+ return .{ .parsed = parsed, .matches = matches, .finished = finished };
+ }
+ pub fn deinit(self: *Restore) void {
+ self.parsed.deinit();
+ gpa.free(self.matches);
+ gpa.free(self.finished);
+ }
+ pub fn pending(self: *const Restore) bool {
+ for (self.finished) |done| if (!done) return true;
+ return false;
+ }
+ pub fn prepare(self: *Restore, server: *Server) void {
+ self.initialize(server);
+ }
+ fn initialize(self: *Restore, server: *Server) void {
+ if (self.initialized or !server.world.workspaces.active or server.getDefaultOutput() == null) return;
+ self.initialized = true;
+ const manager = &server.world.workspaces;
+ const saved = self.parsed.value;
+ for (saved.windows) |window| manager.next_order = @max(manager.next_order, window.order + 1);
+ var tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |top| {
+ top.workspace_order = manager.next_order;
+ manager.next_order += 1;
+ }
+ manager.saved_camera = .{ .offset_x = saved.camera.offset_x, .offset_y = saved.camera.offset_y, .zoom_index = @min(saved.camera.zoom_index, @import("camera.zig").zoom_levels.len - 1) };
+ manager.saved_bounds = .{ .max_x = saved.bounds.max_x, .max_y = saved.bounds.max_y, .origin_x = saved.bounds.origin_x, .origin_y = saved.bounds.origin_y, .width = saved.bounds.width, .height = saved.bounds.height };
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |out| if (self.restore_output_selection) {
+ out.workspace_id = 0;
+ };
+ for (saved.workspaces) |workspace| {
+ if (self.touched[workspace.id - 1]) continue;
+ const slot = &manager.slots[workspace.id - 1];
+ slot.exists = true;
+ slot.automatic = workspace.automatic;
+ var out = server.getDefaultOutput();
+ outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |candidate| if (candidate.isLogicallyEnabled() and std.mem.eql(u8, std.mem.span(candidate.wlr_output.name), workspace.output)) {
+ out = candidate;
+ break;
+ };
+ slot.output = out;
+ if (out) |output| {
+ slot.box = output.usableBox();
+ if (self.restore_output_selection and workspace.visible and output.workspace_id == 0) output.workspace_id = workspace.id;
+ }
+ }
+ outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |out| if (out.isLogicallyEnabled() and out.workspace_id == 0) {
+ for (&manager.slots, 0..) |*slot, index| if (slot.output == out) {
+ out.workspace_id = @intCast(index + 1);
+ break;
+ };
+ };
+ manager.syncOutputs(server);
+ }
+ pub fn apply(self: *Restore, server: *Server, top: *Top) void {
+ if (!server.world.workspaces.active or top.backend == .placeholder) return;
+ self.initialize(server);
+ if (!self.initialized) return;
+ for (self.matches) |id| if (id == top.id) return;
+ const windows = self.parsed.value.windows;
+ var found: ?usize = null;
+ // Prefer a title/instance match; fall back to the first unconsumed
+ // occurrence in saved insertion order when an app changes its title.
+ for (windows, 0..) |saved, index| {
+ if (self.matches[index] != null or !std.mem.eql(u8, saved.app_id, top.appId()) or !std.mem.eql(u8, saved.backend, top.backendName())) continue;
+ if (found == null) found = index;
+ if (std.mem.eql(u8, saved.title, top.title()) and std.mem.eql(u8, saved.instance, top.x11Instance() orelse "")) {
+ found = index;
+ break;
+ }
+ }
+ const index = found orelse {
+ if (!top.in_world) {
+ top.workspace_order = server.world.workspaces.next_order;
+ server.world.workspaces.next_order += 1;
+ }
+ return;
+ };
+ const saved = windows[index];
+ self.matches[index] = top.id;
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ defer server.undo.applying = applying;
+ top.workspace_id = saved.workspace;
+ top.workspace_order = saved.order;
+ // Runtime keys stay unique even when new windows mapped before restore.
+ top.auto_seen = null;
+ if (saved.canvas) |c| top.canvas_state = .{ .geometry = liveGeometry(c.geometry), .zoom_index = c.zoom_index, .layout = if (c.maximized) .maximized else if (c.tile) |tile| blk: {
+ const t = std.meta.stringToEnum(@import("snap.zig").Tile, tile) orelse break :blk .floating;
+ break :blk .{ .tiled = t };
+ } else .floating, .fullscreen = c.fullscreen, .maximize_restore = liveOptional(c.maximize_restore), .tile_restore = liveOptional(c.tile_restore), .fullscreen_restore = liveOptional(c.fullscreen_restore) };
+ top.clearAutoTile(false);
+ if (top.fullscreen) top.setFullscreen(false);
+ top.leaveLayout();
+ top.restoreGeometryNow(liveGeometry(saved.geometry));
+ top.auto_float = saved.floating;
+ top.auto_float_override = saved.floating_override;
+ top.auto_restore = liveOptional(saved.auto_restore);
+ top.tile_restore = liveOptional(saved.tile_restore);
+ if (@import("workspaces.zig").outputFor(top)) |output| {
+ _ = top.moveFromUsableToOutput(output.usableBox(), output);
+ if (saved.tile) |name| if (std.meta.stringToEnum(@import("snap.zig").Tile, name)) |tile| top.setTiledOn(output, tile);
+ if (saved.maximized) top.setMaximizedOn(output);
+ if (saved.fullscreen) top.setFullscreenOn(output);
+ }
+ top.maximize_restore = liveOptional(saved.maximize_restore);
+ top.fullscreen_restore = liveOptional(saved.fullscreen_restore);
+ }
+ pub fn finish(self: *Restore, server: *Server, top: *Top) void {
+ if (!self.initialized) return;
+ for (self.matches, self.parsed.value.windows, 0..) |id, saved, index| if (id == top.id) {
+ if (self.finished[index]) return;
+ self.finished[index] = true;
+ if (saved.group != 0 and top.tab_group != 0) {
+ for (self.matches, self.parsed.value.windows) |other_id, other_saved| {
+ if (other_saved.group != saved.group or other_id == null or other_id == top.id) continue;
+ const other = server.findToplevelById(other_id.?) orelse continue;
+ if (other.tab_group == 0) continue;
+ top.tab_group = other.tab_group;
+ const hidden = if (saved.tab_active) other else top;
+ hidden.detachInput();
+ hidden.setActivated(false);
+ hidden.tab_hidden = true;
+ break;
+ }
+ @import("window_tabs.zig").refreshVisibility(server);
+ }
+ if (saved.minimized) top.minimize();
+ self.rebuild(server) catch |err| std.log.warn("workspace restore: {s}", .{@errorName(err)});
+ if (top.tab_hidden or top.minimized) @import("workspaces.zig").focusFallback(server, if (@import("workspaces.zig").visible(top)) top.workspace_id else null);
+ break;
+ };
+ }
+ pub fn rebuild(self: *Restore, server: *Server) !void {
+ for (self.parsed.value.windows, self.matches) |saved, id| {
+ const at = saved.reinsert orelse continue;
+ const top = server.findToplevelById(id orelse continue) orelse continue;
+ if (self.touched[top.workspace_id - 1]) continue;
+ for (self.parsed.value.windows, self.matches) |anchor, anchor_id| {
+ if ((if (at.group) anchor.group else anchor.order) != at.anchor) continue;
+ const other = server.findToplevelById(anchor_id orelse continue) orelse continue;
+ top.auto_reinsert = .{ .anchor = @import("auto_tiling.zig").key(other), .axis = @enumFromInt(@intFromEnum(at.axis)), .ratio = at.ratio, .before = at.before };
+ break;
+ }
+ }
+
+ for (self.parsed.value.workspaces) |workspace| {
+ if (self.touched[workspace.id - 1]) continue;
+ var cursor: usize = 0;
+ var tree: layout.Tree = .{ .root = if (workspace.nodes.len > 0) try self.buildNode(server, workspace.nodes, &cursor) else null };
+ errdefer tree.deinit(gpa);
+ const target = &server.world.workspaces.tiler.trees[workspace.id - 1];
+ // New unmatched windows are admitted by the normal membership sync.
+ target.deinit(gpa);
+ target.* = tree;
+ const slot = &server.world.workspaces.slots[workspace.id - 1];
+ if (workspace.focus_order) |order| for (self.parsed.value.windows, self.matches) |saved, id| {
+ if (saved.order == order and id != null and server.findToplevelById(id.?) != null) slot.focus = id;
+ };
+ }
+ server.world.workspaces.tiler.schedule(server);
+ server.world.workspaces.refresh(server);
+ }
+ fn buildNode(self: *Restore, server: *Server, flat: []const format.Node, cursor: *usize) !?*layout.Node {
+ const saved = flat[cursor.*];
+ cursor.* += 1;
+ if (saved.id) |key| {
+ for (self.parsed.value.windows, self.matches) |window, id| {
+ if (id == null or (if (saved.group) window.group else window.order) != key) continue;
+ const top = server.findToplevelById(id.?) orelse continue;
+ if (top.workspace_id != window.workspace or @import("auto_tiling.zig").isFloating(top)) continue;
+ const node = try gpa.create(layout.Node);
+ node.* = .{ .member = .{ .key = @import("auto_tiling.zig").key(top), .order = top.workspace_order } };
+ return node;
+ }
+ return null;
+ }
+ const a = try self.buildNode(server, flat, cursor);
+ errdefer {
+ var tree: layout.Tree = .{ .root = a };
+ tree.deinit(gpa);
+ }
+ const b = try self.buildNode(server, flat, cursor);
+ errdefer {
+ var tree: layout.Tree = .{ .root = b };
+ tree.deinit(gpa);
+ }
+ if (a == null) return b;
+ if (b == null) return a;
+ const node = try gpa.create(layout.Node);
+ node.* = .{ .children = .{ .a = a.?, .b = b.? }, .axis = @enumFromInt(@intFromEnum(saved.axis)), .ratio = saved.ratio };
+ return node;
+ }
+};
diff --git a/src/workspaces.zig b/src/workspaces.zig
new file mode 100644
index 0000000..45ca44e
--- /dev/null
+++ b/src/workspaces.zig
@@ -0,0 +1,426 @@
+//! Conventional workspace ownership. Stack/focus order is deliberately separate
+//! from membership; IDs and insertion order survive focus, minimize and remap.
+const std = @import("std");
+const Server = @import("Server.zig");
+const Top = @import("Toplevel.zig");
+const Output = @import("Output.zig");
+const camera = @import("camera.zig");
+const wlr = @import("wlroots");
+const protocol = @import("ipc/protocol.zig");
+const Self = @This();
+pub const count = 32;
+pub const CanvasWindow = struct {
+ geometry: Top.RestoreGeometry,
+ zoom_index: usize,
+ layout: @import("snap.zig").Layout,
+ fullscreen: bool,
+ maximize_restore: ?Top.RestoreGeometry,
+ tile_restore: ?Top.RestoreGeometry,
+ fullscreen_restore: ?Top.RestoreGeometry,
+};
+const Workspace = struct {
+ automatic: bool = true,
+ exists: bool = false,
+ output: ?*Output = null,
+ box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = 0 },
+ focus: ?u64 = null,
+};
+tiler: @import("auto_tiling.zig").Manager = .{},
+active: bool = false,
+changing: bool = false,
+slots: [count]Workspace = @splat(.{}),
+saved_camera: camera.Camera = .{},
+saved_bounds: camera.Bounds = .{},
+next_order: u64 = 1,
+generation: u64 = 0,
+
+pub fn visible(top: *const Top) bool {
+ const self = &top.server.world.workspaces;
+ if (!self.active) return true;
+ if (top.workspace_id == 0 or top.workspace_id > count) return false;
+ const output = self.slots[top.workspace_id - 1].output orelse return false;
+ return output.isLogicallyEnabled() and output.workspace_id == top.workspace_id;
+}
+
+pub fn outputFor(top: *const Top) ?*Output {
+ if (!top.server.world.workspaces.active or top.workspace_id == 0) return null;
+ return top.server.world.workspaces.slots[top.workspace_id - 1].output;
+}
+
+pub fn mapped(self: *Self, top: *Top) void {
+ if (!self.active) {
+ if (top.canvas_state != null) restoreCanvas(top, true);
+ return;
+ }
+ if (top.workspace_generation != self.generation) {
+ top.workspace_id = 0;
+ top.workspace_order = 0;
+ top.workspace_generation = self.generation;
+ top.auto_float = false;
+ top.auto_float_override = null;
+ top.auto_seen = null;
+ top.auto_reinsert = null;
+ }
+ if (top.parentWindow()) |parent| top.workspace_id = parent.workspace_id;
+ if (top.workspace_id == 0) {
+ const output = top.currentOutput() orelse return;
+ top.workspace_id = output.workspace_id;
+ }
+ if (top.workspace_order == 0) {
+ top.workspace_order = self.next_order;
+ self.next_order += 1;
+ }
+ if (top.server.layout_autosave) |autosave| autosave.mapped(top);
+ top.zoom_index = 0;
+ top.zoom_scale = 1;
+ top.zoom_anim.cancel(1);
+ if (outputFor(top)) |output| fit(top, output);
+ @import("auto_tiling.zig").observe(top);
+}
+
+pub fn rememberFocus(self: *Self, top: *Top) void {
+ if (self.active and top.workspace_id != 0) self.slots[top.workspace_id - 1].focus = top.id;
+}
+
+pub fn reveal(self: *Self, top: *Top) void {
+ if (!self.active or self.changing) return;
+ if (visible(top) and top.server.getDefaultOutput() == outputFor(top)) return;
+ self.switchTo(top.server, top.workspace_id);
+}
+
+pub fn cancelGestures(server: *Server) void {
+ server.switcher.cancel();
+ _ = server.input.cancelDrag();
+ server.input.clearGrab();
+ server.input.pan_session = null;
+ server.input.finger_pan = false;
+ server.input.gesture = .none;
+ server.input.zoom_scroll.reset();
+ server.world.cancelPan();
+ server.world.pinching = false;
+ var keyboards = server.input.keyboards.iterator(.forward);
+ while (keyboards.next()) |keyboard| keyboard.cancelModeRepeats();
+}
+
+pub fn setMode(self: *Self, server: *Server, enabled: bool) void {
+ if (self.active == enabled or self.changing or server.greeter_mode) return;
+ self.changing = true;
+ defer self.changing = false;
+ cancelGestures(server);
+ server.undo.clear();
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ defer server.undo.applying = applying;
+ if (enabled) {
+ self.generation += 1;
+ self.saved_camera = server.world.camera;
+ self.saved_bounds = server.world.bounds;
+ // Capture before changing the camera: currentOutput uses presentation.
+ self.assignOutputs(server);
+ var it = server.world.toplevels.iterator(.reverse);
+ while (it.next()) |top| {
+ top.finishMoveAnimation();
+ top.finishZoomAnimation();
+ top.canvas_state = .{
+ .geometry = top.rememberGeometry(),
+ .zoom_index = top.zoom_index,
+ .layout = top.layout(),
+ .fullscreen = top.fullscreen,
+ .maximize_restore = top.maximize_restore,
+ .tile_restore = top.tile_restore,
+ .fullscreen_restore = top.fullscreen_restore,
+ };
+ if (top.currentOutput()) |output| top.workspace_id = output.workspace_id;
+ top.auto_float = false;
+ top.auto_float_override = null;
+ top.auto_seen = null;
+ top.auto_reinsert = null;
+ top.workspace_generation = self.generation;
+ top.workspace_order = self.next_order;
+ self.next_order += 1;
+ }
+ self.active = true;
+ server.world.camera = .{ .focus_zoom = 1 };
+ server.world.snapCamera();
+ it = server.world.toplevels.iterator(.reverse);
+ while (it.next()) |top| self.mapped(top);
+ } else {
+ if (server.layout_autosave) |autosave| {
+ autosave.saveNow();
+ autosave.cancelWorkspaceRestore();
+ }
+ self.active = false;
+ self.tiler.deinit();
+ server.world.camera = self.saved_camera;
+ server.world.camera.zoom_index = @min(server.world.camera.zoom_index, camera.zoom_levels.len - 1);
+ server.world.snapCamera();
+ const topology_changed = self.saved_bounds.origin_x != server.world.bounds.origin_x or
+ self.saved_bounds.origin_y != server.world.bounds.origin_y or
+ self.saved_bounds.width != server.world.bounds.width or self.saved_bounds.height != server.world.bounds.height;
+ var it = server.world.toplevels.iterator(.forward);
+ while (it.next()) |top| {
+ restoreCanvas(top, topology_changed);
+ }
+ self.slots = @splat(.{});
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| output.workspace_id = 0;
+ }
+ self.tiler.schedule(server);
+ self.refresh(server);
+ focusFallback(server, null);
+ var tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |top| if (top.in_world) top.syncChrome(false, false, Top.nowMs()) catch {};
+ server.world.applyCamera();
+ if (server.input.open_control_center) |cc| {
+ cc.shortcuts.cancel();
+ cc.refresh();
+ }
+}
+
+fn assignOutputs(self: *Self, server: *Server) void {
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| {
+ if (!output.isLogicallyEnabled() or output.workspace_id != 0) continue;
+ for (&self.slots, 0..) |*slot, index| {
+ if (slot.exists) continue;
+ slot.* = .{ .exists = true, .output = output, .box = output.usableBox() };
+ output.workspace_id = @intCast(index + 1);
+ break;
+ }
+ }
+}
+
+/// Called after output layout changes and before an Output is freed.
+pub fn forgetOutput(self: *Self, output: *Output) void {
+ for (&self.slots) |*slot| if (slot.output == output) {
+ slot.output = null;
+ };
+ output.workspace_id = 0;
+}
+
+pub fn syncOutputs(self: *Self, server: *Server) void {
+ if (!self.active or self.changing) return;
+ self.assignOutputs(server);
+ var fallback: ?*Output = null;
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| if (output.isLogicallyEnabled()) {
+ fallback = output;
+ break;
+ };
+ for (&self.slots, 0..) |*slot, index| {
+ if (!slot.exists) continue;
+ if (slot.output) |output| if (!output.isLogicallyEnabled()) {
+ output.workspace_id = 0;
+ slot.output = null;
+ };
+ const moved = slot.output == null;
+ if (moved) slot.output = fallback;
+ const output = slot.output orelse continue;
+ const box = output.usableBox();
+ if (moved or !std.meta.eql(box, slot.box)) {
+ if (server.input.tiling_grab != null) server.input.finishTilingGrab(false);
+ var tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |top| if (top.workspace_id == index + 1) {
+ _ = top.moveFromUsableToOutput(slot.box, output);
+ fit(top, output);
+ };
+ slot.box = box;
+ }
+ }
+ self.tiler.schedule(server);
+ self.refresh(server);
+ const focused = @import("ipc/handlers.zig").findFocusedToplevel(server);
+ if (focused == null) focusFallback(server, null);
+}
+
+pub fn switchTo(self: *Self, server: *Server, id: u8) void {
+ if (!self.active or self.changing or id == 0 or id > count or server.locker != null or server.polkit_dialog != null) return;
+ cancelGestures(server);
+ if (server.layout_autosave) |autosave| autosave.navigation();
+ const slot = &self.slots[id - 1];
+ const output = slot.output orelse server.getDefaultOutput() orelse return;
+ slot.exists = true;
+ slot.output = output;
+ slot.box = output.usableBox();
+ output.workspace_id = id;
+ // Selecting a workspace on another output focuses that output, never
+ // duplicates membership onto the output under the pointer.
+ if (Output.atLayout(server, server.input.cursor.x, server.input.cursor.y) != output) {
+ _ = server.input.cursor.warp(null, @as(f64, @floatFromInt(slot.box.x)) + @as(f64, @floatFromInt(slot.box.width)) / 2, @as(f64, @floatFromInt(slot.box.y)) + @as(f64, @floatFromInt(slot.box.height)) / 2);
+ }
+ self.refresh(server);
+ focusFallback(server, id);
+}
+
+pub fn cycle(self: *Self, server: *Server, forward: bool) void {
+ const output = server.getDefaultOutput() orelse return;
+ if (!self.active or output.workspace_id == 0) return;
+ const current: usize = output.workspace_id - 1;
+ for (1..count + 1) |step| {
+ const index = if (forward) (current + step) % count else (current + count - step) % count;
+ if (self.slots[index].exists) {
+ self.switchTo(server, @intCast(index + 1));
+ return;
+ }
+ }
+}
+
+fn root(top: *Top) *Top {
+ var result = top;
+ for (0..32) |_| {
+ result = result.parentWindow() orelse return result;
+ }
+ return result;
+}
+
+pub fn moveTo(self: *Self, top: *Top, id: u8) void {
+ self.transfer(top, id, true);
+}
+
+pub fn placed(self: *Self, top: *Top, output: *Output) void {
+ if (self.active and top.workspace_id != output.workspace_id) self.transfer(top, output.workspace_id, false);
+}
+
+fn transfer(self: *Self, top: *Top, id: u8, translate: bool) void {
+ const server = top.server;
+ if (!self.active or id == 0 or id > count or server.locker != null or server.polkit_dialog != null) return;
+ const leader = root(top);
+ if (leader.workspace_id == id) return;
+ var transaction = @import("layout_undo.zig").Transaction.begin(server, &.{ leader.workspace_id, id });
+ defer transaction.finish();
+ const source = outputFor(leader);
+ const slot = &self.slots[id - 1];
+ slot.exists = true;
+ if (slot.output == null) slot.output = source orelse server.getDefaultOutput();
+ const destination = slot.output orelse return;
+ slot.box = destination.usableBox();
+ var tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |member| {
+ const owner = root(member);
+ if (owner != leader and (leader.tab_group == 0 or owner.tab_group != leader.tab_group)) continue;
+ member.workspace_id = id;
+ if (source) |out| {
+ if (translate and out != destination) _ = member.moveFromUsableToOutput(out.usableBox(), destination);
+ }
+ fit(member, destination);
+ }
+ self.tiler.schedule(server);
+ self.switchTo(server, id);
+ server.world.focus(top);
+}
+
+pub fn focusFallback(server: *Server, workspace: ?u8) void {
+ if (server.locker != null or server.polkit_dialog != null) return;
+ // Lifecycle and visibility repair are not user navigation. In particular,
+ // closing the focused leaf must leave layout undo for surviving members.
+ const applying = server.undo.applying;
+ server.undo.applying = true;
+ defer server.undo.applying = applying;
+ if (workspace) |id| if (server.world.workspaces.slots[id - 1].focus) |remembered| {
+ if (server.findToplevelById(remembered)) |top| if (top.workspace_id == id and visible(top) and !top.tab_hidden and !top.minimized) {
+ server.world.focus(top);
+ return;
+ };
+ };
+ var tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |top| {
+ if (!visible(top) or top.tab_hidden or top.minimized) continue;
+ if (workspace) |id| if (top.workspace_id != id) continue;
+ server.world.focus(top);
+ return;
+ }
+ tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |top| if (top.activated) top.setActivated(false);
+ server.input.seat.keyboardNotifyClearFocus();
+}
+
+fn fit(top: *Top, output: *Output) void {
+ if (top.fullscreen) {
+ top.setFullscreenOn(output);
+ } else if (top.maximized) {
+ top.setMaximizedOn(output);
+ } else if (top.tile) |tile| {
+ top.setTiledOn(output, tile);
+ } else {
+ _ = top.moveFromUsableToOutput(output.usableBox(), output);
+ }
+ top.finishMoveAnimation();
+}
+
+pub fn refresh(self: *Self, server: *Server) void {
+ _ = self;
+ var tops = server.world.toplevels.iterator(.forward);
+ while (tops.next()) |top| {
+ if (!visible(top)) {
+ top.detachInput();
+ top.setActivated(false);
+ if (top.backend == .xwayland) top.backend.xwayland.xsurface.restack(null, .below);
+ }
+ top.applyVisualTransform(Top.nowMs());
+ top.syncForeign();
+ if (server.ipc) |ipc| @import("ipc/events.zig").onWindowChanged(ipc, top);
+ }
+ var closing = server.world.closing.iterator(.forward);
+ while (closing.next()) |top| if (!visible(top)) top.frame_tree.node.setEnabled(false);
+ var nodes = server.world.tree.children.iterator(.forward);
+ while (nodes.next()) |node| {
+ const data_node = @import("scene_data.zig").SceneData.fromNode(node) orelse continue;
+ if (data_node.role == .xwayland_unmanaged) data_node.role.xwayland_unmanaged.syncWorkspaceVisibility();
+ }
+ server.input.seat.pointerNotifyClearFocus();
+ server.refreshTaskbars();
+ server.scheduleFrames();
+ @import("extra_protocols.zig").syncWorkspaces(server);
+}
+
+pub fn data(self: *Self, server: *Server, allocator: std.mem.Allocator) ![]const protocol.WorkspaceData {
+ if (!self.active) return &.{.{ .id = 1, .name = "Canvas", .is_focused = true }};
+ var list: std.ArrayList(protocol.WorkspaceData) = .empty;
+ errdefer list.deinit(allocator);
+ const output = server.getDefaultOutput();
+ for (self.slots, 0..) |slot, index| {
+ if (!slot.exists) continue;
+ var flat: std.ArrayList(@import("config").workspace_layout.Node) = .empty;
+ if (self.tiler.trees[index].root) |root_node| try @import("workspace_persistence.zig").nodes(allocator, &flat, root_node);
+ try list.append(allocator, .{
+ .id = index + 1,
+ .name = names[index],
+ .is_focused = if (output) |out| out.workspace_id == index + 1 else false,
+ .is_visible = if (slot.output) |out| out.workspace_id == index + 1 else false,
+ .output = if (slot.output) |out| std.mem.span(out.wlr_output.name) else null,
+ .automatic = slot.automatic,
+ .window_gap = server.config.compositor.windowGap(),
+ .nodes = flat.items,
+ });
+ }
+ return list.toOwnedSlice(allocator);
+}
+pub const names: [count][:0]const u8 = blk: {
+ @setEvalBranchQuota(20000);
+ var result: [count][:0]const u8 = undefined;
+ for (0..count) |i| result[i] = std.fmt.comptimePrint("{d}", .{i + 1});
+ break :blk result;
+};
+
+fn restoreCanvas(top: *Top, topology_changed: bool) void {
+ top.clearAutoTile(top.canvas_state == null);
+ top.auto_float = false;
+ top.auto_float_override = null;
+ top.auto_seen = null;
+ top.auto_reinsert = null;
+ if (top.canvas_state) |saved| {
+ if (top.fullscreen) top.setFullscreen(false);
+ top.leaveLayout();
+ top.setZoomOrigin(@min(saved.zoom_index, camera.zoom_levels.len - 1));
+ top.restoreGeometry(saved.geometry);
+ top.setPosition(saved.geometry.x, saved.geometry.y);
+ top.applyLayout(saved.layout);
+ if (saved.fullscreen) top.setFullscreen(true);
+ top.maximize_restore = saved.maximize_restore;
+ top.tile_restore = saved.tile_restore;
+ top.fullscreen_restore = saved.fullscreen_restore;
+ if (topology_changed) if (top.currentOutput()) |output| fit(top, output);
+ } else if (top.currentOutput()) |output| fit(top, output);
+ top.canvas_state = null;
+ top.workspace_id = 0;
+}
diff --git a/src/xwayland_surface.zig b/src/xwayland_surface.zig
index d32a123..3e8aafc 100644
--- a/src/xwayland_surface.zig
+++ b/src/xwayland_surface.zig
@@ -450,7 +450,8 @@ fn handleRequestDemandsAttention(listener: *wl.Listener(void)) void {
}
fn handleSetSizeHints(listener: *wl.Listener(void)) void {
- _ = listener;
+ const adapter: *Adapter = @fieldParentPtr("set_size_hints", listener);
+ @import("auto_tiling.zig").observe(adapter.window);
}
fn handleSetDecorations(listener: *wl.Listener(void)) void {
diff --git a/src/xwayland_unmanaged.zig b/src/xwayland_unmanaged.zig
index d142d26..e4d40cd 100644
--- a/src/xwayland_unmanaged.zig
+++ b/src/xwayland_unmanaged.zig
@@ -202,7 +202,7 @@ fn handleMap(listener: *wl.Listener(void)) void {
fn mapRole(self: *Unmanaged) void {
self.syncPosition();
- self.tree.node.setEnabled(true);
+ self.syncWorkspaceVisibility();
self.tree.node.raiseToTop();
self.server.scheduleFrames();
// A toolkit menu/combo/tooltip opens from a click on its parent, never on
@@ -229,6 +229,7 @@ fn handleUnmap(listener: *wl.Listener(void)) void {
}
fn grabKeyboard(self: *Unmanaged) void {
+ if (parentToplevel(self)) |parent| if (!@import("workspaces.zig").visible(parent)) return;
if (self.server.locker != null or self.server.polkit_dialog != null) return;
const surface = self.xsurface.surface orelse return;
@import("Keyboard.zig").enter(self.server, surface);
@@ -244,7 +245,7 @@ fn restoreFocus(self: *Unmanaged) void {
const focused = seat.keyboard_state.focused_surface orelse return;
if (focused != own_surface) return;
const parent_toplevel = parentToplevel(self) orelse self.server.world.toplevels.first();
- const target = if (parent_toplevel) |t| t.surface() else null;
+ const target = if (parent_toplevel) |t| (if (@import("workspaces.zig").visible(t)) t.surface() else null) else null;
if (target) |surface| {
@import("Keyboard.zig").enter(self.server, surface);
} else {
@@ -255,3 +256,12 @@ fn restoreFocus(self: *Unmanaged) void {
pub fn wantsKeyboard(self: *const Unmanaged) bool {
return self.xsurface.overrideRedirectWantsFocus();
}
+
+pub fn syncWorkspaceVisibility(self: *Unmanaged) void {
+ const mapped = if (self.xsurface.surface) |surface| surface.mapped else false;
+ const shown = if (parentToplevel(self)) |parent| @import("workspaces.zig").visible(parent) else true;
+ self.tree.node.setEnabled(mapped and shown);
+ if (!shown) if (self.xsurface.surface) |surface| {
+ if (self.server.input.seat.keyboard_state.focused_surface == surface) self.server.input.seat.keyboardNotifyClearFocus();
+ };
+}
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 68ff687..9feeb17 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -455,7 +455,7 @@ def test_appearance_settings():
ipc.wait_for_panel_settled("control_center")
assert ui.scroll_into_view("theme")["selected_index"] == 2
blue_theme = tomllib.loads((Path(__file__).resolve().parents[1] /
- "src/assets/themes/redi-blue.toml").read_text())["theme"]
+ "assets/themes/redi-blue.toml").read_text())["theme"]
def check_blue():
tokens = ipc.action("get_theme")["tokens"]
diff --git a/tests/dead_keys.py b/tests/dead_keys.py
new file mode 100644
index 0000000..b7940a5
--- /dev/null
+++ b/tests/dead_keys.py
@@ -0,0 +1,192 @@
+#!/usr/bin/env python3
+"""Dead keys and Compose sequences typed into compositor-drawn fields.
+
+A virtual keyboard with the Latin American layout types into the start menu's
+search box. xkbcommon gives a dead key no text, so without the shell's Compose
+step the accent is lost; the table must also follow `[region] language`
+(acute then c is ç in Portuguese, ć elsewhere).
+"""
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+
+from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process
+from xwayland import wait_for, wayland_display_name
+
+ACUTE, A, C, BACKSPACE, B = 26, 30, 46, 14, 48 # evdev codes on `latam`
+ENTER, F2, HOME = 28, 60, 102
+
+
+def compile_client(tmp):
+ xml = ROOT / "protocol/virtual-keyboard-unstable-v1.xml"
+ for mode, suffix in (("client-header", "client-protocol.h"), ("private-code", "protocol.c")):
+ subprocess.run(["wayland-scanner", mode, str(xml), str(tmp / f"vk-{suffix}")], check=True)
+ # The generated header is included by its protocol name.
+ (tmp / "virtual-keyboard-unstable-v1-client-protocol.h").write_text((tmp / "vk-client-protocol.h").read_text())
+ subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", f"-I{tmp}", str(ROOT / "tests/virtual_keyboard_client.c"),
+ str(tmp / "vk-protocol.c"), "-lwayland-client", "-lxkbcommon",
+ "-o", str(tmp / "virtual-keyboard-client")], check=True)
+
+
+class Keyboard:
+ def __init__(self, tmp, layout):
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=wayland_display_name(tmp))
+ env.pop("DISPLAY", None)
+ self.log = tmp / "keyboard.log"
+ with self.log.open("w") as out:
+ self.process = subprocess.Popen([str(tmp / "virtual-keyboard-client"), layout], env=env,
+ stdin=subprocess.PIPE, stdout=out, stderr=out, text=True)
+ wait_for(lambda: "ready\n" in self.log.read_text(), lambda: f"keyboard did not start: {self.log.read_text()}")
+
+ def send(self, line):
+ before = self.log.read_text().count(f"ack {line}\n")
+ self.process.stdin.write(line + "\n")
+ self.process.stdin.flush()
+ wait_for(lambda: self.log.read_text().count(f"ack {line}\n") > before, f"no ack for {line}")
+
+ def press(self, code, hold=0.0):
+ self.send(f"key {code} 1")
+ time.sleep(hold)
+ self.send(f"key {code} 0")
+
+ def close(self):
+ if self.process.poll() is None:
+ self.process.stdin.write("quit\n")
+ self.process.stdin.flush()
+ self.process.wait(timeout=5)
+
+
+def search_text(ipc):
+ return ipc.get_shell_state()["start_menu"].get("search_text") or ""
+
+
+def session(tmp, language, accented_c):
+ config = f'[compositor]\nxwayland = false\n[region]\nlanguage = "{language}"\n[input]\nkey_repeat_delay = 300\n'
+ process, log = spawn_compositor(tmp, config_content=config, env_extra={"DBUS_SESSION_BUS_ADDRESS": ""})
+ keyboard = None
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ ipc.action("open_start_menu")
+ wait_for(lambda: ipc.get_shell_state()["start_menu"]["state"] == "open", "start menu did not open")
+ keyboard = Keyboard(tmp, "latam")
+
+ # Dead key then letter: one accented letter, nothing for the dead key.
+ keyboard.press(ACUTE)
+ assert search_text(ipc) == "", repr(search_text(ipc))
+ keyboard.press(A)
+ wait_for(lambda: search_text(ipc) == "á", lambda: f"expected á, got {search_text(ipc)!r}")
+
+ # The table follows the language.
+ keyboard.press(ACUTE)
+ keyboard.press(C)
+ expected = "á" + accented_c
+ wait_for(lambda: search_text(ipc) == expected, lambda: f"{language}: expected {expected!r}, got {search_text(ipc)!r}")
+
+ # Backspace ends a pending sequence instead of deleting text.
+ keyboard.press(ACUTE)
+ keyboard.press(BACKSPACE)
+ time.sleep(0.2)
+ assert search_text(ipc) == expected, repr(search_text(ipc))
+ keyboard.press(B)
+ wait_for(lambda: search_text(ipc) == expected + "b", lambda: f"after cancel: {search_text(ipc)!r}")
+
+ # Neither the dead key nor the key that completes it repeats.
+ keyboard.send(f"key {ACUTE} 1")
+ time.sleep(1.0)
+ keyboard.send(f"key {ACUTE} 0")
+ keyboard.send(f"key {A} 1")
+ time.sleep(1.0)
+ keyboard.send(f"key {A} 0")
+ time.sleep(0.2)
+ assert search_text(ipc) == expected + "bá", f"repeat leaked: {search_text(ipc)!r}"
+
+ # Plain keys still repeat.
+ keyboard.send(f"key {B} 1")
+ time.sleep(1.0)
+ keyboard.send(f"key {B} 0")
+ assert search_text(ipc).startswith(expected + "bá" + "bbb"), f"plain key stopped repeating: {search_text(ipc)!r}"
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-3000:])
+ raise
+ finally:
+ if keyboard:
+ keyboard.close()
+ stop_process(process)
+ log.close()
+ assert "panic:" not in (tmp / "compositor.log").read_text()
+
+
+def files_rename(tmp, language, accented_c):
+ """The same sequences in an app client: Files' rename field."""
+ home = tmp / "home"
+ home.mkdir()
+ (home / "x.txt").write_text("x")
+ for name in ("data", "config", "state"):
+ (tmp / name).mkdir()
+ # An app gets its language from the environment the compositor builds for
+ # it; stand in for that here.
+ env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp), XDG_DATA_HOME=str(tmp / "data"),
+ XDG_CONFIG_HOME=str(tmp / "config"), XDG_STATE_HOME=str(tmp / "state"),
+ REDIWM_FILES_DEVICES="0", LC_CTYPE=language, LANG=language)
+ env.pop("LC_ALL", None)
+ process, log = spawn_compositor(tmp, config_content="[compositor]\nxwayland = false\n",
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "HOME": str(home)})
+ files = keyboard = None
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ env["WAYLAND_DISPLAY"] = wayland_display_name(tmp)
+ env.pop("DISPLAY", None)
+ with (tmp / "files.log").open("w") as out:
+ files = subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(home)], env=env, stdout=out, stderr=out)
+ window = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None),
+ "Files did not map")
+ ipc.focus_window(window["id"])
+ time.sleep(0.5)
+ keyboard = Keyboard(tmp, "latam")
+ keyboard.press(HOME) # selects the one file
+ keyboard.press(F2)
+ time.sleep(0.3)
+ for key in (ACUTE, A, ACUTE, C):
+ keyboard.press(key)
+ keyboard.press(ENTER)
+ expected = "á" + accented_c + ".txt"
+ wait_for(lambda: (home / expected).exists(),
+ lambda: f"expected {expected!r}, found {sorted(p.name for p in home.iterdir())}")
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-3000:])
+ print((tmp / "files.log").read_text()[-3000:] if (tmp / "files.log").exists() else "")
+ raise
+ finally:
+ if keyboard:
+ keyboard.close()
+ if files:
+ stop_process(files)
+ stop_process(process)
+ log.close()
+ assert "panic:" not in (tmp / "compositor.log").read_text()
+
+
+def run():
+ with tempfile.TemporaryDirectory(prefix="rediwm-dead-keys-") as directory:
+ tmp = Path(directory)
+ compile_client(tmp)
+ for language, accented_c in (("pt_BR.utf8", "ç"), ("es_MX.utf8", "ć")):
+ sub = tmp / language
+ sub.mkdir(mode=0o700)
+ for name in ("virtual-keyboard-client",):
+ (sub / name).symlink_to(tmp / name)
+ session(sub, language, accented_c)
+ print(f"PASS: dead keys compose under {language}")
+ app = tmp / (language + "-files")
+ app.mkdir(mode=0o700)
+ (app / "virtual-keyboard-client").symlink_to(tmp / "virtual-keyboard-client")
+ files_rename(app, language, accented_c)
+ print(f"PASS: Files rename composes under {language}")
+
+
+if __name__ == "__main__":
+ run()
diff --git a/tests/file_chooser.py b/tests/file_chooser.py
index 47116fc..3b18f0d 100644
--- a/tests/file_chooser.py
+++ b/tests/file_chooser.py
@@ -154,6 +154,11 @@ def run():
code, result = finish(request)
assert code == 0 and result["uris"] == [(docs / "new file.txt").as_uri()], result
assert not (docs / "new file.txt").exists()
+ request = start("SaveFile", {"current_name": GLib.Variant("s", "photo.tar.gz")})
+ key(44) # typing replaces only the name, not the extension
+ key(28)
+ code, result = finish(request)
+ assert code == 0 and result["uris"] == [(docs / "z.tar.gz").as_uri()], result
request = start("SaveFile", {"current_name": GLib.Variant("s", "alpha.txt")})
key(28)
assert request[1].is_alive() and windows(), "overwrite was not confirmed"
diff --git a/tests/images_viewer.py b/tests/images_viewer.py
index 62f1e53..39de764 100644
--- a/tests/images_viewer.py
+++ b/tests/images_viewer.py
@@ -112,6 +112,12 @@ def run(scale):
assert ImageChops.difference(baseline, rotated).getbbox(), "rotation did not change pixels"
key(13) # +
key(2) # 100%
+ actual = capture("actual")
+ # 100% is one image pixel per device pixel at any output scale: the
+ # rotated red quadrant is 100 px wide.
+ r, g, b = actual.split()
+ red = ImageChops.multiply(ImageChops.multiply(r.point(lambda v: 255 if v > 200 else 0), g.point(lambda v: 255 if v < 70 else 0)), b.point(lambda v: 255 if v < 70 else 0)).getbbox()
+ assert red and abs(red[2] - red[0] - 100) <= 3, f"100% is not one device pixel per image pixel: {red}"
key(33) # Fit
key(44, ctrl=True) # Rotation is now an edit; undo before browsing.
key(106)
diff --git a/tests/keyboard_shortcuts.py b/tests/keyboard_shortcuts.py
index 4260acc..bb2056f 100644
--- a/tests/keyboard_shortcuts.py
+++ b/tests/keyboard_shortcuts.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Shortcut recording, conflict/cancel handling and persistence in an isolated session."""
+import os
from pathlib import Path
import tempfile
import time
@@ -11,6 +12,9 @@ def run():
with tempfile.TemporaryDirectory(prefix="rediwm-shortcuts-") as directory:
tmp = Path(directory)
original = '# preserved\n[input]\npointer_speed = 0.4\n[keybinds]\n"Super+q" = "close_window"\n"Super+f" = "toggle_fullscreen"\n'
+ workspace_mode = os.getenv("REDIWM_TEST_WORKSPACES") == "1"
+ if workspace_mode:
+ original = '[compositor]\ndesktop_mode = "workspaces"\n' + original.replace('[keybinds]', '[keybinds.workspace]')
process, log = spawn_compositor(tmp, config_content=original, env_extra={"DBUS_SESSION_BUS_ADDRESS": ""})
try:
with IPCClient(tmp, timeout=15) as ipc:
@@ -57,7 +61,7 @@ def run():
assert has("Super+F12") and not has("Cancel")
saved = (tmp / "rediwm-config.toml").read_text()
assert '"Super+F12" = "close_window"' in saved
- assert '"Super+q"' not in saved
+ assert ('"Super+q" = "noop"' in saved) if workspace_mode else ('"Super+q"' not in saved)
assert '# preserved' in saved and 'pointer_speed = 0.4' in saved
# Previously disabled bindings can be reclaimed.
click("Super+F12")
@@ -124,6 +128,11 @@ def run():
assert not has("Close Window")
click("Window Management")
assert has("Close Window")
+ if workspace_mode:
+ click("Disable shortcut")
+ assert '"Super+q" = "noop"' in (tmp / "rediwm-config.toml").read_text()
+ chord("q")
+ assert ipc.get_shell_state()["control_center"] is not None
print("PASS: shortcut conflicts, capture, cancel, save, reuse and groups")
finally:
stop_process(process)
diff --git a/tests/output_destroy.py b/tests/output_destroy.py
index 0885767..5f66a33 100644
--- a/tests/output_destroy.py
+++ b/tests/output_destroy.py
@@ -22,16 +22,33 @@ def run():
str(ROOT / "tests/output_destroy_hook.c"), "-o", str(hook),
*flags, "-ldl"], check=True)
trigger = tmp / "unplug"
+ reconnect = tmp / "replug"
+ workspace_mode = os.getenv("REDIWM_TEST_WORKSPACES") == "1"
+ config = '[compositor]\nxwayland = false\n' + ('desktop_mode = "workspaces"\n[keybinds.workspace]\n' if workspace_mode else '[keybinds]\n') + '"F12" = "quit"\n'
compositor, log = spawn_compositor(
- tmp, outputs="2", config_content='[compositor]\nxwayland = false\n[keybinds]\n"F12" = "quit"\n',
+ tmp, outputs="2", config_content=config,
env_extra={"LD_PRELOAD": str(hook), "REDIWM_TEST_UNPLUG": str(trigger),
+ **({"REDIWM_TEST_REPLUG": str(reconnect)} if workspace_mode else {}),
"XDG_CACHE_HOME": str(tmp / "cache")})
client = None
+ hidden_client = None
try:
with IPCClient(tmp) as ipc:
+ def window(id):
+ return next(w for w in ipc.get_windows() if w["id"] == id)
+
+ def tiled_on(id, name):
+ out = next(o for o in ipc.get_outputs() if o["name"] == name)
+ box = ipc.get_window_debug(id)["chrome_box"]
+ return window(id)["placement"] == "automatic" and (
+ box["x"], box["y"], box["width"], box["height"]) == (
+ out["x"], out["y"], out["logical_width"], out["logical_height"] - out["bottom_exclusion"])
+
wait_for(lambda: len(ipc.get_outputs()) == 2, "two outputs missing")
display = next(p.name for p in tmp.glob("wayland-*")
if not p.name.endswith(".lock"))
+ target = ipc.get_outputs()[0]
+ ipc.move_cursor(20, 20, output=target["name"])
client = subprocess.Popen([str(tmp / "client")], env=dict(
os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@@ -39,19 +56,70 @@ def run():
# The first-created scene output is the hook's unplug target.
target = ipc.get_outputs()[0]
ipc.move_cursor(20, 20, output=target["name"])
- ipc.action('set_camera', {"x": 0, "y": 0})
- px = target["logical_width"] - 40
- py = target["logical_height"] - target["bottom_exclusion"] - 40
- wait_for(lambda: ipc.hit_test(px, py, output=target["name"])["target_type"] == "mini_map", "mini map missing")
- ipc.move_cursor(px, py, output=target["name"])
- ipc.pointer_button(272, True)
+ if not workspace_mode:
+ ipc.action('set_camera', {"x": 0, "y": 0})
+ px = target["logical_width"] - 40
+ py = target["logical_height"] - target["bottom_exclusion"] - 40
+ wait_for(lambda: ipc.hit_test(px, py, output=target["name"])["target_type"] == "mini_map", "mini map missing")
+ ipc.move_cursor(px, py, output=target["name"])
+ ipc.pointer_button(272, True)
+ if workspace_mode:
+ top = ipc.get_windows()[0]
+ membership = top["workspace_id"]
+ hidden_client = subprocess.Popen([str(tmp / "client"), "--app-id", "unplug-hidden"], env=dict(
+ os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ hidden = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "unplug-hidden"), None), "hidden member maps")
+ ipc.action("move_to_workspace", {"id": hidden["id"], "workspace": 7})
+ ipc.focus_window(top["id"])
+ box = ipc.get_window_debug(top["id"])["client_box"]
+ out = next(o for o in ipc.get_outputs() if o["x"] <= box["x"] < o["x"] + o["logical_width"])
+ ipc.move_cursor(box["x"] - out["x"] + 50, box["y"] - out["y"] + 50, output=out["name"])
+ ipc.key(125, True)
+ ipc.pointer_button(272, True)
+ assert ipc.get_input_state()["cursor_mode"] == "move"
trigger.touch()
wait_for(lambda: len(ipc.get_outputs()) == 1, "output did not unplug")
ipc.pointer_button(272, False)
+ if workspace_mode: ipc.key(125, False)
assert ipc.get_input_state()["cursor_mode"] == "passthrough"
assert compositor.poll() is None
assert client.poll() is None
assert ipc.get_windows(), "client disappeared on hot-unplug"
+ if workspace_mode:
+ top = next(w for w in ipc.get_windows() if w["app_id"] != "unplug-hidden")
+ assert top["workspace_id"] == membership, "unplug changed workspace membership"
+ assert window(hidden["id"])["workspace_id"] == 7
+ ipc.focus_window(top["id"])
+ assert ipc.get_focused_window()["id"] == top["id"]
+ assert next(w["id"] for w in ipc.get_workspaces() if w["is_focused"]) == top["workspace_id"]
+ surviving = ipc.get_outputs()[0]["name"]
+ wait_for(lambda: tiled_on(top["id"], surviving), "migrated member retiles")
+ reconnect.touch()
+ wait_for(lambda: len(ipc.get_outputs()) == 2, "output did not reconnect")
+ assert window(top["id"])["workspace_id"] == membership
+ slot = next(w for w in ipc.get_workspaces() if w["id"] == membership)
+ assert slot["output"] == surviving and slot["is_visible"], "reconnect moved an owned workspace"
+ hidden_slot = next(w for w in ipc.get_workspaces() if w["id"] == 7)
+ assert hidden_slot["output"] == surviving and not hidden_slot["is_visible"], "reconnect merged hidden membership"
+ wait_for(lambda: tiled_on(top["id"], surviving) and tiled_on(hidden["id"], surviving), "reconnect keeps both layouts on their owner")
+ ipc.focus_window(hidden["id"])
+ assert next(w for w in ipc.get_workspaces() if w["is_focused"])["id"] == 7
+ ipc.focus_window(top["id"])
+ added = next(o for o in ipc.get_outputs() if o["name"] != surviving)
+ assert added["name"] == target["name"], "reconnect lost connector identity"
+ ipc.move_cursor(200, 200, output=added["name"])
+ empty = next(w for w in ipc.get_workspaces() if w["is_focused"])
+ assert empty["id"] != membership and empty["output"] == added["name"]
+ ipc.action("switch_workspace", {"workspace": empty["id"]})
+ assert ipc.get_focused_window() is None, "new output stole the migrated member"
+ ipc.action("move_to_workspace", {"id": top["id"], "workspace": empty["id"]})
+ wait_for(lambda: tiled_on(top["id"], added["name"]), "retile after transfer to reconnected output")
+ ipc.focus_window(top["id"])
+ assert window(top["id"])["workspace_id"] == empty["id"]
+ ipc.action("undo")
+ wait_for(lambda: window(top["id"])["workspace_id"] == membership and tiled_on(top["id"], surviving), "undo transfer after reconnect")
+ print("PASS: output reconnect keeps migrated ownership, assigns an empty workspace and accepts reversible transfers")
ipc.wait_for_frame(output=ipc.get_outputs()[0]["name"])
# Quit can close IPC before its buffered reply is flushed.
ipc.sock.sendall(b'{"version":1,"command":"key","params":{"keycode":88,"pressed":true}}\n')
@@ -64,6 +132,8 @@ def run():
finally:
if client is not None:
stop_process(client)
+ if hidden_client is not None:
+ stop_process(hidden_client)
stop_process(compositor)
log.close()
diff --git a/tests/output_destroy_hook.c b/tests/output_destroy_hook.c
index 0dbe2e3..4ba9a81 100644
--- a/tests/output_destroy_hook.c
+++ b/tests/output_destroy_hook.c
@@ -4,17 +4,32 @@
#include <assert.h>
#include <dlfcn.h>
#include <stdlib.h>
+#include <string.h>
#include <unistd.h>
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_scene.h>
#include <wlr/types/wlr_cursor.h>
#include <wlr/backend.h>
+#include <wlr/backend/headless.h>
static struct wlr_scene *scene;
static struct wlr_output *target, *dying;
static struct wl_event_source *timer;
static unsigned mutations;
static bool cursor_destroyed;
+static bool unplugged, initialized;
+static struct wlr_backend *headless;
+static unsigned width, height;
+static char *connector_name;
+static bool reconnecting;
+
+void wlr_output_set_name(struct wlr_output *output, const char *name) {
+ void (*set_name)(struct wlr_output *, const char *) =
+ dlsym(RTLD_NEXT, "wlr_output_set_name");
+ assert(set_name);
+ // Present the same connector identity before the backend emits new_output.
+ set_name(output, reconnecting ? connector_name : name);
+}
void wlr_cursor_destroy(struct wlr_cursor *cursor) {
void (*destroy)(struct wlr_cursor *) = dlsym(RTLD_NEXT, "wlr_cursor_destroy");
@@ -33,15 +48,30 @@ void wlr_backend_destroy(struct wlr_backend *backend) {
static int unplug(void *data) {
(void)data;
+ if (unplugged) {
+ if (access(getenv("REDIWM_TEST_REPLUG"), F_OK) != 0) {
+ wl_event_source_timer_update(timer, 20);
+ return 0;
+ }
+ wl_event_source_remove(timer);
+ reconnecting = true;
+ assert(wlr_headless_add_output(headless, width, height));
+ reconnecting = false;
+ free(connector_name);
+ connector_name = NULL;
+ return 0;
+ }
if (access(getenv("REDIWM_TEST_UNPLUG"), F_OK) != 0) {
wl_event_source_timer_update(timer, 20);
return 0;
}
- wl_event_source_remove(timer);
+ if (!getenv("REDIWM_TEST_REPLUG")) wl_event_source_remove(timer);
dying = target;
wlr_output_destroy(target);
dying = NULL;
assert(mutations > 0);
+ unplugged = true;
+ if (getenv("REDIWM_TEST_REPLUG")) wl_event_source_timer_update(timer, 20);
return 0;
}
@@ -51,9 +81,17 @@ struct wlr_scene_output *wlr_scene_output_create(struct wlr_scene *s,
dlsym(RTLD_NEXT, "wlr_scene_output_create");
assert(create);
struct wlr_scene_output *result = create(s, output);
- if (!target && result) {
+ if (!initialized && result) {
+ initialized = true;
scene = s;
target = output;
+ headless = output->backend;
+ width = output->width;
+ height = output->height;
+ if (getenv("REDIWM_TEST_REPLUG")) {
+ connector_name = strdup(output->name);
+ assert(connector_name);
+ }
timer = wl_event_loop_add_timer(output->event_loop, unplug, NULL);
assert(timer);
wl_event_source_timer_update(timer, 20);
diff --git a/tests/shortcuts_inhibit.py b/tests/shortcuts_inhibit.py
index fec0c1a..1ae1c29 100644
--- a/tests/shortcuts_inhibit.py
+++ b/tests/shortcuts_inhibit.py
@@ -31,9 +31,17 @@ def run():
compile_client(tmp)
# restore_shortcuts (Super+Escape) is inherited even by configs with
# their own [keybinds], like hardware keys.
- compositor, log = start_compositor(tmp, '[compositor]\nxwayland = false\n[keybinds]\n'
- '"super+z" = "set_depth 2"\n"super+x" = "set_depth 0"\n'
- '"alt+tab" = "focus_next"\n')
+ workspace_mode = os.getenv("REDIWM_TEST_WORKSPACES") == "1"
+ config = ('[compositor]\nxwayland = false\n' +
+ ('desktop_mode = "workspaces"\n[keybinds.workspace]\n'
+ '"super+z" = "toggle_floating"\n"super+x" = "toggle_floating"\n'
+ if workspace_mode else '[keybinds]\n'
+ '"super+z" = "set_depth 2"\n"super+x" = "set_depth 0"\n') +
+ '"alt+tab" = "focus_next"\n')
+ compositor, log = start_compositor(tmp, config, {
+ "XDG_STATE_HOME": str(tmp / "state"), "XDG_CACHE_HOME": str(tmp / "cache"),
+ "DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/nonexistent-rediwm-test-system-bus",
+ "DBUS_SESSION_BUS_ADDRESS": ""})
clients = []
sock = reader = None
try:
@@ -81,11 +89,16 @@ def run():
assert self.count(line) == count, f"expected exactly {count}x {line!r}: {self.text()[-1500:]}"
def zoom(name, percent):
- wait_for(lambda: window(name)["zoom_percent"] == percent,
- lambda: f"{name} zoom {window(name)['zoom_percent']} != {percent}")
+ if workspace_mode:
+ placement = "floating" if percent == 70 else "automatic"
+ wait_for(lambda: window(name)["placement"] == placement,
+ lambda: f"{name} placement {window(name)['placement']} != {placement}")
+ else:
+ wait_for(lambda: window(name)["zoom_percent"] == percent,
+ lambda: f"{name} zoom {window(name)['zoom_percent']} != {percent}")
def binding_fires(peer):
- """Super+Z zooms the focused window without reaching it."""
+ """The mode's binding runs without reaching the focused client."""
presses = peer.count(f"key {KEY_Z} 1")
chord(KEY_LEFTMETA, KEY_Z)
zoom(peer.name, 70)
@@ -98,11 +111,16 @@ def run():
chord(KEY_LEFTMETA, KEY_Z)
peer.expect_count(f"key {KEY_Z} 1", presses + 1)
assert window(peer.name)["zoom_percent"] == 100, "inhibited binding still ran"
+ if workspace_mode:
+ assert window(peer.name)["placement"] == "automatic", "inhibited tiling binding still ran"
vm = Peer("rediwm.vm")
assert "global zwp_keyboard_shortcuts_inhibit_manager_v1 1" in vm.text().splitlines(), vm.text()
other = Peer("rediwm.other")
focus("rediwm.vm")
+ if workspace_mode:
+ action('switch_workspace', {"workspace": 9})
+ focus("rediwm.vm")
binding_fires(vm)
print("PASS: global advertised; bindings run without an inhibitor")
@@ -119,13 +137,30 @@ def run():
w = window("rediwm.vm")
action('move_cursor', {"x": w["x"] + 40, "y": w["y"] + 40})
key(KEY_LEFTMETA, True)
- key(KEY_LEFTALT, True)
+ if workspace_mode:
+ action('pointer_button', {"button": 272, "pressed": True})
+ else:
+ key(KEY_LEFTALT, True)
action('move_cursor_relative', {"dx": 30, "dy": 10})
mode = input_state()["cursor_mode"]
- key(KEY_LEFTALT, False)
+ if workspace_mode:
+ # Cancel the insertion after inspecting the grab.
+ if mode != "passthrough":
+ key(KEY_ESC, True)
+ key(KEY_ESC, False)
+ action('pointer_button', {"button": 272, "pressed": False})
+ else:
+ key(KEY_LEFTALT, False)
key(KEY_LEFTMETA, False)
return mode
assert super_drag() == "passthrough", "Super-drag panned under an inhibitor"
+ if workspace_mode:
+ before = req({'version': 1, 'command': 'workspaces'})["Workspaces"]
+ chord(KEY_LEFTMETA, 10) # Super+9 must reach the inhibited client.
+ key(KEY_LEFTMETA, True)
+ action('scroll', {"dx": 0, "dy": -15})
+ key(KEY_LEFTMETA, False)
+ assert req({'version': 1, 'command': 'workspaces'})["Workspaces"] == before, "inhibited number/wheel switched workspace"
print("PASS: active inhibitor gets bindings, Alt+Tab and Super-drag")
# Super+Escape takes the bindings back; Escape itself is consumed.
@@ -135,7 +170,8 @@ def run():
vm.expect_count(f"key {KEY_ESC} 1", escapes)
vm.expect_count(f"key {KEY_ESC} 0", 0)
binding_fires(vm)
- assert super_drag() == "pan", "Super-drag did not pan once shortcuts were restored"
+ expected_mode = "move" if workspace_mode else "pan"
+ assert super_drag() == expected_mode, "Super-drag did not resume once shortcuts were restored"
# The revocation lasts until focus leaves the surface.
focus("rediwm.other")
focus("rediwm.vm")
diff --git a/tests/virtual_keyboard_client.c b/tests/virtual_keyboard_client.c
new file mode 100644
index 0000000..ea4fe27
--- /dev/null
+++ b/tests/virtual_keyboard_client.c
@@ -0,0 +1,67 @@
+// A virtual keyboard with a chosen XKB layout, driven from stdin:
+// key <evdev code> <1|0> press or release
+// quit
+// Prints "ready" once the keymap is in, and "ack <line>" after each command.
+#define _GNU_SOURCE
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <wayland-client.h>
+#include <xkbcommon/xkbcommon.h>
+#include "virtual-keyboard-unstable-v1-client-protocol.h"
+
+static struct wl_seat *seat;
+static struct zwp_virtual_keyboard_manager_v1 *manager;
+
+static void global(void *data, struct wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
+ (void)data; (void)version;
+ if (!strcmp(interface, "wl_seat")) seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
+ else if (!strcmp(interface, "zwp_virtual_keyboard_manager_v1"))
+ manager = wl_registry_bind(registry, id, &zwp_virtual_keyboard_manager_v1_interface, 1);
+}
+static void global_remove(void *data, struct wl_registry *registry, uint32_t id) { (void)data; (void)registry; (void)id; }
+static const struct wl_registry_listener registry_listener = {global, global_remove};
+
+int main(int argc, char **argv) {
+ struct xkb_rule_names names = {.layout = argc > 1 ? argv[1] : "us", .variant = argc > 2 ? argv[2] : ""};
+ struct wl_display *display = wl_display_connect(NULL);
+ assert(display);
+ wl_registry_add_listener(wl_display_get_registry(display), &registry_listener, NULL);
+ wl_display_roundtrip(display);
+ assert(seat && manager);
+
+ struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
+ struct xkb_keymap *map = xkb_keymap_new_from_names(context, &names, 0);
+ assert(map);
+ char *text = xkb_keymap_get_as_string(map, XKB_KEYMAP_FORMAT_TEXT_V1);
+ size_t size = strlen(text) + 1;
+ int fd = memfd_create("virtual-keyboard-client", 0);
+ assert(fd >= 0 && write(fd, text, size) == (ssize_t)size);
+ struct zwp_virtual_keyboard_v1 *keyboard = zwp_virtual_keyboard_manager_v1_create_virtual_keyboard(manager, seat);
+ zwp_virtual_keyboard_v1_keymap(keyboard, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, fd, size);
+ close(fd);
+ free(text);
+ xkb_keymap_unref(map);
+ xkb_context_unref(context);
+ wl_display_roundtrip(display);
+ puts("ready");
+ fflush(stdout);
+
+ char line[128];
+ uint32_t time = 100;
+ while (fgets(line, sizeof line, stdin)) {
+ unsigned code, down;
+ if (sscanf(line, "key %u %u", &code, &down) == 2) zwp_virtual_keyboard_v1_key(keyboard, time += 5, code, down);
+ else if (!strncmp(line, "quit", 4)) break;
+ wl_display_roundtrip(display);
+ printf("ack %s", line);
+ fflush(stdout);
+ }
+ zwp_virtual_keyboard_v1_destroy(keyboard);
+ wl_display_roundtrip(display);
+ wl_display_disconnect(display);
+ return 0;
+}
diff --git a/tests/window_corners.py b/tests/window_corners.py
index bd0aef9..9659fef 100644
--- a/tests/window_corners.py
+++ b/tests/window_corners.py
@@ -66,6 +66,123 @@ def settings_resize(scale):
log.close()
+def workspace_focus(scale):
+ """Focus colours both border paths, CSD input survives, and gaps have mode defaults."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-workspace-borders-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ wallpaper = tmp / "wallpaper.png"
+ Image.new("RGB", (64, 64), (48, 50, 56)).save(wallpaper)
+ live = tmp / "live"
+ live.write_text("ff101215\n") # Colour only; configure replies still own size.
+ config = (f'[compositor]\nxwayland = false\nwallpaper = "{wallpaper}"\n'
+ '[desktop]\nenabled = false\n[animations]\nenabled = false\n'
+ '[theme]\nwindow_bg = "#101215"\nshadow = "#00000000"\n')
+ process, log = spawn_compositor(tmp, scale=str(scale), config_content=config,
+ renderer=os.environ.get("REDIWM_TEST_RENDERER", "pixman"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "REDIWM_THEME": str(tmp / "rediwm-config.toml")})
+ clients = []
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ ids, paths = [], []
+ for mode in ("server", "client"):
+ path = tmp / f"{mode}.log"
+ with path.open("w") as stream:
+ clients.append(subprocess.Popen([str(tmp / "client"), "--app-id", "border-" + mode],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ REDIWM_TEST_DECORATION=mode, REDIWM_TEST_LIVE_FILE=str(live)), stdout=stream, stderr=stream))
+ ids.append(wait_for(lambda: next((w["id"] for w in ipc.get_windows()
+ if w["app_id"] == "border-" + mode), None), "map " + mode))
+ paths.append(path)
+ ipc.action("set_desktop_mode", {"mode": "workspaces", "persist": False})
+ wait_for(lambda: all(w["placement"] == "automatic" for w in ipc.get_windows()), "default tiles")
+ assert ipc.get_workspaces()[0]["window_gap"] == 8
+ def tiled_frames():
+ boxes = [ipc.get_window_debug(id)["chrome_box"] for id in ids]
+ return boxes if boxes[1]["x"] - boxes[0]["x"] - boxes[0]["width"] == 8 else None
+ frames = wait_for(tiled_frames, "client split configure replies")
+ assert frames[0]["x"] == 8 and frames[0]["y"] == 8, frames
+ assert frames[1]["x"] - frames[0]["x"] - frames[0]["width"] == 8, frames
+
+ def red(pixel):
+ return pixel[0] > pixel[1] + 60 and pixel[0] > pixel[2] + 60
+
+ def screenshot():
+ ipc.wait_for_frame()
+ path = tmp / "focus.png"
+ path.unlink(missing_ok=True)
+ ipc.screenshot(path=str(path))
+ with Image.open(path) as image:
+ return image.convert("RGB")
+
+ def edges(id):
+ debug = ipc.get_window_debug(id)
+ box = debug["chrome_box"]
+ x, y, w, h = (box[k] for k in ("x", "y", "width", "height"))
+ outside = debug["decoration_mode"] != "server"
+ return [(x + w / 2, y - 1 if outside else y),
+ (x - 1 if outside else x, y + h / 2),
+ (x + w if outside else x + w - 1, y + h / 2),
+ (x + w / 2, y + h if outside else y + h - 1)]
+
+ for active in ids:
+ ipc.focus_window(active)
+ image = screenshot()
+ for id in ids:
+ for x, y in edges(id):
+ # Rect edges round on the device grid; inspect the
+ # whole logical pixel at fractional scales.
+ pixels = [image.getpixel((px, py))
+ for px in range(math.floor(x * scale), math.ceil((x + 1) * scale))
+ for py in range(math.floor(y * scale), math.ceil((y + 1) * scale))]
+ assert any(red(pixel) for pixel in pixels) == (id == active), ("focus border", scale, active, id, x, y, pixels)
+ if active == ids[0]:
+ box = ipc.get_window_debug(active)["chrome_box"]
+ for y in (box["y"], box["y"] + box["height"] - 10):
+ corner = image.crop((round(box["x"] * scale), round(y * scale),
+ round((box["x"] + 10) * scale), round((y + 10) * scale)))
+ assert any(red(corner.getpixel((cx, cy))) for cy in range(corner.height)
+ for cx in range(corner.width)), ("focus corner", scale, y)
+ # A CSD outline must not steal even the first pixel of client input.
+ box = ipc.get_window_debug(ids[1])["client_box"]
+ before = paths[1].read_text().count("button 272 1")
+ ipc.click_at(box["x"], box["y"] + 20)
+ wait_for(lambda: paths[1].read_text().count("button 272 1") == before + 1, "CSD edge click")
+ ipc.fullscreen(ids[1])
+ wait_for(lambda: ipc.get_window_debug(ids[1])["fullscreen"], "fullscreen")
+ wait_for(lambda: ipc.get_window_debug(ids[1])["client_box"]["width"] == ipc.get_outputs()[0]["logical_width"], "fullscreen client configure reply")
+ image = screenshot()
+ # Configure initially paints the fixture pure red. Only the
+ # compositor's distinct #ed1b2e stroke is a fullscreen failure.
+ focus_pixels = [x for x in range(image.width) if image.getpixel((x, 0)) == (237, 27, 46)]
+ assert not focus_pixels, ("fullscreen focus border", scale, focus_pixels[:8])
+ ipc.fullscreen(ids[1])
+ ipc.action("set_window_gap", {"gap": 0, "persist": False})
+ wait_for(lambda: ipc.get_window_debug(ids[0])["chrome_box"]["x"] == 0, "explicit gap zero")
+ assert ipc.get_workspaces()[0]["window_gap"] == 0
+ ipc.focus_window(ids[0])
+ ipc.action("set_desktop_mode", {"mode": "canvas", "persist": False})
+ wait_for(lambda: ipc.get_workspaces()[0]["name"] == "Canvas", "canvas mode")
+ wait_for(lambda: ipc.get_window_debug(ids[1])["client_box"]["width"] == 400, "canvas client configure reply")
+ ipc.action("move_window_to", {"id": ids[0], "x": 80, "y": 80})
+ ipc.action("move_window_to", {"id": ids[1], "x": 650, "y": 80})
+ image = screenshot()
+ for id in ids:
+ for x, y in edges(id):
+ pixel = image.getpixel((math.floor((x + .25) * scale), math.floor((y + .25) * scale)))
+ assert not red(pixel), ("canvas kept focus outline", scale, id, x, y, pixel, ipc.get_window_debug(id))
+ print(f"PASS scale {scale}: workspace focus edges/corners, CSD input, fullscreen, mode defaults and zero gap")
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-4000:])
+ raise
+ finally:
+ for client in clients: stop_process(client)
+ stop_process(process)
+ log.close()
+
+
def run(scale, background=(48, 50, 56), chrome_alpha=0.98):
with tempfile.TemporaryDirectory(prefix="rediwm-corners-") as directory:
tmp = Path(directory)
@@ -159,6 +276,7 @@ def run(scale, background=(48, 50, 56), chrome_alpha=0.98):
if __name__ == "__main__":
for scale in (1, 1.25, 1.5, 2):
+ workspace_focus(scale)
settings_resize(scale)
run(scale)
run(scale, (224, 225, 232))
diff --git a/tests/window_tabs.py b/tests/window_tabs.py
index 97699ea..1c113a9 100644
--- a/tests/window_tabs.py
+++ b/tests/window_tabs.py
@@ -38,6 +38,8 @@ def run():
'[desktop]\nenabled = false\n[animations]\nenabled = false\n'
'[theme]\nchrome_round_buttons = false\n'
'window_bg = "#101215"\nshadow = "#00000000"\n')
+ if os.getenv("REDIWM_TEST_WORKSPACES") == "1":
+ config = config.replace('[compositor]\n', '[compositor]\ndesktop_mode = "workspaces"\n', 1)
process, log = spawn_compositor(tmp, config_content=config,
scale=os.environ.get("REDIWM_TEST_SCALE", "1"),
renderer=os.environ.get("REDIWM_TEST_RENDERER", "pixman"),
@@ -62,7 +64,7 @@ def run():
def spawn(title):
f = (tmp / f"{title}.log").open("w")
- child = subprocess.Popen([str(tmp / "client"), "--app-id", "tab-fixture", "--title", title], env=dict(env, **({"REDIWM_TEST_CLOSE_MARKER": str(marker)} if title == "First" else {})), stdout=f, stderr=f)
+ child = subprocess.Popen([str(tmp / "client"), "--app-id", "tab-fixture", "--title", title], env=dict(env, REDIWM_TEST_COMMANDS="1", **({"REDIWM_TEST_CLOSE_MARKER": str(marker)} if title == "First" else {})), stdin=subprocess.PIPE, text=True, stdout=f, stderr=f)
f.close()
clients.append(child)
return wait_for(lambda: next((w for w in windows() if w["title"] == title), None), title)["id"]
@@ -182,6 +184,28 @@ def run():
# External activation selects an inactive member.
ipc.focus_window(second)
wait_for(lambda: active(group)["id"] == second, "external activation")
+ if os.getenv("REDIWM_TEST_WORKSPACES") == "1":
+ def geometry(wid):
+ return tuple(window(wid)[key] for key in ("x", "y", "width", "height"))
+ grouped = geometry(second)
+ neighbors = {wid: geometry(wid) for wid in (separate, independent_tab)}
+ ipc.action("tiling_action", {"action": "toggle_floating", "id": second})
+ wait_for(lambda: geometry(second) != grouped, "floating group before undo")
+ ipc.action("undo")
+ wait_for(lambda: geometry(second) == grouped, "group undo restores active tile")
+ ipc.focus_window(first)
+ wait_for(lambda: geometry(first) == grouped, "group undo restores inactive tile")
+ assert all(geometry(wid) == rect for wid, rect in neighbors.items())
+ ipc.focus_window(second)
+ before_remap = (window(second)["x"], window(second)["y"], window(second)["width"], window(second)["height"])
+ for phase in ("inactive", "active"):
+ clients[0].stdin.write("unmap\n"); clients[0].stdin.flush()
+ wait_for(lambda: window(first) is None, "withdraw tab")
+ assert window(second)["tab_group"] == group
+ clients[0].stdin.write("remap\n"); clients[0].stdin.flush()
+ wait_for(lambda: window(first) is not None and window(first).get("tab_group") == group, "remap rejoins tab group")
+ wait_for(lambda: (window(first)["x"], window(first)["y"], window(first)["width"], window(first)["height"]) == before_remap, "remapped group keeps one tile")
+ ipc.focus_window(second)
# Geometry belongs to the group across a switch.
ipc.action("move_window_to", {"id": second, "x": 150, "y": 120})
click(second, f"tab/{first}")
@@ -212,9 +236,21 @@ def run():
click(fourth, "tab_previous")
wait_for(lambda: active(group)["id"] != fourth, "overflow navigation")
current = active(group)["id"]
+ before_close = None
+ if os.getenv("REDIWM_TEST_WORKSPACES") == "1":
+ ipc.action("tiling_action", {"action": "toggle_floating", "id": current})
+ ipc.wait_for_frame()
+ before_close = geometry(current)
+ close_neighbors = {wid: geometry(wid) for wid in (separate, independent_tab)}
+ ipc.action("tiling_action", {"action": "toggle_split", "id": current})
+ wait_for(lambda: geometry(current) != before_close, "group rearrangement before close")
click(current, f"tab/{current}/close")
wait_for(lambda: window(current) is None, "close active tab")
assert active(group) is not None
+ if before_close is not None:
+ ipc.action("undo")
+ wait_for(lambda: geometry(active(group)["id"]) == before_close, "undo survives selected tab closure")
+ assert all(geometry(wid) == rect for wid, rect in close_neighbors.items())
ipc.screenshot(os.environ.get("REDIWM_TABS_PREVIEW", str(tmp / "tabs.png")))
# Outer close closes this group only.
click(active(group)["id"], "close")
diff --git a/tests/wlr_protocols.py b/tests/wlr_protocols.py
index e6f3361..621ee8d 100644
--- a/tests/wlr_protocols.py
+++ b/tests/wlr_protocols.py
@@ -270,7 +270,9 @@ def extra_protocols(tmp):
rules = s.ipc.request(query="get_window_rules", params={"id": window["id"]})
assert rules["live"]["opacity"] == 0.75, rules
workspaces = s.ipc.request(query="workspaces")
- assert workspaces == [{"id": 1, "name": "Canvas", "is_focused": True}], workspaces
+ assert workspaces == [{"id": 1, "name": "Canvas", "is_focused": True,
+ "is_visible": True, "output": None, "automatic": False,
+ "window_gap": 0, "nodes": []}], workspaces
child.stdin.write("update\n"); child.stdin.flush()
expect_line(child, "extras-updated")
wait_for(lambda: s.window("rediwm.protocol-extras")["content_type"] == "game", "content hint did not update")
diff --git a/tests/wlr_protocols_client.c b/tests/wlr_protocols_client.c
index 8204084..b548a99 100644
--- a/tests/wlr_protocols_client.c
+++ b/tests/wlr_protocols_client.c
@@ -348,12 +348,20 @@ static uint32_t supported_tf, supported_primaries;
static bool configured, image_ready, color_done, representation_done;
static unsigned workspace_count, group_count, workspace_outputs;
static bool canvas_name, canvas_id, canvas_active;
+static bool workspace_test_mode;
+static unsigned activate_workspace_id;
+static struct ext_workspace_handle_v1 *activate_workspace;
static void ping(void *data, struct xdg_wm_base *base, uint32_t serial) {
(void)data; xdg_wm_base_pong(base, serial);
}
static const struct xdg_wm_base_listener xdg_listener = {.ping = ping};
static void ws_id(void *data, struct ext_workspace_handle_v1 *w, const char *id) {
- (void)data; (void)w; canvas_id = strcmp(id, "rediwm-canvas") == 0;
+ (void)data; canvas_id = strcmp(id, "rediwm-canvas") == 0;
+ if (workspace_test_mode) {
+ printf("workspace %s\n", id);
+ unsigned number = 0;
+ if (sscanf(id, "rediwm-workspace-%u", &number) == 1 && number == activate_workspace_id) activate_workspace = w;
+ }
}
static void ws_name(void *data, struct ext_workspace_handle_v1 *w, const char *name) {
(void)data; (void)w; canvas_name = strcmp(name, "Canvas") == 0;
@@ -365,7 +373,7 @@ static void ws_state(void *data, struct ext_workspace_handle_v1 *w, uint32_t sta
(void)data; (void)w; canvas_active = (state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE) != 0;
}
static void ws_caps(void *data, struct ext_workspace_handle_v1 *w, uint32_t caps) {
- (void)data; (void)w; assert(caps == 0);
+ (void)data; (void)w; assert(caps == (workspace_test_mode ? EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ACTIVATE : 0));
}
static void ws_removed(void *data, struct ext_workspace_handle_v1 *w) { (void)data; (void)w; }
static const struct ext_workspace_handle_v1_listener ws_listener = {
@@ -509,12 +517,27 @@ int main(int argc, char **argv) {
return 1;
}
if (strcmp(argv[1], "dump-registry") == 0) dump_registry_mode = true;
- extras_mode = strcmp(argv[1], "extras") == 0;
+ workspace_test_mode = strcmp(argv[1], "workspaces") == 0;
+ if (workspace_test_mode && argc > 2) activate_workspace_id = (unsigned)atoi(argv[2]);
+ extras_mode = strcmp(argv[1], "extras") == 0 || workspace_test_mode;
display = wl_display_connect(NULL);
assert(display);
struct wl_registry *registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener, NULL);
wl_display_roundtrip(display);
+ if (workspace_test_mode) {
+ assert(workspace_manager);
+ assert(wl_display_roundtrip(display) >= 0);
+ printf("groups %u outputs %u\n", group_count, workspace_outputs);
+ if (activate_workspace_id) {
+ assert(activate_workspace);
+ ext_workspace_handle_v1_activate(activate_workspace);
+ ext_workspace_manager_v1_commit(workspace_manager);
+ assert(wl_display_roundtrip(display) >= 0);
+ }
+ wl_display_disconnect(display);
+ return 0;
+ }
if (extras_mode) return run_extras();
if (strcmp(argv[1], "screencopy") == 0) return run_screencopy();
if (strcmp(argv[1], "lock") == 0) return run_lock();
diff --git a/tests/workspaces.py b/tests/workspaces.py
new file mode 100644
index 0000000..c309fae
--- /dev/null
+++ b/tests/workspaces.py
@@ -0,0 +1,1215 @@
+#!/usr/bin/env python3
+"""Opt-in workspaces, group undo, automatic layout, visibility and presets."""
+import os
+import signal
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+
+from desktop_zoom import build_client, wait_for
+from ipc_client import IPCClient, spawn_compositor, stop_process
+
+
+def run(outputs=1):
+ with tempfile.TemporaryDirectory(prefix="rediwm-workspaces-") as directory:
+ tmp = Path(directory)
+ from wlr_protocols import compile_fixture
+ compile_fixture(tmp)
+ canvas = '''[compositor]
+desktop_mode = "canvas"
+focus_zoom = "keep"
+snap_to_edges = false
+[keybinds]
+"Super+q" = "noop"
+"Super+F12" = "noop"
+[keybinds.workspace]
+"Super+c" = "noop"
+"Super+F12" = "workspace 3"
+'''
+ if os.getenv("REDIWM_TEST_NEGATIVE") == "1":
+ canvas += '\n[[outputs]]\nname = "HEADLESS-1"\nx = 0\ny = 0\n[[outputs]]\nname = "HEADLESS-2"\nx = -1280\ny = -120\n'
+ process, log = spawn_compositor(tmp, outputs=str(outputs), config_content=canvas,
+ renderer=os.getenv("REDIWM_TEST_RENDERER", "pixman"), scale=os.getenv("REDIWM_TEST_SCALE", "1"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "REDIWM_FILES_DEVICES": "0"})
+ clients = []
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), XDG_STATE_HOME=str(tmp / "state"),
+ WAYLAND_DISPLAY=display, REDIWM_TEST_DECORATION="server", REDIWM_TEST_CLOSE_MARKER=str(tmp / "confirm-close"))
+
+ def launch(name):
+ client = subprocess.Popen([str(tmp / "client"), "--app-id", name], env=env)
+ clients.append(client)
+ return wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == name), None), "map " + name)["id"]
+
+ def window(id):
+ return next(w for w in ipc.get_windows() if w["id"] == id)
+
+ def focused():
+ win = ipc.get_focused_window()
+ return win["id"] if win else None
+
+ def workspace():
+ return next(w["id"] for w in ipc.get_workspaces() if w["is_focused"])
+
+ def chord(key, shift=False):
+ ipc.key(125, True)
+ if shift: ipc.key(42, True)
+ ipc.key_press(key)
+ if shift: ipc.key(42, False)
+ ipc.key(125, False)
+
+ def mode(workspaces):
+ (tmp / "rediwm-config.toml").write_text(canvas.replace('desktop_mode = "canvas"',
+ 'desktop_mode = "workspaces"' if workspaces else 'desktop_mode = "canvas"'))
+ wait_for(lambda: (ipc.get_workspaces()[0]["name"] != "Canvas") == workspaces, "mode reload")
+ ipc.wait_for_frame()
+
+ def protocol_workspaces(activate=None):
+ return subprocess.check_output([str(tmp / "fixture"), "workspaces"] + ([str(activate)] if activate else []), env=env, text=True, timeout=15)
+
+ a = launch("workspace-a")
+ ipc.action("move_window_to", {"id": a, "x": 100, "y": 120})
+ ipc.set_zoom(a, 70)
+ time.sleep(.3)
+ before = window(a)
+ ipc.action("set_camera", {"x": 150, "y": 100})
+ ipc.action("set_zoom", {"percent": 85})
+ time.sleep(.4)
+ camera_before = ipc.get_state()["camera"]
+ ipc.key(125, True)
+ ipc.key(88, True) # Hold a canvas noop across the preset change.
+ mode(True)
+ initial_workspace = workspace()
+ ipc.key(88, True) # A held-key repeat must not invoke the new action.
+ assert workspace() == initial_workspace
+ ipc.key(88, False)
+ ipc.key(125, False)
+ original_workspace = window(a)["workspace_id"]
+ assert window(a)["zoom_percent"] == 100, window(a)
+ assert ipc.get_state()["camera"]["zoom_percent"] == 100
+ marker = tmp / "confirm-close"
+ marker.touch()
+ ipc.action("close_window", {"id": a})
+ dialog = wait_for(lambda: next((w for w in ipc.get_windows() if w["title"] == "Confirm close"), None), "dialog map")["id"]
+ assert window(dialog)["workspace_id"] == original_workspace
+ chord("6", shift=True)
+ assert window(a)["workspace_id"] == window(dialog)["workspace_id"] == 6
+ chord("z")
+ assert window(a)["workspace_id"] == window(dialog)["workspace_id"] == original_workspace
+ chord("6", shift=True)
+ ipc.action("close_window", {"id": dialog})
+ wait_for(lambda: focused() == a, "dialog focus returns to owner")
+ marker.unlink()
+ chord(str(original_workspace), shift=True)
+ chord("F12")
+ assert workspace() == 3
+ assert focused() is None, ipc.get_focused_window()
+ debug = ipc.get_window_debug(a)["chrome_box"]
+ hit = ipc.hit_test(debug["x"] + 30, debug["y"] + 40)
+ assert hit.get("window_id") != a, hit
+ ipc.click_at(debug["x"] + 30, debug["y"] + 40)
+ assert focused() is None
+ # A later repaint/commit must not enable the hidden frame again.
+ ipc.wait_for_frame()
+ assert focused() is None
+ b = launch("workspace-b")
+ assert window(b)["workspace_id"] == 3
+ chord("c") # explicit noop overrides the close preset
+ assert window(b)
+ chord("4", shift=True)
+ assert workspace() == 4 and window(b)["workspace_id"] == 4 and focused() == b, (ipc.get_workspaces(), window(b), ipc.get_focused_window())
+ chord("3")
+ assert focused() is None
+ listing = protocol_workspaces(original_workspace)
+ assert "workspace rediwm-canvas" not in listing and "workspace rediwm-workspace-4" in listing, listing
+ assert f"groups {outputs} outputs {outputs}" in listing, listing
+ assert workspace() == original_workspace
+ ipc.focus_window(a)
+ assert workspace() == original_workspace and focused() == a
+ # Settings is a normal workspace member without a wl_surface.
+ ipc.action("open_control_center")
+ settings = wait_for(lambda: (ipc.get_focused_window() or {}).get("id"), "Settings focus")
+ chord("5", shift=True)
+ assert window(settings)["workspace_id"] == 5
+ chord("3")
+ assert focused() is None
+ ipc.focus_window(settings)
+ assert workspace() == 5 and focused() == settings
+ ipc.action("close_window", {"id": settings})
+ ipc.focus_window(b)
+ # Explicit placement floats a tile; Super-drag never pans the camera.
+ ipc.action("move_window_to", {"id": b, "x": 100, "y": 120})
+ ipc.wait_for_frame()
+ box = ipc.get_window_debug(b)["client_box"]
+ x, y = box["x"] + 40, box["y"] + 40
+ old = window(b)
+ ipc.move_cursor(x, y)
+ ipc.key(125, True)
+ ipc.pointer_button(0x110, True)
+ ipc.move_cursor(x + 90, y + 50)
+ ipc.pointer_button(0x110, False)
+ ipc.key(125, False)
+ assert window(b)["x"] == old["x"] + 90, (old, window(b))
+ assert ipc.get_state()["camera"]["x"] == 0
+ # Minimize retains membership, activation restores it, fullscreen
+ # changes geometry without changing workspace ownership.
+ ipc.key_down_up(68) # F10 asks to minimize via xdg-shell.
+ wait_for(lambda: window(b)["is_minimized"], "minimize")
+ assert window(b)["workspace_id"] == 4
+ chord("3")
+ ipc.focus_window(b)
+ assert workspace() == 4 and focused() == b
+ chord("f")
+ chord("f")
+ assert window(b)["workspace_id"] == 4
+ if outputs > 1:
+ other = next(o for o in ipc.get_outputs() if o["x"] != 0)
+ ipc.move_cursor(200, 200, output=other["name"])
+ chord(str(original_workspace))
+ assert focused() == a
+ assert next(o["name"] for o in ipc.get_outputs() if o["is_focused"]) != other["name"]
+ mode(False)
+ restored = window(a)
+ assert (restored["x"], restored["y"], restored["zoom_percent"]) == (before["x"], before["y"], before["zoom_percent"]), (before, restored)
+ assert ipc.get_state()["camera"] == camera_before, (camera_before, ipc.get_state()["camera"])
+ assert all(w["workspace_id"] == 1 for w in ipc.get_windows())
+ # Repeated transitions capture a fresh canvas snapshot each time.
+ mode(True)
+ mode(False)
+ assert window(a)["zoom_percent"] == before["zoom_percent"]
+ ipc.action("reset_camera")
+ time.sleep(.4)
+ # Exercise the actual Desktop segmented control in both directions.
+ ipc.action("open_control_center")
+ time.sleep(.3)
+ def widget_click(widget, fraction=.5):
+ box = widget["box"]
+ panel = ipc.get_shell_state()["control_center"]["box"]
+ ipc.click_at(round(panel["x"] + box["x"] + box["width"] * fraction), round(panel["y"] + box["y"] + box["height"] / 2))
+ widgets = ipc.get_widget_tree("control_center")["widgets"]
+ widget_click(next(w for w in widgets if w["label"] == "Desktop"))
+ for fraction, enabled in [(.75, True), (.25, False)]:
+ widget = next(w for w in ipc.get_widget_tree("control_center")["widgets"] if (w["path"] or "").endswith("/desktop_mode"))
+ widget_click(widget, fraction)
+ wait_for(lambda: (ipc.get_workspaces()[0]["name"] != "Canvas") == enabled, "Settings mode control")
+ assert '[keybinds]\n"Super+q" = "noop"' in (tmp / "rediwm-config.toml").read_text()
+ assert process.poll() is None
+ print(f"PASS: workspaces, visibility, preset, Settings and canvas restore ({outputs} outputs)", flush=True)
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-6000:])
+ raise
+ finally:
+ for client in clients: stop_process(client)
+ stop_process(process)
+ log.close()
+
+
+
+
+def manual_controls():
+ """Shared actions, tile insertion, reversible split resize and remapping."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-tiling-controls-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ from launch_placeholder import build_test_client, create_desktop_entry
+ slow_client = build_test_client(tmp)
+ apps = tmp / "data/applications"
+ apps.mkdir(parents=True)
+ create_desktop_entry(apps, "controls-slow.desktop", "Tiling slow client",
+ f"{slow_client} --app-id controls.slow --sleep-ms 700", "controls.slow")
+ config = '''[compositor]
+desktop_mode = "workspaces"
+window_gap = 8
+placeholder_delay_ms = 120
+[keybinds.workspace]
+"Super+F11" = "tile_left"
+[animations]
+enabled = false
+'''
+ outputs = int(os.getenv("REDIWM_TEST_OUTPUTS", "1"))
+ if outputs > 1 and os.getenv("REDIWM_TEST_NEGATIVE") == "1":
+ config += '\n[[outputs]]\nname = "HEADLESS-1"\nx = 0\ny = 0\n[[outputs]]\nname = "HEADLESS-2"\nx = -1280\ny = -120\n'
+ process, log = spawn_compositor(tmp, outputs=str(outputs), config_content=config,
+ renderer=os.getenv("REDIWM_TEST_RENDERER", "pixman"), scale=os.getenv("REDIWM_TEST_SCALE", "1"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_DATA_HOME": str(tmp / "data")})
+ clients = []
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ XDG_STATE_HOME=str(tmp / "state"), REDIWM_TEST_DECORATION="server", REDIWM_TEST_COMMANDS="1")
+ def launch(name):
+ with (tmp / (name + ".log")).open("w") as stream:
+ child = subprocess.Popen([str(tmp / "client"), "--app-id", name], env=env,
+ stdin=subprocess.PIPE, stdout=stream, stderr=stream, text=True)
+ clients.append(child)
+ return wait_for(lambda: next((w["id"] for w in ipc.get_windows() if w["app_id"] == name), None), "map " + name), child
+ def win(id): return next(w for w in ipc.get_windows() if w["id"] == id)
+ def frame(id):
+ box = ipc.get_window_debug(id)["chrome_box"]
+ return tuple(round(box[k]) for k in ("x", "y", "width", "height"))
+ def expect(id, rect):
+ try: wait_for(lambda: frame(id) == rect, f"tile {id} expected {rect}")
+ except AssertionError: raise AssertionError((id, rect, frame(id))) from None
+ def action(name, id=None):
+ ipc.action("tiling_action", {"action": name, **({"id": id} if id is not None else {})})
+ def chord(key, shift=False, ctrl=False):
+ ipc.key(125, True)
+ if shift: ipc.key(42, True)
+ if ctrl: ipc.key(29, True)
+ ipc.key_press(key)
+ if ctrl: ipc.key(29, False)
+ if shift: ipc.key(42, False)
+ ipc.key(125, False)
+ def move(x, y, output=None):
+ if output is not None: return ipc.move_cursor(x, y, output=output)
+ out = next(o for o in ipc.get_outputs() if o["x"] <= x < o["x"] + o["logical_width"] and o["y"] <= y < o["y"] + o["logical_height"])
+ return ipc.move_cursor(x - out["x"], y - out["y"], output=out["name"])
+ def begin_drag(id, button=0x110):
+ ipc.focus_window(id)
+ box = ipc.get_window_debug(id)["client_box"]
+ x, y = box["x"] + box["width"] // 2, box["y"] + min(50, box["height"] // 2)
+ move(x, y)
+ ipc.key(125, True)
+ ipc.pointer_button(button, True)
+ assert ipc.get_input_state()["cursor_mode"] == ("resize" if button == 0x111 else "move")
+ return x, y
+ def end_drag(button=0x110, cancel=False):
+ if cancel: ipc.key_press("Escape")
+ ipc.pointer_button(button, False)
+ ipc.key(125, False)
+ assert ipc.get_input_state()["cursor_mode"] == "passthrough"
+ a, ca = launch("controls-a")
+ b, cb = launch("controls-b")
+ wait_for(lambda: frame(a)[0] < frame(b)[0] and frame(a)[2] == frame(b)[2], "two halves")
+ halves = {a: frame(a), b: frame(b)}
+ # Each operation owns the complete affected layout, so undo
+ # restores neighbours as well as the explicitly targeted tile.
+ ipc.focus_window(a)
+ action("swap_right", a)
+ expect(a, halves[b]); expect(b, halves[a])
+ chord("z")
+ expect(a, halves[a]); expect(b, halves[b])
+ action("toggle_split", a)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "rotation before undo")
+ # An inapplicable directional operation must keep the snapshot.
+ action("swap_left", a)
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ action("resize_split_right", a)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "key resize before undo")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ for command, params in (("move_window_to", {"id": a, "x": 100, "y": 100}),
+ ("set_window_size", {"id": a, "width": 450, "height": 300})):
+ ipc.action(command, params)
+ wait_for(lambda: frame(b)[2] > halves[b][2], "explicit placement before undo")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ ipc.focus_window(a)
+ chord("F11")
+ wait_for(lambda: frame(b)[2] > halves[b][2], "manual snap before undo")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ action("toggle_floating", a)
+ wait_for(lambda: frame(b)[2] > halves[b][2], "floating before undo")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ action("toggle_workspace_tiling", a)
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["width"] == 400, "workspace off before undo")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ # Late client configure replies cannot make a real floating
+ # resize look like a no-op or evict its starting geometry.
+ action("toggle_floating", a)
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["width"] == 400, "floating resize origin")
+ floating_rect = frame(a)
+ for pointer in (False, True):
+ os.kill(ca.pid, signal.SIGSTOP)
+ try:
+ if pointer:
+ x, y = begin_drag(a, 0x111)
+ move(x + 70, y + 35)
+ end_drag(0x111)
+ else:
+ ipc.action("set_window_size", {"id": a, "width": 450, "height": 300})
+ ipc.action("undo")
+ finally:
+ os.kill(ca.pid, signal.SIGCONT)
+ expect(a, floating_rect)
+ action("toggle_floating", a)
+ expect(a, halves[a]); expect(b, halves[b])
+ for override in ("fullscreen", "minimize"):
+ ipc.focus_window(a)
+ action("resize_split_right", a)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "resize before lifecycle override")
+ if override == "fullscreen":
+ ipc.action("fullscreen_window", {"id": a})
+ wait_for(lambda: ipc.get_window_debug(a)["fullscreen"], "fullscreen before undo")
+ else:
+ ipc.action("minimize_window", {"id": a})
+ wait_for(lambda: win(a)["is_minimized"], "minimize before undo")
+ ipc.action("undo")
+ if override == "fullscreen":
+ assert ipc.get_window_debug(a)["fullscreen"]
+ ipc.action("fullscreen_window", {"id": a})
+ else:
+ assert win(a)["is_minimized"]
+ ipc.focus_window(a)
+ expect(a, halves[a]); expect(b, halves[b])
+ # Group snapshots also restore both sides of a transfer.
+ original = win(a)["workspace_id"]
+ chord("8", shift=True)
+ wait_for(lambda: win(a)["workspace_id"] == 8, "transfer before undo")
+ ipc.action("undo")
+ assert win(a)["workspace_id"] == original
+ expect(a, halves[a]); expect(b, halves[b])
+ # A released divider drag is undoable. Super+Z during a live
+ # divider drag ends the grab first; a late release is harmless.
+ for live in (False, True):
+ x, y = begin_drag(a, 0x111)
+ move(x + 80, y)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "pointer resize before undo")
+ if live:
+ ipc.key_press("z")
+ else:
+ end_drag(0x111)
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ if live: end_drag(0x111)
+ bx, by, bw, bh = frame(b)
+ begin_drag(a)
+ move(bx + bw // 2, by + bh - 30)
+ end_drag()
+ wait_for(lambda: frame(a)[1] > frame(b)[1], "insertion before undo")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ if outputs > 1:
+ source = next(o for o in ipc.get_outputs() if o["x"] <= frame(a)[0] < o["x"] + o["logical_width"])
+ destination = next(o for o in ipc.get_outputs() if o["name"] != source["name"])
+ move(200, 200, output=destination["name"])
+ d, cd = launch("controls-undo-destination")
+ destination_rect = frame(d)
+ for override in ("fullscreen_window", "maximize_window"):
+ ipc.focus_window(a)
+ ipc.action(override, {"id": a})
+ wait_for(lambda: (ipc.get_window_debug(a)["fullscreen"] if override == "fullscreen_window" else win(a)["is_maximized"]), "override before output transfer")
+ override_rect = frame(a)
+ ipc.action("move_window_to", {"id": a, "output": destination["name"]})
+ try:
+ wait_for(lambda: win(a)["workspace_id"] == win(d)["workspace_id"], "forced layout transfer")
+ except AssertionError:
+ raise AssertionError((override, win(a), win(d), ipc.get_outputs())) from None
+ ipc.action("undo")
+ assert win(a)["workspace_id"] == original
+ expect(a, override_rect); expect(d, destination_rect)
+ ipc.action("fullscreen_window" if override == "fullscreen_window" else "restore_window", {"id": a})
+ expect(a, halves[a]); expect(b, halves[b])
+ for floating in (False, True):
+ ipc.focus_window(a)
+ if floating:
+ action("toggle_floating", a)
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["width"] == 400, "floating transfer origin")
+ origin_rect = frame(a)
+ begin_drag(a)
+ move(250, 230, output=destination["name"])
+ end_drag()
+ wait_for(lambda: win(a)["workspace_id"] == win(d)["workspace_id"], "cross-output drop before undo")
+ ipc.action("undo")
+ assert win(a)["workspace_id"] == original
+ expect(a, origin_rect); expect(d, destination_rect)
+ if floating: action("toggle_floating", a)
+ expect(a, halves[a]); expect(b, halves[b])
+ stop_process(cd)
+ wait_for(lambda: all(w["id"] != d for w in ipc.get_windows()), "close destination tile")
+ # Closing the focused leaf after a resize does not consume
+ # undo or resurrect it; the remaining split keeps its ratio.
+ c, cc = launch("controls-undo-closed")
+ wait_for(lambda: frame(b)[3] < halves[b][3], "undo third tile")
+ baseline = {a: frame(a), b: frame(b)}
+ ipc.focus_window(c)
+ action("resize_split_right", a)
+ wait_for(lambda: frame(a)[2] > baseline[a][2], "resize before close and undo")
+ stop_process(cc)
+ wait_for(lambda: all(w["id"] != c for w in ipc.get_windows()), "close undo member")
+ ipc.action("undo")
+ expect(a, halves[a]); expect(b, halves[b])
+ ipc.focus_window(a)
+ chord("Right", shift=True)
+ expect(a, halves[b])
+ expect(b, halves[a])
+ action("swap_left", a)
+ expect(a, halves[a])
+ action("toggle_split", a)
+ wait_for(lambda: frame(a)[1] < frame(b)[1] and frame(a)[2] > halves[a][2], "rotate split")
+ ipc.focus_window(a)
+ chord("j")
+ expect(a, halves[a])
+ chord("Right", ctrl=True)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "resize split key")
+ action("resize_split_left", a)
+ expect(a, halves[a])
+ chord("v")
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["width"] == 400, "float restore")
+ wait_for(lambda: frame(b)[2] > halves[b][2], "remaining tile fills area")
+ chord("v")
+ expect(a, halves[a])
+ expect(b, halves[b])
+ chord("space", shift=True)
+ wait_for(lambda: ipc.get_window_debug(b)["client_box"]["width"] == 400, "workspace floats")
+ action("toggle_workspace_tiling", a)
+ expect(a, halves[a])
+ expect(b, halves[b])
+ # A move preview makes no geometry changes; Escape is exact.
+ from PIL import Image
+ bx, by, bw, bh = frame(b)
+ preview_output = next(o for o in ipc.get_outputs() if o["x"] <= bx < o["x"] + o["logical_width"])
+ def preview_pixel(path):
+ ipc.screenshot(str(path), output=preview_output["name"])
+ image = Image.open(path)
+ scale = image.width / preview_output["logical_width"]
+ return image.getpixel((round((bx + bw // 2 - preview_output["x"]) * scale), round((by + bh - 70 - preview_output["y"]) * scale)))
+ before_preview = preview_pixel(tmp / "before-preview.png")
+ begin_drag(a)
+ move(bx + bw // 2, by + bh - 30)
+ expect(a, halves[a])
+ expect(b, halves[b])
+ ipc.wait_for_frame()
+ assert preview_pixel(tmp / "during-preview.png") != before_preview, "insertion preview is invisible"
+ end_drag(cancel=True)
+ ipc.wait_for_frame()
+ assert preview_pixel(tmp / "after-preview.png") == before_preview, "cancel left a preview behind"
+ expect(a, halves[a])
+ # The same drop inserts below B and collapses A's old split.
+ begin_drag(a)
+ move(bx + bw // 2, by + bh - 30)
+ end_drag()
+ wait_for(lambda: frame(a)[1] > frame(b)[1] and frame(a)[2] > halves[a][2], "drag insertion")
+ action("toggle_split", a)
+ action("swap_left", a)
+ expect(a, halves[a])
+ expect(b, halves[b])
+ # Live split resizing uses an owned snapshot for Escape.
+ x, y = begin_drag(a, 0x111)
+ move(x + 90, y)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "live split resize")
+ end_drag(0x111, cancel=True)
+ expect(a, halves[a])
+ expect(b, halves[b])
+ x, y = begin_drag(a, 0x111)
+ move(x + 90, y)
+ end_drag(0x111)
+ wait_for(lambda: frame(a)[2] > halves[a][2], "committed split resize")
+ resized = {a: frame(a), b: frame(b)}
+ x, y = begin_drag(a, 0x111)
+ move(x + 40, y)
+ wait_for(lambda: frame(a)[2] > resized[a][2], "resize before fullscreen")
+ ipc.action("fullscreen_window", {"id": a})
+ wait_for(lambda: ipc.get_input_state()["cursor_mode"] == "passthrough", "fullscreen cancels tiled grab")
+ end_drag(0x111)
+ ipc.action("fullscreen_window", {"id": a})
+ expect(a, resized[a])
+ expect(b, resized[b])
+ # Real unmap/remap, with the original neighbour still alive.
+ cb.stdin.write("unmap\n"); cb.stdin.flush()
+ wait_for(lambda: all(w["id"] != b for w in ipc.get_windows()), "unmap")
+ wait_for(lambda: frame(a)[2] > resized[a][2], "unmap reflow")
+ cb.stdin.write("remap\n"); cb.stdin.flush()
+ wait_for(lambda: any(w["id"] == b for w in ipc.get_windows()), "remap")
+ expect(a, resized[a])
+ expect(b, resized[b])
+ # A close during a live resize cannot leave a stale tree/grab.
+ c, cc = launch("controls-c")
+ wait_for(lambda: frame(b)[3] < resized[b][3], "third tile")
+ x, y = begin_drag(a, 0x111)
+ move(x + 40, y)
+ stop_process(cc)
+ wait_for(lambda: all(w["id"] != c for w in ipc.get_windows()), "close during resize")
+ end_drag(0x111, cancel=True)
+ expect(a, resized[a])
+ expect(b, resized[b])
+ begin_drag(b)
+ stop_process(cb)
+ wait_for(lambda: all(w["id"] != b for w in ipc.get_windows()), "close dragged tile")
+ end_drag()
+ assert ipc.get_input_state()["grabbed_window_id"] is None
+ # Workspace transfer follows the same membership path as drop.
+ ipc.focus_window(a)
+ original_workspace = win(a)["workspace_id"]
+ chord("7", shift=True)
+ assert win(a)["workspace_id"] == 7
+ chord(str(original_workspace), shift=True)
+ assert win(a)["workspace_id"] == original_workspace
+ if outputs > 1:
+ source = next(o for o in ipc.get_outputs() if o["x"] <= frame(a)[0] < o["x"] + o["logical_width"])
+ destination = next(o for o in ipc.get_outputs() if o["name"] != source["name"])
+ begin_drag(a)
+ move(200, 200, output=destination["name"])
+ end_drag()
+ wait_for(lambda: win(a)["workspace_id"] != original_workspace, "cross-output tile drop")
+ moved = frame(a)
+ assert destination["x"] <= moved[0] < destination["x"] + destination["logical_width"], (destination, moved)
+ # Drop back onto a workspace whose automatic layout is off.
+ move(200, 200, output=source["name"])
+ chord(str(original_workspace))
+ action("toggle_workspace_tiling")
+ begin_drag(a)
+ move(200, 200, output=source["name"])
+ move(260, 230, output=source["name"])
+ end_drag()
+ wait_for(lambda: win(a)["workspace_id"] == original_workspace and ipc.get_window_debug(a)["client_box"]["width"] == 400, "drop onto floating workspace")
+ assert source["x"] <= frame(a)[0] < source["x"] + source["logical_width"]
+ action("toggle_workspace_tiling", a)
+ wait_for(lambda: frame(a)[2] > 1000, "retile destination workspace")
+ # Launch placeholders own one stable slot, transferred to the
+ # real client. Closing a pending placeholder also reflows.
+ full = frame(a)
+ ipc.wait_for("catalog_published", timeout_ms=5000)
+ ipc.action("launch_app", {"desktop_id": "controls-slow.desktop"})
+ ph = wait_for(lambda: next((w for w in ipc.get_windows() if w.get("placeholder")), None), "placeholder")
+ wait_for(lambda: win(ph["id"])["width"] < full[2], "placeholder tile")
+ wait_for(lambda: frame(a)[2] < full[2], "peer acknowledges placeholder split")
+ ph_box = tuple(win(ph["id"])[k] for k in ("x", "y", "width", "height"))
+ peer_box = frame(a)
+ action("toggle_split", ph["id"])
+ wait_for(lambda: win(ph["id"])["width"] > ph_box[2], "placeholder rearrangement")
+ arranged_placeholder = tuple(win(ph["id"])[k] for k in ("x", "y", "width", "height"))
+ real = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "controls.slow" and not w.get("placeholder")), None), "placeholder matched")
+ expect(real["id"], arranged_placeholder)
+ ipc.action("undo")
+ expect(a, peer_box)
+ expect(real["id"], ph_box)
+ ipc.close_window(real["id"])
+ wait_for(lambda: all(w["id"] != real["id"] for w in ipc.get_windows()), "close launched client")
+ expect(a, full)
+ ipc.action("launch_app", {"desktop_id": "controls-slow.desktop"})
+ ph = wait_for(lambda: next((w for w in ipc.get_windows() if w.get("placeholder")), None), "pending placeholder")
+ ipc.close_window(ph["id"])
+ wait_for(lambda: all(w["id"] != ph["id"] for w in ipc.get_windows()), "cancel placeholder")
+ expect(a, full)
+ print(f"PASS: tiling controls, group undo, late replies, insertion, Escape, split resize, remap and lifecycle ({outputs} outputs)", flush=True)
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-7000:])
+ for path in tmp.glob("controls-*.log"): print(path.name, path.read_text()[-1800:])
+ raise
+ finally:
+ for child in clients: stop_process(child)
+ stop_process(process)
+ log.close()
+
+
+def automatic_layout():
+ with tempfile.TemporaryDirectory(prefix="rediwm-auto-tiles-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ config = '''[compositor]
+desktop_mode = "workspaces"
+window_gap = 8
+[keybinds.workspace]
+"Super+Shift+Left" = "tile_left"
+'''
+ process, log = spawn_compositor(tmp, config_content=config,
+ renderer=os.getenv("REDIWM_TEST_RENDERER", "pixman"), scale=os.getenv("REDIWM_TEST_SCALE", "1"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": ""})
+ clients = []
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ XDG_STATE_HOME=str(tmp / "state"), REDIWM_TEST_DECORATION="server")
+ def launch(name, constraints=None):
+ child_env = dict(env)
+ if constraints:
+ path = tmp / (name + ".hints")
+ path.write_text(constraints)
+ child_env["REDIWM_TEST_CONSTRAINTS"] = str(path)
+ with (tmp / (name + ".log")).open("w") as stream:
+ child = subprocess.Popen([str(tmp / "client"), "--app-id", name], env=child_env, stdout=stream, stderr=stream)
+ clients.append(child)
+ top = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == name), None), "map " + name)
+ return top["id"], child
+ def frame(id):
+ b = ipc.get_window_debug(id)["chrome_box"]
+ return tuple(round(b[k]) for k in ("x", "y", "width", "height"))
+ def expect(id, rect):
+ try: wait_for(lambda: frame(id) == rect, f"tile {id} should occupy {rect}")
+ except AssertionError: raise AssertionError((id, rect, frame(id))) from None
+ def chord(key, shift=False):
+ ipc.key(125, True)
+ if shift: ipc.key(42, True)
+ ipc.key_press(key)
+ if shift: ipc.key(42, False)
+ ipc.key(125, False)
+ output = ipc.get_outputs()[0]
+ width = output["logical_width"]
+ height = output["logical_height"] - next(p for p in ipc.list_panels()["panels"] if p.get("name") == "taskbar")["box"]["height"]
+ full = (8, 8, width - 16, height - 16)
+ left_w = (width - 24 + 1) // 2
+ half = (8, 8, left_w, height - 16)
+ right = (16 + left_w, 8, width - 24 - left_w, height - 16)
+ a, ca = launch("auto-a", "0 0 0 0")
+ expect(a, full)
+ oversized, oversized_client = launch("auto-oversized", f"{width} 100 0 0")
+ expect(a, full)
+ stop_process(oversized_client)
+ wait_for(lambda: all(w["id"] != oversized for w in ipc.get_windows()), "close overflow")
+ b, cb = launch("auto-b", "0 0 0 0")
+ expect(a, half)
+ expect(b, right)
+ # A floating snapshot obeys client limits that changed while
+ # it was tiled; undo must not request the obsolete saved size.
+ ipc.focus_window(a)
+ for _ in range(2):
+ ipc.action("tiling_action", {"id": a, "action": "toggle_floating"})
+ if _ == 0:
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["width"] == 400, "floating snapshot")
+ else:
+ expect(a, half)
+ (tmp / "auto-a.hints").write_text("0 0 300 0")
+ ipc.key_down_up(87)
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["width"] == 300, "new live maximum")
+ ipc.action("undo")
+ wait_for(lambda: ipc.get_window_debug(a)["client_box"]["height"] == 260, "floating undo with new maximum")
+ assert ipc.get_window_debug(a)["client_box"]["width"] == 300
+ (tmp / "auto-a.hints").write_text("0 0 0 0")
+ ipc.key_down_up(87)
+ ipc.action("tiling_action", {"id": a, "action": "toggle_floating"})
+ expect(a, half); expect(b, right)
+ c, cc = launch("auto-c", "0 0 0 0")
+ # The second split follows the longer side of the right tile.
+ if right[2] >= right[3]:
+ cw = (right[2] - 8 + 1) // 2
+ second = (right[0], 8, cw, right[3])
+ third = (right[0] + cw + 8, 8, right[2] - cw - 8, right[3])
+ else:
+ ch = (height - 24 + 1) // 2
+ second = (right[0], 8, right[2], ch)
+ third = (right[0], 16 + ch, right[2], height - 24 - ch)
+ expect(a, half)
+ expect(b, second)
+ expect(c, third)
+ for id in (a, b, c, a):
+ ipc.focus_window(id)
+ expect(a, half)
+ expect(b, second)
+ expect(c, third)
+ # Minimize and temporary geometry overrides preserve the split.
+ ipc.focus_window(c)
+ ipc.key_down_up(68)
+ wait_for(lambda: next(w for w in ipc.get_windows() if w["id"] == c)["is_minimized"], "minimized")
+ expect(b, right)
+ ipc.focus_window(c)
+ expect(c, third)
+ ipc.key_down_up(66)
+ expect(b, right)
+ ipc.key_down_up(67)
+ expect(b, second)
+ expect(c, third)
+ chord("f")
+ expect(b, right)
+ chord("f")
+ expect(c, third)
+ # A live minimum-size update overflows only the newest member.
+ (tmp / "auto-c.hints").write_text(f"{width} 100 0 0")
+ ipc.key_down_up(87)
+ expect(b, right)
+ expect(a, half)
+ (tmp / "auto-c.hints").write_text("0 0 0 0")
+ ipc.key_down_up(87)
+ expect(c, third)
+ # Decoration changes keep the same outer frame; maximum sizes
+ # are honored inside the allocated tile without moving peers.
+ ipc.key_down_up(63)
+ expect(c, third)
+ wait_for(lambda: ipc.get_window_debug(c)["client_box"]["width"] == third[2], "client-side decoration")
+ ipc.key_down_up(64)
+ expect(c, third)
+ (tmp / "auto-c.hints").write_text("0 0 250 0")
+ ipc.key_down_up(87)
+ wait_for(lambda: ipc.get_window_debug(c)["client_box"]["width"] == 250, "maximum width")
+ expect(a, half)
+ expect(b, second)
+ (tmp / "auto-c.hints").write_text("0 0 0 0")
+ ipc.key_down_up(87)
+ expect(c, third)
+ # No configure feedback loop after clients acknowledge layout.
+ time.sleep(.4)
+ before = (tmp / "auto-c.log").read_text().count("configure ")
+ time.sleep(.5)
+ assert (tmp / "auto-c.log").read_text().count("configure ") == before
+ # Explicit manual snapping opts out and the other tiles reflow.
+ chord("Left", shift=True)
+ expect(a, half)
+ expect(b, right)
+ stop_process(cc)
+ wait_for(lambda: all(w["id"] != c for w in ipc.get_windows()), "close c")
+ # A smaller output evicts later members deterministically.
+ for name, id in (("auto-a", a), ("auto-b", b)):
+ (tmp / (name + ".hints")).write_text(f"{width // 3} 100 0 0")
+ ipc.focus_window(id)
+ ipc.key_down_up(87)
+ config_path = tmp / "rediwm-config.toml"
+ config_path.write_text(config + '\n[[outputs]]\nname = "HEADLESS-1"\ntransform = "90"\n')
+ ipc.reload_config()
+ smaller = wait_for(lambda: next((o for o in ipc.get_outputs() if o["logical_width"] == output["logical_height"]), None), "output rotated")
+ small_height = smaller["logical_height"] - next(p for p in ipc.list_panels()["panels"] if p.get("name") == "taskbar")["box"]["height"]
+ expect(a, (8, 8, smaller["logical_width"] - 16, small_height - 16))
+ config_path.write_text(config)
+ ipc.reload_config()
+ expect(a, half)
+ expect(b, right)
+ stop_process(cb)
+ wait_for(lambda: all(w["id"] != b for w in ipc.get_windows()), "close b")
+ expect(a, full)
+ fixed, cf = launch("auto-fixed", "240 160 240 160")
+ expect(a, full)
+ wait_for(lambda: ipc.get_window_debug(fixed)["client_box"]["width"] == 240, "fixed width")
+ assert process.poll() is None
+ print("PASS: automatic splits, stable focus, constraints, overflow, overrides, manual snap and close", flush=True)
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-6000:])
+ raise
+ finally:
+ for child in clients: stop_process(child)
+ stop_process(process)
+ log.close()
+
+
+def rollout_acceptance():
+ """Live output changes, real input, bounded configures, idle and lock guards."""
+ from wlr_protocols import compile_fixture, expect_line, locked
+ from ipc_client import IPCError
+ with tempfile.TemporaryDirectory(prefix="rediwm-workspace-rollout-") as directory:
+ tmp = Path(directory)
+ compile_fixture(tmp)
+ base = '[compositor]\nxwayland = false\ndesktop_mode = "workspaces"\nwindow_gap = 8\n'
+ outputs = int(os.getenv("REDIWM_TEST_OUTPUTS", "1"))
+ def config(scale=1, x=0, y=0):
+ value = base + f'[[outputs]]\nname = "HEADLESS-1"\nscale = {scale}\nx = {x}\ny = {y}\n'
+ if outputs > 1:
+ value += '[[outputs]]\nname = "HEADLESS-2"\nscale = 1.5\nx = 1600\ny = -120\n'
+ return value
+ process, log = spawn_compositor(tmp, outputs=str(outputs), config_content=config(), scale="auto",
+ renderer=os.getenv("REDIWM_TEST_RENDERER", "pixman"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": str(tmp / "cache")})
+ clients = []
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ ipc.wait_for("catalog_published", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ XDG_STATE_HOME=str(tmp / "state"), REDIWM_TEST_DECORATION="server")
+ output_name = "HEADLESS-1"
+ ipc.move_cursor(200, 200, output=output_name)
+ workspace_id = next(w["id"] for w in ipc.get_workspaces() if w["is_focused"])
+ ids, paths = [], []
+ for index in range(3):
+ name = f"rollout-{index}"
+ path = tmp / f"{name}.log"
+ with path.open("w") as stream:
+ clients.append(subprocess.Popen([str(tmp / "client"), "--app-id", name], env=env,
+ stdout=stream, stderr=stream))
+ ids.append(wait_for(lambda: next((w["id"] for w in ipc.get_windows() if w["app_id"] == name), None), "map " + name))
+ paths.append(path)
+ def workspace():
+ return next(w for w in ipc.get_workspaces() if w["id"] == workspace_id)
+ def frames():
+ return [ipc.get_window_debug(id)["chrome_box"] for id in ids]
+ def valid_tiles():
+ if any(w["placement"] != "automatic" for w in ipc.get_windows() if w["id"] in ids): return False
+ out = next(o for o in ipc.get_outputs() if o["name"] == output_name)
+ rects = frames()
+ if (min(r["x"] for r in rects), min(r["y"] for r in rects),
+ max(r["x"] + r["width"] for r in rects), max(r["y"] + r["height"] for r in rects)) != (
+ out["x"] + 8, out["y"] + 8, out["x"] + out["logical_width"] - 8,
+ out["y"] + out["logical_height"] - out["bottom_exclusion"] - 8): return False
+ for r in rects:
+ if r["width"] <= 0 or r["height"] <= 0: return False
+ if r["x"] < out["x"] + 8 or r["y"] < out["y"] + 8: return False
+ if r["x"] + r["width"] > out["x"] + out["logical_width"] - 8: return False
+ if r["y"] + r["height"] > out["y"] + out["logical_height"] - out["bottom_exclusion"] - 8: return False
+ for index, a in enumerate(rects):
+ for b in rects[index + 1:]:
+ if not (a["x"] + a["width"] + 8 <= b["x"] or b["x"] + b["width"] + 8 <= a["x"] or
+ a["y"] + a["height"] + 8 <= b["y"] or b["y"] + b["height"] + 8 <= a["y"]): return False
+ return True
+ wait_for(valid_tiles, "initial valid tiles")
+ nodes = workspace()["nodes"]
+ # Reload scale/position while a tile is grabbed. The output
+ # transaction must cancel the preview before translating tiles.
+ for scale, x, y in ((1.5, -960, -100), (1.25, 0, 0), (1, 0, 0)):
+ out = next(o for o in ipc.get_outputs() if o["name"] == output_name)
+ box = ipc.get_window_debug(ids[0])["client_box"]
+ ipc.move_cursor(round(box["x"] - out["x"] + 40), round(box["y"] - out["y"] + 40), output=output_name)
+ ipc.key(125, True)
+ ipc.pointer_button(272, True)
+ assert ipc.get_input_state()["cursor_mode"] == "move"
+ (tmp / "rediwm-config.toml").write_text(config(scale, x, y))
+ ipc.reload_config()
+ # Density alone preserves headless logical dimensions, so
+ # an unchanged usable area may retain the gesture.
+ if (out["x"], out["y"]) == (x, y): ipc.key_down_up(1)
+ wait_for(lambda: ipc.get_input_state()["cursor_mode"] == "passthrough", "output change cancels tile grab")
+ ipc.pointer_button(272, False)
+ ipc.key(125, False)
+ wait_for(valid_tiles, "valid tiles after scale/position reload")
+ assert workspace()["nodes"] == nodes, "output reload changed split topology"
+ ipc.wait_for_frame(output=output_name)
+ # Scene hit testing alone cannot prove delivery to a client.
+ for id, path in zip(ids, paths):
+ presses = path.read_text().splitlines().count("button 272 1")
+ box = ipc.get_window_debug(id)["client_box"]
+ ipc.click_at(round(box["x"] - x + 40), round(box["y"] - y + 40), output=output_name)
+ wait_for(lambda: path.read_text().splitlines().count("button 272 1") == presses + 1, "tiled client receives click after reload")
+ # Measure sleeping threads directly, with no IPC/stat requests
+ # during the sample. Window commits and autosave may wake once;
+ # a repeating layout or rendering timer must fail this bound.
+ ipc.move_cursor(4, 4, output=output_name)
+ time.sleep(.8)
+ configures = [p.read_text().count("configure ") for p in paths]
+ def switches():
+ result = {}
+ for status in Path(f"/proc/{process.pid}/task").glob("*/status"):
+ try:
+ result[status.parent.name] = sum(int(line.split()[1]) for line in status.read_text().splitlines()
+ if line.startswith("voluntary_ctxt_switches:"))
+ except FileNotFoundError:
+ pass # A startup worker may finish between reads.
+ return result
+ before = switches()
+ time.sleep(1.2)
+ after = switches()
+ wakeups = {tid: value - before[tid] for tid, value in after.items() if tid in before}
+ assert all(value <= 4 for value in wakeups.values()), ("tiled idle wakeups", wakeups)
+ assert [p.read_text().count("configure ") for p in paths] == configures, "idle configure storm"
+ print(f"PASS: live scale/origin reload, grab cancellation, real clicks and idle ({wakeups})", flush=True)
+ # A protocol activation must obey the same lock guard as IPC.
+ ipc.action("switch_workspace", {"workspace": 9})
+ ipc.action("switch_workspace", {"workspace": workspace_id})
+ ipc.focus_window(ids[0])
+ original_frames = frames()
+ lock = subprocess.Popen([str(tmp / "fixture"), "lock"], env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ clients.append(lock)
+ expect_line(lock, "locked")
+ assert locked(ipc)
+ for action, params in (
+ ("workspaces", None), ("focus_window", {"id": ids[1]}),
+ ("switch_workspace", {"workspace": 9}), ("move_to_workspace", {"id": ids[0], "workspace": 9}),
+ ("tiling_action", {"id": ids[0], "action": "toggle_floating"}),
+ ("set_desktop_mode", {"mode": "canvas", "persist": False}),
+ ("set_workspace_layout", {"workspace": workspace_id, "automatic": False}),
+ ("set_window_gap", {"gap": 20, "persist": False}), ("undo", None)):
+ try:
+ ipc.request(query=action, params=params)
+ except IPCError as exc:
+ assert "SessionLocked" in str(exc), (action, exc)
+ else:
+ raise AssertionError(f"{action} bypassed the lock")
+ subprocess.run([str(tmp / "fixture"), "workspaces", "9"], env=env,
+ check=True, capture_output=True, text=True, timeout=15)
+ lock.stdin.write("unlock\n")
+ lock.stdin.flush()
+ expect_line(lock, "unlocked")
+ wait_for(lambda: not locked(ipc), "protocol unlock")
+ assert workspace()["is_focused"] and workspace()["is_visible"]
+ assert workspace()["nodes"] == nodes and frames() == original_frames
+ assert ipc.get_focused_window()["id"] == ids[0]
+ # Client death keeps the lock: activation cannot reveal a hidden
+ # workspace even when there is no longer a lock surface.
+ dying = subprocess.Popen([str(tmp / "fixture"), "lock"], env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ clients.append(dying)
+ expect_line(dying, "locked")
+ dying.kill()
+ dying.wait(timeout=5)
+ subprocess.run([str(tmp / "fixture"), "workspaces", "9"], env=env,
+ check=True, capture_output=True, text=True, timeout=15)
+ assert locked(ipc), "activation unlocked after lock-client death"
+ assert process.poll() is None
+ print("PASS: workspace IPC/protocol lock guards, unlock layout and lock-client death", flush=True)
+ except Exception:
+ print((tmp / "compositor.log").read_text()[-6000:])
+ raise
+ finally:
+ for child in clients: stop_process(child)
+ stop_process(process)
+ log.close()
+
+
+def xwayland_routing():
+ with tempfile.TemporaryDirectory(prefix="rediwm-workspace-x11-") as directory:
+ tmp = Path(directory)
+ outputs = int(os.getenv("REDIWM_TEST_OUTPUTS", "1"))
+ config = '[compositor]\ndesktop_mode = "workspaces"\n'
+ if outputs > 1 and os.getenv("REDIWM_TEST_NEGATIVE") == "1":
+ config += '\n[[outputs]]\nname = "HEADLESS-1"\nx = 0\ny = 0\n[[outputs]]\nname = "HEADLESS-2"\nx = -1280\ny = -120\n'
+ process, log = spawn_compositor(tmp, outputs=str(outputs), config_content=config,
+ renderer=os.getenv("REDIWM_TEST_RENDERER", "pixman"),
+ scale=os.getenv("REDIWM_TEST_SCALE", "1"), env_extra={"DBUS_SESSION_BUS_ADDRESS": ""})
+ children = []
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ display = ipc.query("get_runtime_info")["xwayland_display"]
+ assert display
+ env = dict(os.environ, DISPLAY=display, XDG_RUNTIME_DIR=str(tmp), GDK_BACKEND="x11")
+ env.pop("WAYLAND_DISPLAY", None)
+ def chord(key, shift=False):
+ ipc.key(125, True)
+ if shift: ipc.key(42, True)
+ ipc.key_press(key)
+ if shift: ipc.key(42, False)
+ ipc.key(125, False)
+ def move(x, y):
+ out = next(o for o in ipc.get_outputs() if o["x"] <= x < o["x"] + o["logical_width"] and
+ o["y"] <= y < o["y"] + o["logical_height"])
+ ipc.move_cursor(round(x - out["x"]), round(y - out["y"]), output=out["name"])
+ def launch(index):
+ path = tmp / f"gtk-{index}.log"
+ before = {w["id"] for w in ipc.get_windows()}
+ with path.open("w") as stream:
+ child = subprocess.Popen([sys.executable, str(Path(__file__).with_name("xwayland_gtk_client.py"))], env=env, stdin=subprocess.PIPE, stdout=stream, stderr=stream, text=True)
+ children.append(child)
+ top = wait_for(lambda: next((w for w in ipc.get_windows() if w["id"] not in before), None), "GTK map")
+ wait_for(lambda: ipc.get_window_debug(top["id"])["client_box"]["width"] > ipc.get_outputs()[0]["logical_width"] * .8, "GTK automatic tile")
+ return top["id"], child, path
+ one, client_one, log_one = launch(1)
+ chord("2")
+ two, client_two, log_two = launch(2)
+ # X11 carries position and size in the same configure. Exercise
+ # both a swap and a live divider resize before testing real clicks.
+ chord("1", shift=True)
+ def rect(id):
+ box = ipc.get_window_debug(id)["chrome_box"]
+ return tuple(box[k] for k in ("x", "y", "width", "height"))
+ wait_for(lambda: rect(one)[0] < rect(two)[0] and rect(one)[2] < 900, "two GTK tiles")
+ before_one, before_two = rect(one), rect(two)
+ ipc.action("tiling_action", {"action": "swap_right", "id": one})
+ wait_for(lambda: rect(one)[0] == before_two[0], "X11 tile swap")
+ ipc.focus_window(two)
+ box = ipc.get_window_debug(two)["client_box"]
+ x, y = box["x"] + 80, box["y"] + 70
+ move(x, y)
+ ipc.key(125, True)
+ ipc.pointer_button(0x111, True)
+ assert ipc.get_input_state()["cursor_mode"] == "resize"
+ move(x + 60, y)
+ wait_for(lambda: rect(two)[2] > before_one[2], "X11 split resize")
+ ipc.key_press("Escape")
+ ipc.pointer_button(0x111, False)
+ ipc.key(125, False)
+ wait_for(lambda: rect(two) == before_one, "X11 split resize cancellation")
+ chord("2", shift=True)
+ wait_for(lambda: rect(two)[2] > 1000, "X11 transfer reflow")
+ for key, top, child, path in [("2", two, client_two, log_two), ("1", one, client_one, log_one)]:
+ chord(key)
+ box = ipc.get_window_debug(top)["client_box"]
+ move(box["x"] + 70, box["y"] + 80)
+ ipc.pointer_button(0x111, True)
+ ipc.pointer_button(0x111, False)
+ wait_for(lambda: "popup" in path.read_text(), "X11 click reached wrong workspace")
+ child.stdin.write("popdown\n")
+ child.stdin.flush()
+ assert log_two.read_text().splitlines().count("popup") == 1
+ print(f"PASS: actual GTK Xwayland clicks route to the visible workspace ({outputs} outputs)", flush=True)
+ finally:
+ for child in children: stop_process(child)
+ stop_process(process)
+ log.close()
+
+def persistence_controls():
+ """Rules, Settings, shared IPC, duplicate matching and restart split recovery."""
+ import json
+ with tempfile.TemporaryDirectory(prefix="rediwm-workspace-persistence-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ state = tmp / "state"
+ saved_path = state / "rediwm" / "workspace-layout.json"
+ config = '''[compositor]
+ desktop_mode = "canvas"
+ focus_zoom = "keep"
+ floating_apps = ["utility*"]
+ [keybinds.workspace]
+ "Super+F9" = "save_layout checkpoint"
+ "Super+F10" = "restore_layout checkpoint"
+ [[window_rules]]
+ app_id = "rule-app"
+ floating = true
+'''
+ apps = tmp / "data/applications"
+ apps.mkdir(parents=True)
+ (apps / "tab-persist.desktop").write_text('[Desktop Entry]\nType=Application\nName=Persisted tabs\n'
+ f'Exec=env REDIWM_TEST_DECORATION=server {tmp}/client --app-id tab-persist --title GroupNew\n')
+ config = config.replace('focus_zoom = "keep"', 'focus_zoom = "keep"\nwindow_tab_apps = ["tab-persist"]')
+ outputs = int(os.getenv("REDIWM_TEST_OUTPUTS", "1"))
+ if outputs > 1 and os.getenv("REDIWM_TEST_NEGATIVE") == "1":
+ config += '\n[[outputs]]\nname = "HEADLESS-1"\nx = 0\ny = 0\n[[outputs]]\nname = "HEADLESS-2"\nx = -1280\ny = -120\n'
+ expected = {}
+ canvas_positions = {}
+ for phase in (1, 2):
+ runtime = tmp / f"run{phase}"
+ runtime.mkdir()
+ content = config if phase == 1 else config.replace('desktop_mode = "canvas"', 'desktop_mode = "workspaces"')
+ process, log = spawn_compositor(runtime, outputs=outputs, config_content=content,
+ renderer=os.getenv("REDIWM_TEST_RENDERER", "pixman"), scale=os.getenv("REDIWM_TEST_SCALE", "1"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_STATE_HOME": str(state), "XDG_DATA_HOME": str(tmp / "data"), "REDIWM_FILES_DEVICES": "0"})
+ clients = []
+ try:
+ with IPCClient(runtime, timeout=15) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in runtime.glob("wayland-*") if not p.name.endswith(".lock"))
+ env = dict(os.environ, XDG_RUNTIME_DIR=str(runtime), XDG_STATE_HOME=str(state),
+ WAYLAND_DISPLAY=display, REDIWM_TEST_DECORATION="server")
+ def launch(app, title):
+ child = subprocess.Popen([str(tmp / "client"), "--app-id", app, "--title", title], env=env,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ clients.append(child)
+ return wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == app and w["title"] == title), None), "map " + title)["id"]
+ def window(id): return next(w for w in ipc.get_windows() if w["id"] == id)
+ def frame(id):
+ box = ipc.get_window_debug(id)["chrome_box"]
+ return tuple(box[k] for k in ("x", "y", "width", "height"))
+ def chord(key):
+ ipc.key(125, True); ipc.key_press(key); ipc.key(125, False)
+ def click_global(x, y):
+ out = next(o for o in ipc.get_outputs() if o["x"] <= x < o["x"] + o["logical_width"] and o["y"] <= y < o["y"] + o["logical_height"])
+ ipc.click_at(round(x - out["x"]), round(y - out["y"]), output=out["name"])
+ if phase == 1:
+ ids = {title: launch("duplicate-app", title) for title in ("First", "Second")}
+ for index, (title, id) in enumerate(ids.items()):
+ ipc.action("move_window_to", {"id": id, "x": 90 + index * 200, "y": 100 + index * 80})
+ canvas_positions[title] = (window(id)["x"], window(id)["y"])
+ ipc.action("set_desktop_mode", {"mode": "workspaces", "persist": True})
+ for id in ids.values(): ipc.action("move_to_workspace", {"id": id, "workspace": 1})
+ wait_for(lambda: all(window(id)["placement"] == "automatic" for id in ids.values()), "initial tiles")
+ utility = launch("utility-editor", "Utility")
+ rule = launch("rule-app", "Rule")
+ assert window(utility)["placement"] == "floating"
+ assert window(rule)["placement"] == "floating"
+ ipc.action("tiling_action", {"id": rule, "action": "toggle_floating"})
+ wait_for(lambda: window(rule)["placement"] == "automatic", "rule manual override")
+ ipc.action("tiling_action", {"id": rule, "action": "toggle_floating"})
+ ipc.action("set_workspace_layout", {"workspace": 2, "automatic": False})
+ ipc.action("move_to_workspace", {"id": utility, "workspace": 2})
+ target_name = next(w for w in ipc.get_workspaces() if w["id"] == 2)["output"]
+ target_output = next(o for o in ipc.get_outputs() if o["name"] == target_name)
+ ipc.action("move_window_to", {"id": utility, "x": target_output["x"] + 220, "y": target_output["y"] + 160})
+ if outputs > 1: ipc.action("switch_workspace", {"workspace": 3})
+ ipc.action("switch_workspace", {"workspace": 1})
+ group_first = launch("tab-persist", "GroupFirst")
+ ipc.wait_for("catalog_published", timeout_ms=10000)
+ ipc.focus_window(group_first)
+ widget = next(w for w in ipc.get_widget_tree(f"window/{group_first}")["widgets"] if w["name"] == "tab_new")
+ box = widget["global_box"]
+ click_global(box["x"] + box["width"] // 2, box["y"] + box["height"] // 2)
+ group_new = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "tab-persist" and w["title"] == "GroupNew"), None), "new persisted tab")["id"]
+ wait_for(lambda: window(group_first)["tab_group"] == window(group_new)["tab_group"], "persisted tab group")
+ ipc.action("tiling_action", {"id": ids["First"], "action": "toggle_split"})
+ ipc.action("tiling_action", {"id": ids["First"], "action": "resize_split_down"})
+ ipc.action("set_window_gap", {"gap": 12, "persist": True})
+ wait_for(lambda: ipc.get_workspaces()[0]["window_gap"] == 12, "gap setting")
+ time.sleep(.3)
+ expected = {title: frame(id) for title, id in ids.items()}
+ chord("F9")
+ checkpoint = runtime / "layouts" / "checkpoint.toml"
+ wait_for(checkpoint.exists, "named workspace save")
+ assert json.loads(checkpoint.read_text())["version"] == 2
+ ipc.action("set_workspace_layout", {"workspace": 1, "automatic": False})
+ wait_for(lambda: window(ids["First"])["placement"] == "floating", "floating layout")
+ chord("F10")
+ wait_for(lambda: all(frame(id) == expected[title] for title, id in ids.items()), "named split restore")
+ # Settings uses the same setters; toggle a per-app exception.
+ ipc.action("open_control_center")
+ settings = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-settings"), None), "Settings map")["id"]
+ if outputs > 1: ipc.action("move_to_workspace", {"id": settings, "workspace": 3})
+ ipc.action("maximize_window", {"id": settings})
+ time.sleep(.3)
+ def click(widget):
+ box = widget["box"]; panel = ipc.get_shell_state()["control_center"]["box"]
+ click_global(panel["x"] + box["x"] + box["width"] / 2, panel["y"] + box["y"] + box["height"] / 2)
+ desktop = wait_for(lambda: next((w for w in ipc.get_widget_tree("control_center")["widgets"] if w["label"] == "Desktop"), None), "Desktop navigation")
+ click(desktop)
+ tree = ipc.get_widget_tree("control_center")["widgets"]
+ assert any((w["path"] or "").endswith("/workspace_layout") for w in tree)
+ assert any((w["path"] or "").endswith("/workspace_gap") for w in tree)
+ assert any("floating_app:utility*" in (w["path"] or "") for w in tree)
+ from ui_driver import UIDriver
+ ui = UIDriver(ipc)
+ item = ui.scroll_into_view("floating_app:rule-app")
+ ui.click(item)
+ wait_for(lambda: '"rule-app"' in (runtime / "rediwm-config.toml").read_text().split("floating_apps =", 1)[1].splitlines()[0], "Settings floating app save")
+ ui.click(ui.find("floating_app:rule-app", panel="control_center"))
+ wait_for(lambda: '"rule-app"' not in (runtime / "rediwm-config.toml").read_text().split("floating_apps =", 1)[1].splitlines()[0], "Settings floating app removal")
+ ipc.action("close_panel", {"panel": "control_center"})
+ time.sleep(.3)
+ wait_for(lambda: all(frame(id) == expected[title] for title, id in ids.items()), "Settings closure restores tiles")
+ wait_for(saved_path.exists, "workspace autosave", timeout=15)
+ snapshot = json.loads(saved_path.read_text())
+ assert len([w for w in snapshot["windows"] if w["app_id"] == "duplicate-app"]) == 2
+ assert [w["ordinal"] for w in snapshot["windows"] if w["app_id"] == "duplicate-app"] == [0, 1]
+ assert next(w for w in snapshot["workspaces"] if w["id"] == 2)["automatic"] is False
+ else:
+ # Launch in reverse title order: membership is consumed once,
+ # and saved split order does not become the focus stack.
+ ipc.action("set_window_gap", {"gap": 12, "persist": False})
+ wait_for(lambda: any(w["id"] == 2 and not w["automatic"] for w in ipc.get_workspaces()), "empty startup workspace preferences")
+ original_snapshot = saved_path.read_bytes()
+ time.sleep(9) # Cross the first autosave tick before apps map.
+ assert saved_path.read_bytes() == original_snapshot, "autosave erased pending startup matches"
+ ids = {title: launch("duplicate-app", title) for title in ("Second", "First")}
+ utility = launch("utility-editor", "Utility")
+ group_new = launch("tab-persist", "GroupNew")
+ group_first = launch("tab-persist", "GroupFirst")
+ wait_for(lambda: window(group_first)["tab_group"] == window(group_new)["tab_group"], "restart tab group")
+ assert window(group_new)["tab_active"] and not window(group_first)["tab_active"]
+ assert (ipc.get_focused_window() or {}).get("id") != group_first
+ wait_for(lambda: window(utility)["workspace_id"] == 2, "hidden saved membership")
+ assert (ipc.get_focused_window() or {}).get("id") != utility
+ wait_for(lambda: all(frame(id) == expected[title] for title, id in ids.items()), "restart exact split geometry")
+ rule = launch("rule-app", "Rule")
+ assert window(rule)["placement"] == "floating" and window(rule)["floating_override"] is True
+ ipc.action("tiling_action", {"id": rule, "action": "toggle_floating"})
+ wait_for(lambda: window(rule)["placement"] == "automatic", "restored floating exception can retile")
+ ipc.action("undo")
+ wait_for(lambda: window(rule)["placement"] == "floating", "restored floating override undo")
+ ipc.close_window(group_new)
+ wait_for(lambda: window(group_first)["tab_active"], "saved tab fallback after active closes")
+ new = launch("duplicate-app", "Third")
+ assert window(new)["workspace_id"] == 1
+ ipc.action("move_to_workspace", {"id": ids["First"], "workspace": 3})
+ later = launch("unmatched-app", "Later")
+ time.sleep(2.2)
+ assert window(ids["First"])["workspace_id"] == 3, "startup restore fought a user transfer"
+ ipc.action("set_desktop_mode", {"mode": "canvas", "persist": False})
+ wait_for(lambda: ipc.get_workspaces()[0]["name"] == "Canvas", "canvas transition")
+ for title, id in ids.items():
+ wait_for(lambda: (window(id)["x"], window(id)["y"]) == canvas_positions[title], "saved canvas state")
+ assert process.poll() is None
+ finally:
+ stop_process(process)
+ for child in clients: stop_process(child)
+ log.close()
+ print("PASS: floating rules, Settings/IPC, named saves, duplicate matching, restart splits and saved canvas", flush=True)
+
+if __name__ == "__main__":
+ if "--acceptance-only" in sys.argv:
+ rollout_acceptance()
+ sys.exit(0)
+ if "--persistence-only" in sys.argv:
+ persistence_controls()
+ sys.exit(0)
+ persistence_controls()
+ manual_controls()
+ if "--controls-only" in sys.argv: sys.exit(0)
+ automatic_layout()
+ rollout_acceptance()
+ if "--automatic-only" not in sys.argv: run(int(os.getenv("REDIWM_TEST_OUTPUTS", "1")))
+ if os.getenv("REDIWM_TEST_XWAYLAND") == "1": xwayland_routing()
diff --git a/tests/xwayland.py b/tests/xwayland.py
index 912e7d7..38a35ab 100644
--- a/tests/xwayland.py
+++ b/tests/xwayland.py
@@ -265,7 +265,7 @@ def test_server_stop_cleanup():
)
# One read callback sees both requests before idle dispatch.
# They must coalesce rather than queue two frees of the wrapper.
- sock.sendall((json.dumps({"StopXwayland": {}}) + "\n").encode() * 2)
+ sock.sendall((json.dumps({"version": 1, "command": "stop_xwayland"}) + "\n").encode() * 2)
for _ in range(2):
reply = json.loads(reader.readline())
assert "Ok" in reply, reply
diff --git a/tests/zoom_client.c b/tests/zoom_client.c
index 952087c..38aaf26 100644
--- a/tests/zoom_client.c
+++ b/tests/zoom_client.c
@@ -3,6 +3,8 @@
#include "xdg-shell-client-protocol.h"
#include "xdg-decoration-client-protocol.h"
#include <assert.h>
+#include <poll.h>
+#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -22,6 +24,8 @@ static struct xdg_toplevel *toplevel;
static struct zxdg_decoration_manager_v1 *decoration_manager;
static struct zxdg_toplevel_decoration_v1 *decoration;
static int width = 400, height = 260, frames;
+static int test_min_w, test_min_h, test_max_w, test_max_h;
+static int test_unmapped;
static void released(void *data, struct wl_buffer *buffer) {
(void)data;
wl_buffer_destroy(buffer);
@@ -191,6 +195,7 @@ static const struct wl_surface_listener surface_listener = {.enter = entered,
.leave = left};
static void configured(void *data, struct xdg_surface *xs, uint32_t serial) {
(void)data;
+ if (xs == xdg && test_unmapped) return;
xdg_surface_ack_configure(xs, serial);
if (xs == popup_xdg) {
paint(popup_surface, 100, 60, 0xffffff00);
@@ -228,6 +233,10 @@ static void top_configure(void *data, struct xdg_toplevel *t, int32_t w,
width = w;
if (h > 0)
height = h;
+ if (width < test_min_w) width = test_min_w;
+ if (height < test_min_h) height = test_min_h;
+ if (test_max_w && width > test_max_w) width = test_max_w;
+ if (test_max_h && height > test_max_h) height = test_max_h;
}
// A close-confirmation transient used by the window-group regression. The
// marker lets the harness cancel once, then allow the ordinary close path.
@@ -420,6 +429,24 @@ static void key_leave(void *d, struct wl_keyboard *k, uint32_t serial,
(void)serial;
(void)s;
}
+/* Noninstalled fixture: update real xdg size hints, including zero resets. */
+static void update_constraints(void) {
+ const char *path = getenv("REDIWM_TEST_CONSTRAINTS");
+ if (!path) return;
+ FILE *file = fopen(path, "r");
+ if (!file) return;
+ int min_w, min_h, max_w, max_h;
+ if (fscanf(file, "%d %d %d %d", &min_w, &min_h, &max_w, &max_h) == 4) {
+ test_min_w = min_w; test_min_h = min_h;
+ test_max_w = max_w; test_max_h = max_h;
+ if (min_w > 0 && min_w == max_w) width = min_w;
+ if (min_h > 0 && min_h == max_h) height = min_h;
+ xdg_toplevel_set_min_size(toplevel, min_w, min_h);
+ xdg_toplevel_set_max_size(toplevel, max_w, max_h);
+ }
+ fclose(file);
+}
+
static void key(void *d, struct wl_keyboard *k, uint32_t serial, uint32_t time,
uint32_t code, uint32_t state) {
(void)d;
@@ -428,6 +455,10 @@ static void key(void *d, struct wl_keyboard *k, uint32_t serial, uint32_t time,
(void)time;
printf("key %u %u\n", code, state);
if (!state) return;
+ if (code == 87 && getenv("REDIWM_TEST_CONSTRAINTS")) {
+ update_constraints();
+ wl_surface_commit(surface);
+ }
if (decoration && code == 63)
zxdg_toplevel_decoration_v1_set_mode(decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE);
if (decoration && code == 64)
@@ -570,6 +601,7 @@ int main(int argc, char *argv[]) {
xdg_toplevel_add_listener(toplevel, &top_listener, NULL);
if (title) xdg_toplevel_set_title(toplevel, title);
if (!late_app_id && app_id) xdg_toplevel_set_app_id(toplevel, app_id);
+ update_constraints();
const char *initial_state = getenv("REDIWM_TEST_INITIAL_STATE");
if (initial_state && !strcmp(initial_state, "maximized"))
xdg_toplevel_set_maximized(toplevel);
@@ -584,7 +616,36 @@ int main(int argc, char *argv[]) {
mode && !strcmp(mode, "client") ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
}
wl_surface_commit(surface);
- while (wl_display_dispatch(display) >= 0) {
+ if (getenv("REDIWM_TEST_COMMANDS")) {
+ for (;;) {
+ if (wl_display_dispatch_pending(display) < 0) break;
+ wl_display_flush(display);
+ struct pollfd fds[] = {{wl_display_get_fd(display), POLLIN, 0}, {STDIN_FILENO, POLLIN, 0}};
+ if (poll(fds, 2, -1) < 0) { if (errno == EINTR) continue; break; }
+ if (fds[0].revents && wl_display_dispatch(display) < 0) break;
+ if (fds[1].revents) {
+ char command[32];
+ if (!fgets(command, sizeof(command), stdin)) break;
+ if (!strcmp(command, "unmap\n")) {
+ test_unmapped = 1;
+ wl_surface_attach(surface, NULL, 0, 0);
+ }
+ if (!strcmp(command, "remap\n")) {
+ test_unmapped = 0;
+ update_constraints();
+ /* xdg-shell resets role properties when the surface is unmapped. */
+ if (app_id) xdg_toplevel_set_app_id(toplevel, app_id);
+ if (title) xdg_toplevel_set_title(toplevel, title);
+ if (decoration) zxdg_toplevel_decoration_v1_set_mode(decoration,
+ mode && !strcmp(mode, "client") ? ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE : ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
+ }
+ /* An empty commit after unmap requests a fresh initial configure. */
+ if (!strcmp(command, "unmap\n") || !strcmp(command, "remap\n")) wl_surface_commit(surface);
+ if (test_unmapped && wl_display_roundtrip(display) < 0) break;
+ }
+ }
+ } else {
+ while (wl_display_dispatch(display) >= 0) {}
}
return 0;
}