Skip to content

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

Prepare v0.1.3 release

oxydizered75302b0b60
diff --git a/AGENTS.md b/AGENTS.md
index cdafe40..95dcc4a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,494 +1,185 @@
# Notes for agents working on RediWM
-Details that are easy to get wrong. Read the relevant section before touching
-rendering, Xwayland, damage, input, locking or protocol code. Tests: `TESTING.md`.
-
-**Tool use is costly.** Don't poll processes, logs or CI in tight loops: wait
-15–30 s between checks of long operations, batch checks, don't re-read
-unchanged files, stop once you can proceed.
-
-**Don't add tests unless they are really needed or asked for** (Python or Zig).
-The suite is already large and slow to maintain. Prefer running the existing
-tests for what you touched; extend an existing test over writing a new one, and
-add a new file only for a regression that nothing current can cover.
-
-**Before you finish:** build Debug and `-Doptimize=ReleaseSafe`, run
-`zig build test` and the integration tests for what you touched. Some suites
-fail on unmodified builds: compare against a `git worktree` of HEAD before
-calling a failure a regression.
-
-## Rendering
-
-1. **wlroots colours are premultiplied.** `wlr_scene_rect_*` and
- `wlr_render_rect_options.color` take premultiplied `float[4]`. Theme colours
- are `col.Straight` (`src/color.zig`); create/recolour rects only through
- `col.createRect`/`col.setRect`; pack CPU pixels with `Straight.argb()` /
- `Premul.argb()`. Symptom of getting it wrong: white border edges.
-2. **Borders have two render paths.** `chrome.ChromeBuffer` rasterizes curved
- corners; straight edges are `SceneRect`s from `Toplevel.syncBorders`, inset
- by `ceil(frame_radius)`. Change both together. `side_fills` back the border
- beside the client with `window_bg` (between title/footer bands, included in
- opacity).
- * Chrome is two bands (title, footer skirt below the client, since wlroots
- 0.20 can't mask the client). Check `frame.band`, not just `py`. Skirt
- height ≥ `ceil(frame_radius)`; `footerHeight()` sizes and positions it.
- * The skirt takes the client's edge colour: `probeClientEdge` samples the
- last row of the buffer source box (median per channel; wl_shm is
- premultiplied). Resample only on sampled-row damage or a mapping change;
- pointer reuse proves nothing. `readFormat` is memoized per texture (it
- binds GL; per-commit calls cost ~20% idle CPU). `Color.argb` rounds.
-3. **Buffer size ≠ scene destination size** at fractional scale
- (`round(len*scale)` vs `round((off+len)*scale)-round(off*scale)`). Titlebar
- and panel buffers use bilinear filtering; never re-raster per device-grid
- phase (`ChromeBuffer.create` costs 2–8 ms).
-4. **Nested sessions lie about scale:** the Wayland backend never sets buffer
- scale. Judge sharpness with `REDIWM_SCALE=1`. A mismatched startup scale can
- make objects beyond the first size vanish briefly: not a bug.
-5. **Visual debugging:** prefer IPC screenshots/buffer dumps over host `grim`
- (which shows host scaling and covering windows).
-6. **Scene buffers may drop CPU storage:** after GLES upload
- `wlr_scene_buffer.buffer` may be NULL with a valid texture. Persist raster
- sizes separately. Test with `REDIWM_TEST_RENDERER=gles2`.
-7. **Glass:** client textures are `wlr_client_buffer_get(buffer)->texture`;
- track source-surface damage per effect (output damage misses content under
- foreground windows). Empty commits and buffer rotation don't invalidate
- blur. During drags titlebar blur may be held at ≥ 0.98 opacity; every path
- ending a move must schedule a frame.
-8. **Output commits** go through `Output.commitFrameState` (gamma, test state),
- never `wlr_output_commit_state`. `commitIsRedundant` skips commits with no
- damage, colour change, attach-render lock or cursor change; anything new
- that needs a commit without scene damage must be added there. Skipped frames
- get callbacks from `vblank_timer`, never immediately.
-9. **Idle makes no wakeups.** Timers only for known deadlines; worker results
- signal an eventfd. `text.applySize` activates prepared `FT_Size`s (don't
- re-size faces). Title-only changes repaint only the title span and taskbar
- chip. Measure idle CPU with per-thread context switches, not jiffies.
-
-## Damage and retained pixels
-
-* Each reusable shm buffer tracks damage since its own last paint; never write
- a busy buffer. Don't resend unchanged `set_buffer_scale`; prefer compositor v5.
-* `panel_paint.Background` keeps the last complete image; `paintIncremental`
- repairs recycled buffers and rasterizes dirty widgets. Widget setters call
- `markDirty`/`markPaintDirty`; moved widgets damage old and new bounds.
- Convert publish damage at the real raster scale.
-* Compositor-owned buffers in the world reach their projected view with full
- damage unless reported: `Projection.damageBuffer` after `setBuffer`, or
- `Projection.presentOwned` (in-place texture update).
-* Cache keys include visual state, text, geometry and Cairo transform. Round
- globally before subtracting projection group origins.
-* `wlr_client_buffer_apply_damage` updates shm in place only without extra
- locks: anything holding a client buffer across commits marks its lock
- ignorable. v4 `attach(buffer, 0, 0)` still sets OFFSET; only nonzero dx/dy
- is a remap.
-
-## Windows
-
-* **Unmapped ≠ destroyed.** `frame_tree` starts disabled; only `handleMapped`
- enables it. `focusSurface`/`minimize`/`restore` require `in_world`.
- `destroyNow` asserts `backend_gone` (or a compositor-owned backend).
+Details that are easy to get wrong; read the section for what you touch.
+Tests: `TESTING.md`. Area notes are in an `AGENTS.md` beside the code; read
+the one for the directory you work in: `src/files`, `src/editor`,
+`src/desktop`, `src/input`, `src/control_center`, `src/ui`, `src/session`,
+`src/dm`, `src/accounts_helper`, `scripts`.
+
+## Working rules
+
+* Tool use is costly: no tight polling (wait 15–30 s between checks of long
+ operations), batch checks, don't re-read unchanged files.
+* Add tests only when really needed or asked; prefer extending existing ones.
+* Before finishing: build Debug and `-Doptimize=ReleaseSafe`, run
+ `zig build test` and the integration tests for what you touched. Some
+ suites fail on HEAD: compare with a `git worktree` of HEAD before calling a
+ failure a regression.
+
+## Rendering and damage
+
+* **Colours are premultiplied** in wlroots rects; theme colours are
+ `col.Straight`. Create/recolour rects only via `col.createRect`/`setRect`,
+ pack pixels with `Straight.argb()`/`Premul.argb()`. Symptom of a mix-up:
+ white border edges.
+* **Borders have two paths; change both:** `chrome.ChromeBuffer` draws curved
+ corners, `Toplevel.syncBorders` straight `SceneRect`s inset by
+ `ceil(frame_radius)`, with `side_fills` behind them. Chrome is a title band
+ plus a footer skirt under the client (wlroots 0.20 can't mask clients):
+ check `frame.band`, not `py`; `footerHeight()` keeps the skirt ≥
+ `ceil(frame_radius)`.
+* **Skirt colour** comes from `probeClientEdge` (median of the last buffer
+ row; shm is premultiplied). Resample only on damage to that row or a
+ mapping change; pointer reuse proves nothing. `readFormat` stays memoized
+ per texture (it binds GL).
+* **Buffer size ≠ scene size** at fractional scale (`round(len*s)` vs
+ `round((off+len)*s)-round(off*s)`). Chrome/panel buffers filter bilinearly:
+ never re-raster per device-grid phase (`ChromeBuffer.create` costs 2–8 ms).
+* **Nested sessions never set buffer scale:** judge sharpness at
+ `REDIWM_SCALE=1`, and debug visuals with IPC screenshots/buffer dumps, not
+ host `grim`. Brief vanishing after a startup scale mismatch is not a bug.
+* **GLES can NULL `wlr_scene_buffer.buffer`** after upload (the texture
+ stays): persist raster sizes; test with `REDIWM_TEST_RENDERER=gles2`.
+* **Glass** samples `wlr_client_buffer_get(buffer)->texture` and tracks
+ source-surface damage per effect. Empty commits and buffer rotation keep the
+ blur. Drags may hold titlebar blur at ≥ 0.98 opacity, so every path ending a
+ move schedules a frame.
+* **Commit only via `Output.commitFrameState`**, never
+ `wlr_output_commit_state`. `commitIsRedundant` skips commits with no damage,
+ colour change, attach-render lock or cursor change; register anything new
+ there. Skipped frames get callbacks from `vblank_timer`, never immediately.
+* **Idle makes no wakeups:** timers only for real deadlines, workers signal an
+ eventfd, `text.applySize` instead of re-sizing faces, title changes repaint
+ only their span and taskbar chip. Measure with per-thread context switches.
+* **Damage:** each reusable shm buffer tracks damage since its own last paint;
+ never write a busy one. `panel_paint.Background` keeps the last full image
+ (`paintIncremental` repairs); widget setters `markDirty`/`markPaintDirty`,
+ moves damage old and new bounds; convert publish damage at the real raster
+ scale. Compositor-owned world buffers send full damage unless reported
+ (`Projection.damageBuffer` after `setBuffer`, or `presentOwned`). Cache keys
+ include visual state, text, geometry and Cairo transform; round globally
+ before subtracting projection group origins.
+* **Client buffers:** `wlr_client_buffer_apply_damage` works in place only
+ without extra locks, so mark long-held locks ignorable. v4
+ `attach(buffer, 0, 0)` still sets OFFSET; only nonzero dx/dy remaps. Don't
+ resend unchanged `set_buffer_scale`; prefer compositor v5.
+
+## Windows and focus
+
+* **Unmapped ≠ destroyed.** `frame_tree` stays disabled until `handleMapped`;
+ `focusSurface`/`minimize`/`restore` need `in_world`; `destroyNow` asserts
+ `backend_gone` (or a compositor-owned backend).
* **Tiles are compositor-owned geometry** like maximize (`snap.zig`,
- `tile`/`tile_target`/`tile_restore`, included in `forcedGeometry()`).
- `Toplevel.layout()` reads the `maximized` field, not `isMaximized()` (xdg
- acks a commit later). Leaving a layout without moving goes through
- `leaveLayout()`.
-* **Compositor-drawn windows (`Backend.shell`)**: Settings is an ordinary
- window whose body `ControlCenter` paints into `scene_tree` at `render_scale`
- and presents with `presentOwned`. No wl_surface, so focus is "first in
- `world.toplevels`, activated, no seat focus, desktop unfocused"
- (`hasKeyboardFocus`); `World.focusSurface` deactivates a previous `.shell`
- window and calls `Desktop.yieldKeyboard`; `findFocusedToplevel` returns it.
- Compositor bindings run before it gets keys. Pointer coordinates come from
- `localPoint`. `close()` frees the content and `Toplevel.destroy`s the window
- (which may animate from a snapshot), so clear `backend.shell.control_center`
- and the node's scene data first; never close from inside a widget callback.
+ `forcedGeometry()`). `Toplevel.layout()` reads the `maximized` field, not
+ `isMaximized()` (xdg acks later). Leaving a layout without moving goes
+ through `leaveLayout()`.
+* **`Backend.shell` windows** (Settings) paint into `scene_tree` and present
+ with `presentOwned`. No wl_surface: focused = first in `world.toplevels`,
+ activated, no seat focus (`hasKeyboardFocus`). Never close one from a
+ widget callback; details in `src/control_center/AGENTS.md`.
+* **Desktop keyboard focus is shell focus:** taking it clears seat focus; a
+ surface gaining seat focus, or a `.shell` window, takes it back.
+* **Input** details are in `src/input/AGENTS.md`. Cross-cutting: every client
+ motion path calls `clientMotion` then `sync`; Escape cancels drags through
+ `Input.cancelDrag` (wlroots doesn't); compositor drop targets
+ (`desktop_drop.Target`) end the grab before negotiating;
+ `wlr_data_source_send` closes its fd.
## Xwayland
-* With native scaling X11 renders at N = `ceil(max output scale)`.
- `Xwayland.create` runs before outputs exist; `refreshScale` (after
- `Output.create`) recomputes N. Reproduce ordering bugs with per-output config
- scale, not `REDIWM_SCALE`. Scale changes after X11 surfaces exist wait for a
- restart. `xwayland_scale` 0 = automatic.
-* Units: `surfaceScale()` = N; `clientSurfaceGeometry()` is X units;
- `clientGeometry()` world units (`ceil(surface/N)`); `requestSize()`/
- `commitPosition()` take world units; `applySizeClip()` and `probeClientEdge()`
- surface units. Content trees use `rediwm_projection_set_tree_scale(1/N)`.
- X11 chrome density is 0.75.
+* X11 renders at N = `ceil(max output scale)`. `Xwayland.create` runs before
+ outputs exist; `refreshScale` recomputes N after `Output.create`. Reproduce
+ ordering bugs with per-output config scale, not `REDIWM_SCALE`. Scale
+ changes wait for a restart once X11 surfaces exist.
+* Units: `clientSurfaceGeometry()` X units; `clientGeometry()`,
+ `requestSize()`, `commitPosition()` world units (`ceil(surface/N)`);
+ `applySizeClip()`, `probeClientEdge()` surface units; `surfaceScale()` = N.
+ Content trees use `rediwm_projection_set_tree_scale(1/N)`; X11 chrome
+ density is 0.75.
* Clamp stale off-screen geometry of new X11 windows in
`handleRequestConfigure` (except `open_rules`/`forcedGeometry()`).
-* Keep `scene.restack_xwayland_surfaces = false`; `Toplevel.raise` keeps scene
- and X11 stacking in sync. Activation must not raise an owner above its
- transients. Compositor hit tests can't prove X11 routing.
-
-## Input
-
-* **Text input/IME** (`input/text_input.zig`): `syncFocus` is the only enter
- path. IM grabs replace client delivery only; bindings, hardware keys and
- shell/lock UI win. An IM's own virtual keyboard bypasses its grab.
- Lock/auth reject virtual input. `GetTextInput` never returns text.
-* **Layouts:** layout-zero fallback is for binding lookup only; text uses the
- active XKB state.
-* **Shell key repeat:** one `shell_repeat` per keyboard; a new shell target
- needs a `ShellTarget` case and a freeable panel calls `forgetShellTarget`.
- Return, Escape, Tab and modifier chords never repeat.
-* **Pointer constraints** (`input/pointer_constraints.zig`): every client
- motion path calls `clientMotion` then `sync`. Active only with pointer and
- keyboard focus; new compositor input modes go in `motionReachesClient` or
- `candidate`. `sendDeactivated` destroys oneshots synchronously: clear
- `active` first.
-* **Shortcuts inhibit** gates only switcher, screenshot shortcuts and final
- dispatch; hardware keys, VT switching and open panels still win.
-* **Drag-and-drop:** wlroots does not cancel a drag on Escape; `Keyboard`
- calls `Input.cancelDrag` (destroys the source, then `pointerEndGrab`).
- `input/drag_dodge.zig` slides a file manager aside through
- `Toplevel.setDodge`, a presentation-only offset added in
- `applyVisualTransform`: never fold it into `x`/`y`/`move_x` (it would grow the
- canvas, reach IPC and saved layouts, and outlive the drag). Anything that
- stops showing a window must `clearDodge` it (`detachInput` does).
-* **Touch/tablet** use their own protocol only when
- `directInputReachesClients()`; otherwise they emulate the pointer (send your
- own `pointerNotifyFrame`). Touchscreens map to `output_name` or the built-in
- panel. A closed lid hides built-in panels only while another display is on;
- undocked, logind owns the lid.
-
-## Desktop (`[desktop] enabled`)
-
-* `desktop/App` and its worker never depend on the compositor; the worker is a
- thread that never calls the host. Tests set `REDIWM_DESKTOP_DIR`.
-* One retained canvas published as 240-logical-px tiles; only damaged tiles
- get new buffers. Rasterize the selection band once per paint; repair clips
- snap outward to device pixels. Labels/icons are rasterized at exact scale.
-* Desktop keyboard focus is shell focus: taking it clears seat focus; any
- surface gaining seat focus (or a `.shell` window) takes it back.
-* Drops: `desktop_drop.Target` ends the grab first, then negotiates with the
- source. `wlr_data_source_send` closes its fd.
-* A `.desktop` file runs only if `Worker.trustedLauncher` accepts it
- (installed or linked into the menus, root-owned, executable, or an exact
- copy of the installed entry); otherwise it is an `untrusted` plain file whose
- own Name/Icon are never shown. Allow Launching is `chmod u+x`.
+* Keep `scene.restack_xwayland_surfaces = false`; `Toplevel.raise` syncs scene
+ and X11 stacking and never raises an owner above its transients. Compositor
+ hit tests can't prove X11 routing.
## Security, lock and login
-* **Greeter** (`rediwm --greeter`) is a lock that never unlocks; only
- `rediwm-dm` decides. It writes nothing under `$HOME` and runs no Xwayland,
- autostart, IPC, notifications, tray, portal, polkit, services, audio,
- desktop or external-tool globals; anything new that owns a bus name, spawns
- or writes must be skipped there (`tests/greeter.py`). Secrets stay in
- mlocked, wiped buffers.
-* **rediwm-dm** never blocks; workers own one PAM handle each. Signal masks
- survive exec (clear them). `PR_SET_PDEATHSIG` is cleared by `setuid`. The
- greeter is untrusted input. Never format JSON with `{s}`. Only daemon and
- workers are root; don't sandbox `rediwm-dm.service` (users inherit it).
- `--test`, `--confdir`, `--data-dir` and `--marker` are refused as root.
-* **A crash never unlocks.** `Lock.announce` reports `locked`/`unlocked` on
- `REDIWM_SESSION_FD` (first thing in `engage`); `rediwm-session` queues `lock`
- before restarting a compositor that crashed while locked, and `main.zig`
- takes it and locks before the backend starts. Lock-before-sleep holds a
- logind delay inhibitor until `Lock.covered()` (the builtin lock sets
- `Output.lock_commit_pending` too). logind `Lock` is followed for
- `REDIWM_LOGIN_SESSION` only; `Unlock` is ignored on purpose.
-* **The lock never polls.** Its one timer redraws the clock at the next minute
- boundary; the PAM worker (`session/auth.c`) signals an eventfd that
- `Lock.authReady` watches only while an attempt runs. Don't add a periodic
- tick (a 100 ms one cost ~10 wakeups/s for as long as the session stayed locked).
-* **Lock volume/brightness** (`session/lock_controls.zig`): sliders at the
- bottom centre of the built-in lock, the pointer/touch way to what the
- hardware keys already do behind it. Never in the greeter (no audio, no
- external tools) and hidden under an ext-session-lock client's surface. They
- are their own small raster (`View.controls_node`), so a drag never re-rasters
- the clock, avatar and field. A row exists only while its backend reports
- (`Lock.controlsChanged` from the audio wake and the brightness helper's
- result); a drag shows its own value until release. Events only, no timer.
-* **Production reads no test-hook environment.** `REDIWM_*_PREVIEW` lives only
- in `test` blocks and `REDIWM_TEST_*` only in noninstalled fixtures. The polkit
- helper socket comes from `[polkit] helper_socket`; `REDIWM_POLKIT_HELPER_SOCKET`
- is read by `polkit_test_service` alone, because it decides where the user's
- password is sent. `strings` a ReleaseSafe `rediwm` for these names after
- touching env handling.
-* **App scopes** (`session/app_scope.zig`): every user-app launch path calls
- `app_scope.place(server, pid, id)` after spawning, moving it into its own
- `app-rediwm-<id>-<pid>.scope` in app.slice (systemd-oomd kills whole
- cgroups; a shared session scope dies with a runaway app). Worker threads
- hand pids to the main thread first (desktop: `Worker.takeStarted`). Off in
- nested/headless sessions unless `REDIWM_APP_SCOPES=1`; never in the greeter.
-* **Account management** runs through the root-owned
- `rediwm-accounts-helper` under `pkexec`; the compositor never runs as root.
- The helper treats stdin JSON and `PKEXEC_UID` as untrusted, validates every
- operation, passes argv arrays to absolute system tools, and never accepts
- passwords in argv. Its authorization-only request changes no system state.
- Keep the helper, policy and client out of greeter mode.
-* **IPC** refuses everything with `SessionLocked` while `locker != null`
- (event subscriptions re-check). Synthetic input and pixel reads need
- `[ipc] automation` (read once at startup). Socket only in a private
- directory, umask 0177. Sandboxed callers (checked via `SO_PEERPIDFD` and
- `.flatpak-info`) need an explicit `[[sandbox_allow]]` `ipc` allowance, fail
- closed, and are re-checked on reload.
-* **Security context** (`src/global_filter.zig`): privileged globals are
- hidden from `wp_security_context_v1` clients and guess-binds are protocol
- errors, unless `[[sandbox_allow]]` grants the group. Nested contexts are fatal.
-* **External protocols** (`tests/wlr_protocols.py`): a client
- ext-session-lock is a `Lock` with `origin = .client`, so every `locker`
- guard applies; client death keeps the session locked. Screencopy policy runs
- in `guardScreencopy` (disconnects during lock/polkit). Foreign-toplevel
- sync sits next to every `onWindowChanged`/`onWindowMoved`. Output
- management applies through `Output.applyAndPersist`. Output power `off`
- sets `Output.power_off`; only a client `on` clears it.
-* **Explicit sync** (linux-drm-syncobj): projection moves `output_sample` to
- the view and copies wait points; other GPU reads use `ReadFence`; CPU reads
- check `AcquireWait.ready`. `REDIWM_NO_EXPLICIT_SYNC=1` withholds it.
+* **Greeter** (`rediwm --greeter`) never unlocks (only `rediwm-dm` decides),
+ writes nothing under `$HOME`, and runs no Xwayland, autostart, IPC,
+ notifications, tray, portal, polkit, services, audio, desktop or
+ external-tool globals: skip anything new that owns a bus name, spawns or
+ writes (`tests/greeter.py`). Secrets stay in mlocked, wiped buffers.
+* **A crash never unlocks.** `Lock.announce` reports state on
+ `REDIWM_SESSION_FD` first thing in `engage`; `rediwm-session` queues `lock`
+ for a compositor that died locked, and `main.zig` locks before the backend
+ starts. Lock-before-sleep holds a logind delay inhibitor until
+ `Lock.covered()`. Only `REDIWM_LOGIN_SESSION`'s logind `Lock` is followed;
+ `Unlock` is ignored on purpose. The lock never polls.
+* **Only rediwm-dm and the accounts helper run as root** (see their
+ `AGENTS.md`); never the compositor.
+* **No test hooks in production:** `REDIWM_*_PREVIEW` only in `test` blocks,
+ `REDIWM_TEST_*` only in noninstalled fixtures; only `polkit_test_service`
+ reads `REDIWM_POLKIT_HELPER_SOCKET` (it decides where passwords go).
+ `strings` a ReleaseSafe `rediwm` after touching env handling.
+* **App scopes:** every user-app launch calls `app_scope.place` (own scope in
+ app.slice, since systemd-oomd kills whole cgroups); workers hand pids to the
+ main thread first. Off nested/headless unless `REDIWM_APP_SCOPES=1`; never
+ in the greeter.
+* **IPC** fails with `SessionLocked` while `locker != null` (subscriptions
+ re-check). Synthetic input and pixel reads need `[ipc] automation`. Socket
+ only in a private directory, umask 0177. Sandboxed callers need an explicit
+ `[[sandbox_allow]]` `ipc` allowance, fail closed and are re-checked on
+ reload. `scroll` is natural by default (negative dy pages down).
+* **Security context** (`global_filter.zig`) hides privileged globals from
+ `wp_security_context_v1` clients (guess-binds are protocol errors) unless
+ `[[sandbox_allow]]` grants the group; nested contexts are fatal.
+* **Protocols:** a client ext-session-lock is a `Lock` with
+ `origin = .client`, so `locker` guards apply and its death keeps the session
+ locked. Screencopy policy is `guardScreencopy`; foreign-toplevel sync sits
+ beside every `onWindowChanged`/`onWindowMoved`; output management goes
+ through `Output.applyAndPersist`; only a client `on` clears
+ `Output.power_off`.
+* **Explicit sync:** projection moves `output_sample` to the view with its
+ wait points; other GPU reads use `ReadFence`, CPU reads check
+ `AcquireWait.ready`.
-## Build and platform gotchas
+## Shared UI
-* `ui`, `dbus` and `config` are named build modules rooted in their own
- directories. Keep dependencies one-way: no compositor imports in them.
- Configuration parsing/persistence lives in `config/`; applying settings,
- watching for reloads and launching actions live in `config_runtime/`.
- Shared raster support (`text`, `anim`, `sdf`, icons) belongs to `ui/`.
+* Widget callbacks carry `owner` + `id`: a stable host pointer that outlives
+ the tree, never a global. Finish state updates before calling back, reset
+ the dispatcher on rebuild, defer host destruction until dispatch returns.
+* `ui/widgets/` owns every control's look (fields, buttons, dialogs,
+ checkboxes, toggles, scrollbars, sliders, battery badge): never hand-draw or
+ hand-hit-test one (`src/ui/AGENTS.md`).
+* App clients (Files, Images, PDF) draw through `ui/cairo.zig` with theme
+ tokens (`app_*`, `shellPalette().accent`) and shell icons. Text is
+ `window_fg` only (placeholder at half alpha) at `text_size`,
+ `heading_size` or `status_size`, never hardcoded sizes. Load the theme with
+ `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`.
+
+## Build and platform
+
+* `ui`, `dbus` and `config` are named modules with one-way dependencies (no
+ compositor imports). Parsing/persistence is `config/`, applying and reloads
+ `config_runtime/`, shared raster code (`text`, `anim`, `sdf`, icons) `ui/`.
`memory` owns the process allocator; executables own its shutdown.
* ReleaseSafe's `_FORTIFY_SOURCE` breaks translate-c on `bits/fcntl2.h`: use
`std.os.linux` or `@cUndef("_FORTIFY_SOURCE")`. Never `@cInclude`
- glib/gobject/gio/librsvg; hand-declare the ABI.
-* No runtime `parseColor()` in comptime defaults.
-* **Raw syscalls:** `std.os.linux.*` return `-errno` in `usize` (use
- `std.os.linux.errno`); `std.posix.system.*` are libc (`std.posix.errno`).
-* zig-wlroots types referencing `ext.*`/`wp.*` need the protocol in
- `build.zig`'s scanner. Some fields declared non-null can be NULL
- (`ForeignToplevelHandleV1.event.Fullscreen.output`,
- `ScreencopyFrameV1.buffer`): read through `*const ?*T`. `wlr.Pointer` is
- 8 bytes short of the C struct (no trailing `data`): embed it through an
- extern wrapper (`input/virtual.zig`), or `wlr_pointer_init` overwrites the
- next field.
-* **Debug builds use `DebugAllocator`** for `main.gpa` (optimized builds use
- libc). Freed memory reads `0xaa…` (glibc `MALLOC_PERTURB_` gives `0xa5…`);
- leaks print at exit into the compositor log. Free process-lifetime caches in
- `main.start`'s defers, or allocate state that must outlive shutdown (worker
- threads still reading it) from `std.heap.c_allocator`. Never mix: memory
- from `gpa` must go back to `gpa`.
-* Cairo `ARGB32` is premultiplied `0xAARRGGBB` like RediWM buffers.
- `png.zig` supports only 8-bpc non-interlaced truecolour(+alpha).
-* `/sys/class/power_supply/*/uevent` reads can be expensive: read on uevents
- and the minute tick only.
-
-## Releases and install
-
-* **`scripts/install.sh` installs a prebuilt per-distro tarball** (`--build`
- compiles; running from a checkout implies `--build`). It must stay
- self-contained up to the download, since `curl | sh` has no repo yet.
- `scripts/make-release.sh` builds each tarball in a clean podman/docker
- container of its distro and installs it with the real `install.sh` in a
- fresh one; run it before publishing and read the verify step's output.
-* **One tarball per distro, not per architecture-and-glibc.** Package ABIs
- differ (libjpeg is `.so.8` on Arch/Ubuntu, `.so.62` on Debian/Fedora with a
- different struct layout). A derivative uses its parent's tarball; if its
- libraries don't match, `unresolved_libs` (missing libs or too-new
- glibc symbol versions) or a failed package install falls back to a source
- build. A checksum mismatch never falls back: it dies.
-* **`DEPENDS` is generated from the built binaries' `NEEDED` libraries**
- (`release-build.sh`), never hand-kept; only the extras (Xwayland, portals,
- Python, Mesa drivers) are listed by hand. Libraries bundled in `lib/rediwm`
- are excluded, and which ones get bundled depends on what the build
- container has installed, so never install the distro's own wlroots there.
-* **Releases are always built with the pinned, patched wlroots** from
- `build-wlroots.sh`, whose recipe hash includes the script itself (editing
- even a comment rebuilds everyone's private prefix). `rediwm`'s RUNPATH picks
- up the build prefix when linking it; `release-build.sh` scrubs that with
- patchelf and `release-verify.sh` rejects any `/work/` path.
-* **CPU is `-Dcpu=x86_64_v2`.** Zig defaults to the build machine's CPU, which
- would put illegal instructions into every user's binary. Releases are
- x86_64 only; other CPUs build from source.
-* Checksums come from the same GitHub release as the tarballs, so they catch
- corruption, not a compromised release. Signing is not done yet.
-
-## Files Git
-
-* `files/git.zig` never runs a repository's own programs: a folder's `.git`
- arrives with archives and USB sticks. Every command uses `safe_options` and
- `cleanEnv` (no fsmonitor, hooks, pager, transports or lazy fetches);
- `trustedRepository` refuses repositories whose own (local, worktree or
- included) configuration names filter or Git LFS commands, and `status`
- ignores submodules (their configuration is not checked).
-
-## Files thumbnails
-
-* **Decoding avoids GdkPixbuf for JPEG and PNG.** On current systems gdk-pixbuf
- routes them through sandboxed glycin loader processes and ignores scaled
- decode (a 12 MP JPEG costs ~150 ms). `files/thumb_codec.c` decodes JPEG at
- 1/2–1/8 inside libjpeg's DCT and streams PNG rows into an area-averaging
- downscaler, so no full raster exists. Anything it reports unsupported
- (WebP, GIF, SVG, interlaced PNG, CMYK JPEG) falls back to
- `images/decode.zig` (`loadWith` with a box), which is also what the viewer's
- `loader.zig` re-exports. Re-measure before "simplifying" this.
-* **`files/thumbs.zig` is the only owner of the raster cache**: 2 nice'd
- workers, queue replaced on every `request` (scrolling cancels queued work),
- results handed over under the mutex and an eventfd, LRU by bytes and entry
- count. Workers never touch Cairo or Wayland. Keys are path plus the
- mtime and size the *listing* reported; a stale file is dropped without an
- entry and retried after the next rescan. Failures are remembered per file
- state. Idle must stay at zero wakeups: no timers.
-* **App side:** `stepThumbs` re-requests only when the visible rows or
- `view_revision` change; `drainThumbs` damages just the arrived icons
- through `addDamage`. `itemIconRect` is the single source of icon geometry
- for painting and damage: change them together. Thumbnails are drawn in
- `drawItemIcon` (grid 48, list 24, drag icon 32) with a bilinear-filtered
- 128 px raster.
-* **Shared freedesktop cache** (`$XDG_CACHE_HOME/thumbnails/normal|large`):
- name is the MD5 of the GLib-escaped `file://` URI, validated by
- `Thumb::MTime` (and `Thumb::Size` when present) against the *target's* stat.
- Entries are written after the UI has its pixels, via tmp file + rename, mode
- 0600, only when the original is bigger than 128 px. Tests set a scratch
- `XDG_CACHE_HOME`. `REDIWM_FILES_THUMBNAILS=0` turns thumbnails off.
-
-## Files devices
-
-* **Transport vs policy.** `files/volumes.c` is a GLib thread holding a GDBus
- object-manager client for UDisks2 on the system bus (not `src/dbus`: that is
- tied to the compositor's `wl.EventLoop`). It only publishes raw records and
- runs Mount/Unmount with interactive polkit authorization. What to list, the
- label and the stick/drive icon are `volumes.zig`'s `shown`/`kindOf`.
- `HintIgnore` hides EFI partitions; `HintSystem` volumes mounted outside
- `/run/media`, `/media`, `/mnt` (`/`, `/home`, `/boot`) are hidden by the
- mount rule, because UDisks2 does not ignore them. Loop devices are
- `HintSystem` too, so only that rule decides them.
-* **Lifetime.** The thread is never joined: `vol_stop` posts a quit and the
- thread frees its own state, so shutdown cannot block on a bus that does not
- answer. Do not use the monitor or its wake fd after `stop`. Publishing is
- coalesced (40 ms one-shot per burst of signals) and only on a real change;
- idle makes no wakeups.
-* **Ejecting is unmounting.** A device stays listed, dimmed, while attached;
- power-off would make SSDs vanish. Eject first leaves the volume if the view
- is inside it, and is refused while a file operation runs. One mount/eject at
- a time (`device_op`); a mount opens the volume only if `navigation_count`
- is unchanged.
-* **Sidebar rows.** DEVICES sits below File System, so hover-glide row indices
- stay in order: devices are `places.len + k`, hover keys 600+k (row) and
- 700+k (eject button). `placeY` for those indices and `deviceBlock()` move the
- Git card and scroll extent; change them together.
-* **Tests.** The device list talks to the host's real system bus, so every test
- that launches Files sets `REDIWM_FILES_DEVICES=0` (or a dead
- `DBUS_SYSTEM_BUS_ADDRESS`). To try it for real without touching disks:
- `truncate -s 64M x.img && mkfs.ext4 -L X x.img && udisksctl loop-setup -f x.img`
- (polkit allows it for an active session), then `udisksctl loop-delete -b`.
- Never click an unmounted internal partition in a real session: mounting it
- raises an admin prompt.
-
-## Files pins
-
-* **Pins are PLACES rows the user drops in.** `files/pins.zig` owns the list
- (`$XDG_STATE_HOME/rediwm/files-places`, one absolute path per line). The file
- is the truth: `pinDropped`/`removePin` re-read it before changing (a second
- window must not overwrite the first's pins) and the keyboard `enter` event
- calls `refreshPins`. Tests need a scratch `XDG_STATE_HOME`.
-* **Row indices are in drawn order** (the hover glide needs that): built-ins
- 0..`pin_base`-1, pins, File System (`systemIndex()`), devices
- (`deviceBase()`). Never use `places.len` as a row index; go through
- `rowKind`. Hover keys: 300+i built-in (File System is 300+`pin_base`), 600+k
- device, 700+k eject, 800+j pin. `pinRowY` positions pins and the drop line;
- `placeY` for File System and everything below it follows the pin count.
-* **Files drops** (`main.zig` `dragOver`/`dragDropped`) accept `text/uri-list`:
- PLACES pins with *copy* only; the content area transfers to the hovered folder
- or, on empty space, the displayed directory. Files sources advertise
- `application/x-rediwm-file-transfer`: the receiving job owns moves and the
- source never deletes on `dnd_finished`. Ctrl at drag start offers copy only;
- other sources copy. After `drop` the offer leaves `drag_offer` (a `leave`
- would destroy it) and is read through a nonblocking pipe (`drop_receiving`,
- poll slot 15). Snapshot the destination before reading. Drops use the normal
- conflict/progress jobs without touching cut-clipboard state; reject a folder
- dropped into itself/descendants, including through symlinks. Pins take their
- gap from `pin_drop`. Ctrl-click deselection waits for release so Ctrl-drag
- preserves the selection.
-* **Pins are not built-ins:** a built-in place's path is refused ("Already in
- Places"), a hidden built-in can be dropped back as a pin, a missing target
- stays listed dimmed, a file pin opens like a double click (a chooser browses
- its folder).
-
-## Text editor
-
-* **Never give Pango more than a few lines.** One layout of 1 MiB took 46 s
- (cost grows faster than the line count); `view.zig` lays out one *segment*
- (`lines.zig`: a logical line, or a piece of one folded at `fold` = 16 KiB,
- cut after a nearby space) at a time in a content-keyed cache (`Layouts`), so
- edits need no invalidation. Pieces are a function of the line start alone, so
- walking up or down finds the same ones; keep `lines.zig`'s property test
- green when touching it.
-* **Scroll is `Document.top` (a byte offset) plus `Tab.dy` pixels into that
- line**, never a pixel count from the file start (needs every line's height).
- `Document.replace` shifts `top` and the line waypoints (`retarget`) so edits
- above the view do not move it. `Port.clamp` after any change; `locate`
- returns null for a position more than three viewports away, so jump
- (`jumpTo`) instead of walking.
-* **Scrollbar units:** pixels (exact) up to `exact_limit`, bytes above it,
- because a drag in progress must not see its units shift as the height
- estimate improves. Line numbers come from sparse waypoints (`linesBefore`).
-* **Large saves are written in place** (`Operation.startSave` `borrow`, above
- `copy_limit`) and `Document.locked` refuses edits meanwhile; smaller ones are
- copied. Anything that frees or reallocates the text during a save is a
- use-after-free. Loads read straight into one buffer sized from `fstat`, sniff
- the first 64 KiB for binary data and refuse files that will not fit in
- `MemAvailable` (`ensureMemory`).
-* **Benchmark in ReleaseSafe.** Debug makes the vector scans ~50x slower and
- fakes a regression. Editing near the start of a huge file memmoves the tail
- (about 100 ms per keystroke at 2 GB); a gap buffer would fix it but every
- `text.items` reader (segmenter, find, IME, clipboard) would need to learn it.
-* A selected line break is not in the segment layout, so `paintLine` draws the
- highlight out to the margin itself (wrapped mode only, as Pango did).
-
-## Shared UI
-
-* Widget callbacks carry `owner` and `id`; pass a stable host or section
- pointer instead of a global current instance. The owner must outlive the
- widget tree. Finish widget state updates before calling back; reset the
- dispatcher when rebuilding, and defer host destruction until dispatch returns.
-* One look per control: `ui/widgets/field.zig`, `button.zig`, `avatar.zig`,
- `dialog.zig`, `checkbox.zig`, `toggle.zig` own stateless painters used by widget trees and
- hand-laid screens alike. Don't hand-draw fields or buttons.
-* **The battery badge** (`ui/widgets/battery.zig`: frame, glyph, percentage,
- charging bolt) is the taskbar's artwork, shared. `sample` is the pixel math
- (per device pixel, badge-local units); the taskbar's per-pixel raster calls
- it and `paint` draws it into any `Renderer`, so the two cannot drift. The
- caller owns the data (hide it when there is no battery) and the connection
- shimmer's clock (`Spec.shimmer`). Don't redraw the glyph elsewhere.
-* **One scrollbar** (`ui/widgets/scrollbar.zig`, Files' look): a track-less
- thumb centred in a `gutter(scrollbar_width)` strip, thin at rest, widening
- and tinting to the accent on hover/drag, holding a faint tint after a
- scroll. Never hand-draw or hand-hit-test one. `Geometry.compute` gives the
- thumb for any axis and unit (pixels, or items for a strip that scrolls by
- item), `press` the grab-or-page decision, `Drag` the pointer-to-offset map,
- `look` + `paint` (Renderer) / `cairo.drawScrollbar` (Cairo) the pixels, and
- `Appearance.step` the feedback: edge-triggered on what is drawn, and the
- app's loop sleeps until `deadline` and runs frames only while `active`
- (`barTimeout` in PDF/Editor, `animationTimeout` in Images, `pollTimeout` in
- Files). Paint-only popups pass `.{}` for the rest look. The gutter is the
- bar's: layouts keep content out of it and a press in it never reaches
- content. Widget trees get all of this from `.scroll_container`: hosts call
- `scroll_container.stepBars` beside `stepGlides` and carry `ScrollState.bar`
- across rebuilds.
-* **Sliders reuse the scrollbar's feedback** (`SliderData.feel` is a
- `scrollbar.Appearance`): hover and drag tint and thicken the track, a change
- holds the faint tint. `stepBars` steps sliders too (`slider.stepFeedback`);
- `Dispatcher.setHovered`/`pointerLeave` keep `hovered` in step. A value
- readout is `slider.valuePill` (a `.text` with `pill`), found from its slider
- by `findPill` (first pill under the slider's parent), lit by drag only. A
- theme slider's save rebuilds Settings the moment the button is released, so
- `panel.rebuildTree` carries named sliders' state across (`slider.capture`/
- `restore` + `input.adoptHover`) on the same page; an unnamed slider starts
- fresh. Never change `Appearance.width` per call site: it is every bar's width.
-* Cairo clients use `ui/cairo.zig` (`drawText`, `setSource`, `Layer`); toolbar
- glyphs are shell icons, not Cairo paths. Colours come from theme tokens:
- app surfaces are `app_*`, red accents `shellPalette().accent`. Files, Images
- and PDF text is `window_fg` only (no `text_secondary`/`window_dim` blue-grey;
- a placeholder is `window_fg` at half alpha) at `text_size`, with
- `heading_size` for column/section headings and `status_size` for status
- lines. Don't hardcode sizes there; window chrome keeps its own. Clients read the theme with
- `files/settings.zig` (`loadTheme` before the first frame, PDF before its
- sandbox; Files' worker follows edits).
-* A `.scroll_container` scrolls along its `direction`: `.row` is sideways with
- the bar along the bottom edge, so set `.direction` explicitly (it defaults to
- `.row`). Rebuilt trees carry the offset over themselves (the wallpaper strip
- copies it from its old widget). Appearance's wallpaper strip owns a
- `wallpaper_strip.Strip` (decode worker + eventfd) that outlives rebuilds and
- is restarted only when the image list changes; thumbnail slices stay valid
- until then. IPC `scroll` follows `invert_scroll` (default natural: negative
- dy moves a page down).
-* Secrets live in `secret_input.Input` over caller-owned (mlocked) storage.
- Hand-laid secret fields draw the caret through `CaretOverlay`.
+ glib/gobject/gio/librsvg; hand-declare the ABI. No runtime `parseColor()`
+ in comptime defaults.
+* `std.os.linux.*` return `-errno` in `usize` (`std.os.linux.errno`);
+ `std.posix.system.*` are libc (`std.posix.errno`).
+* zig-wlroots: `ext.*`/`wp.*` types need the protocol in `build.zig`'s
+ scanner. `ForeignToplevelHandleV1.event.Fullscreen.output` and
+ `ScreencopyFrameV1.buffer` can be NULL: read through `*const ?*T`.
+ `wlr.Pointer` is 8 bytes short: embed it in an extern wrapper
+ (`input/virtual.zig`) or `wlr_pointer_init` overwrites the next field.
+* Debug `main.gpa` is `DebugAllocator`: freed memory reads `0xaa…` (glibc
+ `MALLOC_PERTURB_`: `0xa5…`), leaks print at exit in the compositor log. Free
+ process-lifetime caches in `main.start`'s defers; state workers read during
+ shutdown comes from `std.heap.c_allocator`. Never mix allocators.
+* Cairo `ARGB32` is premultiplied `0xAARRGGBB`, like our buffers. `png.zig`
+ reads only 8-bpc non-interlaced truecolour(+alpha). Read
+ `/sys/class/power_supply/*/uevent` only on uevents and the minute tick.
diff --git a/TESTING.md b/TESTING.md
index a6ace1e..b7e5278 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -86,7 +86,7 @@ origin), `zoom_osd.py` (shared zoom OSD,
(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
-maximize/fullscreen placement, restore, window rules and depth), `taskbar_peek.py`, `taskbar_items.py`,
+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`,
`control_center.py --services-only` (private systemd and polkit fixture: availability, in-table loading, unlock/lock and prompt cancellation, startup settings, Notify service types and isolated drop-in edits, runtime actions, authorization refusal, analysis, live updates and lifetime),
@@ -205,10 +205,13 @@ caret blinking and idle wakeups, and title glyph dimensions across resizes
(`REDIWM_EDITOR_DRAG=1` exercises pointer resizing). Supports `REDIWM_TEST_SCALE`,
`REDIWM_TEST_RENDERER`, and `REDIWM_EDITOR_PREVIEW=/tmp/editor.png`.
-**PDF viewer**: `zig build test-pdf`, `pdf_viewer.py` (rendering and navigation),
-`pdf_sandbox.py` (a test-only parser hook checks file, syscall, inherited-FD,
-environment and Wayland restrictions, plus failure to install the sandbox).
-Requires Poppler GLib, libseccomp, Linux Landlock ABI 3+, and Python Cairo.
+**PDF viewer**: `zig build test-pdf`, `pdf_viewer.py` (rendering, navigation,
+tiled fit width, and printing through a fake Print portal on a private bus; run
+it with `REDIWM_SCALE=2` too, where tiles split differently), `pdf_sandbox.py`
+(a test-only parser hook checks file, syscall, inherited-FD, environment and
+Wayland restrictions, that the print helper's socket cannot pass descriptors,
+plus failure to install the sandbox). Requires Poppler GLib, libseccomp, Linux
+Landlock ABI 3+, Python Cairo, and `dbus-daemon`.
**Browsers**: `brave_input.py` (optional; `REDIWM_TEST_BRAVE=/path`), a smoke
test of focus, clipboard, navigation and scrolling in a fresh profile.
diff --git a/build.zig b/build.zig
index b3d6d86..471c129 100644
--- a/build.zig
+++ b/build.zig
@@ -234,8 +234,9 @@ pub fn build(b: *std.Build) void {
});
pdf.root_module.addImport("wayland", wayland);
pdf.root_module.addCSourceFile(.{ .file = b.path("src/pdf/sandbox.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
+ pdf.root_module.addCSourceFile(.{ .file = b.path("src/pdf/print.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
pdf.root_module.linkSystemLibrary("seccomp", .{});
- inline for (.{ "wayland-client", "wayland-cursor", "poppler-glib", "cairo", "gobject-2.0", "glib-2.0", "xkbcommon" }) |lib| pdf.root_module.linkSystemLibrary(lib, .{});
+ inline for (.{ "wayland-client", "wayland-cursor", "poppler-glib", "cairo", "gio-2.0", "gobject-2.0", "glib-2.0", "xkbcommon" }) |lib| pdf.root_module.linkSystemLibrary(lib, .{});
const install_pdf = b.addInstallArtifact(pdf, .{});
const pdf_entry = b.addInstallFileWithDir(b.path("data/rediwm-pdf.desktop"), .prefix, "share/applications/rediwm-pdf.desktop");
b.getInstallStep().dependOn(&install_pdf.step);
@@ -780,7 +781,7 @@ 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 {
- 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", "open", "usb-stick", "drive", "eject", "users", "squares" }) |name| {
+ 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") });
}
}
diff --git a/docs/wiki/Apps-and-Services.md b/docs/wiki/Apps-and-Services.md
index 8aac251..8113371 100644
--- a/docs/wiki/Apps-and-Services.md
+++ b/docs/wiki/Apps-and-Services.md
@@ -49,7 +49,11 @@ Files, Images and the editor also run on other Wayland compositors.
The PDF viewer is sandboxed with Landlock (ABI 3 or newer) and needs a
compositor with `security-context-v1`, which RediWM has. It refuses to parse
a document if it can't isolate itself. Each PDF gets its own viewer. Web links
-copy their address instead of opening. Details in `docs/pdf-security.md`.
+copy their address instead of opening.
+
+Print (toolbar button or Ctrl+P) opens the print dialog of xdg-desktop-portal
+(GTK's, by default). A helper started before the sandbox hands the portal the
+file you opened; the sandboxed parser can only ask it to print.
## Desktop
diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.md
index 659e158..a819caf 100644
--- a/docs/wiki/Theme.md
+++ b/docs/wiki/Theme.md
@@ -248,8 +248,8 @@ Numeric tokens accept 0–4096 unless constrained below. Fractions ending in
| `field_radius` | `8.0` |
| `shadow_size` | `24.0` |
| `shadow_offset_y` | `8.0` |
-| `start_menu_width` | `560.0` |
-| `start_menu_max_height` | `600.0` |
+| `start_menu_width` | `0` (automatic) |
+| `start_menu_max_height` | `0` (automatic) |
| `start_menu_radius` | `14.0` |
| `start_menu_left_pad` | `2.0` |
| `start_menu_bottom_pad` | `6.0` |
@@ -336,4 +336,12 @@ fit their available space. The scrollbar reserves room for its maximum width;
In **Settings → Appearance → Start menu**, **Choose file…** selects a PNG or
SVG for the Start button logo and applies it immediately. **Reset to default**
-restores the bundled R logo. Both choices are saved with the theme.
+restores the bundled R logo. Both choices are saved with the theme. A preview
+beside the buttons shows the logo as the taskbar draws it (the bundled R when a
+chosen file cannot be loaded). The **Menu width** (400–900) and **Menu height**
+(360–900) sliders in the same section set `start_menu_width` and
+`start_menu_max_height`; the menu is still capped to the output. Left at `0`
+(the default) the menu is sized to the screen: 560 x 600 on a screen of about
+1700 x 1070 logical pixels or more, and the same share of the screen (33% wide,
+56% high) on smaller ones, never below 400 x 360. **Size to screen** returns to
+that.
diff --git a/icons/print.svg b/icons/print.svg
new file mode 100644
index 0000000..1ab822e
--- /dev/null
+++ b/icons/print.svg
@@ -0,0 +1,3 @@
+<svg width="20" height="20" viewBox="-10 -10 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#000000" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+<path d="M-5 -3V-8H5V-3M-5 5H-8V-3H8V5H5"/><rect x="-5" y="1" width="10" height="7"/>
+</svg>
diff --git a/icons/view-list.svg b/icons/view-list.svg
index e6f3c2a..2f12df1 100644
--- a/icons/view-list.svg
+++ b/icons/view-list.svg
@@ -1,3 +1,3 @@
-<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#000000" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
-<rect x="2" y="3" width="1" height="1"/><path d="M7 3H16"/><rect x="2" y="9" width="1" height="1"/><path d="M7 9H16"/><rect x="2" y="15" width="1" height="1"/><path d="M7 15H16"/>
+<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+<rect x="2" y="2.5" width="1" height="1"/><path d="M7 3H16"/><rect x="2" y="8.5" width="1" height="1"/><path d="M7 9H16"/><rect x="2" y="14.5" width="1" height="1"/><path d="M7 15H16"/>
</svg>
diff --git a/scripts/AGENTS.md b/scripts/AGENTS.md
new file mode 100644
index 0000000..235fb34
--- /dev/null
+++ b/scripts/AGENTS.md
@@ -0,0 +1,29 @@
+# Releases and install
+
+* **`install.sh` installs a prebuilt per-distro tarball** (`--build` compiles;
+ running from a checkout implies `--build`). It must stay self-contained up to
+ the download, since `curl | sh` has no repo yet. `make-release.sh` builds
+ each tarball in a clean podman/docker container of its distro and installs
+ it with the real `install.sh` in a fresh one; run it before publishing and
+ read the verify step's output.
+* **One tarball per distro, not per architecture-and-glibc.** Package ABIs
+ differ (libjpeg is `.so.8` on Arch/Ubuntu, `.so.62` on Debian/Fedora with a
+ different struct layout). A derivative uses its parent's tarball; if its
+ libraries don't match, `unresolved_libs` (missing libs or too-new glibc
+ symbol versions) or a failed package install falls back to a source build.
+ A checksum mismatch never falls back: it dies.
+* **`DEPENDS` is generated from the built binaries' `NEEDED` libraries**
+ (`release-build.sh`), never hand-kept; only the extras (Xwayland, portals,
+ Python, Mesa drivers) are listed by hand. Libraries bundled in `lib/rediwm`
+ are excluded, and which ones get bundled depends on what the build container
+ has installed, so never install the distro's own wlroots there.
+* **Releases always use the pinned, patched wlroots** from `build-wlroots.sh`,
+ whose recipe hash includes the script itself (editing even a comment
+ rebuilds everyone's private prefix). `rediwm`'s RUNPATH picks up the build
+ prefix when linking; `release-build.sh` scrubs it with patchelf and
+ `release-verify.sh` rejects any `/work/` path.
+* **CPU is `-Dcpu=x86_64_v2`.** Zig defaults to the build machine's CPU, which
+ would put illegal instructions into every user's binary. Releases are x86_64
+ only; other CPUs build from source.
+* Checksums come from the same GitHub release as the tarballs, so they catch
+ corruption, not a compromised release. Signing is not done yet.
diff --git a/src/Input.zig b/src/Input.zig
index c9c14d0..40a334f 100644
--- a/src/Input.zig
+++ b/src/Input.zig
@@ -386,9 +386,7 @@ pub fn focusForPress(input: *Input, hit: scene_data.Hit) void {
.surface => |res| input.server.world.focusSurface(res.toplevel, res.surface),
.layer => |res| res.owner.focus(),
.xwayland_unmanaged => |res| if (res.owner.wantsKeyboard()) {
- if (input.seat.getKeyboard()) |keyboard| {
- input.seat.keyboardNotifyEnter(res.surface, keyboard.keycodes[0..keyboard.num_keycodes], &keyboard.modifiers);
- }
+ @import("Keyboard.zig").enter(input.server, res.surface);
},
else => {},
}
@@ -2105,11 +2103,8 @@ fn processClientButton(
if (hit == .layer) hit.layer.owner.focus();
if (hit == .xwayland_unmanaged and hit.xwayland_unmanaged.owner.wantsKeyboard()) {
- const seat = input.seat;
const surface = hit.xwayland_unmanaged.surface;
- if (seat.getKeyboard()) |keyboard| {
- seat.keyboardNotifyEnter(surface, keyboard.keycodes[0..keyboard.num_keycodes], &keyboard.modifiers);
- }
+ @import("Keyboard.zig").enter(input.server, surface);
}
// Any keyboard-focus change belonging to this click must be requested
// before pointerNotifyButton, not after: a client's own request_start_drag
diff --git a/src/Keyboard.zig b/src/Keyboard.zig
index d9d989a..8faf7e4 100644
--- a/src/Keyboard.zig
+++ b/src/Keyboard.zig
@@ -166,6 +166,35 @@ fn handleKey(listener: *wl.Listener(*wlr.Keyboard.event.Key), event: *wlr.Keyboa
keyboard.processKey(event.time_msec, event.keycode, event.state);
}
+/// Focus enters must contain only keys delivered to clients. A raw hardware
+/// snapshot also includes shell shortcuts (e.g. Tab still held when Alt is
+/// released); their swallowed releases would leave them stuck in Xwayland.
+pub fn enter(server: *Server, surface: *wlr.Surface) void {
+ const seat = server.input.seat;
+ const wlr_keyboard = seat.getKeyboard() orelse return;
+ var owner: ?*Keyboard = null;
+ var keyboards = server.input.keyboards.iterator(.forward);
+ while (keyboards.next()) |keyboard| {
+ if (keyboard.device == &wlr_keyboard.base) {
+ owner = keyboard;
+ break;
+ }
+ }
+ var keys: [32]u32 = undefined;
+ var count: usize = 0;
+ for (wlr_keyboard.keycodes[0..wlr_keyboard.num_keycodes]) |code| {
+ if (owner) |keyboard| {
+ if (code < keyboard.client_pressed.len and
+ (!keyboard.client_pressed[code] or keyboard.polkit_consumed[code])) continue;
+ }
+ if (count < keys.len) {
+ keys[count] = code;
+ count += 1;
+ }
+ }
+ seat.keyboardNotifyEnter(surface, keys[0..count], &wlr_keyboard.modifiers);
+}
+
pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state: wl.Keyboard.KeyState) void {
keyboard.noteShellKey(event_keycode, state);
if (keyboard.server.locker != null and @import("input/text_input.zig").isVirtual(keyboard.device)) return;
diff --git a/src/LayerSurface.zig b/src/LayerSurface.zig
index 5df5e72..c70c18b 100644
--- a/src/LayerSurface.zig
+++ b/src/LayerSurface.zig
@@ -3,6 +3,7 @@ const std = @import("std");
const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
const Server = @import("Server.zig");
+const Output = @import("Output.zig");
const SceneData = @import("scene_data.zig").SceneData;
const gpa = @import("main.zig").gpa;
const Self = @This();
@@ -17,7 +18,7 @@ output_destroy: wl.Listener(*wlr.Output) = .init(outputDestroyed),
output_commit: wl.Listener(*wlr.Output.event.Commit) = .init(outputCommitted),
pub fn create(server: *Server, layer: *wlr.LayerSurfaceV1) !void {
- const output = layer.output orelse if (server.getDefaultOutput()) |o| o.wlr_output else {
+ const output = layer.output orelse defaultOutput(server) orelse {
layer.destroy();
return;
};
@@ -33,6 +34,21 @@ pub fn create(server: *Server, layer: *wlr.LayerSurfaceV1) !void {
output.events.destroy.add(&self.output_destroy);
output.events.commit.add(&self.output_commit);
}
+
+fn defaultOutput(server: *Server) ?*wlr.Output {
+ if (server.getDefaultOutput()) |output| return output.wlr_output;
+ // Sleeping outputs still host layers. Closing a new layer just because
+ // every screen is dark makes clients such as notification daemons retry.
+ if (server.preferredPrimaryOutput()) |output| {
+ if (output.idle_blanked) return output.wlr_output;
+ }
+ var outputs = server.outputs.iterator(.forward);
+ while (outputs.next()) |output| {
+ if (output.isLogicallyEnabled() and output.idle_blanked) return output.wlr_output;
+ }
+ return null;
+}
+
pub fn localPoint(self: *Self, x: f64, y: f64) @import("geometry.zig").Vec2 {
return @import("scene_data.zig").toNodeLocal(&self.scene.tree.node, x, y);
}
@@ -47,8 +63,12 @@ pub fn arrange(self: *Self) void {
self.scene.tree.node.reparent(parent);
var full: wlr.Box = undefined;
self.server.output_layout.getBox(self.layer.output, &full);
+ const output = Output.fromWlr(self.layer.output.?);
+ if (output) |out| if (out.idle_blanked) {
+ full = out.cached_box;
+ };
var usable = full;
- if (@import("Output.zig").fromWlr(self.layer.output.?)) |output| usable = output.usableBox();
+ if (output) |out| usable = out.usableBox();
self.scene.configure(&full, &usable);
}
fn committed(listener: *wl.Listener(*wlr.Surface), _: *wlr.Surface) void {
diff --git a/src/Server.zig b/src/Server.zig
index 6421afb..7ecb32e 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -47,6 +47,8 @@ const Server = @This();
const log = std.log.scoped(.compositor);
+extern fn wl_display_set_default_max_buffer_size(display: *wl.Server, size: usize) void;
+
pub const CompositorError = error{
ServerCreateFailed,
BackendCreateFailed,
@@ -324,6 +326,10 @@ fn firstAvailableOutput(server: *Server) ?*Output {
pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io: std.Io, environ: std.process.Environ, theme_path: ?[]const u8, argv: []const [*:0]const u8, greeter: bool) CompositorError!void {
const wl_server = wl.Server.create() catch return error.ServerCreateFailed;
errdefer wl_server.destroy();
+ // Let temporarily busy clients catch up with input/event bursts instead
+ // of disconnecting when the default 4 KiB outgoing buffer fills. This is
+ // a growth limit, not an allocation per client; keep it bounded at 1 MiB.
+ wl_display_set_default_max_buffer_size(wl_server, 1024 * 1024);
var session: ?*wlr.Session = null;
const backend = wlr.Backend.autocreate(wl_server.getEventLoop(), &session) catch return error.BackendCreateFailed;
@@ -1618,6 +1624,7 @@ fn handleIconWake(fd: c_int, mask: wl.EventMask, server: *Server) c_int {
if (output.start_menu) |sm| sm.iconsReady();
}
if (server.notifications) |mgr| mgr.iconsReady();
+ if (server.input.open_control_center) |cc| @import("control_center/sections/appearance.zig").iconsReady(&cc.appearance);
if (server.tray) |tray| tray.changed();
server.scheduleFrames();
return 0;
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index c2a74b8..bbe7a2d 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -124,7 +124,8 @@ pub fn startButtonBox(bar: *Taskbar) wlr.Box {
.height = size,
};
}
-fn startIconSize() i32 {
+/// Logical size the start button logo is drawn at.
+pub fn startIconSize() i32 {
const configured: i32 = @intFromFloat(@round(ui_theme.global.start_button_icon_size));
return @max(8, @min(configured, buttonSize()));
}
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index 2656ba4..8e62b39 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -144,6 +144,7 @@ shadow_tree: *wlr.SceneTree,
shadow_corners: [4]*wlr.SceneBuffer,
shadow_edges: [4]*wlr.SceneBuffer,
shadow_fallback: *wlr.SceneBuffer,
+resize_grab: *wlr.SceneBuffer,
glass_effect: ?*glass.Effect = null,
titlebar_buffer: *wlr.SceneBuffer,
footer_buffer: *wlr.SceneBuffer,
@@ -297,6 +298,7 @@ const ChromeNodes = struct {
shadow_corners: [4]*wlr.SceneBuffer,
shadow_edges: [4]*wlr.SceneBuffer,
shadow_fallback: *wlr.SceneBuffer,
+ resize_grab: *wlr.SceneBuffer,
glass_effect: ?*glass.Effect,
titlebar_buffer: *wlr.SceneBuffer,
footer_buffer: *wlr.SceneBuffer,
@@ -314,6 +316,11 @@ fn createChromeNodes(server: *Server) !ChromeNodes {
frame_tree.node.setEnabled(false);
if (!@import("projection.zig").setTreeZoom(&frame_tree.node, 1)) return error.OutOfMemory;
+ // Input only: no buffer, so never drawn. Gives the edges their reach past
+ // the frame without depending on the shadow (`shadow_size = 0`).
+ const resize_grab = try frame_tree.createSceneBuffer(null);
+ resize_grab.point_accepts_input = chromeAcceptsInput;
+
const shadow_tree = try frame_tree.createSceneTree();
var shadow_corners: [4]*wlr.SceneBuffer = undefined;
for (&shadow_corners) |*buf| {
@@ -357,6 +364,7 @@ fn createChromeNodes(server: *Server) !ChromeNodes {
.shadow_corners = shadow_corners,
.shadow_edges = shadow_edges,
.shadow_fallback = shadow_fallback,
+ .resize_grab = resize_grab,
.glass_effect = glass_effect,
.titlebar_buffer = titlebar_buffer,
.footer_buffer = footer_buffer,
@@ -372,6 +380,7 @@ fn finishCreate(toplevel: *Toplevel, nodes: ChromeNodes, scene_tree: *wlr.SceneT
toplevel.shadow_corners = nodes.shadow_corners;
toplevel.shadow_edges = nodes.shadow_edges;
toplevel.shadow_fallback = nodes.shadow_fallback;
+ toplevel.resize_grab = nodes.resize_grab;
toplevel.glass_effect = nodes.glass_effect;
toplevel.titlebar_buffer = nodes.titlebar_buffer;
toplevel.footer_buffer = nodes.footer_buffer;
@@ -406,6 +415,7 @@ pub fn create(server: *Server, xdg_toplevel: *wlr.XdgToplevel) !void {
.shadow_corners = nodes.shadow_corners,
.shadow_edges = nodes.shadow_edges,
.shadow_fallback = nodes.shadow_fallback,
+ .resize_grab = nodes.resize_grab,
.glass_effect = nodes.glass_effect,
.titlebar_buffer = nodes.titlebar_buffer,
.footer_buffer = nodes.footer_buffer,
@@ -450,6 +460,7 @@ pub fn createXwayland(server: *Server, xsurface: *wlr.XwaylandSurface) !void {
.shadow_corners = nodes.shadow_corners,
.shadow_edges = nodes.shadow_edges,
.shadow_fallback = nodes.shadow_fallback,
+ .resize_grab = nodes.resize_grab,
.glass_effect = nodes.glass_effect,
.titlebar_buffer = nodes.titlebar_buffer,
.footer_buffer = nodes.footer_buffer,
@@ -584,6 +595,7 @@ pub fn createPlaceholder(
.shadow_corners = nodes.shadow_corners,
.shadow_edges = nodes.shadow_edges,
.shadow_fallback = nodes.shadow_fallback,
+ .resize_grab = nodes.resize_grab,
.glass_effect = nodes.glass_effect,
.titlebar_buffer = nodes.titlebar_buffer,
.footer_buffer = nodes.footer_buffer,
@@ -694,6 +706,7 @@ pub fn createShell(server: *Server, cc: *ControlCenter, width: i32, height: i32)
.shadow_corners = nodes.shadow_corners,
.shadow_edges = nodes.shadow_edges,
.shadow_fallback = nodes.shadow_fallback,
+ .resize_grab = nodes.resize_grab,
.glass_effect = nodes.glass_effect,
.titlebar_buffer = nodes.titlebar_buffer,
.footer_buffer = nodes.footer_buffer,
@@ -1269,6 +1282,7 @@ fn attachSceneData(toplevel: *Toplevel) void {
scene_data.SceneData.attach(&toplevel.chrome_data, &buf.node);
}
scene_data.SceneData.attach(&toplevel.chrome_data, &toplevel.shadow_fallback.node);
+ scene_data.SceneData.attach(&toplevel.chrome_data, &toplevel.resize_grab.node);
scene_data.SceneData.attach(&toplevel.chrome_data, &toplevel.titlebar_buffer.node);
scene_data.SceneData.attach(&toplevel.chrome_data, &toplevel.footer_buffer.node);
for (toplevel.side_fills) |rect| {
@@ -2771,6 +2785,7 @@ pub fn syncChrome(toplevel: *Toplevel, sample_edge: bool, rebuild_shadow: bool,
toplevel.last_titlebar = null;
toplevel.last_footer = null;
toplevel.shadow_tree.node.setEnabled(false);
+ toplevel.resize_grab.node.setEnabled(false);
toplevel.content_tree.node.setPosition(0, 0);
const animated = visualChromeSize(toplevel, now_ms, geometry_box.width, geometry_box.height);
toplevel.chrome_width = animated.w;
@@ -2859,6 +2874,7 @@ pub fn syncChrome(toplevel: *Toplevel, sample_edge: bool, rebuild_shadow: bool,
toplevel.footer_buffer.setDestSize(width, footer);
toplevel.syncBorders(width, height);
+ toplevel.syncResizeGrab(width, height);
if (rebuild_shadow) try toplevel.syncShadow(width, height, radius);
// wlr_scene_xdg_surface_create origin is the geometry top-left.
@@ -2977,6 +2993,15 @@ fn syncShadow(toplevel: *Toplevel, width: i32, height: i32, radius: f32) !void {
toplevel.last_shadow = memo;
}
+// Unchanged position and size are no-ops in wlroots, so this runs on every
+// sync. Off while maximized, like the shadow: `startResize` refuses then.
+fn syncResizeGrab(toplevel: *Toplevel, width: i32, height: i32) void {
+ const reach: i32 = @intFromFloat(@ceil(resize.reach_outside));
+ toplevel.resize_grab.node.setEnabled(!toplevel.isMaximized());
+ toplevel.resize_grab.node.setPosition(-reach, -reach);
+ toplevel.resize_grab.setDestSize(width + 2 * reach, height + 2 * reach);
+}
+
fn syncBorders(toplevel: *Toplevel, width: i32, height: i32) void {
const inset: i32 = if (toplevel.isMaximized())
0
diff --git a/src/World.zig b/src/World.zig
index 50e29a0..075485e 100644
--- a/src/World.zig
+++ b/src/World.zig
@@ -175,27 +175,7 @@ pub fn focusSurface(world: *World, toplevel: *Toplevel, surface: ?*wlr.Surface)
seat.keyboardClearFocus();
return;
};
- const wlr_keyboard = seat.getKeyboard() orelse return;
- // Authentication keys held while focus returns must not enter a client.
- var keys: [32]u32 = undefined;
- var count: usize = 0;
- var keyboards = world.server.input.keyboards.iterator(.forward);
- var consumed: ?*const [768]bool = null;
- while (keyboards.next()) |keyboard| {
- if (keyboard.device == &wlr_keyboard.base) consumed = &keyboard.polkit_consumed;
- }
- for (wlr_keyboard.keycodes[0..wlr_keyboard.num_keycodes]) |code| {
- if (consumed) |mask| if (code < mask.len and mask[code]) continue;
- if (count < keys.len) {
- keys[count] = code;
- count += 1;
- }
- }
- seat.keyboardNotifyEnter(
- next,
- keys[0..count],
- &wlr_keyboard.modifiers,
- );
+ @import("Keyboard.zig").enter(world.server, next);
}
/// A transient dialog must stay above its owner even when the owner itself
diff --git a/src/accounts_helper/AGENTS.md b/src/accounts_helper/AGENTS.md
new file mode 100644
index 0000000..40aa65d
--- /dev/null
+++ b/src/accounts_helper/AGENTS.md
@@ -0,0 +1,8 @@
+# rediwm-accounts-helper
+
+Root-owned, run under `pkexec`; the compositor never runs as root.
+
+* Stdin JSON and `PKEXEC_UID` are untrusted: validate every operation.
+* Pass argv arrays to absolute system tools; never accept passwords in argv.
+* The authorization-only request changes no system state.
+* Helper, polkit policy and client (`src/accounts`) stay out of greeter mode.
diff --git a/src/assets/themes/rediwm-dark.toml b/src/assets/themes/rediwm-dark.toml
index fb11204..6e6105e 100644
--- a/src/assets/themes/rediwm-dark.toml
+++ b/src/assets/themes/rediwm-dark.toml
@@ -20,8 +20,6 @@ selection_alpha = 0.35
field_radius = 8
shadow_size = 24
shadow_offset_y = 8
-start_menu_width = 560
-start_menu_max_height = 600
start_menu_radius = 14
start_menu_left_pad = 2
start_menu_bottom_pad = 6
diff --git a/src/assets/themes/rediwm-light.toml b/src/assets/themes/rediwm-light.toml
index 495cd77..c05acc7 100644
--- a/src/assets/themes/rediwm-light.toml
+++ b/src/assets/themes/rediwm-light.toml
@@ -19,8 +19,6 @@ caret_width = 1.5
field_radius = 8
shadow_size = 24
shadow_offset_y = 8
-start_menu_width = 560
-start_menu_max_height = 600
start_menu_radius = 14
start_menu_left_pad = 2
start_menu_bottom_pad = 6
diff --git a/src/config/default.zig b/src/config/default.zig
index 8bc03ae..e27630f 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -37,6 +37,8 @@ pub const source =
\\ # each pill's top/bottom margin in the bar (capped)
\\start_button_gap = 4.0 # gap to the left of the start button and between start button and first pill
\\start_button_icon_size = 36.0 # start button logo size; capped to the button itself
+ \\# start_menu_width = 560.0 # start menu size; omitted or 0 sizes it to the screen
+ \\# start_menu_max_height = 600.0
\\start_menu_left_pad = 2.0 # start menu distance from left edge
\\start_menu_bottom_pad = 6.0 # start menu gap above the taskbar
\\start_menu_icon_left_pad = 12.0 # start menu app row left/right inset
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
new file mode 100644
index 0000000..29d7314
--- /dev/null
+++ b/src/control_center/AGENTS.md
@@ -0,0 +1,17 @@
+# Settings (`ControlCenter`)
+
+Settings is an ordinary window with a compositor-drawn body (`Backend.shell`).
+
+* The body paints into `scene_tree` at `render_scale` and presents with
+ `presentOwned`.
+* No wl_surface, so focus is "first in `world.toplevels`, activated, no seat
+ focus, desktop unfocused" (`hasKeyboardFocus`). `World.focusSurface`
+ deactivates a previous `.shell` window and calls `Desktop.yieldKeyboard`;
+ `findFocusedToplevel` returns it.
+* Compositor bindings run before it gets keys. Pointer coordinates come from
+ `localPoint`.
+* `close()` frees the content and `Toplevel.destroy`s the window (which may
+ animate from a snapshot): clear `backend.shell.control_center` and the
+ node's scene data first, and never close from inside a widget callback.
+* Saving a theme slider rebuilds the page on release: `panel.rebuildTree`
+ carries named sliders' state across (`src/ui/AGENTS.md`, "Sliders").
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index f0854b6..8ad24dc 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -27,6 +27,11 @@ const folder_picker = @import("../folder_picker.zig");
const wl = @import("wayland").server.wl;
const actions = @import("../../config_runtime/actions.zig");
const anim = @import("ui").anim;
+const col = @import("../../color.zig");
+const geometry = @import("../../geometry.zig");
+const start_button = @import("../../taskbar/start_button.zig");
+const menu_size = @import("../../start_menu/size.zig");
+const wlr = @import("wlroots");
const ipc_animations = @import("../../ipc/animations.zig");
const segmented_width: f32 = 180;
@@ -79,6 +84,8 @@ const px_chip_width = 9;
const px_window_gap = 10;
const px_chrome_height = 11;
const px_chrome_control_gap = 12;
+const px_menu_width = 13;
+const px_menu_height = 14;
pub const Section = struct {
cc: *panel.ControlCenter = undefined,
@@ -135,7 +142,7 @@ pub const Section = struct {
inactive_opacity_header_children: [2]Widget = undefined,
inactive_opacity_group_children: [2]Widget = undefined,
inactive_opacity_value_buf: [16]u8 = undefined,
- px: [13]PxControl = undefined,
+ px: [15]PxControl = undefined,
taskbar_section_children: [8]Widget = undefined,
taskbar_position_children: [2]Widget = undefined,
items_children: [3]Widget = undefined,
@@ -143,12 +150,80 @@ pub const Section = struct {
item_controls: [taskbar_items.count][3]Widget = undefined,
item_drag: ?struct { index: usize, press_y: f32, moved: bool = false, items: taskbar_items.Config } = null,
item_focus: ?taskbar_items.Item = null,
- start_menu_section_children: [6]Widget = undefined,
- start_logo_children: [3]Widget = undefined,
+ start_menu_section_children: [9]Widget = undefined,
+ start_size_children: [2]Widget = undefined,
+ start_logo_children: [2]Widget = undefined,
+ start_logo_body: [2]Widget = undefined,
+ start_logo_tile: [1]Widget = undefined,
+ start_logo_info: [2]Widget = undefined,
start_logo_buttons: [2]Widget = undefined,
start_logo_error: ?[]const u8 = null,
+ /// The preview is waiting on the icon service; `iconsReady` rebuilds.
+ start_logo_pending: bool = false,
};
+/// Slider ranges for the start menu's size. They only bound what the sliders
+/// offer: `StartMenu.relayout` caps both to the output and floors them at
+/// 320 x 240, which a hand-edited theme can still reach but leaves one row.
+/// Until a slider is moved the theme holds 0 and the menu is sized to the
+/// output (`start_menu/size.zig`); the sliders show that size.
+const menu_width_min = menu_size.min_width;
+const menu_width_max: f32 = 900;
+const menu_height_min = menu_size.min_height;
+const menu_height_max: f32 = 900;
+const start_logo_tile_size: f32 = 56;
+
+const StartLogo = struct {
+ image: layout.ImageData,
+ /// Logical size the image is drawn at.
+ size: i32,
+ /// A chosen file failed to load, so `image` is the bundled logo.
+ failed: bool,
+};
+
+/// The logo the taskbar is showing: the chosen file, else the bundled R (also
+/// when the file cannot be loaded), with the bundled one tinted the way
+/// `Taskbar.paintPartPixel` tints it. Mirrors `Taskbar.refreshStartLogo`.
+/// Pixels are copied into `a`, so nothing is pinned in the icon service.
+fn startLogoImage(out: *Section, a: std.mem.Allocator, logical: i32) StartLogo {
+ const server = out.cc.server;
+ const custom = theme.global.start_button_icon;
+ const size_px = geometry.devicePixels(logical, out.cc.toplevel.render_scale);
+ var result: StartLogo = .{ .image = .{ .fallback_icon = null }, .size = logical, .failed = false };
+ out.start_logo_pending = false;
+
+ var lookup = server.iconLookup(if (custom.len > 0) custom else start_button.builtin_logo, size_px);
+ if (lookup == .missing and custom.len > 0) {
+ result.failed = true;
+ lookup = server.iconLookup(start_button.builtin_logo, size_px);
+ }
+ const entry = switch (lookup) {
+ .ready => |e| e,
+ .pending => {
+ out.start_logo_pending = true;
+ return result;
+ },
+ .missing => return result,
+ };
+ const pixels = a.dupe(u32, entry.pixels) catch return result;
+ if (custom.len == 0) {
+ if (theme.taskbar(.start_button_logo_color)) |tint| {
+ for (pixels) |*pixel| {
+ var c = col.Straight.fromRgba(tint);
+ c.a *= @as(f32, @floatFromInt(pixel.* >> 24)) / 255.0;
+ pixel.* = c.argb();
+ }
+ }
+ }
+ result.image = .{ .pixels = pixels, .width = entry.size, .height = entry.size, .fallback_icon = null };
+ return result;
+}
+
+/// A decode finished: a preview that was waiting for one can now show it.
+pub fn iconsReady(s: *Section) void {
+ if (s.start_logo_pending and s.cc.page == .appearance) s.cc.refresh();
+}
+
fn indexOfNearest(values: []const f32, v: f32) usize {
var best: usize = 0;
var best_d = @abs(values[0] - v);
@@ -528,6 +603,14 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
out.taskbar_section_children = .{ sectionLabel("TASKBAR"), position_row, taskbar_row, chip_width_row, chip_gap_row, start_gap_row, start_icon_row, items_group };
const taskbar_section: Widget = .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.taskbar_section_children };
+ var output_box: wlr.Box = undefined;
+ out.cc.server.output_layout.getBox(out.cc.wlr_output, &output_box);
+ const menu_now = menu_size.wanted(t, @floatFromInt(output_box.width), @floatFromInt(output_box.height));
+ const menu_pinned = t.start_menu_width > 0 or t.start_menu_max_height > 0;
+ const menu_width_row = pxGroup(out, px_menu_width, "Menu width", std.math.clamp(menu_now.width, menu_width_min, menu_width_max), menu_width_min, menu_width_max, 10, &PxHandler(px_menu_width, "start_menu_width", false).changed);
+ out.px[px_menu_width].group_children[1].name = "start_menu_width";
+ const menu_height_row = pxGroup(out, px_menu_height, "Menu height", std.math.clamp(menu_now.height, menu_height_min, menu_height_max), menu_height_min, menu_height_max, 10, &PxHandler(px_menu_height, "start_menu_max_height", false).changed);
+ out.px[px_menu_height].group_children[1].name = "start_menu_height";
const menu_left_row = pxGroup(out, px_menu_left, "Menu left padding", std.math.clamp(t.start_menu_left_pad, 0.0, 40.0), 0, 40, 2, &PxHandler(px_menu_left, "start_menu_left_pad", false).changed);
const menu_bottom_row = pxGroup(out, px_menu_bottom, "Menu bottom padding", std.math.clamp(t.start_menu_bottom_pad, 0.0, 40.0), 0, 40, 2, &PxHandler(px_menu_bottom, "start_menu_bottom_pad", false).changed);
const icon_left_row = pxGroup(out, px_icon_left, "Icon left padding", std.math.clamp(t.start_menu_icon_left_pad, 0.0, 32.0), 0, 32, 2, &PxHandler(px_icon_left, "start_menu_icon_left_pad", false).changed);
@@ -536,13 +619,49 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .name = "start_logo_choose", .kind = .{ .button = .{ .label = "Choose file…", .owner = out, .on_click = &onChooseStartLogo, .state = if (folder_picker.running()) .disabled else .idle } }, .width = .{ .fixed = 124 }, .height = .{ .fixed = 30 } },
.{ .name = "start_logo_reset", .kind = .{ .button = .{ .label = "Reset to default", .owner = out, .on_click = &onResetStartLogo, .state = if (t.start_button_icon.len == 0 or folder_picker.running()) .disabled else .idle } }, .width = .{ .fixed = 140 }, .height = .{ .fixed = 30 } },
};
+ const logo = startLogoImage(out, arena, Taskbar.startIconSize());
+ const logo_note: []const u8 = out.start_logo_error orelse blk: {
+ if (t.start_button_icon.len == 0) break :blk "Default R logo · PNG or SVG";
+ const name = std.fs.path.basename(t.start_button_icon);
+ if (logo.failed) break :blk std.fmt.allocPrint(arena, "{s} could not be loaded · showing the default R", .{name}) catch name;
+ break :blk name;
+ };
+ // The logo sits on the taskbar, so it is shown on the taskbar's colour.
+ var tile_bg = theme.taskbar(.taskbar_bg);
+ tile_bg[3] = 1;
+ out.start_logo_tile = .{.{
+ .name = "start_logo_preview",
+ .kind = .{ .image = logo.image },
+ .width = .{ .fixed = @floatFromInt(logo.size) },
+ .height = .{ .fixed = @floatFromInt(logo.size) },
+ }};
+ out.start_logo_info = .{
+ .{ .name = "start_logo_file", .kind = .{ .text = .{ .content = logo_note, .font_size = 12, .color = pal.dim } } },
+ .{ .kind = .container, .direction = .row, .gap = 8, .children = &out.start_logo_buttons },
+ };
+ out.start_logo_body = .{
+ .{
+ .name = "start_logo_tile",
+ .kind = .{ .rect = .{ .color = tile_bg, .radius = 10, .border_width = 1, .border_color = pal.border_soft } },
+ .width = .{ .fixed = start_logo_tile_size },
+ .height = .{ .fixed = start_logo_tile_size },
+ .justify = .center,
+ .@"align" = .center,
+ .children = &out.start_logo_tile,
+ },
+ .{ .kind = .container, .direction = .column, .gap = 8, .justify = .center, .width = .{ .flex = 1 }, .children = &out.start_logo_info },
+ };
out.start_logo_children = .{
labelWidget("Start button logo"),
- .{ .name = "start_logo_file", .kind = .{ .text = .{ .content = out.start_logo_error orelse (if (t.start_button_icon.len == 0) "Default R logo · PNG or SVG" else std.fs.path.basename(t.start_button_icon)), .font_size = 12, .color = pal.dim } } },
- .{ .kind = .container, .direction = .row, .gap = 8, .children = &out.start_logo_buttons },
+ .{ .kind = .container, .direction = .row, .gap = 12, .@"align" = .center, .children = &out.start_logo_body },
};
const logo_row: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.start_logo_children };
- out.start_menu_section_children = .{ sectionLabel("START MENU"), logo_row, menu_left_row, menu_bottom_row, icon_left_row, icon_bottom_row };
+ out.start_size_children = .{
+ .{ .name = "start_menu_size_note", .kind = .{ .text = .{ .content = if (menu_pinned) "Custom size" else "Sized to fit your screen · move a slider to set your own", .font_size = 12, .color = pal.dim } }, .width = .{ .flex = 1 } },
+ .{ .name = "start_menu_size_auto", .kind = .{ .button = .{ .label = "Size to screen", .owner = out, .on_click = &onAutoMenuSize, .state = if (menu_pinned) .idle else .disabled } }, .width = .{ .fixed = 124 }, .height = .{ .fixed = 30 } },
+ };
+ const menu_size_row: Widget = .{ .kind = .container, .direction = .row, .gap = 8, .@"align" = .center, .children = &out.start_size_children };
+ out.start_menu_section_children = .{ sectionLabel("START MENU"), logo_row, menu_width_row, menu_height_row, menu_size_row, menu_left_row, menu_bottom_row, icon_left_row, icon_bottom_row };
const start_menu_section: Widget = .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.start_menu_section_children };
out.row_storage = .{
@@ -923,6 +1042,14 @@ fn onStartLogoChosen(owner: ?*anyopaque, path: ?[]const u8) void {
} else if (server.input.open_control_center) |cc| cc.refresh();
}
+/// Hands the menu's size back to the output: 0 is "automatic".
+fn onAutoMenuSize(owner: ?*anyopaque, _: usize) void {
+ const s = section(owner);
+ theme.global.start_menu_width = 0;
+ theme.global.start_menu_max_height = 0;
+ applyThemeChange(s);
+}
+
fn onResetStartLogo(owner: ?*anyopaque, _: usize) void {
const s = section(owner);
s.start_logo_error = null;
diff --git a/src/control_center/sections/default_apps.zig b/src/control_center/sections/default_apps.zig
index d3d5ed2..7866f55 100644
--- a/src/control_center/sections/default_apps.zig
+++ b/src/control_center/sections/default_apps.zig
@@ -73,6 +73,7 @@ fn save(owner: ?*anyopaque, comptime kind: defaults.Kind, index: usize) void {
}
extern fn g_desktop_app_info_new(id: [*:0]const u8) ?*anyopaque;
extern fn g_app_info_set_as_default_for_type(app: *anyopaque, content_type: [*:0]const u8, err: ?*?*anyopaque) c_int;
+extern fn g_app_info_reset_type_associations(content_type: [*:0]const u8) void;
extern fn g_object_unref(object: *anyopaque) void;
fn setDirectoryDefault(id: []const u8) !void {
@@ -81,6 +82,10 @@ fn setDirectoryDefault(id: []const u8) !void {
const app = g_desktop_app_info_new(terminated) orelse return error.ApplicationUnavailable;
defer g_object_unref(app);
if (g_app_info_set_as_default_for_type(app, "inode/directory", null) == 0) return error.AssociationFailed;
+ // GIO checks the file: scheme before the path's MIME type. An old file
+ // manager registered here overrides inode/directory (and regular files).
+ // Let local URIs resolve through their individual MIME associations.
+ g_app_info_reset_type_associations("x-scheme-handler/file");
}
fn fileChanged(owner: ?*anyopaque, _: usize, index: usize) void {
diff --git a/src/delete_dialog.zig b/src/delete_dialog.zig
index 62b48ec..cb1e7e7 100644
--- a/src/delete_dialog.zig
+++ b/src/delete_dialog.zig
@@ -25,6 +25,7 @@ pub const State = struct {
bytes: i64 = 0,
preview: ?icons.Entry = null,
permanent: bool = false,
+ empty_trash: bool = false,
focus: enum { cancel, toggle, confirm } = .cancel,
keyboard_focus: bool = false,
@@ -34,6 +35,10 @@ pub const State = struct {
const box = self.placement.box(g.box(), w, h);
g.x = box.x;
g.y = box.y;
+ if (self.empty_trash) {
+ g.toggle.w = 0;
+ g.toggle.h = 0;
+ }
return g;
}
@@ -72,7 +77,7 @@ pub const State = struct {
if (sym == c.XKB_KEY_Tab or sym == c.XKB_KEY_ISO_Left_Tab) {
self.keyboard_focus = true;
const n: usize = @intFromEnum(self.focus);
- self.focus = @enumFromInt((n + (if (sym == c.XKB_KEY_Tab) @as(usize, 1) else 2)) % 3);
+ self.focus = if (self.empty_trash) (if (self.focus == .cancel) .confirm else .cancel) else @enumFromInt((n + (if (sym == c.XKB_KEY_Tab) @as(usize, 1) else 2)) % 3);
}
if (sym == c.XKB_KEY_space or ((sym == c.XKB_KEY_Return or sym == c.XKB_KEY_KP_Enter) and self.keyboard_focus)) return switch (self.focus) {
.cancel => .cancel,
@@ -108,7 +113,7 @@ pub const State = struct {
t.button_font_size = shell_ui.textSize();
r.palette = t;
dialog.paintWindowFrame(r, layer.local(), background);
- dialog.paintWindowTitle(r, layer.local(), if (self.paths.items.len > 1) "Delete items?" else if (self.folder) "Delete folder?" else "Delete file?", .trash, null);
+ dialog.paintWindowTitle(r, layer.local(), if (self.empty_trash) "Empty Trash?" else if (self.paths.items.len > 1) "Delete items?" else if (self.folder) "Delete folder?" else "Delete file?", .trash, null);
const hover = g.target(mx, my);
button.paint(r, g.close, .{ .variant = .chrome, .icon = .close, .label = "Close" }, .{ .pointer = if (hover == .close) .hover else .idle });
r.drawText(16, g.header + 16, g.width - 32, 24, .{
@@ -123,17 +128,17 @@ pub const State = struct {
const icon_y = inset_y + (inset_h - icon_size) / 2;
if (self.preview) |im| {
r.drawImageCover(28, icon_y, icon_size, icon_size, 0, .{ .pixels = im.pixels, .width = @intCast(im.size), .height = @intCast(im.size) });
- } else r.drawIcon(28, icon_y, icon_size, icon_size, .{ .id = if (self.folder) .folder else .document, .color = t.fg });
+ } else r.drawIcon(28, icon_y, icon_size, icon_size, .{ .id = if (self.empty_trash) .trash else if (self.folder) .folder else .document, .color = t.fg });
var buf: [256]u8 = undefined;
- const name = if (self.paths.items.len == 1) self.name else std.fmt.bufPrint(&buf, "{d} selected items", .{self.paths.items.len}) catch "Selected items";
+ const name = if (self.empty_trash) "All items in Trash" else if (self.paths.items.len == 1) self.name else std.fmt.bufPrint(&buf, "{d} selected items", .{self.paths.items.len}) catch "Selected items";
r.drawText(76, inset_y + @max(0, (inset_h - 48) / 2), g.width - 108, @min(24, inset_h), .{ .content = name, .font_size = shell_ui.textSize(), .weight = 600, .color = t.fg });
var detail_buf: [128]u8 = undefined;
- const detail = if (self.paths.items.len > 1) "Files and folders in this selection" else if (self.folder) "Folder · includes its contents" else std.fmt.bufPrint(&detail_buf, "{s} · {d:.1} {s}", .{ if (std.ascii.eqlIgnoreCase(std.fs.path.extension(self.name), ".pdf")) "PDF document" else "File", @as(f64, @floatFromInt(@max(0, self.bytes))) / (if (self.bytes >= 1048576) @as(f64, 1048576) else if (self.bytes >= 1024) @as(f64, 1024) else 1), if (self.bytes >= 1048576) "MB" else if (self.bytes >= 1024) "KB" else "bytes" }) catch "File";
+ const detail = if (self.empty_trash) "Permanently delete all trashed files and folders" else if (self.paths.items.len > 1) "Files and folders in this selection" else if (self.folder) "Folder · includes its contents" else std.fmt.bufPrint(&detail_buf, "{s} · {d:.1} {s}", .{ if (std.ascii.eqlIgnoreCase(std.fs.path.extension(self.name), ".pdf")) "PDF document" else "File", @as(f64, @floatFromInt(@max(0, self.bytes))) / (if (self.bytes >= 1048576) @as(f64, 1048576) else if (self.bytes >= 1024) @as(f64, 1024) else 1), if (self.bytes >= 1048576) "MB" else if (self.bytes >= 1024) "KB" else "bytes" }) catch "File";
if (inset_h >= 48) r.drawText(76, inset_y + (inset_h - 48) / 2 + 28, g.width - 108, 20, .{ .content = detail, .font_size = shell_ui.textSize(), .color = t.fg });
const focus = if (self.keyboard_focus) self.focus else null;
- checkbox.paint(r, g.toggle, "Delete permanently", .{ .checked = self.permanent, .focused = focus == .toggle });
+ if (!self.empty_trash) checkbox.paint(r, g.toggle, "Delete permanently", .{ .checked = self.permanent, .focused = focus == .toggle });
button.paint(r, g.cancel, .{ .size = .sm, .label = "Cancel" }, .{ .focused = focus == .cancel, .pointer = if (hover == .cancel) .hover else .idle });
- button.paint(r, g.confirm, .{ .variant = .primary, .size = .sm, .leading_icon = .trash, .label = if (self.permanent) "Delete permanently" else "Move to Trash" }, .{ .focused = focus == .confirm, .pointer = if (hover == .confirm) .hover else .idle });
+ button.paint(r, g.confirm, .{ .variant = .primary, .size = .sm, .leading_icon = .trash, .label = if (self.empty_trash) "Empty Trash" else if (self.permanent) "Delete permanently" else "Move to Trash" }, .{ .focused = focus == .confirm, .pointer = if (hover == .confirm) .hover else .idle });
}
};
diff --git a/src/desktop/AGENTS.md b/src/desktop/AGENTS.md
new file mode 100644
index 0000000..e7f15a1
--- /dev/null
+++ b/src/desktop/AGENTS.md
@@ -0,0 +1,18 @@
+# Desktop icons (`[desktop] enabled`)
+
+Desktop keyboard focus and compositor drop targets are in the root
+`AGENTS.md` ("Windows and focus", "Input").
+
+* `App` (`app.zig`) and its worker (`watcher.zig`) never depend on the
+ compositor; the worker is a thread that never calls the host. Tests set
+ `REDIWM_DESKTOP_DIR`.
+* One retained canvas published as 240-logical-px tiles (`embedded.zig`); only
+ damaged tiles get new buffers. Rasterize the selection band once per paint;
+ repair clips snap outward to device pixels. Labels/icons are rasterized at
+ exact scale.
+* A `.desktop` file runs only if `Worker.trustedLauncher` (`watcher.zig`)
+ accepts it (installed or linked into the menus, root-owned, executable, or
+ an exact copy of the installed entry); otherwise it is an `untrusted` plain
+ file whose own Name/Icon are never shown. Allow Launching is `chmod u+x`.
+* Launches go through `app_scope.place` like every other user app: the worker
+ hands pids over with `Worker.takeStarted`.
diff --git a/src/desktop/app.zig b/src/desktop/app.zig
index 2938893..41f5a92 100644
--- a/src/desktop/app.zig
+++ b/src/desktop/app.zig
@@ -662,7 +662,7 @@ pub const App = struct {
fn menuLabels(self: *App) []const []const u8 {
switch (self.menuBuiltin()) {
.home => return &.{"Open"},
- .trash => return &.{ "Open", "Empty Trash" },
+ .trash => return &.{ "Open", "Empty Trash…" },
.none => {},
}
const icon_labels = [_][]const u8{ "Open", "Open With…", "Cut", "Copy", "Rename", "Move to Trash", "Properties", "Allow Launching" };
@@ -689,8 +689,11 @@ pub const App = struct {
fn menuAction(self: *App, row: usize) void {
const builtin = self.menuBuiltin();
if (builtin != .none) {
- if (row == 0) self.openSelected() else if (builtin == .trash and row == 1)
- self.worker.enqueue(.{ .kind = .empty_trash, .path = "" });
+ if (row == 0) self.openSelected() else if (builtin == .trash and row == 1) {
+ self.deletion.deinit();
+ self.deletion = .{ .permanent = true, .empty_trash = true };
+ self.edit = .trash;
+ }
return;
}
if (self.menu_icon != null) {
@@ -769,6 +772,7 @@ pub const App = struct {
self.edit = .none;
},
.toggle => {
+ if (self.deletion.empty_trash) return;
self.deletion.permanent = !self.deletion.permanent;
self.deletion.focus = .toggle;
},
@@ -794,8 +798,12 @@ pub const App = struct {
}
defer self.edit = .none;
if (self.edit == .trash) {
- for (self.deletion.paths.items) |path| {
- self.worker.enqueue(.{ .kind = if (self.deletion.permanent) .delete else .trash, .path = path });
+ if (self.deletion.empty_trash) {
+ self.worker.enqueue(.{ .kind = .empty_trash, .path = "" });
+ } else {
+ for (self.deletion.paths.items) |path| {
+ self.worker.enqueue(.{ .kind = if (self.deletion.permanent) .delete else .trash, .path = path });
+ }
}
self.deletion.deinit();
return;
@@ -1507,9 +1515,18 @@ test "desktop motion keeps menu highlights and moving selections live" {
app.menu_icon = 1;
try std.testing.expectEqual(@as(usize, 2), app.menuLabels().len);
try std.testing.expectEqualStrings("Open", app.menuLabels()[0]);
- try std.testing.expectEqualStrings("Empty Trash", app.menuLabels()[1]);
+ try std.testing.expectEqualStrings("Empty Trash…", app.menuLabels()[1]);
try std.testing.expectEqual(@import("ui").layout.IconId.trash, app.menuIcon(1));
try std.testing.expectEqual(@as(?[]const u8, null), app.menuHint(1));
+ // Opening and cancelling must not enqueue work (the worker is undefined).
+ app.menuAction(1);
+ try std.testing.expect(app.edit == .trash);
+ try std.testing.expect(app.deletion.empty_trash and app.deletion.permanent);
+ app.deleteAction(.toggle);
+ try std.testing.expect(app.deletion.permanent);
+ app.deleteAction(.cancel);
+ try std.testing.expect(app.edit == .none);
+ try std.testing.expect(!app.deletion.empty_trash);
app.icons.items = &.{};
app.menu_icon = null;
app.menu = false;
diff --git a/src/dm/AGENTS.md b/src/dm/AGENTS.md
new file mode 100644
index 0000000..6513dc7
--- /dev/null
+++ b/src/dm/AGENTS.md
@@ -0,0 +1,10 @@
+# rediwm-dm
+
+Runs as root. The greeter (`rediwm --greeter`) is untrusted input.
+
+* The daemon never blocks; workers own one PAM handle each.
+* Signal masks survive exec: clear them. `setuid` clears `PR_SET_PDEATHSIG`.
+* Never format JSON with `{s}`.
+* Only the daemon and workers are root. Don't sandbox `rediwm-dm.service`:
+ user sessions inherit it.
+* `--test`, `--confdir`, `--data-dir` and `--marker` are refused as root.
diff --git a/src/editor/AGENTS.md b/src/editor/AGENTS.md
new file mode 100644
index 0000000..08b30fc
--- /dev/null
+++ b/src/editor/AGENTS.md
@@ -0,0 +1,30 @@
+# Text editor
+
+* **Never give Pango more than a few lines.** One layout of 1 MiB took 46 s
+ (cost grows faster than the line count). `view.zig` lays out one *segment*
+ at a time (`lines.zig`: a logical line, or a piece of one folded at `fold` =
+ 16 KiB, cut after a nearby space) in a content-keyed cache (`Layouts`), so
+ edits need no invalidation. Pieces are a function of the line start alone,
+ so walking up or down finds the same ones; keep `lines.zig`'s property test
+ green when touching it.
+* **Scroll is `Document.top` (a byte offset) plus `Tab.dy` pixels into that
+ line**, never a pixel count from the file start (that needs every line's
+ height). `Document.replace` shifts `top` and the line waypoints
+ (`retarget`) so edits above the view don't move it. `Port.clamp` after any
+ change; `locate` returns null for a position more than three viewports away,
+ so jump (`jumpTo`) instead of walking.
+* **Scrollbar units** are pixels (exact) up to `exact_limit` and bytes above
+ it, because a drag in progress must not see its units shift as the height
+ estimate improves. Line numbers come from sparse waypoints (`linesBefore`).
+* **Large saves are written in place** (`Operation.startSave` `borrow`, above
+ `copy_limit`) and `Document.locked` refuses edits meanwhile; smaller ones are
+ copied. Anything that frees or reallocates the text during a save is a
+ use-after-free. Loads read straight into one buffer sized from `fstat`, sniff
+ the first 64 KiB for binary data and refuse files that won't fit in
+ `MemAvailable` (`ensureMemory`).
+* **Benchmark in ReleaseSafe.** Debug makes the vector scans ~50x slower and
+ fakes a regression. Editing near the start of a huge file memmoves the tail
+ (about 100 ms per keystroke at 2 GB); a gap buffer would fix it, but every
+ `text.items` reader (segmenter, find, IME, clipboard) would need to learn it.
+* A selected line break is not in the segment layout, so `paintLine` draws the
+ highlight out to the margin itself (wrapped mode only, as Pango did).
diff --git a/src/files/AGENTS.md b/src/files/AGENTS.md
new file mode 100644
index 0000000..87fc130
--- /dev/null
+++ b/src/files/AGENTS.md
@@ -0,0 +1,111 @@
+# Files
+
+Text, colour and theme rules shared with Images and PDF are in the root
+`AGENTS.md` ("Shared UI"). Every test that launches Files sets
+`REDIWM_FILES_DEVICES=0` and scratch `XDG_STATE_HOME`/`XDG_DATA_HOME`
+(`TESTING.md`, "Common knobs").
+
+## Git
+
+`git.zig` never runs a repository's own programs: a folder's `.git` arrives
+with archives and USB sticks. Every command uses `safe_options` and `cleanEnv`
+(no fsmonitor, hooks, pager, transports or lazy fetches); `trustedRepository`
+refuses repositories whose own (local, worktree or included) configuration
+names filter or Git LFS commands, and `status` ignores submodules (their
+configuration is not checked).
+
+## Thumbnails
+
+* **Decoding avoids GdkPixbuf for JPEG and PNG.** Current gdk-pixbuf routes
+ them through sandboxed glycin loader processes and ignores scaled decode (a
+ 12 MP JPEG costs ~150 ms). `thumb_codec.c` decodes JPEG at 1/2–1/8 inside
+ libjpeg's DCT and streams PNG rows into an area-averaging downscaler, so no
+ full raster exists. Whatever it reports unsupported (WebP, GIF, SVG,
+ interlaced PNG, CMYK JPEG) falls back to `images/decode.zig` (`loadWith`
+ with a box), which the viewer's `loader.zig` also re-exports. Re-measure
+ before "simplifying" this.
+* **`thumbs.zig` alone owns the raster cache**: 2 nice'd workers, the queue
+ replaced on every `request` (scrolling cancels queued work), results handed
+ over under the mutex and an eventfd, LRU by bytes and entry count. Workers
+ never touch Cairo or Wayland. Keys are path plus the mtime and size the
+ *listing* reported; a stale file is dropped without an entry and retried
+ after the next rescan. Failures are remembered per file state. No timers:
+ idle stays at zero wakeups.
+* **App side:** `stepThumbs` re-requests only when the visible rows or
+ `view_revision` change; `drainThumbs` damages just the arrived icons through
+ `addDamage`. `itemIconRect` is the single source of icon geometry for
+ painting and damage. Thumbnails are drawn in `drawItemIcon` (grid 48, list
+ 24, drag icon 32) from a bilinear-filtered 128 px raster.
+* **Shared freedesktop cache** (`$XDG_CACHE_HOME/thumbnails/normal|large`):
+ the name is the MD5 of the GLib-escaped `file://` URI, validated by
+ `Thumb::MTime` (and `Thumb::Size` when present) against the *target's* stat.
+ Entries are written after the UI has its pixels, via tmp file + rename, mode
+ 0600, only when the original is bigger than 128 px. Tests set a scratch
+ `XDG_CACHE_HOME`. `REDIWM_FILES_THUMBNAILS=0` turns thumbnails off.
+
+## Devices
+
+* **Transport vs policy.** `volumes.c` is a GLib thread holding a GDBus
+ object-manager client for UDisks2 on the system bus (not `src/dbus`, which
+ is tied to the compositor's `wl.EventLoop`). It only publishes raw records
+ and runs Mount/Unmount with interactive polkit authorization. What to list,
+ the label and the stick/drive icon are `volumes.zig`'s `shown`/`kindOf`.
+ `HintIgnore` hides EFI partitions; `HintSystem` volumes mounted outside
+ `/run/media`, `/media` and `/mnt` (`/`, `/home`, `/boot`) are hidden by the
+ mount rule, because UDisks2 does not ignore them. Loop devices are
+ `HintSystem` too, so only that rule decides them.
+* **Lifetime.** The thread is never joined: `vol_stop` posts a quit and the
+ thread frees its own state, so shutdown cannot block on a bus that does not
+ answer. Don't use the monitor or its wake fd after `stop`. Publishing is
+ coalesced (one 40 ms one-shot per burst of signals) and happens only on a
+ real change.
+* **Ejecting is unmounting.** A device stays listed, dimmed, while attached;
+ power-off would make SSDs vanish. Eject first leaves the volume if the view
+ is inside it, and is refused while a file operation runs. One mount/eject at
+ a time (`device_op`); a mount opens the volume only if `navigation_count` is
+ unchanged.
+* **Trying it for real** without touching disks:
+ `truncate -s 64M x.img && mkfs.ext4 -L X x.img && udisksctl loop-setup -f x.img`
+ (polkit allows it for an active session), then `udisksctl loop-delete -b`.
+ Never click an unmounted internal partition in a real session: mounting it
+ raises an admin prompt.
+
+## Sidebar rows
+
+Rows are indexed in drawn order, which the hover glide relies on: built-ins
+`0..pin_base` (`places`; Recent hides when unavailable, and those from
+`places_start` on can be unpinned through `unpinned_places`), then pins, then
+devices from `deviceBase()`. Go through `rowKind`; never use `places.len` as a
+row index. Hover keys: 300+i built-in, 800+j pin, 600+k device, 700+k eject.
+`pinRowY` positions pins and the drop line; `placeY` for devices,
+`deviceBlock()` and `gitCard` follow the pin and device counts: change them
+together.
+
+## Pins
+
+* **Pins are PLACES rows the user drops in.** `pins.zig` owns the list
+ (`$XDG_STATE_HOME/rediwm/files-places`, one absolute path per line). The
+ file is the truth: `pinDropped`/`removePin` re-read it before changing (a
+ second window must not overwrite the first's pins) and the keyboard `enter`
+ event calls `refreshPins`.
+* **Pins are not built-ins:** a visible built-in place's path is refused
+ ("Already in Places"), a hidden built-in can be dropped back as a pin, a
+ missing target stays listed dimmed, and a file pin opens like a double click
+ (a chooser browses its folder).
+
+## Drops
+
+`main.zig` `dragOver`/`dragDropped` accept `text/uri-list`: PLACES pins with
+*copy* only; the content area transfers to the hovered folder or, on empty
+space, the displayed directory.
+
+* Files sources advertise `application/x-rediwm-file-transfer`: the receiving
+ job owns moves and the source never deletes on `dnd_finished`. Ctrl at drag
+ start offers copy only; other sources copy.
+* After `drop` the offer leaves `drag_offer` (a `leave` would destroy it) and
+ is read through a nonblocking pipe (`drop_receiving`, poll slot 15).
+ Snapshot the destination before reading.
+* Drops use the normal conflict/progress jobs without touching cut-clipboard
+ state; reject a folder dropped into itself or a descendant, including
+ through symlinks. Pins take their gap from `pin_drop`.
+* Ctrl-click deselection waits for release so Ctrl-drag keeps the selection.
diff --git a/src/files/app.zig b/src/files/app.zig
index 201b2a4..3d03c1c 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -1,6 +1,7 @@
const std = @import("std");
const archive = @import("archive.zig");
const scrollbar = @import("ui").widgets.scrollbar;
+const splitter = @import("ui").widgets.splitter;
const anim = @import("ui").anim;
const c = @import("c.zig").api;
const git = @import("git.zig");
@@ -38,6 +39,29 @@ const Editor = @import("editor.zig").Editor;
const DeviceOp = struct { id: []u8, unmount: bool, open: bool, navigation: u32 };
const MenuKind = enum { new, sort, filter, file, background, sidebar, device, chooser_filter };
+const PlaceAction = enum {
+ open,
+ open_window,
+ empty_trash,
+ unpin,
+ remove_pin,
+ properties,
+ mount,
+ eject,
+
+ fn label(self: PlaceAction) []const u8 {
+ return switch (self) {
+ .open => "Open",
+ .open_window => "Open in New Window",
+ .empty_trash => "Empty Trash…",
+ .unpin => "Unpin",
+ .remove_pin => "Remove from Places",
+ .properties => "Properties",
+ .mount => "Mount",
+ .eject => "Eject",
+ };
+ }
+};
const FileAction = enum {
open,
open_with,
@@ -263,8 +287,8 @@ pub const App = struct {
git_expanded: bool = true,
/// The "Git View" checkbox: off shows a repository like any other folder.
git_view: bool = true,
- column_weights: ?[5]f64 = null,
- git_column_weight: ?f64 = null,
+ column_widths: ?[5]f64 = null,
+ git_column_widths: ?[5]f64 = null,
column_resize: ?struct { column: usize, x: f64, widths: [5]f64 } = null,
sort_mode: Sort = .name,
recent_sort_mode: Sort = .modified,
@@ -281,6 +305,7 @@ pub const App = struct {
menu_y: f64 = 0,
menu_selected: usize = 0,
file_menu_labels: [12][]const u8 = undefined,
+ place_menu_labels: [4][]const u8 = undefined,
menu_place: usize = 0,
unpinned_places: u8 = 0,
/// Folders and files the user dropped into PLACES (see pins.zig); they sit
@@ -345,6 +370,9 @@ pub const App = struct {
last_ms: i64,
} = null,
sidebar_scroll: i32 = 0,
+ /// User width for this window; responsive layouts still hide the pane.
+ sidebar_requested: ?i32 = null,
+ sidebar_resize: ?splitter.Drag = null,
/// Eased sidebar width and place pitch (-1 until the first `stepLayout`,
/// which adopts the current targets without animating).
sidebar_glide: anim.Anim = .{},
@@ -356,6 +384,10 @@ pub const App = struct {
sidebar_scroll_appearance: scrollbar.Appearance = .{},
sidebar_scroll_observed: i32 = 0,
scrollbar_width: f32 = 8,
+ scroll_x: f64 = 0,
+ horizontal_drag: scrollbar.Drag = .{},
+ horizontal_appearance: scrollbar.Appearance = .{},
+ horizontal_observed: f64 = 0,
scroll_drag: scrollbar.Drag = .{},
scroll_appearance: scrollbar.Appearance = .{},
scroll_observed: i32 = 0,
@@ -623,7 +655,7 @@ pub const App = struct {
fn clipToViewport(self: *App, rect: header.Rect) header.Rect {
const top: f64 = @floatFromInt(self.viewTop());
- const bottom = @min(rect.y + rect.h, @as(f64, @floatFromInt(self.h - self.footerHeight())));
+ const bottom = @min(rect.y + rect.h, @as(f64, @floatFromInt(self.contentBottom())));
const y = @max(rect.y, top);
return .{ .x = rect.x, .y = y, .w = rect.w, .h = @max(0, bottom - y) };
}
@@ -632,6 +664,7 @@ pub const App = struct {
/// paints its own fill.
fn hoveredPlace(self: *App) ?usize {
if (self.dialog != null or self.menu != null) return null;
+ if (self.sidebar_resize != null or self.overSidebarDivider(self.mouse_x, self.mouse_y)) return null;
const width: f64 = @floatFromInt(self.sidebarWidth());
if (self.mouse_x < 0 or self.mouse_x >= width) return null;
if (self.sidebarScrollbar()) |bar| if (self.mouse_x >= @as(f64, bar.track.x)) return null;
@@ -746,7 +779,7 @@ pub const App = struct {
self.hover_active = self.hover_active or !self.sort_feedback.animation.settled(now);
// Only visible cards need samples or a frame clock. Logical selection
// changes immediately; painting and damage share these sampled fades.
- const viewport_h = @max(0, self.h - self.viewTop() - self.footerHeight());
+ const viewport_h = @max(0, self.contentBottom() - self.viewTop());
const first: usize = @min(self.items.items.len, @as(usize, @intCast(@divTrunc(self.scroll_y, self.rowHeight()))) * per_row);
const last: usize = @min(self.items.items.len, @as(usize, @intCast(@divTrunc(self.scroll_y + viewport_h, self.rowHeight()) + 1)) * per_row);
for (self.items.items[first..last], first..) |*item, idx| {
@@ -808,6 +841,7 @@ pub const App = struct {
self.sidebar_scroll_drag.end();
self.w = @max(360, new_w);
self.h = @max(240, new_h);
+ if (self.sidebar_requested != null and self.w >= 500) self.syncSidebarWidth();
self.clampScroll();
self.clampSidebarScroll();
if (self.menu) |kind| self.openMenu(kind, self.menu_x, self.menu_y);
@@ -857,7 +891,7 @@ pub const App = struct {
}
pub fn navigate(self: *App, new_path: []const u8) void {
- if (self.chooser != null and recent.isLocation(new_path)) return;
+ if (!self.recentAvailable() and recent.isLocation(new_path)) return;
self.rememberView();
self.history.navigate(new_path) catch return;
self.applyHistoryNav(self.history.current);
@@ -1393,6 +1427,16 @@ pub const App = struct {
self.invalidate();
}
+ fn openEmptyTrashDialog(self: *App) void {
+ self.closeDialog();
+ self.dialog = .{
+ .kind = .trash_confirm,
+ .title = "Empty Trash?",
+ .deletion = .{ .permanent = true, .empty_trash = true },
+ };
+ self.invalidate();
+ }
+
pub fn openTrashConfirmDialog(self: *App) void {
if (self.history.archive_len > 0) return;
var count: usize = 0;
@@ -1670,6 +1714,7 @@ pub const App = struct {
.cancel => self.closeDialog(),
.confirm => self.confirmDialog(),
.toggle => {
+ if (self.dialog.?.deletion.empty_trash) return;
self.dialog.?.deletion.permanent = !self.dialog.?.deletion.permanent;
self.dialog.?.deletion.focus = .toggle;
},
@@ -1680,13 +1725,13 @@ pub const App = struct {
fn executeDeletion(self: *App) void {
const state = &self.dialog.?.deletion;
- const result = if (state.permanent) ops_mod.deleteItems(self.io, state.paths.items) else ops_mod.trashItems(self.io, state.paths.items);
+ const result = if (state.empty_trash) ops_mod.emptyTrash(self.io) else if (state.permanent) ops_mod.deleteItems(self.io, state.paths.items) else ops_mod.trashItems(self.io, state.paths.items);
result catch |err| {
- self.setStatusNotice(if (state.permanent) "Could not delete all items" else if (err == error.GioNotAvailable) "Trash unavailable (gio not installed)" else "Could not move all items to Trash", true);
+ self.setStatusNotice(if (state.empty_trash) "Could not empty Trash" else if (state.permanent) "Could not delete all items" else if (err == error.GioNotAvailable) "Trash unavailable (gio not installed)" else "Could not move all items to Trash", true);
self.refresh();
return;
};
- self.setStatusNotice(if (state.permanent) "Items permanently deleted" else "Items moved to Trash", false);
+ self.setStatusNotice(if (state.empty_trash) "Trash emptied" else if (state.permanent) "Items permanently deleted" else "Items moved to Trash", false);
self.refresh();
}
@@ -1884,7 +1929,14 @@ pub const App = struct {
if (opts.mode == .save or (opts.mode == .open and !opts.multiple and self.filename.text.items.len > 0)) {
const name = self.filename.text.items;
if (!chooser_mod.validName(name)) return error.InvalidName;
- const path = try std.fs.path.join(self.allocator, &.{ self.history.current, name });
+ const path = if (self.isRecent()) selected: {
+ // Recent spans directories, so the filename alone is not a path.
+ for (self.items.items) |item| {
+ if (item.selected and std.mem.eql(u8, item.name, name))
+ break :selected try self.allocator.dupe(u8, item.path);
+ }
+ return error.NoSelection;
+ } else try std.fs.path.join(self.allocator, &.{ self.history.current, name });
defer self.allocator.free(path);
const zpath = try self.allocator.dupeZ(u8, path);
defer self.allocator.free(zpath);
@@ -2093,7 +2145,7 @@ pub const App = struct {
return self.contentTop() + if (self.list_view) @as(i32, 30) else 0;
}
fn compactList(self: *App) bool {
- return self.list_view and self.h - self.viewTop() - self.footerHeight() < 80;
+ return self.list_view and self.contentBottom() - self.viewTop() < 80;
}
fn itemInset(self: *App) i32 {
return if (self.compactList()) 0 else 20;
@@ -2110,13 +2162,37 @@ pub const App = struct {
}
fn sidebarTargetWidth(self: *App) i32 {
- return if (self.w >= 700) 208 else if (self.w >= 500) 160 else 0;
+ if (self.w < 500) return 0;
+ if (self.sidebar_requested) |width| return std.math.clamp(width, 160, @divTrunc(self.w, 2));
+ return if (self.w >= 700) 208 else 160;
}
/// The width being drawn: it eases toward `sidebarTargetWidth` when a
/// resize crosses a threshold.
fn sidebarWidth(self: *App) i32 {
- return if (self.sidebar_px >= 0) self.sidebar_px else self.sidebarTargetWidth();
+ return @min(@divTrunc(self.w, 2), if (self.sidebar_px >= 0) self.sidebar_px else self.sidebarTargetWidth());
+ }
+
+ fn syncSidebarWidth(self: *App) void {
+ self.sidebar_px = self.sidebarTargetWidth();
+ self.sidebar_glide.cancel(@floatFromInt(self.sidebar_px));
+ }
+
+ fn sidebarDivider(self: *App) ?splitter.Geometry {
+ if (self.w < 500 or self.sidebarWidth() < 160) return null;
+ return .{ .x = @floatFromInt(self.sidebarWidth()), .y = @floatFromInt(self.contentTop()), .h = @floatFromInt(@max(0, self.h - self.contentTop() - self.footerHeight())) };
+ }
+
+ fn overSidebarDivider(self: *App, x: f64, y: f64) bool {
+ if (self.dialog != null or self.menu != null) return false;
+ const divider = self.sidebarDivider() orelse return false;
+ return divider.contains(x, y);
+ }
+
+ fn damageSidebarDivider(self: *App) void {
+ const divider = self.sidebarDivider() orelse return;
+ const rect = divider.line(true);
+ self.addDamage(.{ .x = rect.x, .y = rect.y, .w = rect.w, .h = rect.h });
}
fn placeTargetStep(self: *App) i32 {
@@ -2175,7 +2251,7 @@ pub const App = struct {
fn itemAt(self: *App, x: f64, y: f64) ?usize {
const gx = @as(i32, @intFromFloat(x)) - self.sidebarWidth() - 20;
- if (y < @as(f64, @floatFromInt(self.viewTop())) or y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) return null;
+ if (y < @as(f64, @floatFromInt(self.viewTop())) or y >= @as(f64, @floatFromInt(self.contentBottom()))) return null;
const gy = @as(i32, @intFromFloat(y)) - self.viewTop() - self.itemInset() + self.scroll_y;
if (gx < 0 or gy < 0) return null;
const col = @divTrunc(gx, self.cellWidth());
@@ -2218,27 +2294,15 @@ pub const App = struct {
return .{ 64, 40, 40, @min(136, width - 184), 40 };
}
- fn columnMinimumTotal(minimum: [5]f64) f64 {
- var total: f64 = 0;
- for (minimum) |value| total += value;
- return total;
- }
-
fn listWidths(self: *App) [5]f64 {
const width: f64 = @floatFromInt(self.cellWidth() - 20);
if (self.repository() != null) {
+ if (self.git_column_widths) |widths| return widths;
const minimum = gitColumnMinimums(width);
- const extra = @max(0, width - minimum[0] - minimum[1]);
- const name = if (self.git_column_weight) |weight| minimum[0] + weight * extra else @max(minimum[0], width - 164);
+ const name = @max(minimum[0], width - 164);
return .{ name, width - name, 0, 0, 0 };
}
- if (self.column_weights) |weights| {
- const minimum = columnMinimums(width);
- const extra = @max(0, width - columnMinimumTotal(minimum));
- var widths: [5]f64 = undefined;
- for (weights, 0..) |weight, i| widths[i] = minimum[i] + weight * extra;
- return widths;
- }
+ if (self.column_widths) |widths| return widths;
const minimum = columnMinimums(width);
const detail = @max(minimum[1], @min(110, width * 0.14));
const modified = @max(minimum[3], @min(160, width * 0.20));
@@ -2256,13 +2320,14 @@ pub const App = struct {
fn listColumn(self: *App, column: usize) header.Rect {
const widths = self.listWidths();
- var x: f64 = @floatFromInt(self.sidebarWidth() + 20);
+ var x: f64 = @as(f64, @floatFromInt(self.sidebarWidth() + 20)) - self.horizontalOffset();
for (widths[0..column]) |width| x += width;
return .{ .x = x, .y = @floatFromInt(self.contentTop()), .w = widths[column], .h = 30 };
}
fn columnBoundary(self: *App, x: f64, y: f64) ?usize {
if (!self.list_view or self.dialog != null or self.menu != null) return null;
+ if (x < @as(f64, @floatFromInt(self.sidebarWidth())) or x >= @as(f64, @floatFromInt(self.w - self.scrollbarGutter()))) return null;
for (0..self.columnLabels().len - 1) |i| {
const rect = self.listColumn(i);
if (y >= rect.y and y < rect.y + rect.h and @abs(x - (rect.x + rect.w)) <= 4) return i;
@@ -2273,26 +2338,12 @@ pub const App = struct {
fn resizeColumn(self: *App, x: f64) void {
const drag = self.column_resize orelse return;
var widths = drag.widths;
- var total: f64 = 0;
- for (widths) |width| total += width;
- if (self.repository() != null) {
- const minimum = gitColumnMinimums(total);
- const extra = total - minimum[0] - minimum[1];
- if (extra <= 0) return;
- const delta = std.math.clamp(x - drag.x, minimum[0] - widths[0], widths[1] - minimum[1]);
- self.git_column_weight = (widths[0] + delta - minimum[0]) / extra;
- self.invalidate();
- return;
- }
- const minimum = columnMinimums(total);
- const extra = total - columnMinimumTotal(minimum);
- if (extra <= 0) return;
- const delta = std.math.clamp(x - drag.x, minimum[drag.column] - widths[drag.column], widths[drag.column + 1] - minimum[drag.column + 1]);
- widths[drag.column] += delta;
- widths[drag.column + 1] -= delta;
- var weights: [5]f64 = undefined;
- for (widths, 0..) |width, i| weights[i] = (width - minimum[i]) / extra;
- self.column_weights = weights;
+ const minimum: f64 = if (self.repository() != null)
+ (if (drag.column == 0) 96 else 64)
+ else if (drag.column == 0) 64 else 40;
+ widths[drag.column] = @max(minimum, widths[drag.column] + x - drag.x);
+ if (self.repository() != null) self.git_column_widths = widths else self.column_widths = widths;
+ self.clampScroll();
self.invalidate();
}
@@ -2564,6 +2615,10 @@ pub const App = struct {
}
fn renderColumns(self: *App, cr: *c.cairo_t) void {
if (!self.list_view) return;
+ c.cairo_save(cr);
+ defer c.cairo_restore(cr);
+ c.cairo_rectangle(cr, @floatFromInt(self.sidebarWidth()), @floatFromInt(self.contentTop()), @floatFromInt(self.w - self.sidebarWidth() - self.scrollbarGutter()), 30);
+ c.cairo_clip(cr);
setSource(cr, ui_theme.global.app_bar);
c.cairo_rectangle(cr, @floatFromInt(self.sidebarWidth()), @floatFromInt(self.contentTop()), @floatFromInt(self.w - self.sidebarWidth()), 30);
c.cairo_fill(cr);
@@ -2621,6 +2676,10 @@ pub const App = struct {
return recent.isLocation(self.history.current);
}
+ fn recentAvailable(self: *const App) bool {
+ return if (self.chooser) |opts| opts.mode == .open else true;
+ }
+
fn effectiveSort(self: *const App) Sort {
return if (self.isRecent()) self.recent_sort_mode else self.sort_mode;
}
@@ -2686,7 +2745,7 @@ pub const App = struct {
fn placeVisible(self: *App, index: usize) bool {
return switch (self.rowKind(index)) {
- .builtin => if (index == 2 and self.chooser != null) false else !placePinnable(index) or self.unpinned_places & (@as(u8, 1) << @as(u3, @intCast(index - places_start))) == 0,
+ .builtin => if (index == 2 and !self.recentAvailable()) false else !placePinnable(index) or self.unpinned_places & (@as(u8, 1) << @as(u3, @intCast(index - places_start))) == 0,
.pin => true,
.device => |k| k < self.device_list.items.len,
};
@@ -2720,6 +2779,36 @@ pub const App = struct {
self.focus = .file_view;
}
+ fn openPlaceWindow(self: *App, index: usize) void {
+ if (self.chooser != null) return;
+ var buf: [4096]u8 = undefined;
+ const path = if (self.deviceAt(index)) |volume|
+ volume.mount orelse return
+ else
+ self.placePath(index, &buf) orelse return;
+ if (index == 1) std.Io.Dir.cwd().createDirPath(self.io, path) catch {
+ self.setStatusNotice("Could not open Trash", true);
+ return;
+ };
+ if (!recent.isLocation(path) and pins_mod.kindOf(path) != .dir) {
+ self.setStatusNotice("Could not open folder", true);
+ return;
+ }
+ var exe: [4096]u8 = undefined;
+ const n = c.readlink("/proc/self/exe", &exe, exe.len);
+ const executable: []const u8 = if (n > 0 and n < exe.len) exe[0..@intCast(n)] else "rediwm-files";
+ var child = std.process.spawn(self.io, .{
+ .argv = &.{ executable, path },
+ }) catch {
+ self.setStatusNotice("Could not open new window", true);
+ return;
+ };
+ self.children.add(self.allocator, child.id.?) catch {
+ child.kill(self.io);
+ self.setStatusNotice("Could not open new window", true);
+ };
+ }
+
/// A click on a pin: a folder is browsed, a file opened as a double-click
/// would (a file chooser browses the folder holding it instead).
fn openPin(self: *App, j: usize) void {
@@ -2839,7 +2928,7 @@ pub const App = struct {
if (self.chooser != null or self.dialog != null or self.menu != null or self.history.archive_len > 0) return null;
if (self.job_state == .running or self.job_state == .waiting_conflict) return null;
if (x < @as(f64, @floatFromInt(self.sidebarWidth())) or x >= @as(f64, @floatFromInt(self.w - self.scrollbarGutter())) or
- y < @as(f64, @floatFromInt(self.viewTop())) or y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) return null;
+ y < @as(f64, @floatFromInt(self.viewTop())) or y >= @as(f64, @floatFromInt(self.contentBottom()))) return null;
if (self.itemAt(x, y)) |idx| {
const item = self.items.items[idx];
if (!item.is_dir or item.missing or item.is_broken) return null;
@@ -3144,9 +3233,32 @@ pub const App = struct {
return scrollbar.Geometry.compute(.vertical, track, viewport, @floatFromInt(self.sidebarExtent() - self.contentTop()), @floatFromInt(self.sidebar_scroll));
}
+ fn maxHorizontalScroll(self: *App) f64 {
+ if (!self.list_view) return 0;
+ var total: f64 = 0;
+ for (self.listWidths()) |width| total += width;
+ const overflow = total - @as(f64, @floatFromInt(self.cellWidth() - 20));
+ return if (overflow > 0.001) overflow else 0;
+ }
+
+ fn horizontalOffset(self: *App) f64 {
+ return std.math.clamp(self.scroll_x, 0, self.maxHorizontalScroll());
+ }
+
+ fn contentBottom(self: *App) i32 {
+ return self.h - self.footerHeight() - (if (self.maxHorizontalScroll() > 0) self.scrollbarGutter() else @as(i32, 0));
+ }
+
+ fn horizontalScrollbar(self: *App) ?scrollbar.Geometry {
+ if (self.maxHorizontalScroll() <= 0) return null;
+ const viewport: f32 = @floatFromInt(self.w - self.sidebarWidth() - self.scrollbarGutter());
+ const track: scrollbar.Rect = .{ .x = @floatFromInt(self.sidebarWidth()), .y = @floatFromInt(self.contentBottom()), .w = viewport, .h = @floatFromInt(self.scrollbarGutter()) };
+ return scrollbar.Geometry.compute(.horizontal, track, viewport, viewport + @as(f32, @floatCast(self.maxHorizontalScroll())), @floatCast(self.horizontalOffset()));
+ }
+
/// The file view's bar, along the window's right edge below the header.
fn scrollbarGeometry(self: *App) ?scrollbar.Geometry {
- const viewport: f32 = @floatFromInt(@max(0, self.h - self.viewTop() - self.footerHeight()));
+ const viewport: f32 = @floatFromInt(@max(0, self.contentBottom() - self.viewTop()));
const gutter: f32 = @floatFromInt(self.scrollbarGutter());
const track: scrollbar.Rect = .{ .x = @as(f32, @floatFromInt(self.w)) - gutter, .y = @floatFromInt(self.viewTop()), .w = gutter, .h = viewport };
return scrollbar.Geometry.compute(.vertical, track, viewport, @floatFromInt(self.contentHeight()), @floatFromInt(self.scroll_y));
@@ -3407,13 +3519,14 @@ pub const App = struct {
}
fn clampScroll(self: *App) void {
+ self.scroll_x = self.horizontalOffset();
const max_scroll = self.maxScroll();
self.scroll_y = std.math.clamp(self.scroll_y, 0, max_scroll);
}
fn maxScroll(self: *App) i32 {
const total_h = self.contentHeight();
- const viewport_h = self.h - self.viewTop() - self.footerHeight();
+ const viewport_h = self.contentBottom() - self.viewTop();
return @max(0, total_h - viewport_h);
}
@@ -3421,7 +3534,7 @@ pub const App = struct {
const row = @divTrunc(@as(i32, @intCast(idx)), self.columns());
const row_top = if (row == 0) 0 else self.itemInset() + row * self.rowHeight();
const row_bottom = self.itemInset() + row * self.rowHeight() + self.cardHeight();
- const viewport_h = self.h - self.viewTop() - self.footerHeight();
+ const viewport_h = self.contentBottom() - self.viewTop();
if (row_top < self.scroll_y) {
self.scroll_y = row_top;
@@ -3769,6 +3882,7 @@ pub const App = struct {
return 0;
}
if (self.menu != null) return 100 + (self.menuHit(x, y) orelse 99);
+ if (self.sidebar_resize != null or self.overSidebarDivider(x, y)) return 0;
if (self.chooser) |opts| {
if (y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) {
for (0..4 + opts.choices.len) |i| {
@@ -3778,7 +3892,7 @@ pub const App = struct {
}
}
if (header.hit(self.w, self.inRepository(), x, y)) |action| return 200 + @as(usize, @intFromEnum(action));
- if (self.list_view) {
+ if (self.list_view and x >= @as(f64, @floatFromInt(self.sidebarWidth())) and x < @as(f64, @floatFromInt(self.w - self.scrollbarGutter()))) {
for (self.columnLabels(), 0..) |_, i| {
if (i < 4 and self.listColumn(i).contains(x, y)) return 400 + i;
}
@@ -3814,6 +3928,20 @@ pub const App = struct {
}
pub fn handleMotion(self: *App, x: f64, y: f64) void {
+ if (self.sidebar_resize) |drag| {
+ self.mouse_x = x;
+ self.mouse_y = y;
+ const width = drag.widthAt(x, 160, @divTrunc(self.w, 2));
+ if (width != self.sidebarWidth()) {
+ self.sidebar_requested = width;
+ self.syncSidebarWidth();
+ self.clampScroll();
+ self.clampSidebarScroll();
+ self.invalidate();
+ }
+ return;
+ }
+ if (self.overSidebarDivider(self.mouse_x, self.mouse_y) != self.overSidebarDivider(x, y)) self.damageSidebarDivider();
if (self.dialog) |*dlg| {
const moved = switch (dlg.kind) {
.properties => dlg.properties.?.motion(self.w, self.h, x, y),
@@ -3867,6 +3995,12 @@ pub const App = struct {
self.invalidate();
}
}
+ if (self.horizontal_drag.active) {
+ if (self.horizontalScrollbar()) |bar| {
+ self.scroll_x = self.horizontal_drag.offsetAt(bar, @floatCast(x), @floatCast(y));
+ self.invalidate();
+ }
+ }
}
pub fn cancelDrag(self: *App) void {
@@ -3876,6 +4010,9 @@ pub const App = struct {
if (dlg.applications) |*apps| apps.placement.grab = null;
}
self.column_resize = null;
+ if (self.sidebar_resize != null) self.damageSidebarDivider();
+ self.sidebar_resize = null;
+ self.horizontal_drag.end();
if (self.selection_band != null) self.invalidate();
self.selection_band = null;
self.drag_origin = null;
@@ -3887,7 +4024,7 @@ pub const App = struct {
fn bandRect(self: *App) header.Rect {
const band = self.selection_band.?;
const x = std.math.clamp(self.mouse_x, @as(f64, @floatFromInt(self.sidebarWidth())), @as(f64, @floatFromInt(self.w - self.scrollbarGutter())));
- const y = std.math.clamp(self.mouse_y, @as(f64, @floatFromInt(self.viewTop())), @as(f64, @floatFromInt(self.h - self.footerHeight()))) + @as(f64, @floatFromInt(self.scroll_y));
+ const y = std.math.clamp(self.mouse_y, @as(f64, @floatFromInt(self.viewTop())), @as(f64, @floatFromInt(self.contentBottom()))) + @as(f64, @floatFromInt(self.scroll_y));
return .{ .x = @min(band.x, x), .y = @min(band.y, y), .w = @abs(x - band.x), .h = @abs(y - band.y) };
}
@@ -3952,6 +4089,10 @@ pub const App = struct {
}
pub fn handleWheel(self: *App, delta_px: f64, now: i64) void {
+ if (self.shift and self.dialog == null and self.mouse_x >= @as(f64, @floatFromInt(self.sidebarWidth()))) {
+ self.handleHorizontalScroll(delta_px);
+ return;
+ }
if (self.dialog) |*dlg| {
if (dlg.properties) |*props| {
props.wheel(delta_px, self.w, self.h);
@@ -3994,6 +4135,10 @@ pub const App = struct {
}
pub fn handleScroll(self: *App, delta_px: f64) void {
+ if (self.shift and self.dialog == null and self.mouse_x >= @as(f64, @floatFromInt(self.sidebarWidth()))) {
+ self.handleHorizontalScroll(delta_px);
+ return;
+ }
if (self.dialog != null) {
self.handleWheel(delta_px, nowMs());
return;
@@ -4012,6 +4157,16 @@ pub const App = struct {
self.invalidate();
}
+ pub fn handleHorizontalScroll(self: *App, delta_px: f64) void {
+ if (delta_px == 0 or self.dialog != null or self.mouse_x < @as(f64, @floatFromInt(self.sidebarWidth()))) return;
+ self.cancelWheel();
+ self.menu = null;
+ const next = std.math.clamp(self.horizontalOffset() + delta_px, 0, self.maxHorizontalScroll());
+ if (next == self.scroll_x) return;
+ self.scroll_x = next;
+ self.invalidate();
+ }
+
pub fn handleButton(self: *App, button: u32, pressed: bool) void {
// Mice report side buttons either as SIDE/EXTRA or BACK/FORWARD.
if (button == 0x113 or button == 0x116 or button == 0x114 or button == 0x115) {
@@ -4066,6 +4221,14 @@ pub const App = struct {
const x = self.mouse_x;
const y = self.mouse_y;
if (button == 0x110) {
+ if (self.overSidebarDivider(x, y)) {
+ self.sidebar_resize = .{ .origin = x, .width = self.sidebarWidth() };
+ self.sidebar_requested = self.sidebarWidth();
+ self.syncSidebarWidth();
+ self.last_click_index = null;
+ self.damageSidebarDivider();
+ return;
+ }
if (self.columnBoundary(x, y)) |column| {
self.column_resize = .{ .column = column, .x = x, .widths = self.listWidths() };
self.last_click_index = null;
@@ -4264,6 +4427,20 @@ pub const App = struct {
}
}
+ if (self.horizontalScrollbar()) |bar| {
+ if (bar.track.contains(@floatCast(x), @floatCast(y))) {
+ if (button == 0x110) {
+ if (scrollbar.press(bar, @floatCast(x), @floatCast(y), @floatCast(self.horizontalOffset()))) |action| switch (action) {
+ .grab => self.horizontal_drag.begin(bar, @floatCast(x), @floatCast(y), @floatCast(self.horizontalOffset())),
+ .page => |offset| {
+ self.scroll_x = offset;
+ self.invalidate();
+ },
+ };
+ }
+ return;
+ }
+ }
// Use the same scrollbar gutter for input and content layout.
if (x >= @as(f64, @floatFromInt(self.w - self.scrollbarGutter())) and y >= @as(f64, @floatFromInt(self.contentTop())) and y < @as(f64, @floatFromInt(self.h - self.footerHeight()))) {
if (self.scrollbarGeometry()) |bar| {
@@ -4281,7 +4458,7 @@ pub const App = struct {
}
// File view area
- if (y >= @as(f64, @floatFromInt(self.contentTop())) and y < @as(f64, @floatFromInt(self.h - self.footerHeight())) and x < @as(f64, @floatFromInt(self.w - self.scrollbarGutter()))) {
+ if (y >= @as(f64, @floatFromInt(self.contentTop())) and y < @as(f64, @floatFromInt(self.contentBottom())) and x < @as(f64, @floatFromInt(self.w - self.scrollbarGutter()))) {
self.focus = .file_view;
if (self.itemAt(x, y)) |idx| {
if (button == 0x110) {
@@ -4546,12 +4723,12 @@ pub const App = struct {
const last_idx = self.items.items.len - 1;
self.selectIndex(last_idx);
} else if (sym == c.XKB_KEY_Page_Down) {
- const page_rows = @max(1, @divTrunc(self.h - self.viewTop() - self.footerHeight(), self.rowHeight())) * self.columns();
+ const page_rows = @max(1, @divTrunc(self.contentBottom() - self.viewTop(), self.rowHeight())) * self.columns();
const cur = self.focused_index orelse 0;
const new_idx = @min(self.items.items.len - 1, cur + @as(usize, @intCast(@max(1, page_rows))));
self.selectIndex(new_idx);
} else if (sym == c.XKB_KEY_Page_Up) {
- const page_rows = @max(1, @divTrunc(self.h - self.viewTop() - self.footerHeight(), self.rowHeight())) * self.columns();
+ const page_rows = @max(1, @divTrunc(self.contentBottom() - self.viewTop(), self.rowHeight())) * self.columns();
const cur = self.focused_index orelse 0;
const page_u = @as(usize, @intCast(@max(1, page_rows)));
const new_idx = if (cur > page_u) cur - page_u else 0;
@@ -4746,7 +4923,7 @@ pub const App = struct {
else => false,
},
.background => row == 2,
- .sidebar => row == self.menuLabels().len - 1,
+ .sidebar => self.placeActions()[row] == .properties,
else => false,
};
}
@@ -4839,6 +5016,28 @@ pub const App = struct {
return &.{ .open, .cut, .copy, .paste, .rename, .trash, .properties };
}
+ fn placeActions(self: *App) []const PlaceAction {
+ const new_window = self.chooser == null;
+ return switch (self.rowKind(self.menu_place)) {
+ .builtin => |index| switch (index) {
+ 1 => if (new_window) &.{ .open, .open_window, .empty_trash, .properties } else &.{ .open, .empty_trash, .properties },
+ 2 => if (new_window) &.{ .open, .open_window } else &.{.open},
+ else => if (placePinnable(index))
+ (if (new_window) &.{ .open, .open_window, .unpin, .properties } else &.{ .open, .unpin, .properties })
+ else
+ (if (new_window) &.{ .open, .open_window, .properties } else &.{ .open, .properties }),
+ },
+ .pin => |j| if (new_window and self.pins.items.items[j].kind == .dir)
+ &.{ .open, .open_window, .remove_pin, .properties }
+ else
+ &.{ .open, .remove_pin, .properties },
+ .device => if (self.deviceAt(self.menu_place)) |volume|
+ (if (volume.mount == null) &.{.mount} else if (new_window) &.{ .open, .open_window, .eject } else &.{ .open, .eject })
+ else
+ &.{},
+ };
+ }
+
fn menuLabels(self: *App) []const []const u8 {
return switch (self.menu orelse return &.{}) {
.new => &.{ "New Folder", "New File" },
@@ -4852,16 +5051,11 @@ pub const App = struct {
for (actions, 0..) |action, i| self.file_menu_labels[i] = action.label();
break :blk self.file_menu_labels[0..actions.len];
},
- .sidebar => if (self.menu_place == 2) &.{"Open"} else if (placePinnable(self.menu_place))
- &.{ "Open", "Unpin", "Properties" }
- else switch (self.rowKind(self.menu_place)) {
- .pin => &.{ "Open", "Remove from Places", "Properties" },
- else => &.{ "Open", "Properties" },
+ .sidebar, .device => blk: {
+ const actions = self.placeActions();
+ for (actions, 0..) |action, i| self.place_menu_labels[i] = action.label();
+ break :blk self.place_menu_labels[0..actions.len];
},
- .device => if (self.deviceAt(self.menu_place)) |volume|
- (if (volume.mount != null) &.{ "Open", "Eject" } else &.{"Mount"})
- else
- &.{},
.background => if (self.history.archive_len > 0 or self.isRecent()) &.{"Refresh"} else &.{ "New Folder", "New File", "Paste", "Refresh" },
.chooser_filter => self.chooser_filter_labels.items,
};
@@ -4886,28 +5080,29 @@ pub const App = struct {
fn runMenu(self: *App, row: usize) void {
const kind = self.menu orelse return;
- const properties_row = self.menuLabels().len - 1;
+ const place_action: ?PlaceAction = if ((kind == .sidebar or kind == .device) and row < self.placeActions().len) self.placeActions()[row] else null;
const file_action: ?FileAction = if (kind == .file and row < self.fileActions().len) self.fileActions()[row] else null;
self.menu = null;
switch (kind) {
- .sidebar => {
- if (row == 0) {
- self.openPlace(self.menu_place);
- } else if (row == 1 and placePinnable(self.menu_place)) {
+ .sidebar, .device => if (place_action) |action| switch (action) {
+ .open => self.openPlace(self.menu_place),
+ .open_window => self.openPlaceWindow(self.menu_place),
+ .empty_trash => self.openEmptyTrashDialog(),
+ .unpin => {
self.unpinned_places |= @as(u8, 1) << @as(u3, @intCast(self.menu_place - places_start));
self.sidebar_scroll = std.math.clamp(self.sidebar_scroll, 0, @max(0, self.sidebarExtent() - (self.h - self.footerHeight())));
self.nav_hover = .{};
self.savePreferences();
- } else if (row == 1 and self.pinIndex(self.menu_place) != null) {
+ },
+ .remove_pin => {
self.removePin(self.pinIndex(self.menu_place).?);
- } else if (row == properties_row) {
+ },
+ .properties => {
var buf: [4096]u8 = undefined;
if (self.placePath(self.menu_place, &buf)) |path| self.openProperties(path, null);
- }
- },
- .device => if (self.deviceAt(self.menu_place) != null) {
- const k = self.menu_place - self.deviceBase();
- if (self.device_list.items[k].mount == null or row == 0) self.activateDevice(k) else self.ejectDevice(k);
+ },
+ .mount => self.activateDevice(self.menu_place - self.deviceBase()),
+ .eject => self.ejectDevice(self.menu_place - self.deviceBase()),
},
.chooser_filter => {
if (row < self.chooser.?.filters.len) self.chooser.?.filter_index = row;
@@ -5099,9 +5294,9 @@ pub const App = struct {
self.renderSidebarScrollbar(cr);
// 3. Content Area (Files View)
- const viewport_h = self.h - self.viewTop() - self.footerHeight();
+ const viewport_h = self.contentBottom() - self.viewTop();
c.cairo_save(cr);
- c.cairo_rectangle(cr, @floatFromInt(self.sidebarWidth()), @floatFromInt(self.viewTop()), w_f - @as(f64, @floatFromInt(self.sidebarWidth())), @as(f64, @floatFromInt(viewport_h)));
+ c.cairo_rectangle(cr, @floatFromInt(self.sidebarWidth()), @floatFromInt(self.viewTop()), w_f - @as(f64, @floatFromInt(self.sidebarWidth() + self.scrollbarGutter())), @as(f64, @floatFromInt(viewport_h)));
c.cairo_clip(cr);
if (self.list_view) {
@@ -5133,6 +5328,10 @@ pub const App = struct {
self.renderColumns(cr);
+ if (self.sidebarDivider()) |divider| {
+ shell_ui.drawSplitter(cr, divider, self.sidebar_resize != null or self.overSidebarDivider(self.mouse_x, self.mouse_y));
+ }
+
// 4. Scrollbar
self.renderScrollbar(cr);
@@ -5190,12 +5389,14 @@ pub const App = struct {
}
pub fn pointerCursor(self: *App, x: f64, y: f64) [*:0]const u8 {
+ if (self.sidebar_resize != null) return "col-resize";
if (self.text_dragging) return "text";
- if (self.menu != null or self.selection_band != null or self.drag_origin != null or self.scroll_drag.active or self.sidebar_scroll_drag.active) return "default";
+ if (self.menu != null or self.selection_band != null or self.drag_origin != null or self.scroll_drag.active or self.sidebar_scroll_drag.active or self.horizontal_drag.active) return "default";
if (self.dialog != null) {
return if (self.activeEditor() != null and self.editorRect().contains(x, y)) "text" else "default";
}
if (self.column_resize != null or self.columnBoundary(x, y) != null) return "col-resize";
+ if (self.overSidebarDivider(x, y)) return "col-resize";
if (self.chooser != null and self.chooserRect(0).contains(x, y)) return "text";
if (self.focus != .location_bar and !self.search_visible and header.field(self.w).contains(x, y)) return "pointer";
return if (header.field(self.w).contains(x, y)) "text" else "default";
@@ -5394,7 +5595,7 @@ pub const App = struct {
if (cut) c.cairo_push_group(cr);
const icon = self.itemIconRect(index);
self.drawItemIcon(cr, item, icon.x, icon.y, icon.w);
- const label_x = x + (if (self.list_view) @as(f64, 42) else 26);
+ const label_x = x - self.horizontalOffset() + (if (self.list_view) @as(f64, 42) else 26);
setSource(cr, ui_theme.global.window_fg);
const name_width = if (self.list_view) self.listColumn(0).w - 46 else width - 42;
// A path that does not fit loses its head, so the file's own name stays readable.
@@ -5501,7 +5702,7 @@ pub const App = struct {
const cols = self.columns();
const size: f64 = if (self.list_view) 24 else 48;
return .{
- .x = @as(f64, @floatFromInt(self.sidebarWidth() + 20 + @mod(index, cols) * self.cellWidth())) + (if (self.list_view) @as(f64, 12) else 26),
+ .x = @as(f64, @floatFromInt(self.sidebarWidth() + 20 + @mod(index, cols) * self.cellWidth())) + (if (self.list_view) @as(f64, 12) else 26) - self.horizontalOffset(),
.y = @as(f64, @floatFromInt(self.viewTop() + self.itemInset() + @divTrunc(index, cols) * self.rowHeight() - self.scroll_y)) + (if (self.compactList()) @as(f64, 3) else if (self.list_view) @as(f64, 6) else 20),
.w = size,
.h = size,
@@ -5550,7 +5751,7 @@ pub const App = struct {
if (!self.thumbs_enabled) return;
const cols = self.columns();
const row_h = self.rowHeight();
- const viewport_h = @max(0, self.h - self.viewTop() - self.footerHeight());
+ const viewport_h = @max(0, self.contentBottom() - self.viewTop());
const row0 = @divTrunc(self.scroll_y, row_h);
const row1 = @divTrunc(self.scroll_y + viewport_h, row_h);
const request: ThumbRequest = .{ .revision = self.view_revision, .row0 = row0, .row1 = row1, .cols = cols };
@@ -5577,7 +5778,7 @@ pub const App = struct {
if (self.thumb_arrived.items.len == 0) return;
const cols = self.columns();
const row_h = self.rowHeight();
- const viewport_h = @max(0, self.h - self.viewTop() - self.footerHeight());
+ const viewport_h = @max(0, self.contentBottom() - self.viewTop());
const first = @divTrunc(self.scroll_y, row_h) * cols;
const last = @min(@as(i32, @intCast(self.items.items.len)), (@divTrunc(self.scroll_y + viewport_h, row_h) + 1) * cols);
var index = first;
@@ -5734,7 +5935,7 @@ pub const App = struct {
const idle = self.menu == null and self.dialog == null;
const hovered = if (bar) |b| idle and b.overThumb(@floatCast(self.mouse_x), @floatCast(self.mouse_y)) else false;
if (self.scroll_appearance.step(now, self.scroll_y != self.scroll_observed, hovered, self.scroll_drag.active, bar != null)) {
- const viewport: f64 = @floatFromInt(@max(0, self.h - self.viewTop() - self.footerHeight()));
+ const viewport: f64 = @floatFromInt(@max(0, self.contentBottom() - self.viewTop()));
self.addDamage(.{ .x = @floatFromInt(self.w - self.scrollbarGutter()), .y = @floatFromInt(self.viewTop()), .w = @floatFromInt(self.scrollbarGutter()), .h = viewport });
}
self.scroll_observed = self.scroll_y;
@@ -5744,6 +5945,13 @@ pub const App = struct {
if (side) |b| self.addDamage(.{ .x = b.track.x, .y = b.track.y, .w = b.track.w, .h = b.track.h });
}
self.sidebar_scroll_observed = self.sidebar_scroll;
+ const horizontal = self.horizontalScrollbar();
+ const horizontal_hovered = if (horizontal) |b| idle and b.overThumb(@floatCast(self.mouse_x), @floatCast(self.mouse_y)) else false;
+ const offset = self.horizontalOffset();
+ if (self.horizontal_appearance.step(now, offset != self.horizontal_observed, horizontal_hovered, self.horizontal_drag.active, horizontal != null)) {
+ if (horizontal) |b| self.addDamage(.{ .x = b.track.x, .y = b.track.y, .w = b.track.w, .h = b.track.h });
+ }
+ self.horizontal_observed = offset;
}
fn renderScrollEdges(self: *App, cr: *c.cairo_t, viewport_h: i32) void {
@@ -5751,7 +5959,7 @@ pub const App = struct {
const depth: f64 = @min(12, @as(f64, @floatFromInt(viewport_h)) / 2);
for ([_]bool{ true, false }) |top| {
if (if (top) self.scroll_y <= 0 else self.scroll_y >= self.maxScroll()) continue;
- const edge: f64 = @floatFromInt(if (top) self.viewTop() else self.h - self.footerHeight());
+ const edge: f64 = @floatFromInt(if (top) self.viewTop() else self.contentBottom());
const inner = edge + if (top) depth else -depth;
const gradient = c.cairo_pattern_create_linear(0, edge, 0, inner) orelse continue;
defer c.cairo_pattern_destroy(gradient);
@@ -5764,6 +5972,9 @@ pub const App = struct {
}
fn renderScrollbar(self: *App, cr: *c.cairo_t) void {
+ if (self.horizontalScrollbar()) |bar| {
+ shell_ui.drawScrollbar(cr, scrollbar.look(bar, self.horizontal_appearance, self.scrollbar_width, ui_theme.shellPalette()));
+ }
const bar = self.scrollbarGeometry() orelse return;
shell_ui.drawScrollbar(cr, scrollbar.look(bar, self.scroll_appearance, self.scrollbar_width, ui_theme.shellPalette()));
}
@@ -6311,40 +6522,6 @@ test "history restores names and scroll while tolerating removed items" {
try std.testing.expectEqual(@as(?usize, 12), app.selection_anchor);
}
-test "stationary visual hover does no paint work and sidebar can reach bottom" {
- var app = try testApp();
- defer app.deinit();
- try testItems(&app, 12);
- app.handleMotion(250, 160);
- app.dirty = false;
- app.handleMotion(260, 170);
- try std.testing.expect(!app.dirty);
- app.handleMotion(490, 160);
- try std.testing.expect(app.dirty);
- app.h = 240;
- app.handleMotion(70, 175);
- app.handleScroll(800);
- try std.testing.expect(app.sidebar_scroll > 0);
- try std.testing.expect(app.placeY(App.pin_base - 1) + 30 <= app.h - 26);
- app.list_view = true;
- app.w = 360;
- for (App.column_labels, 0..) |_, i| {
- const rect = app.listColumn(i);
- try std.testing.expect(rect.x >= 0 and rect.x + rect.w <= 360 and rect.w > 40);
- if (i == 4) {
- const previous = app.sort_mode;
- app.sortByColumn(i);
- try std.testing.expectEqual(previous, app.sort_mode);
- continue;
- }
- app.sortByColumn(i);
- try std.testing.expectEqual(i, app.sortColumn());
- const descending = app.sortDescending();
- app.sortByColumn(i);
- try std.testing.expect(descending != app.sortDescending());
- }
-}
-
test "retained hover repairs match complete Cairo rasters at scale 1 and 1.5" {
const before = anim.currentSettings();
defer anim.applySettings(before);
@@ -6828,6 +7005,63 @@ test "viewport edge shadows at top middle bottom and when content fits" {
try std.testing.expectEqual(@as(u8, 0), pixels[@as(usize, @intCast(app.viewTop())) * stride + x * 4 + 3]);
}
+test "sidebar divider resizes within limits without selecting or sorting" {
+ var app = try testApp();
+ defer app.deinit();
+ try testItems(&app, 2);
+ app.resize(960, 540);
+ app.stepLayout(0);
+ app.items.items[0].selected = true;
+ const sort = app.sort_mode;
+ const y: f64 = @floatFromInt(app.contentTop() + 15);
+ // Grab slightly off the line: starting a drag must not jump the width.
+ app.handleMotion(210, y);
+ try std.testing.expectEqualStrings("col-resize", std.mem.span(app.pointerCursor(210, y)));
+ app.handleButton(0x110, true);
+ try std.testing.expect(app.sidebar_resize != null);
+ app.handleMotion(210, y);
+ try std.testing.expectEqual(@as(i32, 208), app.sidebarWidth());
+ app.handleMotion(342, y);
+ try std.testing.expectEqual(@as(i32, 340), app.sidebarWidth());
+ app.stepLayout(1000);
+ try std.testing.expectEqual(@as(i32, 340), app.sidebarWidth());
+ app.handleMotion(10000, -50);
+ try std.testing.expectEqual(@as(i32, 480), app.sidebarWidth());
+ try std.testing.expectEqualStrings("col-resize", std.mem.span(app.pointerCursor(10000, -50)));
+ app.handleMotion(-10000, y);
+ try std.testing.expectEqual(@as(i32, 160), app.sidebarWidth());
+ app.handleMotion(342, y);
+ app.handleButton(0x110, false);
+ try std.testing.expect(app.sidebar_resize == null and app.selection_band == null and app.drag_origin == null);
+ try std.testing.expect(app.items.items[0].selected and !app.items.items[1].selected);
+ try std.testing.expectEqual(sort, app.sort_mode);
+ app.handleMotion(400, y);
+ try std.testing.expectEqual(@as(i32, 340), app.sidebarWidth());
+ // Window resizes clamp the drawn width but retain the user's preference.
+ app.resize(500, 540);
+ try std.testing.expectEqual(@as(i32, 250), app.sidebarWidth());
+ app.resize(960, 540);
+ try std.testing.expectEqual(@as(i32, 340), app.sidebarWidth());
+ app.handleMotion(340, y);
+ app.handleButton(0x110, true);
+ app.handleKey(c.XKB_KEY_Escape, "");
+ try std.testing.expect(app.sidebar_resize == null);
+ app.handleMotion(500, y);
+ try std.testing.expectEqual(@as(i32, 340), app.sidebarWidth());
+ app.openMenu(.background, 400, y);
+ try std.testing.expect(!app.overSidebarDivider(340, y));
+ app.menu = null;
+ try std.testing.expect(!app.overSidebarDivider(340, 20));
+ try std.testing.expect(!app.overSidebarDivider(340, @floatFromInt(app.h - 1)));
+ app.resize(360, 540);
+ app.stepLayout(2000);
+ app.stepLayout(3000);
+ try std.testing.expectEqual(@as(i32, 0), app.sidebarWidth());
+ try std.testing.expect(app.sidebarDivider() == null);
+ app.resize(960, 540);
+ try std.testing.expectEqual(@as(i32, 340), app.sidebarWidth());
+}
+
test "sidebar scrollbar pages, drags outside and resets on resize" {
const saved = anim.currentSettings();
defer anim.applySettings(saved);
@@ -6897,35 +7131,66 @@ test "file selection fades in and out while logical selection is immediate" {
try std.testing.expectEqual(@as(f32, 0), app.items.items[1].selection_fill.alpha);
}
-test "list column resize keeps adjacent columns bounded and does not sort" {
- var app = try testApp();
- defer app.deinit();
- app.list_view = true;
- const original = app.listWidths();
- const rect = app.listColumn(0);
- const x = rect.x + rect.w;
- const y = rect.y + 15;
- try std.testing.expectEqualStrings("col-resize", std.mem.span(app.pointerCursor(x, y)));
- app.handleMotion(x, y);
- app.handleButton(0x110, true);
- app.handleMotion(x + 25, y + 100);
- try std.testing.expectApproxEqAbs(original[0] + 25, app.listWidths()[0], 0.001);
- try std.testing.expectApproxEqAbs(original[1] - 25, app.listWidths()[1], 0.001);
- try std.testing.expectEqualStrings("col-resize", std.mem.span(app.pointerCursor(x + 25, y + 100)));
- app.handleMotion(x + 1000, y);
- try std.testing.expectApproxEqAbs(@as(f64, 40), app.listWidths()[1], 0.001);
- app.handleButton(0x110, false);
- try std.testing.expect(app.column_resize == null);
- try std.testing.expectEqual(Sort.name, app.sort_mode);
- app.w = 360;
- var total: f64 = 0;
- for (app.listWidths()) |width| {
- try std.testing.expect(width >= 40);
- total += width;
+test "list column resize pushes following columns and scrolls in Files and chooser" {
+ for ([_]bool{ false, true }) |chooser| {
+ var app = try testApp();
+ defer app.deinit();
+ if (chooser) try app.configureChooser(.{ .mode = .open });
+ app.list_view = true;
+ try testItems(&app, 20);
+ const original = app.listWidths();
+ const last = app.listColumn(4);
+ const rect = app.listColumn(3);
+ const x = rect.x + rect.w;
+ const y = rect.y + 15;
+ try std.testing.expectEqualStrings("col-resize", std.mem.span(app.pointerCursor(x, y)));
+ app.handleMotion(x, y);
+ app.handleButton(0x110, true);
+ app.handleMotion(x + 120, y + 100);
+ const widths = app.listWidths();
+ for (original, 0..) |width, i| {
+ try std.testing.expectApproxEqAbs(width + (if (i == 3) @as(f64, 120) else 0), widths[i], 0.001);
+ }
+ try std.testing.expectApproxEqAbs(last.x + 120, app.listColumn(4).x, 0.001);
+ app.handleButton(0x110, false);
+ try std.testing.expect(app.column_resize == null);
+ try std.testing.expectEqual(Sort.name, app.sort_mode);
+ const bar = app.horizontalScrollbar().?;
+ try std.testing.expectEqual(@as(?usize, null), app.itemAt(bar.track.x + 40, bar.track.y + 1));
+ try std.testing.expectEqual(@as(?[]const u8, null), app.dropDirectoryAt(bar.track.x + 40, bar.track.y + 1));
+ const thumb_x = bar.thumb.x + bar.thumb.w / 2;
+ const thumb_y = bar.thumb.y + bar.thumb.h / 2;
+ app.handleMotion(thumb_x, thumb_y);
+ app.handleButton(0x110, true);
+ try std.testing.expect(app.horizontal_drag.active);
+ app.handleMotion(@floatFromInt(app.w + 100), thumb_y);
+ try std.testing.expectApproxEqAbs(@as(f64, 120), app.horizontalOffset(), 0.001);
+ try std.testing.expectApproxEqAbs(last.x, app.listColumn(4).x, 0.001);
+ app.handleButton(0x110, false);
+ try std.testing.expect(!app.horizontal_drag.active);
+ app.shift = true;
+ app.handleWheel(-60, 1000);
+ try std.testing.expectApproxEqAbs(@as(f64, 60), app.horizontalOffset(), 0.001);
+ app.shift = false;
+ app.handleHorizontalScroll(-1000);
+ try std.testing.expectEqual(@as(f64, 0), app.horizontalOffset());
+ app.resize(360, 400);
+ try std.testing.expectEqualDeep(widths, app.listWidths());
+ try std.testing.expect(app.horizontalScrollbar() != null);
+ app.resize(1600, 600);
+ try std.testing.expect(app.horizontalScrollbar() == null);
+ try std.testing.expectEqual(@as(f64, 0), app.horizontalOffset());
+ // Shrinking clamps only the dragged column.
+ const name = app.listColumn(0);
+ app.handleMotion(name.x + name.w, name.y + 15);
+ app.handleButton(0x110, true);
+ app.handleMotion(-1000, name.y + 15);
+ app.handleButton(0x110, false);
+ try std.testing.expectEqual(@as(f64, 64), app.listWidths()[0]);
+ try std.testing.expectEqualSlices(f64, widths[1..], app.listWidths()[1..]);
+ app.list_view = false;
+ try std.testing.expect(app.horizontalScrollbar() == null);
}
- try std.testing.expectApproxEqAbs(@as(f64, @floatFromInt(app.cellWidth() - 20)), total, 0.001);
- app.list_view = false;
- try std.testing.expectEqualStrings("default", std.mem.span(app.pointerCursor(x, y)));
}
test "sidebar menus unpin only Places and close gaps without changing selection" {
@@ -6938,13 +7203,14 @@ test "sidebar menus unpin only Places and close gaps without changing selection"
app.handleMotion(70, @floatFromInt(y + 10));
app.handleButton(0x111, true);
try std.testing.expectEqual(MenuKind.sidebar, app.menu.?);
- try std.testing.expectEqualStrings("Unpin", app.menuLabels()[1]);
- try std.testing.expectEqualStrings("Properties", app.menuLabels()[2]);
- app.runMenu(2); // Properties must not alter pinned places.
+ try std.testing.expectEqualStrings("Open in New Window", app.menuLabels()[1]);
+ try std.testing.expectEqualStrings("Unpin", app.menuLabels()[2]);
+ try std.testing.expectEqualStrings("Properties", app.menuLabels()[3]);
+ app.runMenu(3); // Properties must not alter pinned places.
app.closeDialog();
try std.testing.expect(app.placeVisible(App.places_start));
app.openMenu(.sidebar, 70, @floatFromInt(y));
- app.runMenu(1);
+ app.runMenu(2);
try std.testing.expect(!app.placeVisible(App.places_start));
try std.testing.expectEqual(y, app.placeY(App.places_start + 1));
try std.testing.expectEqual(@as(?usize, App.places_start + 1), app.placeAt(70, @floatFromInt(y + 10)));
@@ -6953,21 +7219,36 @@ test "sidebar menus unpin only Places and close gaps without changing selection"
for ([_]usize{ 0, 1 }) |index| {
app.menu_place = index;
app.openMenu(.sidebar, 70, 140);
- try std.testing.expectEqual(@as(usize, 2), app.menuLabels().len);
- try std.testing.expectEqualStrings("Properties", app.menuLabels()[1]);
- app.runMenu(1);
+ try std.testing.expectEqual(@as(usize, if (index == 1) 4 else 3), app.menuLabels().len);
+ try std.testing.expectEqualStrings("Properties", app.menuLabels()[app.menuLabels().len - 1]);
+ if (index == 1) {
+ try std.testing.expectEqualStrings("Empty Trash…", app.menuLabels()[2]);
+ app.runMenu(2);
+ try std.testing.expect(app.dialog.?.deletion.empty_trash);
+ try std.testing.expect(app.dialog.?.deletion.permanent);
+ try std.testing.expectEqual(deletion.Action.none, app.dialog.?.deletion.key(c.XKB_KEY_Tab));
+ try std.testing.expectEqual(deletion.Action.confirm, app.dialog.?.deletion.key(c.XKB_KEY_Return));
+ app.deleteAction(.toggle);
+ try std.testing.expect(app.dialog.?.deletion.permanent);
+ app.deleteAction(.cancel);
+ try std.testing.expect(app.dialog == null);
+ app.openMenu(.sidebar, 70, 140);
+ }
+ app.runMenu(app.menuLabels().len - 1);
try std.testing.expect(app.placeVisible(index));
}
app.menu_place = 2;
app.openMenu(.sidebar, 70, 210);
- try std.testing.expectEqualSlices([]const u8, &.{"Open"}, app.menuLabels());
+ try std.testing.expectEqualStrings("Open", app.menuLabels()[0]);
+ try std.testing.expectEqualStrings("Open in New Window", app.menuLabels()[1]);
+ try std.testing.expectEqual(@as(usize, 0), app.menuSeparatorSpace());
app.menu = null;
try std.testing.expect(app.placeVisible(2));
try std.testing.expectEqual(app.placeY(1) + app.placeStep(), app.placeY(2));
for (App.places_start..App.pin_base) |index| {
app.menu_place = index;
app.openMenu(.sidebar, 70, 140);
- app.runMenu(1);
+ app.runMenu(2);
}
try std.testing.expectEqual(@as(u8, 0x7f), app.unpinned_places);
try std.testing.expectEqual(@as(?usize, null), app.placeAt(70, @floatFromInt(y + 10)));
@@ -7037,10 +7318,20 @@ test "pins sit after Projects, take drops by gap and keep the rows in drawn orde
// Only a pin offers removal, which closes the gap again.
app.menu_place = App.pin_base + 1;
app.openMenu(.sidebar, 70, 140);
- try std.testing.expectEqualStrings("Remove from Places", app.menuLabels()[1]);
- app.runMenu(1);
+ try std.testing.expectEqualStrings("Open in New Window", app.menuLabels()[1]);
+ try std.testing.expectEqualStrings("Remove from Places", app.menuLabels()[2]);
+ app.runMenu(2);
try std.testing.expectEqual(@as(usize, 2), app.pins.items.items.len);
try std.testing.expectEqualStrings("null", app.pins.items.items[1].name());
+ app.menu = .sidebar;
+ try std.testing.expectEqualStrings("Remove from Places", app.menuLabels()[1]); // File pins keep their file actions.
+ app.pins.items.items[1].kind = .missing;
+ try std.testing.expectEqualStrings("Remove from Places", app.menuLabels()[1]);
+ app.chooser = .{ .mode = .open };
+ app.menu_place = App.pin_base;
+ try std.testing.expectEqualStrings("Remove from Places", app.menuLabels()[1]);
+ app.menu_place = 0;
+ try std.testing.expectEqualStrings("Properties", app.menuLabels()[1]);
try std.testing.expectEqual(places_bottom + 2 * step, app.placeY(App.pin_base + 1));
}
@@ -7078,7 +7369,8 @@ test "Sidebar lists devices under Places; only mounted ones eject" {
app.menu = .device;
app.menu_place = mounted;
- try std.testing.expectEqualStrings("Eject", app.menuLabels()[1]);
+ try std.testing.expectEqualStrings("Open in New Window", app.menuLabels()[1]);
+ try std.testing.expectEqualStrings("Eject", app.menuLabels()[2]);
app.menu_place = unmounted;
try std.testing.expectEqual(@as(usize, 1), app.menuLabels().len);
try std.testing.expectEqualStrings("Mount", app.menuLabels()[0]);
@@ -7167,17 +7459,18 @@ test "Git layout has two columns, scrollable sidebar and display-only deleted ro
app.handleMotion(boundary_x, boundary_y);
app.handleButton(0x110, true);
app.handleMotion(boundary_x - 40, boundary_y + 100);
- try std.testing.expectApproxEqAbs(@as(f64, 204), app.listColumn(1).w, 0.001);
+ try std.testing.expectApproxEqAbs(@as(f64, 164), app.listColumn(1).w, 0.001);
try std.testing.expectEqualStrings("col-resize", std.mem.span(app.pointerCursor(boundary_x - 40, boundary_y + 100)));
app.handleMotion(boundary_x + 1000, boundary_y);
- try std.testing.expectApproxEqAbs(@as(f64, 64), app.listColumn(1).w, 0.001);
+ try std.testing.expectApproxEqAbs(@as(f64, 164), app.listColumn(1).w, 0.001);
app.handleButton(0x110, false);
try std.testing.expect(app.column_resize == null);
try std.testing.expectEqual(sort, app.sort_mode);
app.resize(360, 300);
const widths = app.listWidths();
try std.testing.expect(widths[0] >= 96 and widths[1] >= 64);
- try std.testing.expectApproxEqAbs(@as(f64, @floatFromInt(app.cellWidth() - 20)), widths[0] + widths[1], 0.001);
+ try std.testing.expect(widths[0] + widths[1] > @as(f64, @floatFromInt(app.cellWidth() - 20)));
+ try std.testing.expect(app.horizontalScrollbar() != null);
app.resize(960, 540);
app.sortByColumn(1);
try std.testing.expectEqual(sort, app.sort_mode);
diff --git a/src/files/main.zig b/src/files/main.zig
index eb21cd9..4120527 100644
--- a/src/files/main.zig
+++ b/src/files/main.zig
@@ -80,6 +80,8 @@ pub const Client = struct {
drag_icon: ?DragIcon = null,
axis_source: wl.Pointer.AxisSource = .wheel,
axis_delta: f64 = 0,
+ horizontal_delta: f64 = 0,
+ horizontal_notches: ?f64 = null,
axis_notches: ?f64 = null,
clipboard_revision: usize = 0,
offers: std.ArrayList(*Offer) = .empty,
@@ -177,12 +179,13 @@ pub const Client = struct {
/// the poll, including file-operation state changes. Only animation and
/// known deadlines need a timeout; an idle window sleeps.
fn pollTimeout(self: *Client) c_int {
- if (self.app.wheel_glide.active() or self.app.selectionNeedsScroll() or self.app.hover_active or self.app.layout_active or self.app.scroll_appearance.active or self.app.sidebar_scroll_appearance.active) return 16;
+ if (self.app.wheel_glide.active() or self.app.selectionNeedsScroll() or self.app.hover_active or self.app.layout_active or self.app.scroll_appearance.active or self.app.sidebar_scroll_appearance.active or self.app.horizontal_appearance.active) return 16;
if (self.app.hasRunningFolderSize()) return 33;
var deadline: ?i64 = null;
if (self.app.status_notice != null) deadline = self.app.status_notice_until;
if (self.app.scanNoticeDeadline()) |at| deadline = earlier(deadline, at);
if (self.app.scroll_appearance.deadline) |at| deadline = earlier(deadline, at);
+ if (self.app.horizontal_appearance.deadline) |at| deadline = earlier(deadline, at);
if (self.app.sidebar_scroll_appearance.deadline) |at| deadline = earlier(deadline, at);
// Transfers expire once strictly past their timeout.
if (self.receiving) |receive| deadline = earlier(deadline, receive.started + transfer.timeout_ms + 1);
@@ -410,15 +413,15 @@ pub const Client = struct {
.axis => |ev| {
if (ev.axis == .vertical_scroll) {
self.axis_delta += ev.value.toDouble();
- if (self.pointer.?.getVersion() < 5) self.flushScroll();
- }
+ } else self.horizontal_delta += ev.value.toDouble();
+ if (self.pointer.?.getVersion() < 5) self.flushScroll();
},
.axis_source => |ev| self.axis_source = ev.axis_source,
.axis_discrete => |ev| {
- if (ev.axis == .vertical_scroll) self.axis_notches = (self.axis_notches orelse 0) + @as(f64, @floatFromInt(ev.discrete));
+ if (ev.axis == .vertical_scroll) self.axis_notches = (self.axis_notches orelse 0) + @as(f64, @floatFromInt(ev.discrete)) else self.horizontal_notches = (self.horizontal_notches orelse 0) + @as(f64, @floatFromInt(ev.discrete));
},
.axis_value120 => |ev| {
- if (ev.axis == .vertical_scroll) self.axis_notches = (self.axis_notches orelse 0) + @as(f64, @floatFromInt(ev.value120)) / 120.0;
+ if (ev.axis == .vertical_scroll) self.axis_notches = (self.axis_notches orelse 0) + @as(f64, @floatFromInt(ev.value120)) / 120.0 else self.horizontal_notches = (self.horizontal_notches orelse 0) + @as(f64, @floatFromInt(ev.value120)) / 120.0;
},
.frame => self.flushScroll(),
else => {},
@@ -430,9 +433,13 @@ pub const Client = struct {
const pixels_per_notch = 100.0;
const pixels = if (self.axis_notches) |n| n * pixels_per_notch else self.axis_delta * (pixels_per_notch / 15.0);
self.app.handleWheel(pixels, app_mod.nowMs());
- } else if (self.axis_delta != 0) {
- self.app.handleScroll(self.axis_delta);
+ self.app.handleHorizontalScroll(if (self.horizontal_notches) |n| n * pixels_per_notch else self.horizontal_delta * (pixels_per_notch / 15.0));
+ } else {
+ if (self.axis_delta != 0) self.app.handleScroll(self.axis_delta);
+ self.app.handleHorizontalScroll(self.horizontal_delta);
}
+ self.horizontal_delta = 0;
+ self.horizontal_notches = null;
self.axis_delta = 0;
self.axis_notches = null;
}
@@ -489,7 +496,7 @@ pub const Client = struct {
}
fn refreshCursor(self: *Client) void {
- if (self.app.column_resize != null) {
+ if (self.app.column_resize != null or self.app.sidebar_resize != null) {
self.setCursor("col-resize");
return;
}
diff --git a/src/files/ops.zig b/src/files/ops.zig
index 47b78d5..414d8a9 100644
--- a/src/files/ops.zig
+++ b/src/files/ops.zig
@@ -121,6 +121,16 @@ pub fn deleteItems(io: std.Io, paths: []const []const u8) !void {
if (result != .exited or result.exited != 0) return error.DeleteFailed;
}
+/// Let GIO remove both trashed contents and their restore metadata.
+pub fn emptyTrash(io: std.Io) !void {
+ var child = std.process.spawn(io, .{ .argv = &.{ "gio", "trash", "--empty" } }) catch |err| {
+ if (err == error.FileNotFound) return error.GioNotAvailable;
+ return error.TrashFailed;
+ };
+ const result = try child.wait(io);
+ if (result != .exited or result.exited != 0) return error.TrashFailed;
+}
+
pub fn trashItems(io: std.Io, paths: []const []const u8) !void {
if (paths.len == 0) return;
var args: std.ArrayList([]const u8) = .empty;
diff --git a/src/files_main.zig b/src/files_main.zig
index 2df94f5..6640016 100644
--- a/src/files_main.zig
+++ b/src/files_main.zig
@@ -45,6 +45,11 @@ const Target = struct {
fn resolveTarget(allocator: std.mem.Allocator, environ: std.process.Environ, target: ?[]const u8, allow_file: bool) !Target {
const home = environ.getPosix("HOME") orelse "/";
+ if (allow_file and target != null and @import("files/recent.zig").isLocation(target.?)) {
+ const path = try allocator.dupe(u8, target.?);
+ return .{ .path = path, .directory = path, .selected = null };
+ }
+
var path_to_check: []const u8 = undefined;
if (target) |t| {
if (std.mem.startsWith(u8, t, "~")) {
diff --git a/src/input/AGENTS.md b/src/input/AGENTS.md
new file mode 100644
index 0000000..c03a7c7
--- /dev/null
+++ b/src/input/AGENTS.md
@@ -0,0 +1,29 @@
+# Input
+
+* **Text input/IME** (`text_input.zig`): `syncFocus` is the only enter path.
+ IM grabs replace client delivery only (bindings, hardware keys and
+ shell/lock UI win); an IM's own virtual keyboard bypasses its grab.
+ Lock/auth reject virtual input. IPC `GetTextInput` never returns text.
+* **Layouts:** layout-zero fallback is for binding lookup only; text uses the
+ active XKB state.
+* **Shell key repeat:** one `shell_repeat` per keyboard; a new shell target
+ needs a `ShellTarget` case, a freeable panel calls `forgetShellTarget`.
+ Return, Escape, Tab and modifier chords never repeat.
+* **Pointer constraints** (`pointer_constraints.zig`): every client motion
+ path calls `clientMotion` then `sync`. Active only with pointer and keyboard
+ focus; new compositor input modes go in `motionReachesClient` or
+ `candidate`. `sendDeactivated` destroys oneshots synchronously: clear
+ `active` first.
+* **Shortcuts inhibit** gates only the switcher, screenshot shortcuts and
+ final dispatch; hardware keys, VT switching and open panels still win.
+* **Drag dodge** (`drag_dodge.zig`) slides a file manager aside through
+ `Toplevel.setDodge`, a presentation-only offset added in
+ `applyVisualTransform`. Never fold it into `x`/`y`/`move_x` (it would grow
+ the canvas, reach IPC and saved layouts, and outlive the drag). Anything
+ that stops showing a window must `clearDodge` it (`detachInput` does).
+* **Touch/tablet** use their own protocol only when
+ `directInputReachesClients()`; otherwise they emulate the pointer (send your
+ own `pointerNotifyFrame`). Touchscreens map to `output_name` or the built-in
+ panel.
+* **Lid:** a closed lid hides built-in panels only while another display is
+ on; undocked, logind owns the lid.
diff --git a/src/pdf/app.zig b/src/pdf/app.zig
index e1d7048..99fd437 100644
--- a/src/pdf/app.zig
+++ b/src/pdf/app.zig
@@ -48,15 +48,68 @@ pub const Action = enum {
next_page,
zoom_out,
zoom_in,
- fit_mode,
+ fit_width,
+ fit_page,
rotate,
open_dialog,
find_toggle,
find_prev,
find_next,
find_close,
+ print,
};
+/// Toolbar buttons left to right, shared by painting and hit testing.
+const ToolbarButton = struct { x: f64, w: f64, act: Action };
+const toolbar_buttons = [_]ToolbarButton{
+ .{ .x = 10.0, .w = 32.0, .act = .toggle_sidebar },
+ .{ .x = 52.0, .w = 32.0, .act = .prev_page },
+ .{ .x = 88.0, .w = 32.0, .act = .next_page },
+ .{ .x = 210.0, .w = 32.0, .act = .zoom_out },
+ .{ .x = 286.0, .w = 32.0, .act = .zoom_in },
+ .{ .x = 326.0, .w = 76.0, .act = .fit_width },
+ .{ .x = 406.0, .w = 70.0, .act = .fit_page },
+ .{ .x = 484.0, .w = 32.0, .act = .rotate },
+ .{ .x = 524.0, .w = 64.0, .act = .find_toggle },
+ .{ .x = 596.0, .w = 32.0, .act = .print },
+};
+const toolbar_button_y: f64 = 6.0;
+const toolbar_button_h: f64 = 32.0;
+
+/// Pages whose raster exceeds this render as square tiles of `tile_px`
+/// device pixels, of which only those in view are rendered.
+fn rasterTiled(px_w: f64, px_h: f64) bool {
+ return px_w > 2048 or px_h > 2048 or px_w * px_h > 4 * 1024 * 1024;
+}
+const tile_px: f64 = 1024.0;
+
+/// The tiles of a page raster that intersect the canvas: half-open index
+/// ranges over a grid in the raster's device pixels, the unit of
+/// `cache.TileKey` and of the worker's clip.
+const TileSpan = struct {
+ raster_w: f64,
+ raster_h: f64,
+ x0: usize = 0,
+ x1: usize = 0,
+ y0: usize = 0,
+ y1: usize = 0,
+
+ fn key(self: TileSpan, tx: usize, ty: usize) cache.TileKey {
+ const x = @as(f64, @floatFromInt(tx)) * tile_px;
+ const y = @as(f64, @floatFromInt(ty)) * tile_px;
+ return .{
+ .x = @intFromFloat(x),
+ .y = @intFromFloat(y),
+ .w = @intFromFloat(@min(tile_px, self.raster_w - x)),
+ .h = @intFromFloat(@min(tile_px, self.raster_h - y)),
+ };
+ }
+};
+
+fn tileClip(tk: cache.TileKey) layout.Rect {
+ return .{ .x = @floatFromInt(tk.x), .y = @floatFromInt(tk.y), .w = @floatFromInt(tk.w), .h = @floatFromInt(tk.h) };
+}
+
pub const Dialog = enum { none, information, password };
pub const Focus = enum { none, page_number, password, search };
@@ -162,6 +215,9 @@ pub const App = struct {
clipboard_text: ?[:0]u8 = null,
clipboard_request: bool = false,
+ /// Set by the Print button; main.zig hands it to the print helper.
+ print_request: bool = false,
+
pub fn init(initial_path: [:0]const u8, document_fd: c_int) !App {
const wkr = try worker.Worker.init(document_fd);
errdefer wkr.deinit();
@@ -342,11 +398,7 @@ pub const App = struct {
}
// Open fitted to the first page's size; refit to the real ones.
if (self.zoom_mode != .manual) self.updateEffectiveZoom();
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
- self.dirty = true;
+ self.relayout();
},
.page_rendered => |*pr| {
@@ -443,41 +495,26 @@ pub const App = struct {
for (vis_range.start_index..vis_range.end_index + 1) |i| {
if (count >= jobs.len) break;
const p = dl.pages[i];
- const p_px_w = p.logical_width * @as(f64, @floatFromInt(self.scale));
- const p_px_h = p.logical_height * @as(f64, @floatFromInt(self.scale));
-
- // Large-page tile rendering above threshold
- if (p_px_w > 2048 or p_px_h > 2048 or p_px_w * p_px_h > 4 * 1024 * 1024) {
- const tile_size = 1024.0 / @as(f64, @floatFromInt(self.scale));
- var ty: f64 = 0;
- while (ty < p.logical_height) : (ty += tile_size) {
- var tx: f64 = 0;
- while (tx < p.logical_width) : (tx += tile_size) {
- if (count >= jobs.len) break;
- const tw = @min(tile_size, p.logical_width - tx);
- const th = @min(tile_size, p.logical_height - ty);
- const tile_clip = layout.Rect{ .x = tx, .y = ty, .w = tw, .h = th };
- const tile_key = cache.TileKey{
- .x = @intFromFloat(tx),
- .y = @intFromFloat(ty),
- .w = @intFromFloat(tw),
- .h = @intFromFloat(th),
+
+ // Large pages: only the tiles in view.
+ if (self.tileSpan(cv, p)) |span| {
+ for (span.y0..span.y1) |ty| for (span.x0..span.x1) |tx| {
+ if (count >= jobs.len) break;
+ const tk = span.key(tx, ty);
+ const pk = cache.PageKey.init(self.generation, i, effective_scale, self.rotation, tk);
+ if (self.page_cache.get(pk) == null) {
+ jobs[count] = .{
+ .kind = .render_page,
+ .priority = 0,
+ .generation = self.generation,
+ .page_index = i,
+ .scale = effective_scale,
+ .rotation = self.rotation,
+ .clip = tileClip(tk),
};
- const pk = cache.PageKey.init(self.generation, i, effective_scale, self.rotation, tile_key);
- if (self.page_cache.get(pk) == null) {
- jobs[count] = .{
- .kind = .render_page,
- .priority = 0,
- .generation = self.generation,
- .page_index = i,
- .scale = effective_scale,
- .rotation = self.rotation,
- .clip = tile_clip,
- };
- count += 1;
- }
+ count += 1;
}
- }
+ };
} else {
const pk = cache.PageKey.init(self.generation, i, effective_scale, self.rotation, null);
if (self.page_cache.get(pk) == null) {
@@ -537,8 +574,9 @@ pub const App = struct {
}
}
- // 3. Nearby prefetch page (priority 2)
- if (vis_range.start_index > 0 and count < jobs.len) {
+ // 3. Nearby prefetch page (priority 2), unless it would be tiled: a
+ // whole raster of it would be large, and drawn tiles replace it.
+ if (vis_range.start_index > 0 and count < jobs.len and !self.isTiled(dl.pages[vis_range.start_index - 1])) {
const prev = vis_range.start_index - 1;
const pk = cache.PageKey.init(self.generation, prev, effective_scale, self.rotation, null);
if (self.page_cache.get(pk) == null) {
@@ -553,7 +591,7 @@ pub const App = struct {
count += 1;
}
}
- if (vis_range.end_index + 1 < dl.pages.len and count < jobs.len) {
+ if (vis_range.end_index + 1 < dl.pages.len and count < jobs.len and !self.isTiled(dl.pages[vis_range.end_index + 1])) {
const next = vis_range.end_index + 1;
const pk = cache.PageKey.init(self.generation, next, effective_scale, self.rotation, null);
if (self.page_cache.get(pk) == null) {
@@ -604,6 +642,64 @@ pub const App = struct {
);
}
+ /// Lays the pages out again after a zoom, rotation or size change and
+ /// returns to the same reading position.
+ fn relayout(self: *App) void {
+ self.recomputeLayout() catch {};
+ if (self.doc_layout) |dl| {
+ const cv_h = self.canvasRect().h;
+ const anchored = layout.scrollToAnchor(dl.pages, self.anchor, cv_h);
+ self.scroll_y = @min(anchored, @max(0.0, dl.total_height - cv_h));
+ }
+ self.dirty = true;
+ }
+
+ fn setZoomMode(self: *App, mode: ZoomMode) void {
+ self.zoom_mode = mode;
+ self.updateEffectiveZoom();
+ self.relayout();
+ }
+
+ fn zoomBy(self: *App, factor: f64) void {
+ if (self.doc_layout == null) return;
+ self.zoom_mode = .manual;
+ self.zoom = std.math.clamp(self.zoom * factor, 0.2, 5.0);
+ self.relayout();
+ }
+
+ /// Ctrl+wheel: a 15-unit wheel notch zooms 1.2x, like the buttons;
+ /// touchpads zoom smoothly in proportion.
+ pub fn handleZoomScroll(self: *App, delta: f64) void {
+ self.zoomBy(std.math.pow(f64, 1.2, -delta / 15.0));
+ }
+
+ fn isTiled(self: *const App, p: layout.PageLayout) bool {
+ const s: f64 = @floatFromInt(self.scale);
+ return rasterTiled(@ceil(p.logical_width * s), @ceil(p.logical_height * s));
+ }
+
+ /// The visible tiles of page `p`, or null when it renders whole.
+ fn tileSpan(self: *const App, cv: Rect, p: layout.PageLayout) ?TileSpan {
+ if (!self.isTiled(p)) return null;
+ const s: f64 = @floatFromInt(self.scale);
+ var span: TileSpan = .{ .raster_w = @ceil(p.logical_width * s), .raster_h = @ceil(p.logical_height * s) };
+ // The canvas in page coordinates, clamped to the page.
+ const page_x = self.pageX(cv, p);
+ const page_y = cv.y + p.y_offset - self.scroll_y;
+ const x0 = @max(0.0, cv.x - page_x) * s;
+ const x1 = @min(p.logical_width, cv.x + cv.w - page_x) * s;
+ const y0 = @max(0.0, cv.y - page_y) * s;
+ const y1 = @min(p.logical_height, cv.y + cv.h - page_y) * s;
+ if (x1 <= x0 or y1 <= y0) return span;
+ const cols = @ceil(span.raster_w / tile_px);
+ const rows = @ceil(span.raster_h / tile_px);
+ span.x0 = @intFromFloat(@floor(x0 / tile_px));
+ span.x1 = @intFromFloat(@min(cols, @ceil(x1 / tile_px)));
+ span.y0 = @intFromFloat(@floor(y0 / tile_px));
+ span.y1 = @intFromFloat(@min(rows, @ceil(y1 / tile_px)));
+ return span;
+ }
+
fn updateEffectiveZoom(self: *App) void {
// Nothing to fit before the document opens (first configure, password prompt).
if (self.page_sizes.items.len == 0) return;
@@ -657,11 +753,7 @@ pub const App = struct {
if (self.zoom_mode != .manual) {
self.updateEffectiveZoom();
}
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
- self.dirty = true;
+ self.relayout();
}
pub fn requestClose(self: *App) void {
@@ -1050,18 +1142,6 @@ pub const App = struct {
}
fn handleToolbarClick(self: *App) void {
- const tb = self.toolbarRect();
- const actions = [_]struct { x: f64, w: f64, act: Action }{
- .{ .x = 10.0, .w = 32.0, .act = .toggle_sidebar },
- .{ .x = 52.0, .w = 32.0, .act = .prev_page },
- .{ .x = 88.0, .w = 32.0, .act = .next_page },
- .{ .x = 210.0, .w = 32.0, .act = .zoom_out },
- .{ .x = 286.0, .w = 32.0, .act = .zoom_in },
- .{ .x = 326.0, .w = 84.0, .act = .fit_mode },
- .{ .x = 418.0, .w = 32.0, .act = .rotate },
- .{ .x = 458.0, .w = 64.0, .act = .find_toggle },
- };
-
// Page number editor field click: x=124..204
if (self.px >= 124.0 and self.px <= 204.0 and self.py >= 6.0 and self.py <= 38.0) {
self.focus = .page_number;
@@ -1073,13 +1153,12 @@ pub const App = struct {
return;
}
- for (actions) |item| {
- if (self.px >= item.x and self.px <= item.x + item.w and self.py >= 6.0 and self.py <= 38.0) {
+ for (toolbar_buttons) |item| {
+ if (self.px >= item.x and self.px <= item.x + item.w and self.py >= toolbar_button_y and self.py <= toolbar_button_y + toolbar_button_h) {
self.triggerAction(item.act);
return;
}
}
- _ = tb;
}
fn handleSidebarClick(self: *App) void {
@@ -1162,10 +1241,7 @@ pub const App = struct {
.toggle_sidebar => {
self.sidebar_open = !self.sidebar_open;
if (self.zoom_mode != .manual) self.updateEffectiveZoom();
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
+ self.relayout();
},
.prev_page => {
if (self.current_page > 0) self.goToPage(self.current_page - 1);
@@ -1173,37 +1249,14 @@ pub const App = struct {
.next_page => {
if (self.current_page + 1 < self.n_pages) self.goToPage(self.current_page + 1);
},
- .zoom_out => {
- self.zoom_mode = .manual;
- self.zoom = @max(0.2, self.zoom / 1.2);
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
- },
- .zoom_in => {
- self.zoom_mode = .manual;
- self.zoom = @min(5.0, self.zoom * 1.2);
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
- },
- .fit_mode => {
- self.zoom_mode = if (self.zoom_mode == .fit_width) .fit_page else .fit_width;
- self.updateEffectiveZoom();
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
- },
+ .zoom_out => self.zoomBy(1.0 / 1.2),
+ .zoom_in => self.zoomBy(1.2),
+ .fit_width => self.setZoomMode(.fit_width),
+ .fit_page => self.setZoomMode(.fit_page),
.rotate => {
self.rotation = self.rotation.rotateClockwise();
if (self.zoom_mode != .manual) self.updateEffectiveZoom();
- self.recomputeLayout() catch {};
- if (self.doc_layout) |dl| {
- self.scroll_y = layout.scrollToAnchor(dl.pages, self.anchor, self.canvasRect().h);
- }
+ self.relayout();
},
.open_dialog => {
self.dialog = .information;
@@ -1232,10 +1285,21 @@ pub const App = struct {
self.search_open = false;
self.focus = .none;
},
+ .print => if (self.n_pages > 0 and !self.loading) {
+ self.print_request = true;
+ },
}
self.dirty = true;
}
+ /// Reports a print helper problem in the information dialog.
+ pub fn showMessage(self: *App, message: []const u8) void {
+ self.dialog = .information;
+ self.focus = .none;
+ self.error_message = message;
+ self.dirty = true;
+ }
+
pub fn handleKey(self: *App, sym: u32, utf8: []const u8) void {
// Ctrl+W closes immediately regardless of focus
if (self.ctrl and (sym == 'w' or sym == 'W')) {
@@ -1314,6 +1378,7 @@ pub const App = struct {
'w', 'W' => self.closed = true,
'o', 'O' => self.triggerAction(.open_dialog),
'f', 'F' => self.triggerAction(.find_toggle),
+ 'p', 'P' => self.triggerAction(.print),
'l', 'L' => {
self.focus = .page_number;
self.editor.text.clearRetainingCapacity();
@@ -1342,18 +1407,8 @@ pub const App = struct {
'r', 'R' => self.triggerAction(.rotate),
'+', '=' => self.triggerAction(.zoom_in),
'-' => self.triggerAction(.zoom_out),
- '0' => {
- self.zoom_mode = .fit_width;
- self.updateEffectiveZoom();
- self.recomputeLayout() catch {};
- self.dirty = true;
- },
- '9' => {
- self.zoom_mode = .fit_page;
- self.updateEffectiveZoom();
- self.recomputeLayout() catch {};
- self.dirty = true;
- },
+ '0' => self.triggerAction(.fit_width),
+ '9' => self.triggerAction(.fit_page),
0xffbe => { // F3
if (self.shift) {
self.triggerAction(.find_prev);
@@ -1477,36 +1532,40 @@ pub const App = struct {
c.api.cairo_fill(cr);
// Check page cache
- const p_px_w = p.logical_width * @as(f64, @floatFromInt(self.scale));
- const p_px_h = p.logical_height * @as(f64, @floatFromInt(self.scale));
- const is_tiled = (p_px_w > 2048 or p_px_h > 2048 or p_px_w * p_px_h > 4 * 1024 * 1024);
-
var painted_pixels = false;
- if (is_tiled) {
- const tile_size = 1024.0 / @as(f64, @floatFromInt(self.scale));
- var ty: f64 = 0;
- while (ty < p.logical_height) : (ty += tile_size) {
- var tx: f64 = 0;
- while (tx < p.logical_width) : (tx += tile_size) {
- const tw = @min(tile_size, p.logical_width - tx);
- const th = @min(tile_size, p.logical_height - ty);
- const tk = cache.TileKey{
- .x = @intFromFloat(tx),
- .y = @intFromFloat(ty),
- .w = @intFromFloat(tw),
- .h = @intFromFloat(th),
- };
- const pk = cache.PageKey.init(self.generation, i, effective_scale, self.rotation, tk);
- if (self.page_cache.get(pk)) |cp| {
- self.drawCachedSurface(cr, cp, page_x + tx, page_y + ty, tw, th);
- painted_pixels = true;
- }
+ if (self.tileSpan(cv, p)) |span| {
+ var tiles: [64]?*cache.CachedPage = undefined;
+ var n: usize = 0;
+ var complete = true;
+ for (span.y0..span.y1) |ty| for (span.x0..span.x1) |tx| {
+ const pk = cache.PageKey.init(self.generation, i, effective_scale, self.rotation, span.key(tx, ty));
+ const cp = self.page_cache.get(pk);
+ complete = complete and cp != null;
+ if (n < tiles.len) {
+ tiles[n] = cp;
+ n += 1;
+ }
+ };
+ // An older whole-page raster stands in under missing tiles.
+ if (!complete) {
+ if (self.page_cache.findBest(self.generation, i, self.rotation)) |best| {
+ self.drawCachedSurface(cr, best, page_x, page_y, p.logical_width, p.logical_height);
+ painted_pixels = true;
}
}
+ n = 0;
+ for (span.y0..span.y1) |ty| for (span.x0..span.x1) |tx| {
+ if (n >= tiles.len) break;
+ defer n += 1;
+ const cp = tiles[n] orelse continue;
+ const tk = span.key(tx, ty);
+ self.drawRaster(cr, cp, page_x, page_y, @floatFromInt(tk.x), @floatFromInt(tk.y));
+ painted_pixels = true;
+ };
} else {
const pk = cache.PageKey.init(self.generation, i, effective_scale, self.rotation, null);
if (self.page_cache.get(pk)) |cp| {
- self.drawCachedSurface(cr, cp, page_x, page_y, p.logical_width, p.logical_height);
+ self.drawRaster(cr, cp, page_x, page_y, 0, 0);
painted_pixels = true;
}
}
@@ -1560,6 +1619,16 @@ pub const App = struct {
if (self.hbar()) |bar| shell_ui.drawScrollbar(cr, scrollbar.look(bar, self.hbar_appearance, ui_theme.global.scrollbar_width, ui_theme.shellPalette()));
}
+ /// Draws a raster at the current zoom one pixel per device pixel, with
+ /// the page origin on the device grid: resampling would soften text and
+ /// leave seams between tiles. `x`, `y` place it within the page raster.
+ fn drawRaster(self: *App, cr: *c.api.cairo_t, cp: *cache.CachedPage, page_x: f64, page_y: f64, x: f64, y: f64) void {
+ const s: f64 = @floatFromInt(self.scale);
+ const origin_x = @round(page_x * s);
+ const origin_y = @round(page_y * s);
+ self.drawCachedSurface(cr, cp, (origin_x + x) / s, (origin_y + y) / s, @as(f64, @floatFromInt(cp.width)) / s, @as(f64, @floatFromInt(cp.height)) / s);
+ }
+
fn drawCachedSurface(self: *App, cr: *c.api.cairo_t, cp: *cache.CachedPage, x: f64, y: f64, target_w: f64, target_h: f64) void {
_ = self;
const surf = c.api.cairo_image_surface_create_for_data(
@@ -1751,12 +1820,25 @@ pub const App = struct {
c.api.cairo_line_to(cr, tb.x + tb.w, tb.h - 0.5);
c.api.cairo_stroke(cr);
- // Sidebar toggle button
- self.renderButtonIcon(cr, 10.0, 6.0, 32.0, 32.0, .view_grid, "Toggle sidebar");
-
- // Previous & Next page buttons
- self.renderButtonText(cr, 52.0, 6.0, 32.0, 32.0, "◀");
- self.renderButtonText(cr, 88.0, 6.0, 32.0, 32.0, "▶");
+ for (toolbar_buttons) |item| {
+ const x = item.x;
+ const y = toolbar_button_y;
+ const w = item.w;
+ const h = toolbar_button_h;
+ switch (item.act) {
+ .toggle_sidebar => self.renderButtonIcon(cr, x, y, w, h, .view_grid, "Toggle sidebar"),
+ .prev_page => self.renderButtonText(cr, x, y, w, h, "◀"),
+ .next_page => self.renderButtonText(cr, x, y, w, h, "▶"),
+ .zoom_out => self.renderButtonText(cr, x, y, w, h, "−"),
+ .zoom_in => self.renderButtonText(cr, x, y, w, h, "+"),
+ .fit_width => self.renderToggle(cr, x, y, w, h, "Fit width", self.zoom_mode == .fit_width),
+ .fit_page => self.renderToggle(cr, x, y, w, h, "Fit page", self.zoom_mode == .fit_page),
+ .rotate => self.renderButtonIcon(cr, x, y, w, h, .rotate, "Rotate"),
+ .find_toggle => self.renderButtonText(cr, x, y, w, h, if (self.search_open) "Find ▲" else "Find"),
+ .print => self.renderButtonIcon(cr, x, y, w, h, .print, "Print"),
+ else => {},
+ }
+ }
// Page number field: [ 3 ] / 42
var pbuf: [32]u8 = undefined;
@@ -1783,23 +1865,11 @@ pub const App = struct {
shell_ui.setSource(cr, ui_theme.global.window_fg);
shell_ui.drawText(cr, total_str, 180.0, 26.0, shell_ui.textSize(), false);
- // Zoom controls: − [ 125% ] +
- self.renderButtonText(cr, 210.0, 6.0, 32.0, 32.0, "−");
+ // Zoom level between − and +
var zbuf: [16]u8 = undefined;
- const zstr = std.fmt.bufPrint(&zbuf, "{d}%", .{@as(i32, @intFromFloat(self.zoom * 100.0))}) catch "100%";
+ const zstr = std.fmt.bufPrint(&zbuf, "{d}%", .{@as(i32, @intFromFloat(@round(self.zoom * 100.0)))}) catch "100%";
const zw = shell_ui.measureText(cr, zstr, shell_ui.textSize(), true);
shell_ui.drawText(cr, zstr, 246.0 + (36.0 - zw) / 2.0, 26.0, shell_ui.textSize(), true);
- self.renderButtonText(cr, 286.0, 6.0, 32.0, 32.0, "+");
-
- // Fit mode button
- const fit_label = if (self.zoom_mode == .fit_width) "Fit width" else if (self.zoom_mode == .fit_page) "Fit page" else "Manual";
- self.renderButtonText(cr, 326.0, 6.0, 84.0, 32.0, fit_label);
-
- // Rotate button
- self.renderButtonIcon(cr, 418.0, 6.0, 32.0, 32.0, .rotate, "Rotate");
-
- // Find button
- self.renderButtonText(cr, 458.0, 6.0, 64.0, 32.0, if (self.search_open) "Find ▲" else "Find");
}
fn renderSearchBar(self: *App, cr: *c.api.cairo_t) void {
@@ -1860,15 +1930,12 @@ pub const App = struct {
c.api.cairo_rectangle(cr, 0, 0, @floatFromInt(self.w), @floatFromInt(self.h));
c.api.cairo_fill(cr);
- // Dialog box
- shell_ui.setSource(cr, ui_theme.global.window_bg);
- c.api.cairo_rectangle(cr, dx, dy, dw, dh);
- c.api.cairo_fill(cr);
-
- shell_ui.setSource(cr, ui_theme.global.window_border);
- c.api.cairo_set_line_width(cr, 1.0);
- c.api.cairo_rectangle(cr, dx, dy, dw, dh);
- c.api.cairo_stroke(cr);
+ // The shared card stays opaque when the window background is glass.
+ if (shell_ui.Layer.begin(cr, .{ .x = @floatCast(dx), .y = @floatCast(dy), .w = @floatCast(dw), .h = @floatCast(dh) })) |value| {
+ var frame = value;
+ ui_dialog.paintFrame(&frame.renderer, frame.local());
+ frame.finish();
+ }
// Title
const title = switch (self.dialog) {
@@ -1916,6 +1983,17 @@ pub const App = struct {
}, .{ .pointer = if (is_hover) .hover else .idle });
}
+ /// A text button shown selected while its mode is active.
+ fn renderToggle(self: *App, cr: *c.api.cairo_t, x: f64, y: f64, w: f64, h: f64, label: []const u8, selected: bool) void {
+ const is_hover = self.px >= x and self.px <= x + w and self.py >= y and self.py <= y + h;
+ var layer = shell_ui.Layer.begin(cr, .{ .x = @floatCast(x), .y = @floatCast(y), .w = @floatCast(w), .h = @floatCast(h) }) orelse return;
+ defer layer.finish();
+ ui_button.paint(&layer.renderer, layer.local(), .{
+ .variant = .ghost,
+ .label = label,
+ }, .{ .pointer = if (is_hover) .hover else .idle, .selected = selected });
+ }
+
fn renderButtonIcon(self: *App, cr: *c.api.cairo_t, x: f64, y: f64, w: f64, h: f64, icon: IconId, tooltip: []const u8) void {
const is_hover = self.px >= x and self.px <= x + w and self.py >= y and self.py <= y + h;
var layer = shell_ui.Layer.begin(cr, .{ .x = @floatCast(x), .y = @floatCast(y), .w = @floatCast(w), .h = @floatCast(h) }) orelse return;
diff --git a/src/pdf/c.zig b/src/pdf/c.zig
index 3c3eaf8..b3c6408 100644
--- a/src/pdf/c.zig
+++ b/src/pdf/c.zig
@@ -26,7 +26,11 @@ pub const api = @cImport({
});
pub extern fn rediwm_pdf_open_document(path: [*:0]const u8) c_int;
-pub extern fn rediwm_pdf_sandbox_enter(document_fd: c_int, display_fd: c_int) c_int;
+/// `print_fd` is the print helper's socket or -1; it stays open in the sandbox.
+pub extern fn rediwm_pdf_sandbox_enter(document_fd: c_int, display_fd: c_int, print_fd: c_int) c_int;
+/// Forks the unsandboxed print helper (print.c); returns the viewer's end of
+/// its socket, or -1.
+pub extern fn rediwm_pdf_print_start(document_fd: c_int, path: [*:0]const u8) c_int;
// GLib & Poppler types declared by hand without @cInclude.
pub const PopplerDocument = opaque {};
diff --git a/src/pdf/cache.zig b/src/pdf/cache.zig
index 3907500..a1a48c1 100644
--- a/src/pdf/cache.zig
+++ b/src/pdf/cache.zig
@@ -7,7 +7,7 @@ const document = @import("document.zig");
pub const PAGE_CACHE_LIMIT: usize = 128 * 1024 * 1024;
pub const THUMB_CACHE_LIMIT: usize = 16 * 1024 * 1024;
-/// Tile bounds in page logical pixels.
+/// Tile bounds in pixels of the page's raster at the key's scale.
pub const TileKey = struct {
x: u32,
y: u32,
diff --git a/src/pdf/document.zig b/src/pdf/document.zig
index 8ae42e5..1a3d29f 100644
--- a/src/pdf/document.zig
+++ b/src/pdf/document.zig
@@ -15,8 +15,10 @@ pub const Error = error{
};
pub const RenderOptions = struct {
+ /// Zoom times the output's buffer scale.
scale: f64 = 1.0,
rotation: layout.Rotation = .deg0,
+ /// Part of the raster to render, in its pixels (not logical units).
clip: ?layout.Rect = null,
};
diff --git a/src/pdf/main.zig b/src/pdf/main.zig
index 6cb8b84..4422398 100644
--- a/src/pdf/main.zig
+++ b/src/pdf/main.zig
@@ -67,6 +67,8 @@ pub const Client = struct {
xkb_context: ?*c.api.xkb_context = null,
xkb_state: ?*c.api.xkb_state = null,
key_repeat: key_repeat.KeyRepeat = .{},
+ /// Socket to the unsandboxed print helper, or -1 without one.
+ print_fd: c_int = -1,
app: app_mod.App,
pub fn registryEvent(registry: *wl.Registry, event: wl.Registry.Event, self: *Client) void {
@@ -303,7 +305,9 @@ pub const Client = struct {
},
.axis => |ev| {
if (ev.axis == .vertical_scroll) {
- if (self.app.shift) {
+ if (self.app.ctrl) {
+ self.app.handleZoomScroll(ev.value.toDouble());
+ } else if (self.app.shift) {
self.app.handleHorizontalScroll(ev.value.toDouble());
} else {
self.app.handleScroll(ev.value.toDouble());
@@ -586,6 +590,37 @@ pub const Client = struct {
c.api.cairo_stroke(cr);
}
+ /// Asks the helper for the print dialog; it answers only on failure.
+ fn requestPrint(self: *Client) void {
+ self.app.print_request = false;
+ if (self.print_fd >= 0) {
+ const request: u8 = 'p';
+ if (c.api.write(self.print_fd, &request, 1) == 1) return;
+ self.closePrint();
+ }
+ self.app.showMessage("Printing is not available.");
+ }
+
+ fn readPrintReplies(self: *Client) void {
+ var buf: [16]u8 = undefined;
+ const n = c.api.read(self.print_fd, &buf, buf.len);
+ if (n <= 0) {
+ if (n < 0 and std.posix.errno(n) == .INTR) return;
+ return self.closePrint();
+ }
+ for (buf[0..@intCast(n)]) |reply| switch (reply) {
+ 'u' => self.app.showMessage("No print service answered (xdg-desktop-portal)."),
+ 'f' => self.app.showMessage("The document could not be printed."),
+ else => {},
+ };
+ }
+
+ fn closePrint(self: *Client) void {
+ if (self.print_fd < 0) return;
+ _ = c.api.close(self.print_fd);
+ self.print_fd = -1;
+ }
+
fn publishClipboard(self: *Client) void {
const mgr = self.data_manager orelse return;
const dev = self.data_device orelse return;
@@ -724,6 +759,7 @@ pub fn run(init: std.process.Init.Minimal) !void {
\\ 0 / 9: Fit width / Fit page
\\ R: Rotate 90° clockwise
\\ Ctrl+L: Jump to page
+ \\ Ctrl+P: Print
\\ PageUp / PageDown / Space: Move viewport
\\ Home / End: First / Last page
\\ Ctrl+W / Esc: Close window / dialog
@@ -749,6 +785,10 @@ pub fn run(init: std.process.Init.Minimal) !void {
const document_fd = c.rediwm_pdf_open_document(initial_path.ptr);
if (document_fd < 0) return error.CannotOpenRegularFile;
defer _ = c.api.close(document_fd);
+ // Printing needs the session bus, which the sandbox denies: fork the
+ // helper now, while this process is unsandboxed and single-threaded.
+ const print_fd = c.rediwm_pdf_print_start(document_fd, initial_path.ptr);
+ if (print_fd < 0) std.log.warn("print helper unavailable; printing is disabled", .{});
const force_csd = init.environ.getPosix("REDIWM_PDF_FORCE_CSD") != null;
// Read before the sandbox closes the filesystem.
@import("../files/settings.zig").loadTheme(a, std.Io.Threaded.global_single_threaded.io(), init.environ);
@@ -761,15 +801,17 @@ pub fn run(init: std.process.Init.Minimal) !void {
const display = try @import("connection.zig").connect();
defer display.disconnect();
- if (c.rediwm_pdf_sandbox_enter(document_fd, display.getFd()) != 0) {
+ if (c.rediwm_pdf_sandbox_enter(document_fd, display.getFd(), print_fd) != 0) {
std.log.err("required PDF sandbox could not be installed; refusing to parse the document", .{});
return error.SandboxUnavailable;
}
var self = Client{
.display = display,
+ .print_fd = print_fd,
.app = try app_mod.App.init(initial_path, document_fd),
};
+ defer self.closePrint();
defer self.app.deinit();
defer for (self.buffers) |slot| {
if (slot) |buffer| buffer.destroy();
@@ -832,6 +874,7 @@ pub fn run(init: std.process.Init.Minimal) !void {
if (self.app.clipboard_request) {
self.publishClipboard();
}
+ if (self.app.print_request) self.requestPrint();
if (self.app.closed) {
self.running = false;
break;
@@ -862,6 +905,8 @@ pub fn run(init: std.process.Init.Minimal) !void {
var fds = [_]c.api.struct_pollfd{
.{ .fd = display.getFd(), .events = @intCast(c.api.POLLIN | @as(c_int, if (flushed == .AGAIN) c.api.POLLOUT else 0)), .revents = 0 },
.{ .fd = self.app.worker.fds[0], .events = c.api.POLLIN, .revents = 0 },
+ // poll ignores a negative fd.
+ .{ .fd = self.print_fd, .events = c.api.POLLIN, .revents = 0 },
};
const now = key_repeat.nowMs();
var timeout: c_int = if (self.key_repeat.timeoutMs(now)) |wait| @intCast(@min(wait, 60_000)) else -1;
@@ -873,6 +918,7 @@ pub fn run(init: std.process.Init.Minimal) !void {
display.cancelRead();
}
if ((fds[0].revents & (c.api.POLLERR | c.api.POLLHUP)) != 0) return error.DisplayFailed;
+ if (fds[2].revents != 0) self.readPrintReplies();
if (display.dispatchPending() != .SUCCESS) return error.DisplayFailed;
self.repeatDue();
}
diff --git a/src/pdf/print.c b/src/pdf/print.c
new file mode 100644
index 0000000..317ca02
--- /dev/null
+++ b/src/pdf/print.c
@@ -0,0 +1,220 @@
+// Printing for the sandboxed viewer. The parser process may not connect to
+// the session bus, so before the sandbox is installed it forks this helper.
+// The helper never receives PDF bytes from the parser: it holds the document
+// descriptor opened from the user's path, and the viewer's end of a socket
+// pair can only ask it to print that document. It hands the document to the
+// xdg-desktop-portal Print interface, whose dialog the person confirms.
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <gio/gio.h>
+#include <glib-unix.h>
+#include <signal.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+// Viewer to helper.
+#define REQUEST_PRINT 'p'
+// Helper to viewer: no print portal answered, or the print job failed.
+#define REPLY_UNAVAILABLE 'u'
+#define REPLY_FAILED 'f'
+
+#define PORTAL_NAME "org.freedesktop.portal.Desktop"
+#define PORTAL_PATH "/org/freedesktop/portal/desktop"
+
+typedef struct {
+ int document, peer;
+ char *title;
+ GMainLoop *loop;
+ GDBusConnection *bus;
+ // While a print dialog is open: its request object and Response watch.
+ gboolean busy;
+ char *request;
+ guint response;
+ unsigned serial;
+ // The viewer has exited; quit once the open dialog is answered.
+ gboolean closing;
+} helper;
+
+static void reply(helper *h, char code) {
+ ssize_t n;
+ do n = write(h->peer, &code, 1);
+ while (n < 0 && errno == EINTR);
+}
+
+static void finish(helper *h) {
+ if (h->response) g_dbus_connection_signal_unsubscribe(h->bus, h->response);
+ h->response = 0;
+ g_clear_pointer(&h->request, g_free);
+ h->busy = FALSE;
+ if (h->closing) g_main_loop_quit(h->loop);
+}
+
+static void on_response(GDBusConnection *bus, const char *sender, const char *path,
+ const char *interface, const char *signal, GVariant *params, gpointer data) {
+ (void)bus; (void)sender; (void)path; (void)interface; (void)signal;
+ helper *h = data;
+ guint32 code = 2;
+ if (g_variant_is_of_type(params, G_VARIANT_TYPE("(ua{sv})"))) g_variant_get_child(params, 0, "u", &code);
+ // 0 sent to the printer, 1 cancelled in the dialog, 2 failed.
+ if (code == 2) reply(h, REPLY_FAILED);
+ finish(h);
+}
+
+static void watch_request(helper *h, const char *path) {
+ if (h->response) g_dbus_connection_signal_unsubscribe(h->bus, h->response);
+ g_free(h->request);
+ h->request = g_strdup(path);
+ h->response = g_dbus_connection_signal_subscribe(
+ h->bus, PORTAL_NAME, "org.freedesktop.portal.Request", "Response", h->request, NULL,
+ G_DBUS_SIGNAL_FLAGS_NONE, on_response, h, NULL);
+}
+
+// A Response cannot arrive any more; the next print reconnects.
+static void on_closed(GDBusConnection *bus, gboolean vanished, GError *error, gpointer data) {
+ (void)bus; (void)vanished; (void)error;
+ helper *h = data;
+ if (h->busy) {
+ reply(h, REPLY_FAILED);
+ finish(h);
+ }
+}
+
+static void on_called(GObject *source, GAsyncResult *result, gpointer data) {
+ helper *h = data;
+ GError *error = NULL;
+ GVariant *ret = g_dbus_connection_call_with_unix_fd_list_finish(G_DBUS_CONNECTION(source), NULL, result, &error);
+ if (!ret) {
+ fprintf(stderr, "rediwm-pdf: print portal: %s\n", error->message);
+ g_error_free(error);
+ // Already reported if the bus closed under the call.
+ if (h->busy) {
+ reply(h, REPLY_UNAVAILABLE);
+ finish(h);
+ }
+ return;
+ }
+ const char *handle = NULL;
+ g_variant_get(ret, "(&o)", &handle);
+ // A portal that ignored handle_token answers on a path of its own.
+ if (h->busy && g_strcmp0(handle, h->request) != 0) watch_request(h, handle);
+ g_variant_unref(ret);
+}
+
+static void start_print(helper *h) {
+ GError *error = NULL;
+ if (h->bus && g_dbus_connection_is_closed(h->bus)) g_clear_object(&h->bus);
+ if (!h->bus) {
+ h->bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error);
+ if (!h->bus) {
+ fprintf(stderr, "rediwm-pdf: print: no session bus: %s\n", error->message);
+ g_error_free(error);
+ reply(h, REPLY_UNAVAILABLE);
+ return;
+ }
+ g_dbus_connection_set_exit_on_close(h->bus, FALSE);
+ g_signal_connect(h->bus, "closed", G_CALLBACK(on_closed), h);
+ }
+
+ // A new open file description, so the print system reads from offset 0
+ // independently of the parser's reads.
+ char proc[64];
+ snprintf(proc, sizeof proc, "/proc/self/fd/%d", h->document);
+ int fd = open(proc, O_RDONLY | O_CLOEXEC | O_NOCTTY);
+ if (fd < 0) {
+ fprintf(stderr, "rediwm-pdf: print: cannot reopen the document: %s\n", strerror(errno));
+ reply(h, REPLY_FAILED);
+ return;
+ }
+ GUnixFDList *fds = g_unix_fd_list_new_from_array(&fd, 1);
+
+ // Subscribe before calling: the request path is known from the token.
+ char token[32];
+ snprintf(token, sizeof token, "rediwm_pdf%u", ++h->serial);
+ char *sender = g_strdup(g_dbus_connection_get_unique_name(h->bus) + 1);
+ g_strdelimit(sender, ".", '_');
+ char *path = g_strdup_printf(PORTAL_PATH "/request/%s/%s", sender, token);
+ watch_request(h, path);
+ g_free(path);
+ g_free(sender);
+ h->busy = TRUE;
+
+ GVariantBuilder options;
+ g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT);
+ g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(token));
+ // RediWM has no xdg-foreign, so the dialog cannot name a parent window.
+ g_dbus_connection_call_with_unix_fd_list(
+ h->bus, PORTAL_NAME, PORTAL_PATH, "org.freedesktop.portal.Print", "Print",
+ g_variant_new("(ssha{sv})", "", h->title, 0, &options), G_VARIANT_TYPE("(o)"),
+ G_DBUS_CALL_FLAGS_NONE, -1, fds, NULL, on_called, h);
+ g_object_unref(fds);
+}
+
+static gboolean on_peer(gint fd, GIOCondition condition, gpointer data) {
+ helper *h = data;
+ char buf[16];
+ ssize_t n = (condition & G_IO_IN) ? read(fd, buf, sizeof buf) : 0;
+ if (n < 0 && (errno == EINTR || errno == EAGAIN)) return G_SOURCE_CONTINUE;
+ if (n <= 0) {
+ h->closing = TRUE;
+ if (!h->busy) g_main_loop_quit(h->loop);
+ return G_SOURCE_REMOVE;
+ }
+ // One dialog at a time: presses while it is open do nothing.
+ if (memchr(buf, REQUEST_PRINT, (size_t)n) && !h->busy) start_print(h);
+ return G_SOURCE_CONTINUE;
+}
+
+static int keep_only(int a, int b) {
+ int lower = a < b ? a : b, upper = a < b ? b : a;
+ if (lower < 3 || lower == upper) return -1;
+ if (lower > 3 && close_range(3, (unsigned)lower - 1, 0) < 0) return -1;
+ if (upper > lower + 1 && close_range((unsigned)lower + 1, (unsigned)upper - 1, 0) < 0) return -1;
+ return close_range((unsigned)upper + 1, ~0u, 0);
+}
+
+static int run(int document, int peer, const char *path) {
+ // The viewer's other descriptors (Wayland, the caller's) are not ours.
+ if (keep_only(document, peer) < 0) return 1;
+ prctl(PR_SET_NAME, "rediwm-pdf-prnt", 0, 0, 0);
+ signal(SIGCHLD, SIG_DFL);
+ int devnull = open("/dev/null", O_RDONLY | O_CLOEXEC);
+ if (devnull >= 0) {
+ dup2(devnull, STDIN_FILENO);
+ close(devnull);
+ }
+
+ helper h = { .document = document, .peer = peer };
+ h.title = g_path_get_basename(path);
+ // Job titles travel as D-Bus strings, which must be UTF-8.
+ if (!g_utf8_validate(h.title, -1, NULL)) {
+ g_free(h.title);
+ h.title = g_strdup("Document");
+ }
+ h.loop = g_main_loop_new(NULL, FALSE);
+ g_unix_fd_add(peer, G_IO_IN | G_IO_HUP | G_IO_ERR, on_peer, &h);
+ g_main_loop_run(h.loop);
+ return 0;
+}
+
+int rediwm_pdf_print_start(int document, const char *path) {
+ int pair[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, pair) < 0) return -1;
+ // The sandboxed viewer cannot wait(); the kernel reaps the helper.
+ signal(SIGCHLD, SIG_IGN);
+ pid_t pid = fork();
+ if (pid < 0) {
+ close(pair[0]);
+ close(pair[1]);
+ return -1;
+ }
+ if (pid == 0) {
+ close(pair[0]);
+ _exit(run(document, pair[1], path));
+ }
+ close(pair[1]);
+ return pair[0];
+}
diff --git a/src/pdf/sandbox.c b/src/pdf/sandbox.c
index 968dab8..0fe3e8b 100644
--- a/src/pdf/sandbox.c
+++ b/src/pdf/sandbox.c
@@ -53,13 +53,26 @@ static int single_threaded(void) {
return 0;
}
-static int close_inherited(int document, int display) {
- if (document < 3 || display < 3 || document == display) { errno = EINVAL; return -1; }
- int lower = document < display ? document : display;
- int upper = document < display ? display : document;
- if (lower > 3 && close_range(3, (unsigned)lower - 1, 0) < 0) return -1;
- if (upper > lower + 1 && close_range((unsigned)lower + 1, (unsigned)upper - 1, 0) < 0) return -1;
- return close_range((unsigned)upper + 1, ~0u, 0);
+// Closes every descriptor above stdio except `keep`; negative entries are
+// unused slots.
+static int close_inherited(const int *keep, unsigned count) {
+ int sorted[3];
+ unsigned n = 0;
+ if (count > sizeof(sorted) / sizeof(sorted[0])) { errno = EINVAL; return -1; }
+ for (unsigned i = 0; i < count; i++) {
+ if (keep[i] < 0) continue;
+ if (keep[i] < 3) { errno = EINVAL; return -1; }
+ unsigned at = n++;
+ while (at > 0 && sorted[at - 1] > keep[i]) { sorted[at] = sorted[at - 1]; at--; }
+ if (at > 0 && sorted[at - 1] == keep[i]) { errno = EINVAL; return -1; }
+ sorted[at] = keep[i];
+ }
+ unsigned next = 3;
+ for (unsigned i = 0; i < n; i++) {
+ if ((unsigned)sorted[i] > next && close_range(next, (unsigned)sorted[i] - 1, 0) < 0) return -1;
+ next = (unsigned)sorted[i] + 1;
+ }
+ return close_range(next, ~0u, 0);
}
static int read_tree(int rules, const char *path) {
@@ -173,8 +186,14 @@ done:
return 0;
}
-int rediwm_pdf_sandbox_enter(int document, int display) {
- if (single_threaded() < 0 || close_inherited(document, display) < 0) return -1;
+// `print` is the print helper's socket (see print.c), or -1. The viewer
+// may only read and write bytes on it: sendmsg is limited to `display`, so
+// no descriptor can be passed out.
+int rediwm_pdf_sandbox_enter(int document, int display, int print) {
+ if (document < 0 || display < 0) { errno = EINVAL; return -1; }
+ const int keep[] = { document, display, print };
+ const unsigned kept = sizeof(keep) / sizeof(keep[0]);
+ if (single_threaded() < 0 || close_inherited(keep, kept) < 0) return -1;
// Drop terminal input, and ensure diagnostics cannot be read as input.
int null = open("/dev/null", O_RDONLY | O_CLOEXEC);
if (null < 0 || dup2(null, STDIN_FILENO) < 0) { if (null >= 0) close(null); return -1; }
@@ -200,7 +219,7 @@ int rediwm_pdf_sandbox_enter(int document, int display) {
if (clearenv() < 0) return -1;
password_codec = iconv_open("ISO-8859-1", "UTF-8");
if (password_codec == (iconv_t)-1) return -1;
- if (single_threaded() < 0 || close_inherited(document, display) < 0) return -1;
+ if (single_threaded() < 0 || close_inherited(keep, kept) < 0) return -1;
struct rlimit core = {0, 0}, memory = {2ULL << 30, 2ULL << 30}, files = {128, 128};
if (setrlimit(RLIMIT_CORE, &core) < 0 || setrlimit(RLIMIT_AS, &memory) < 0 ||
setrlimit(RLIMIT_NOFILE, &files) < 0 || prctl(PR_SET_DUMPABLE, 0) < 0 ||
diff --git a/src/power_menu.zig b/src/power_menu.zig
index 22f4383..f12a98a 100644
--- a/src/power_menu.zig
+++ b/src/power_menu.zig
@@ -236,12 +236,8 @@ pub const PowerMenu = struct {
.{ .kind = .container, .direction = .row, .@"align" = .center, .justify = .end, .gap = 10, .height = .{ .fixed = 20 }, .children = &menu.header_children },
.{ .kind = .container, .direction = .row, .gap = tile_gap, .height = .{ .fixed = tile_height }, .children = &menu.cards },
};
- // Keep the neutral panel tint, but use the glass alpha throughout
- // the open state. Window chrome is nearly opaque and hides the blur.
- var panel_color = t.window_bg;
- panel_color[3] = t.glass[3];
menu.root = .{
- .kind = .{ .rect = .{ .color = panel_color, .radius = panel_radius, .border_width = 1, .border_color = t.border } },
+ .kind = .{ .rect = .{ .color = t.window_bg, .radius = panel_radius, .border_width = 1, .border_color = t.border } },
.direction = .column,
.@"align" = .stretch,
.gap = 20,
diff --git a/src/resize.zig b/src/resize.zig
index 5613a5a..9357087 100644
--- a/src/resize.zig
+++ b/src/resize.zig
@@ -184,9 +184,8 @@ pub fn selectEdgesFromQuadrant(
};
}
-/// How far a grab reaches past the frame, over the drop shadow. Only pixels a
-/// chrome buffer covers can be hit, so this never exceeds the shadow margin
-/// in practice (smallest preset is 16).
+/// How far a grab reaches past the frame. `Toplevel.resize_grab` covers this
+/// band whether or not a shadow is drawn there.
pub const reach_outside: f64 = 10.0;
/// How far it reaches into the frame, where chrome (titlebar, footer skirt)
/// is exposed. Beside the client the frame border is 1 px and the client
diff --git a/src/session/AGENTS.md b/src/session/AGENTS.md
new file mode 100644
index 0000000..80b1267
--- /dev/null
+++ b/src/session/AGENTS.md
@@ -0,0 +1,20 @@
+# Lock internals
+
+Cross-cutting lock rules (greeter, crash handling, IPC refusal, client
+ext-session-lock) are in the root `AGENTS.md`.
+
+* `Lock.covered()` releases the lock-before-sleep inhibitor; the builtin lock
+ also sets `Output.lock_commit_pending`.
+
+* **The lock never polls.** Its one timer redraws the clock at the next minute
+ boundary; the PAM worker (`auth.c`) signals an eventfd that `Lock.authReady`
+ watches only while an attempt runs. Don't add a periodic tick (a 100 ms one
+ cost ~10 wakeups/s for as long as the session stayed locked).
+* **Lock volume/brightness** (`lock_controls.zig`): sliders at the bottom
+ centre of the built-in lock, the pointer/touch way to what the hardware keys
+ already do behind it. Never in the greeter (no audio, no external tools) and
+ hidden under an ext-session-lock client's surface. They are their own small
+ raster (`View.controls_node`), so a drag never re-rasters the clock, avatar
+ and field. A row exists only while its backend reports
+ (`Lock.controlsChanged` from the audio wake and the brightness helper's
+ result); a drag shows its own value until release. Events only, no timer.
diff --git a/src/start_menu/mod.zig b/src/start_menu/mod.zig
index 7e30110..ce1f10c 100644
--- a/src/start_menu/mod.zig
+++ b/src/start_menu/mod.zig
@@ -10,5 +10,7 @@ pub const launch = @import("launch.zig");
pub const model = @import("model.zig");
pub const Model = model.Model;
+pub const size = @import("size.zig");
+
pub const panel = @import("panel.zig");
pub const StartMenu = panel.StartMenu;
diff --git a/src/start_menu/panel.zig b/src/start_menu/panel.zig
index 7805fee..0e03c92 100644
--- a/src/start_menu/panel.zig
+++ b/src/start_menu/panel.zig
@@ -32,6 +32,7 @@ const applications = @import("applications.zig");
const AppEntry = applications.AppEntry;
const launch = @import("launch.zig");
const model_mod = @import("model.zig");
+const size_mod = @import("size.zig");
const Model = model_mod.Model;
const Category = model_mod.Category;
const SearchResult = model_mod.SearchResult;
@@ -745,7 +746,7 @@ pub const StartMenu = struct {
.border_color = t.start_menu_border,
} },
.direction = .column,
- .width = .{ .fixed = t.start_menu_width },
+ .width = .{ .fixed = menu.wantedSize().width },
.height = .auto,
.children = root_kids,
};
@@ -762,15 +763,23 @@ pub const StartMenu = struct {
}
}
+ /// The size the theme asks for on this menu's output, before the caps in
+ /// `relayout`: its own values, else the automatic ones (`size.zig`).
+ fn wantedSize(menu: *StartMenu) size_mod.Size {
+ var box: wlr.Box = undefined;
+ menu.server.output_layout.getBox(menu.wlr_output, &box);
+ return size_mod.wanted(theme.global, @floatFromInt(box.width), @floatFromInt(box.height));
+ }
+
pub fn relayout(menu: *StartMenu) void {
menu.background.invalidate();
var output_box: wlr.Box = undefined;
menu.server.output_layout.getBox(menu.wlr_output, &output_box);
if (output_box.width <= 0 or output_box.height <= 0) return;
- const t = theme.global;
- const max_allowed_h = @min(t.start_menu_max_height, @as(f32, @floatFromInt(output_box.height)) * 0.85);
- const max_allowed_w = @min(t.start_menu_width, @as(f32, @floatFromInt(output_box.width)) - 40);
+ const wanted = menu.wantedSize();
+ const max_allowed_h = @min(wanted.height, @as(f32, @floatFromInt(output_box.height)) * 0.85);
+ const max_allowed_w = @min(wanted.width, @as(f32, @floatFromInt(output_box.width)) - 40);
const target_height = @max(240, max_allowed_h);
const target_width = @max(320, max_allowed_w);
diff --git a/src/start_menu/size.zig b/src/start_menu/size.zig
new file mode 100644
index 0000000..9c8dc02
--- /dev/null
+++ b/src/start_menu/size.zig
@@ -0,0 +1,79 @@
+//! The start menu's size. A theme that leaves `start_menu_width` and
+//! `start_menu_max_height` at 0 (their default) gets a menu sized to the
+//! output; a nonzero value is the user's own and is used as written.
+//!
+//! The design size is what the menu looks right at on a 2560x1600 panel at
+//! scale 1.5. Outputs at least that large (in logical pixels) get exactly that:
+//! its rows and text do not grow with the screen, so a bigger menu would only
+//! add empty space. Smaller outputs get the same proportion of their screen,
+//! down to a floor that still fits the search box, a few rows and the footer.
+const std = @import("std");
+const Theme = @import("ui").theme.Theme;
+
+pub const design_width: f32 = 560;
+pub const design_height: f32 = 600;
+/// Logical size of the output the design was judged on (2560x1600 / 1.5).
+const design_screen_width: f32 = 1706;
+const design_screen_height: f32 = 1066;
+
+/// Smallest size the automatic sizing, and Settings' sliders, will pick.
+/// `StartMenu.relayout` keeps its own lower floor (320x240) for sizes a
+/// hand-edited theme sets.
+pub const min_width: f32 = 400;
+pub const min_height: f32 = 360;
+
+pub const Size = struct { width: f32, height: f32 };
+
+/// The automatic size for an output of `output_w` x `output_h` logical pixels.
+pub fn automatic(output_w: f32, output_h: f32) Size {
+ return .{
+ .width = axis(design_width, output_w, design_screen_width, min_width),
+ .height = axis(design_height, output_h, design_screen_height, min_height),
+ };
+}
+
+fn axis(design: f32, output: f32, design_output: f32, floor: f32) f32 {
+ if (output <= 0) return design;
+ return @round(std.math.clamp(design * output / design_output, floor, design));
+}
+
+/// Width and height the theme asks for on this output, before the caps that
+/// keep the menu on screen: its own values, else the automatic ones.
+pub fn wanted(t: Theme, output_w: f32, output_h: f32) Size {
+ const auto = automatic(output_w, output_h);
+ return .{
+ .width = if (t.start_menu_width > 0) t.start_menu_width else auto.width,
+ .height = if (t.start_menu_max_height > 0) t.start_menu_max_height else auto.height,
+ };
+}
+
+test "the design output gets the design size and larger ones do not grow it" {
+ const at_design = automatic(2560.0 / 1.5, 1600.0 / 1.5);
+ try std.testing.expectEqual(design_width, at_design.width);
+ try std.testing.expectEqual(design_height, at_design.height);
+ const uhd = automatic(3840, 2160);
+ try std.testing.expectEqual(design_width, uhd.width);
+ try std.testing.expectEqual(design_height, uhd.height);
+}
+
+test "smaller outputs get the same proportion, down to the floor" {
+ // 1366x768 at scale 1: the proportions of the design (33% x 56%).
+ const laptop = automatic(1366, 768);
+ try std.testing.expectEqual(@as(f32, 448), laptop.width);
+ try std.testing.expectEqual(@as(f32, 432), laptop.height);
+ const tiny = automatic(800, 600);
+ try std.testing.expectEqual(min_width, tiny.width);
+ try std.testing.expectEqual(min_height, tiny.height);
+ // No output yet: the design size rather than the floor.
+ try std.testing.expectEqual(design_width, automatic(0, 0).width);
+}
+
+test "a theme's own nonzero values win, per axis" {
+ var t: Theme = .{};
+ const auto = wanted(t, 1366, 768);
+ try std.testing.expectEqual(@as(f32, 448), auto.width);
+ t.start_menu_width = 700;
+ const mixed = wanted(t, 1366, 768);
+ try std.testing.expectEqual(@as(f32, 700), mixed.width);
+ try std.testing.expectEqual(@as(f32, 432), mixed.height);
+}
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
new file mode 100644
index 0000000..e4b8f06
--- /dev/null
+++ b/src/ui/AGENTS.md
@@ -0,0 +1,43 @@
+# Shared widget internals
+
+The rules every caller follows (callback owners, one look per control, app
+text and colours, secrets) are in the root `AGENTS.md` ("Shared UI").
+
+* **The scrollbar** (`widgets/scrollbar.zig`, Files' look): a track-less thumb
+ centred in a `gutter(scrollbar_width)` strip, thin at rest, widening and
+ tinting to the accent on hover/drag, holding a faint tint after a scroll.
+ `Geometry.compute` gives the thumb for any axis and unit (pixels, or items
+ for a strip that scrolls by item), `press` the grab-or-page decision, `Drag`
+ the pointer-to-offset map, `look` + `paint` (Renderer) /
+ `cairo.drawScrollbar` (Cairo) the pixels, and `Appearance.step` the
+ feedback. It is edge-triggered on what is drawn: the app's loop sleeps until
+ `deadline` and runs frames only while `active` (`barTimeout` in PDF/Editor,
+ `animationTimeout` in Images, `pollTimeout` in Files). Paint-only popups pass
+ `.{}` for the rest look. The gutter belongs to the bar: layouts keep content
+ out of it and a press in it never reaches content. Never change
+ `Appearance.width` per call site: it is every bar's width.
+* **Scroll containers** (`.scroll_container`) give widget trees all of the
+ above: hosts call `scroll_container.stepBars` beside `stepGlides` and carry
+ `ScrollState.bar` across rebuilds. It scrolls along its `direction`, which
+ defaults to `.row` (sideways, bar along the bottom edge), so set it
+ explicitly. Rebuilt trees carry the offset over themselves (the wallpaper
+ strip copies it from its old widget). Appearance's wallpaper strip owns a
+ `wallpaper_strip.Strip` (decode worker + eventfd) that outlives rebuilds and
+ restarts only when the image list changes; thumbnail slices stay valid until
+ then.
+* **Sliders reuse the scrollbar's feedback** (`SliderData.feel` is a
+ `scrollbar.Appearance`): hover and drag tint and thicken the track, a change
+ holds the faint tint. `stepBars` steps sliders too (`slider.stepFeedback`);
+ `Dispatcher.setHovered`/`pointerLeave` keep `hovered` in step. A value
+ readout is `slider.valuePill` (a `.text` with `pill`), found from its slider
+ by `findPill` (first pill under the slider's parent) and lit by drag only.
+ Saving a theme slider rebuilds Settings the moment the button is released,
+ so `panel.rebuildTree` carries named sliders' state across on the same page
+ (`slider.capture`/`restore` + `input.adoptHover`); an unnamed slider starts
+ fresh.
+* **The battery badge** (`widgets/battery.zig`: frame, glyph, percentage,
+ charging bolt) is the taskbar's artwork. `sample` is the pixel math (per
+ device pixel, badge-local units); the taskbar's per-pixel raster calls it and
+ `paint` draws it into any `Renderer`, so the two cannot drift. The caller
+ owns the data (hide it when there is no battery) and the connection
+ shimmer's clock (`Spec.shimmer`).
diff --git a/src/ui/cairo.zig b/src/ui/cairo.zig
index 8811d61..17613ce 100644
--- a/src/ui/cairo.zig
+++ b/src/ui/cairo.zig
@@ -10,6 +10,7 @@ const paint = @import("paint.zig");
const theme = @import("theme.zig");
const text = @import("text.zig");
const scrollbar = @import("widgets/scrollbar.zig");
+const splitter = @import("widgets/splitter.zig");
pub const Rect = @import("widgets/field.zig").Rect;
const allocator = std.heap.c_allocator;
@@ -59,6 +60,14 @@ pub fn setSource(cr_any: *anyopaque, color: [4]f32) void {
c.cairo_set_source_rgba(@ptrCast(cr_any), color[0], color[1], color[2], color[3]);
}
+pub fn drawSplitter(cr_any: *anyopaque, geometry: splitter.Geometry, engaged: bool) void {
+ const cr: *c.cairo_t = @ptrCast(cr_any);
+ const rect = geometry.line(engaged);
+ setSource(cr, splitter.color(engaged));
+ c.cairo_rectangle(cr, rect.x, rect.y, rect.w, rect.h);
+ c.cairo_fill(cr);
+}
+
/// Fills a scrollbar thumb: `scrollbar.look` through Cairo, the counterpart of
/// `scrollbar.paint` for the widget tree.
pub fn drawScrollbar(cr_any: *anyopaque, look: scrollbar.Look) void {
diff --git a/src/ui/layout.zig b/src/ui/layout.zig
index d99a210..9c4318f 100644
--- a/src/ui/layout.zig
+++ b/src/ui/layout.zig
@@ -131,6 +131,7 @@ pub const IconId = enum {
undo,
save,
fit,
+ print,
home,
open,
// Files' devices.
diff --git a/src/ui/mod.zig b/src/ui/mod.zig
index 367f38d..dc74d9a 100644
--- a/src/ui/mod.zig
+++ b/src/ui/mod.zig
@@ -9,6 +9,7 @@ pub const input = @import("input.zig");
pub const widgets = struct {
pub const scrollbar = @import("widgets/scrollbar.zig");
+ pub const splitter = @import("widgets/splitter.zig");
pub const select = @import("widgets/select.zig");
pub const button = @import("widgets/button.zig");
pub const checkbox = @import("widgets/checkbox.zig");
diff --git a/src/ui/paint.zig b/src/ui/paint.zig
index 0f79b05..cc7490c 100644
--- a/src/ui/paint.zig
+++ b/src/ui/paint.zig
@@ -677,7 +677,7 @@ fn iconDistance(id: IconId, px: f32, py: f32, cx: f32, cy: f32, half: f32, thick
const base = @min(ring_open, arrow);
break :blk if (id == .restart_shell) @min(base, sdCircle(px, py, cx, cy, half * 0.24)) else base;
},
- .git_branch, .home, .generic, .folder, .document, .terminal, .settings, .keyboard, .edit, .browser, .wifi, .ethernet, .globe, .mouse, .display, .music, .headphones, .bluetooth, .battery, .notification, .eye, .eye_off, .refresh, .cut, .copy, .paste, .trash, .trash_can, .view_grid, .view_list, .sort, .filter, .zoom_in, .zoom_out, .rotate, .crop, .undo, .save, .fit, .open, .usb_stick, .drive, .eject, .users, .squares => sdCircle(px, py, cx, cy, half * 0.6),
+ .git_branch, .home, .generic, .folder, .document, .terminal, .settings, .keyboard, .edit, .browser, .wifi, .ethernet, .globe, .mouse, .display, .music, .headphones, .bluetooth, .battery, .notification, .eye, .eye_off, .refresh, .cut, .copy, .paste, .trash, .trash_can, .view_grid, .view_list, .sort, .filter, .zoom_in, .zoom_out, .rotate, .crop, .undo, .save, .fit, .print, .open, .usb_stick, .drive, .eject, .users, .squares => sdCircle(px, py, cx, cy, half * 0.6),
};
}
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index 97114ed..474cef4 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -80,6 +80,7 @@ fn source(id: IconId) ?[]const u8 {
.undo => @embedFile("shell-icon-undo"),
.save => @embedFile("shell-icon-save"),
.fit => @embedFile("shell-icon-fit"),
+ .print => @embedFile("shell-icon-print"),
.open => @embedFile("shell-icon-open"),
.usb_stick => @embedFile("shell-icon-usb-stick"),
.drive => @embedFile("shell-icon-drive"),
@@ -138,7 +139,7 @@ fn rasterize(svg: []const u8, size: i32) ?Mask {
test "bundled shell SVGs render nonempty transparent masks at fractional scales" {
defer deinit();
- for ([_]IconId{ .usb_stick, .drive, .eject, .home, .settings, .mouse, .display, .music, .headphones, .wifi, .bluetooth, .battery, .notification, .volume, .volume_muted, .power, .clock, .lock, .logout, .reboot }) |id| {
+ for ([_]IconId{ .print, .usb_stick, .drive, .eject, .home, .settings, .mouse, .display, .music, .headphones, .wifi, .bluetooth, .battery, .notification, .volume, .volume_muted, .power, .clock, .lock, .logout, .reboot }) |id| {
for ([_]i32{ 24, 36, 48 }) |size| {
const mask = get(id, size) orelse return error.InvalidShellIcon;
var visible = false;
diff --git a/src/ui/theme.zig b/src/ui/theme.zig
index 1d4118e..4ceae0d 100644
--- a/src/ui/theme.zig
+++ b/src/ui/theme.zig
@@ -130,8 +130,9 @@ pub const Theme = struct {
shadow: [4]f32 = .{ 0, 0, 0, 0.35 },
shadow_size: f32 = 24.0, // blur/softness radius, logical px
shadow_offset_y: f32 = 8.0, // vertical offset, logical px
- start_menu_width: f32 = 560.0,
- start_menu_max_height: f32 = 600.0,
+ // 0 sizes the menu to the output (`start_menu/size.zig`); set either to pin it.
+ start_menu_width: f32 = 0,
+ start_menu_max_height: f32 = 0,
start_menu_radius: f32 = 14.0,
start_menu_bg: [4]f32 = .{ 29.0 / 255.0, 34.0 / 255.0, 41.0 / 255.0, 0.98 }, // #1d2229
start_menu_border: [4]f32 = .{ 1, 1, 1, 0.12 },
@@ -798,7 +799,8 @@ test "writeInto then parse round-trips every field" {
var t: Theme = .{};
// Exercise every registered field with a non-default value, so omission
// from either parser or serializer cannot pass as a default round-trip.
- inline for (number_keys) |name| @field(t, name) *= 0.9;
+ // Keys defaulting to 0 (automatic sizes) would stay at the default under *= 0.9.
+ inline for (number_keys) |name| @field(t, name) = if (@field(t, name) == 0) 500 else @field(t, name) * 0.9;
inline for (color_keys) |name| @field(t, name) = .{ 16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 0.321 };
inline for (optional_color_keys) |name| @field(t, name) = .{ 16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 0.321 };
t.accent = .{ 167.0 / 255.0, 139.0 / 255.0, 250.0 / 255.0, 1 };
diff --git a/src/ui/widgets/splitter.zig b/src/ui/widgets/splitter.zig
new file mode 100644
index 0000000..ca99b60
--- /dev/null
+++ b/src/ui/widgets/splitter.zig
@@ -0,0 +1,32 @@
+//! A vertical pane divider with a wider pointer target than its painted line.
+const theme = @import("../theme.zig");
+pub const Rect = @import("field.zig").Rect;
+
+pub const Geometry = struct {
+ x: f64,
+ y: f64,
+ h: f64,
+
+ pub fn contains(self: Geometry, x: f64, y: f64) bool {
+ return @abs(x - self.x) <= 4 and y >= self.y and y < self.y + self.h;
+ }
+
+ pub fn line(self: Geometry, engaged: bool) Rect {
+ const width: f32 = if (engaged) 2 else 1;
+ return .{ .x = @as(f32, @floatCast(self.x)) - width, .y = @floatCast(self.y), .w = width, .h = @floatCast(self.h) };
+ }
+};
+
+pub fn color(engaged: bool) [4]f32 {
+ return if (engaged) theme.shellPalette().accent else theme.global.app_item_border;
+}
+
+pub const Drag = struct {
+ origin: f64,
+ width: i32,
+
+ pub fn widthAt(self: Drag, x: f64, minimum: i32, maximum: i32) i32 {
+ const value = @as(f64, @floatFromInt(self.width)) + x - self.origin;
+ return @intFromFloat(@round(@min(@max(value, @as(f64, @floatFromInt(minimum))), @as(f64, @floatFromInt(maximum)))));
+ }
+};
diff --git a/src/xwayland_unmanaged.zig b/src/xwayland_unmanaged.zig
index ab9c98f..8016e82 100644
--- a/src/xwayland_unmanaged.zig
+++ b/src/xwayland_unmanaged.zig
@@ -221,9 +221,7 @@ fn handleUnmap(listener: *wl.Listener(void)) void {
fn grabKeyboard(self: *Unmanaged) void {
if (self.server.locker != null or self.server.polkit_dialog != null) return;
const surface = self.xsurface.surface orelse return;
- const seat = self.server.input.seat;
- const keyboard = seat.getKeyboard() orelse return;
- seat.keyboardNotifyEnter(surface, keyboard.keycodes[0..keyboard.num_keycodes], &keyboard.modifiers);
+ @import("Keyboard.zig").enter(self.server, surface);
}
/// If this popup still holds keyboard focus when it unmaps (closed via
@@ -235,11 +233,10 @@ fn restoreFocus(self: *Unmanaged) void {
const seat = self.server.input.seat;
const focused = seat.keyboard_state.focused_surface orelse return;
if (focused != own_surface) return;
- const keyboard = seat.getKeyboard() orelse return;
const parent_toplevel = parentToplevel(self) orelse self.server.world.toplevels.first();
const target = if (parent_toplevel) |t| t.surface() else null;
if (target) |surface| {
- seat.keyboardNotifyEnter(surface, keyboard.keycodes[0..keyboard.num_keycodes], &keyboard.modifiers);
+ @import("Keyboard.zig").enter(self.server, surface);
} else {
seat.keyboardClearFocus();
}
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 6e8e03a..31fb77b 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Appearance settings: window chrome opacity, inactive window opacity, file-drag dodge and animations controls.
+"""Appearance settings: window chrome opacity, inactive window opacity, file-drag dodge, animations controls, Start button logo preview and Start menu size.
Verifies UI controls, live compositor updates, and persistence to config.toml.
"""
@@ -101,6 +101,17 @@ def test_appearance_settings():
colors = image.convert("RGB").crop((0, image.height - 80, 100, image.height)).getdata()
return sum(1 for c in colors if c == (18, 231, 73)) > 100
+ def logo_preview():
+ """(green pixels, pixels differing from the tile colour) inside Settings' logo preview."""
+ ipc.wait_for_frame()
+ box = ui.scroll_into_view("start_logo_tile")["global_box"]
+ shot = tmp / f"preview-shot-{next(logo_shots)}.png"
+ ipc.screenshot(str(shot))
+ with Image.open(shot) as image:
+ crop = image.convert("RGB").crop((box["x"] + 6, box["y"] + 6, box["x"] + box["width"] - 6, box["y"] + box["height"] - 6))
+ pixels = list(crop.getdata())
+ return sum(1 for c in pixels if c == (18, 231, 73)), sum(1 for c in pixels if c != pixels[0])
+
assert ui.scroll_into_view("start_logo_reset")["is_disabled"]
click_widget(ui.scroll_into_view("start_logo_choose"))
window = wait_for(chooser, "logo file chooser")
@@ -118,6 +129,7 @@ def test_appearance_settings():
wait_for(lambda: chooser() is None, "logo chooser accepted")
wait_for(lambda: read_config()["theme"].get("start_button_icon") == str(logo), "saved logo path")
wait_for(logo_visible, "custom taskbar logo")
+ wait_for(lambda: logo_preview()[0] > 100, "Settings previews the chosen logo")
ipc.reload_config()
ipc.wait_for_panel_settled("control_center")
assert not ui.scroll_into_view("start_logo_reset")["is_disabled"]
@@ -138,6 +150,59 @@ def test_appearance_settings():
ipc.reload_config()
ipc.wait_for_panel_settled("control_center")
assert not logo_visible()
+ wait_for(lambda: logo_preview()[0] == 0 and logo_preview()[1] > 50, "Settings previews the default logo")
+
+ def menu_slider(name, fraction):
+ box = ui.scroll_into_view(name)["global_box"]
+ ipc.click_at(round(box["x"] + min(box["width"] - 1, box["width"] * fraction)), round(box["y"] + box["height"] / 2))
+ ipc.wait_for_panel_settled("control_center")
+
+ # Untouched, the menu is sized to the output (start_menu/size.zig):
+ # 560x600 from about 1706x1066 logical pixels up, the same share
+ # of the screen below that, never under 400x360.
+ output = ipc.get_outputs()[0]
+ auto_w = round(min(560, max(400, 560 * output["logical_width"] / 1706)))
+ auto_h = round(min(600, max(360, 600 * output["logical_height"] / 1066)))
+ assert ui.scroll_into_view("start_menu_width")["value"] == auto_w
+ assert ui.scroll_into_view("start_menu_height")["value"] == auto_h
+ assert ui.scroll_into_view("start_menu_size_auto")["is_disabled"]
+ assert "start_menu_width" not in read_config()["theme"]
+
+ def start_menu_box():
+ ipc.action("open_start_menu")
+ ipc.wait_for("menu_opened", timeout_ms=5000)
+ box = ipc.get_shell_state()["start_menu"]["box"]
+ ipc.close_panel("start_menu")
+ ipc.wait_for("menu_closed", timeout_ms=5000)
+ return box["width"], box["height"]
+
+ assert start_menu_box() == (auto_w, auto_h)
+ for fraction, width, height in ((0, 400, 360), (1, 900, 900)):
+ menu_slider("start_menu_width", fraction)
+ menu_slider("start_menu_height", fraction)
+ saved = read_config()["theme"]
+ assert saved["start_menu_width"] == width and saved["start_menu_max_height"] == height, saved
+ assert ui.scroll_into_view("start_menu_width")["value"] == width
+ assert ui.scroll_into_view("start_menu_height")["value"] == height
+ if fraction == 0:
+ # Exactly the chosen size: it is below any output's cap.
+ ipc.action("open_start_menu")
+ ipc.wait_for("menu_opened", timeout_ms=5000)
+ box = ipc.get_shell_state()["start_menu"]["box"]
+ assert (box["width"], box["height"]) == (width, height), box
+ ipc.close_panel("start_menu")
+ ipc.wait_for("menu_closed", timeout_ms=5000)
+
+ # Size to screen hands both back to the output.
+ assert not ui.scroll_into_view("start_menu_size_auto")["is_disabled"]
+ click_widget(ui.scroll_into_view("start_menu_size_auto"))
+ ipc.wait_for_panel_settled("control_center")
+ theme_saved = read_config()["theme"]
+ assert "start_menu_width" not in theme_saved and "start_menu_max_height" not in theme_saved, theme_saved
+ assert ui.scroll_into_view("start_menu_width")["value"] == auto_w
+ assert ui.scroll_into_view("start_menu_height")["value"] == auto_h
+ assert ui.scroll_into_view("start_menu_size_auto")["is_disabled"]
+ assert start_menu_box() == (auto_w, auto_h)
focus_zoom = ui.scroll_into_view("focus_zoom")
assert focus_zoom.get("selected_index") == 1, "boost should be the default"
diff --git a/tests/control_center.py b/tests/control_center.py
index e3fd660..3e11c12 100644
--- a/tests/control_center.py
+++ b/tests/control_center.py
@@ -330,6 +330,12 @@ def default_applications(scale):
"XDG_CONFIG_HOME": str(tmp / "config"), "XDG_CACHE_HOME": str(tmp / "cache"),
"REDIWM_DESKTOP_DIR": str(desktop), "DBUS_SESSION_BUS_ADDRESS": "",
"PULSE_SERVER": "unix:" + str(tmp / "no-audio")}
+ association_path = tmp / "config/mimeapps.list"
+ association_path.parent.mkdir(parents=True)
+ association_path.write_text(
+ '[Default Applications]\nx-scheme-handler/file=test-terminal.desktop;\n'
+ 'text/plain=test-terminal.desktop;\n'
+ '[Added Associations]\nx-scheme-handler/file=test-terminal.desktop;\n')
process, log = spawn_compositor(tmp, scale=scale, env_extra=env,
config_content='[desktop]\nenabled = true\n')
try:
@@ -350,6 +356,20 @@ def default_applications(scale):
ipc.wait_for_frame()
association = (tmp / "config/mimeapps.list").read_text()
assert "inode/directory=test-files.desktop" in association, association
+ # Transmission opens file: URIs through GIO. A stale scheme
+ # handler must not override the selected folder application.
+ assert "x-scheme-handler/file=" not in association, association
+ launch_env = dict(os.environ, **env)
+ subprocess.run(['gio', 'open', folder.as_uri()], env=launch_env, check=True)
+ wait(lambda: (tmp / "files").exists(), "file URI uses selected manager")
+ assert json.loads((tmp / "files").read_text()) == ["--fixture", str(folder)]
+ (tmp / "files").unlink()
+ document = tmp / "sample.txt"
+ document.write_text("fixture")
+ subprocess.run(['gio', 'open', document.as_uri()], env=launch_env, check=True)
+ wait(lambda: (tmp / "terminal").exists(), "file URI keeps document association")
+ assert json.loads((tmp / "terminal").read_text()) == ["--fixture", str(document)]
+ (tmp / "terminal").unlink()
# Reapply the current choice after another app changes the association.
association_path = tmp / "config/mimeapps.list"
association_path.write_text(association.replace(
diff --git a/tests/desktop_icons.py b/tests/desktop_icons.py
index b4d52a6..e41f3d8 100644
--- a/tests/desktop_icons.py
+++ b/tests/desktop_icons.py
@@ -458,6 +458,14 @@ def run():
wait_for(lambda: files_marker.exists() and files_marker.read_text()==str(trash_dir), 'Trash menu should wrap from Empty Trash to Open')
trashed_file=trash_dir/'empty-trash.txt';trashed_file.write_text('fixture')
click(152,172,273);key(108);key(28)
+ time.sleep(.2)
+ assert trashed_file.exists(), 'Desktop emptied Trash before confirmation'
+ key(1)
+ assert trashed_file.exists(), 'Cancelling Empty Trash deleted contents'
+ click(152,172,273);click(200,224)
+ time.sleep(.2)
+ assert trashed_file.exists(), 'Clicking Empty Trash bypassed confirmation'
+ key(15);key(28) # Tab reaches confirmation, without a deletion-mode checkbox.
wait_for(lambda: not any(trash_dir.iterdir()), 'Empty Trash did not clear the scratch Trash')
assert home.is_dir() and trash_dir.is_dir(), 'built-in action removed its folder'
reader.close();sock.close()
diff --git a/tests/file_chooser.py b/tests/file_chooser.py
index d0fe377..47116fc 100644
--- a/tests/file_chooser.py
+++ b/tests/file_chooser.py
@@ -29,11 +29,22 @@ def run():
(docs / "alpha.txt").write_text("keep this")
(docs / "beta.txt").write_text("second")
(docs / "image.png").write_bytes(b"fixture")
+ recent_dir = home / "Other folder"
+ recent_dir.mkdir()
+ recent_text = recent_dir / "alpha.txt"
+ recent_text.write_text("recent file in another directory")
+ data = tmp / "data"
+ data.mkdir()
+ (data / "recently-used.xbel").write_text(
+ '<xbel version="1.0">' + ''.join(
+ f'<bookmark href="{path.as_uri()}" visited="2026-01-0{day}T00:00:00Z"/>'
+ for path, day in [(docs / "beta.txt", 1), (recent_text, 2), (docs / "image.png", 3)]
+ ) + '</xbel>')
cfg = tmp / "config"
portals = cfg / "xdg-desktop-portal" / "rediwm-portals.conf"
portals.parent.mkdir(parents=True)
portals.write_text("# preserved\n[preferred]\ndefault=gtk\norg.freedesktop.impl.portal.ScreenCast=wlr\norg.freedesktop.impl.portal.Settings=rediwm;gtk\norg.freedesktop.impl.portal.FileChooser=rediwm;gtk\n")
- proc, log = spawn_compositor(tmp, env_extra={"HOME": str(home), "XDG_CONFIG_HOME": str(cfg), "REDIWM_FORCE_DBUS": "1", "GIO_USE_VFS": "local"})
+ proc, log = spawn_compositor(tmp, env_extra={"HOME": str(home), "XDG_CONFIG_HOME": str(cfg), "XDG_DATA_HOME": str(data), "REDIWM_FILES_DEVICES": "0", "REDIWM_FORCE_DBUS": "1", "GIO_USE_VFS": "local"})
try:
sock = wait_for(lambda: next(iter(tmp.glob("rediwm-*.sock")), None), "IPC")
with IPCClient(str(sock)) as ipc:
@@ -101,6 +112,19 @@ def run():
assert code == 0 and set(result["uris"]) == {(docs / "alpha.txt").as_uri(), (docs / "beta.txt").as_uri()}, result
print("multiple selection excludes filtered files", flush=True)
+ for multiple in (False, True):
+ request = start("OpenFile", {"filters": filters, "multiple": GLib.Variant("b", multiple)})
+ click(request[3], 70, 190) # Recent, below Trash
+ if multiple:
+ key(30, ctrl=True)
+ else:
+ key(102) # newest matching file
+ key(28)
+ code, result = finish(request)
+ expected = {recent_text.as_uri(), (docs / "beta.txt").as_uri()} if multiple else {recent_text.as_uri()}
+ assert code == 0 and set(result["uris"]) == expected, (code, result)
+ print("Recent opens full paths across folders with filters and multiple selection", flush=True)
+
request = start("OpenFile", {"filters": GLib.Variant("a(sa(us))", [("Text files", [(0, "*.txt")]), ("Images", [(0, "*.png")])])})
click(request[3], 650, 490)
key(108)
diff --git a/tests/files_controls.py b/tests/files_controls.py
index 0cadcef..f6557b9 100644
--- a/tests/files_controls.py
+++ b/tests/files_controls.py
@@ -58,6 +58,13 @@ def run():
marker = tmp / "opened"
opener = helpers / "gio"
opener.write_text('#!/bin/sh\n[ "$1" = "open" ] || exit 1\nprintf "%s" "$2" > "' + str(marker) + '"\n')
+ # Never invoke the real trash backend: it could include mounted trash.
+ empty_marker = tmp / "trash-emptied"
+ opener.write_text(opener.read_text().replace(
+ '[ "$1" = "open" ] || exit 1',
+ '[ "$1" = "trash" ] && [ "$2" = "--empty" ] && '
+ '[ "$#" = "2" ] && { printf emptied > "' + str(empty_marker) + '"; exit 0; }\n'
+ '[ "$1" = "open" ] || exit 1'))
opener.chmod(0o755)
applications = data / "applications"
applications.mkdir()
@@ -151,6 +158,26 @@ def run():
"did not open " + name)
marker.unlink()
+ def open_place_window(y, expected_title):
+ before = windows()
+ original = next(w for w in before if w["id"] == win["id"])
+ ids = {w["id"] for w in before}
+ click(70, y, 273)
+ key(108) # Open in New Window
+ key(28)
+ new = wait_for(lambda: next((w for w in windows() if w["id"] not in ids), None),
+ "sidebar did not open a new window")
+ wait_for(lambda: any(w["id"] == new["id"] and
+ w["title"] == expected_title + " — RediWM Files" for w in windows()),
+ "new window did not open " + expected_title)
+ assert next(w for w in windows() if w["id"] == win["id"])["title"] == original["title"], \
+ "Open in New Window navigated the original window"
+ action('close_window', {"id": new["id"]})
+ wait_for(lambda: all(w["id"] != new["id"] for w in windows()),
+ "new window did not close")
+ action('focus_window', {"id": win["id"]})
+ time.sleep(.2)
+
if "--archive-only" in sys.argv:
archive_dir = tmp / "archive-check"
archive_dir.mkdir()
@@ -209,6 +236,12 @@ def run():
key(105, alt=True)
title("Home")
+ # New windows use the clicked place and leave the current folder alone.
+ open_place_window(305, "Documents")
+ open_place_window(140, "Home")
+ open_place_window(210, "Recent")
+ open_place_window(175, "Trash")
+
# Trash below Home opens the local trash, even before its first use.
click(70, 175)
title("Trash")
@@ -217,6 +250,25 @@ def run():
click(70, 140)
title("Home")
+ # Empty Trash is a sidebar action independent of the current folder.
+ def empty_trash_dialog():
+ click(70, 175, button=273)
+ key(108) # Down: Open in New Window
+ key(108) # Down: Empty Trash…
+ key(28) # Open the confirmation, without executing it.
+ assert not empty_marker.exists(), "Trash emptied before confirmation"
+
+ empty_trash_dialog()
+ key(1) # Escape cancels.
+ assert not empty_marker.exists(), "Cancel emptied Trash"
+ title("Home")
+ empty_trash_dialog()
+ key(15) # Tab skips the unavailable permanent-delete toggle.
+ key(28)
+ wait_for(empty_marker.exists, "Empty Trash did not invoke gio trash --empty")
+ empty_marker.unlink()
+ title("Home")
+
# Recent below Trash uses shared history, newest opened first,
# and opens real paths (including spaces and Unicode).
click(70, 210)
@@ -241,7 +293,7 @@ def run():
key(49, ctrl=True) # Ctrl+N cannot create inside a virtual location.
title("Recent")
click(70, 210, 273)
- key(28) # The Recent menu offers Open only.
+ key(28) # Open Recent in the current window.
title("Recent")
write_recent(recent_old)
time.sleep(.3)
@@ -341,6 +393,7 @@ def run():
title("Documents")
click(70, 305, 273)
key(108)
+ key(108)
key(28) # Unpin
title("Documents") # Unpin does not navigate or delete the folder.
assert (home / "Documents").is_dir()
@@ -348,7 +401,8 @@ def run():
assert saved[0] == ord("3") and saved[3] & 2 and saved[4] == 1, saved
click(70, 305) # Downloads now occupies Documents' old row.
title("Downloads")
- click(70, 140, 273) # Home has Open and Properties, without Unpin.
+ click(70, 140, 273) # Home has Open, Open in New Window and Properties.
+ key(108)
key(108)
key(28) # Properties opens a modal without navigating.
title("Downloads")
@@ -357,7 +411,55 @@ def run():
key(28)
title("Home")
- print("PASS: Files navigation, Recent, toolbar and Places controls", flush=True)
+ # The pane divider resizes independently of file selection and
+ # stays within its minimum and half the client width.
+ from PIL import Image
+
+ def sidebar_shot():
+ shot = tmp / "sidebar.png"
+ shot.unlink(missing_ok=True)
+ action('screenshot', {"path": str(shot)})
+ box = request({"version": 1, "command": 'get_window_debug', "params": {"id": win["id"]}})["WindowDebug"]["client_box"]
+ with Image.open(shot) as full:
+ return full.convert("RGB").crop((box["x"], box["y"], box["x"] + box["width"], box["y"] + box["height"]))
+
+ def pane_width_is(width):
+ image = sidebar_shot()
+ background = image.getpixel((5, 120))
+ return (image.getpixel((width - 20, 120)) == background and
+ image.getpixel((width - 1, 120)) != background and
+ image.getpixel((width + 2, 120)) != background)
+
+ def drag_divider(start, end):
+ box = request({"version": 1, "command": 'get_window_debug', "params": {"id": win["id"]}})["WindowDebug"]["client_box"]
+ action('move_cursor', {"x": box["x"] + start, "y": box["y"] + 140})
+ action('pointer_button', {"button": 272, "pressed": True})
+ action('move_cursor', {"x": box["x"] + end, "y": box["y"] + 190})
+ action('pointer_button', {"button": 272, "pressed": False})
+
+ drag_divider(208, 340)
+ wait_for(lambda: pane_width_is(340), "sidebar did not grow with its divider")
+ title("Home")
+ click(727, 80) # The same divider works in list view.
+ drag_divider(340, 850)
+ wait_for(lambda: pane_width_is(480), "sidebar exceeded half the window width")
+ action('set_window_size', {"id": win["id"], "width": 600, "height": 540})
+ wait_for(lambda: sidebar_shot().width == 600 and pane_width_is(300),
+ "sidebar did not clamp after the window shrank")
+ action('set_window_size', {"id": win["id"], "width": 960, "height": 540})
+ wait_for(lambda: sidebar_shot().width == 960 and pane_width_is(480),
+ "sidebar forgot its width after the window grew")
+ drag_divider(480, 20)
+ wait_for(lambda: pane_width_is(160), "sidebar shrank below its minimum")
+ drag_divider(160, 208)
+ wait_for(lambda: pane_width_is(208), "sidebar divider did not release")
+ click(690, 80) # Restore the grid for the remaining checks.
+ click(70, 305)
+ title("Downloads")
+ click(70, 140)
+ title("Home")
+
+ print("PASS: Files navigation, Recent, toolbar, Places and sidebar resizing", flush=True)
if "--places-only" in sys.argv:
return
diff --git a/tests/files_drag.py b/tests/files_drag.py
index 45d2545..d26f36a 100644
--- a/tests/files_drag.py
+++ b/tests/files_drag.py
@@ -251,6 +251,21 @@ def run_pin():
drag(0, 80, 270)
time.sleep(.3)
assert pins() == [str(n) for n in names], pins()
+ # A folder pin can open a separate window without navigating this one.
+ click(80, 526, 273)
+ for code in (108, 28):
+ ipc.action('key', {"keycode": code, "pressed": True})
+ ipc.action('key', {"keycode": code, "pressed": False})
+ new = wait_for(lambda: next((w for w in ipc.get_windows()
+ if w["app_id"] == "rediwm-files" and w["id"] != win["id"]), None),
+ "folder pin did not open a new window")
+ assert new["title"] == "second folder — RediWM Files", new
+ assert next(w for w in ipc.get_windows() if w["id"] == win["id"])["title"] == win["title"]
+ ipc.close_window(new["id"])
+ wait_for(lambda: all(w["id"] != new["id"] for w in ipc.get_windows()), "new pin window did not close")
+ ipc.action('focus_window', {"id": win["id"]})
+ time.sleep(.3)
+ box = ipc.get_window_debug(win["id"])["client_box"]
# A click opens a folder pin.
click(80, 526)
wait_for(lambda: any(w["title"].startswith("second folder") for w in ipc.get_windows()), "pin did not open its folder")
diff --git a/tests/layer_lifecycle.py b/tests/layer_lifecycle.py
index 09dc6e4..385e246 100644
--- a/tests/layer_lifecycle.py
+++ b/tests/layer_lifecycle.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Disconnect and recreate real layer clients; no freed layers may remain listed."""
+"""Layer clients survive screen blanking; disconnect leaves no stale entries."""
import os
from pathlib import Path
import subprocess
@@ -29,8 +29,12 @@ def run():
tmp = Path(directory)
layer_client = build_layer_client(tmp)
compositor, log = spawn_compositor(
- tmp, config_content="[compositor]\nxwayland = false\n",
- env_extra={"XDG_CACHE_HOME": str(tmp / "cache")})
+ tmp, outputs="2", config_content="[compositor]\nxwayland = false\n",
+ env_extra={"XDG_CACHE_HOME": str(tmp / "cache"),
+ "XDG_DATA_HOME": str(tmp / "data"),
+ "DBUS_SESSION_BUS_ADDRESS": "unix:path=" + str(tmp / "missing-bus"),
+ "PULSE_SERVER": "unix:" + str(tmp / "missing-pulse"),
+ "PIPEWIRE_RUNTIME_DIR": str(tmp)})
client = None
try:
with IPCClient(tmp) as ipc:
@@ -46,6 +50,43 @@ def run():
wait_for(lambda: not ipc.query('get_layer_surfaces')["surfaces"], "destroyed layer still listed")
assert compositor.poll() is None
print("layer lifecycle: disconnect/recreate leaves no stale layer entries")
+
+ # A disabled monitor must not be chosen over an enabled but
+ # sleeping one when the client leaves output selection to us.
+ disabled, active = ipc.get_outputs()
+ ipc.action('set_output_config', {"output": disabled["name"], "enabled": False})
+ active = next(o for o in ipc.get_outputs() if o["name"] == active["name"])
+ ipc.action('set_idle_config', {"enabled": True, "blank_after_seconds": 10,
+ "suspend_after_seconds": 0})
+ ipc.action('advance_idle_time', {"seconds": 15})
+ wait_for(lambda: all(not o["enabled"] for o in ipc.get_outputs()), "outputs did not blank")
+
+ client = subprocess.Popen([str(layer_client)], env=env,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+ def mapped_layer():
+ assert client.poll() is None, "layer client was closed while the display was asleep"
+ return next((s for s in ipc.get_layer_surfaces() if s["mapped"]), None)
+
+ layer = wait_for(mapped_layer, "layer did not map while display was asleep")
+ expected_box = {"x": active["x"], "y": active["y"],
+ "width": active["logical_width"], "height": active["logical_height"]}
+ assert layer["output"] == active["name"], layer
+ assert layer["box"] == expected_box, (layer, expected_box)
+ assert all(not o["enabled"] for o in ipc.get_outputs()), "layer woke a display"
+ assert ipc.query('get_idle_state')["state"] == "blanked"
+
+ ipc.action('key', {"keycode": 30, "pressed": True})
+ ipc.action('key', {"keycode": 30, "pressed": False})
+ wait_for(lambda: next(o for o in ipc.get_outputs() if o["name"] == active["name"])["enabled"],
+ "display did not wake")
+ assert not next(o for o in ipc.get_outputs() if o["name"] == disabled["name"])["enabled"]
+ assert mapped_layer()["box"] == expected_box
+ stop_process(client)
+ client = None
+ wait_for(lambda: not ipc.get_layer_surfaces(), "woken layer left a stale entry")
+ assert compositor.poll() is None
+ print("layer lifecycle: maps while asleep at saved size, stays dark, survives wake")
except Exception:
log.flush()
print((tmp / "compositor.log").read_text())
diff --git a/tests/pdf_sandbox_hook.c b/tests/pdf_sandbox_hook.c
index e0a4589..2cf2ea9 100644
--- a/tests/pdf_sandbox_hook.c
+++ b/tests/pdf_sandbox_hook.c
@@ -13,6 +13,7 @@
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
+#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <unistd.h>
@@ -112,8 +113,30 @@ static void probe(int document_fd) {
CHECK(fd >= 0 && ftruncate(fd, 4096) == 0 && write(fd, "ok", 2) == 2);
close(fd);
- // Use a separate event queue because this runs on the PDF worker.
CHECK(filtered_display);
+ // The print helper's socket is the one other socket. It carries request
+ // bytes only (writing one would open a real print dialog): passing a
+ // descriptor out over it must be refused.
+ int display_fd = wl_display_get_fd(filtered_display), sockets = 0;
+ for (int other = 3; other < 128; other++) {
+ struct stat st;
+ if (other == display_fd || fstat(other, &st) < 0 || !S_ISSOCK(st.st_mode)) continue;
+ sockets++;
+ char byte = 0;
+ struct iovec iov = { .iov_base = &byte, .iov_len = 1 };
+ union { char buf[CMSG_SPACE(sizeof(int))]; struct cmsghdr align; } control;
+ memset(&control, 0, sizeof(control));
+ struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1, .msg_control = control.buf, .msg_controllen = sizeof(control.buf) };
+ struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+ memcpy(CMSG_DATA(cmsg), &document_fd, sizeof(int));
+ CHECK(denied(sendmsg(other, &msg, MSG_DONTWAIT)));
+ }
+ CHECK(sockets == 1);
+
+ // Use a separate event queue because this runs on the PDF worker.
struct wl_event_queue *queue = wl_display_create_queue(filtered_display);
CHECK(queue);
struct wl_registry *registry = wl_display_get_registry(filtered_display);
diff --git a/tests/pdf_viewer.py b/tests/pdf_viewer.py
index c62b85c..0dca9ff 100755
--- a/tests/pdf_viewer.py
+++ b/tests/pdf_viewer.py
@@ -7,6 +7,7 @@ import shutil
import tempfile
import time
import sys
+import warnings
import cairo
from PIL import Image
from ipc_client import IPCClient, ROOT
@@ -42,6 +43,89 @@ def generate_fixture_pdf(path: Path):
surface.finish()
+def generate_tall_pdf(path: Path):
+ """One tall page: fit width rasterizes it in tiles. Its top is a blue left
+ half and a red right half."""
+ surface = cairo.PDFSurface(str(path), 400, 1600)
+ cr = cairo.Context(surface)
+ cr.set_source_rgb(0, 0, 1)
+ cr.rectangle(0, 0, 200, 400)
+ cr.fill()
+ cr.set_source_rgb(1, 0, 0)
+ cr.rectangle(200, 0, 200, 400)
+ cr.fill()
+ surface.finish()
+
+
+class FakePrintPortal:
+ """org.freedesktop.portal.Print on a private bus. Records each document it
+ is handed, then answers the request with `response` (0 printed, 2 failed)."""
+
+ XML = """<node><interface name="org.freedesktop.portal.Print">
+ <method name="Print"><arg type="s" direction="in"/><arg type="s" direction="in"/>
+ <arg type="h" direction="in"/><arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
+ </interface></node>"""
+
+ def __init__(self):
+ import threading
+ from gi.repository import Gio, GLib
+ self.GLib = GLib
+ self.jobs = []
+ self.response = 0
+ self.daemon = subprocess.Popen(["dbus-daemon", "--session", "--nofork", "--print-address=1"],
+ stdout=subprocess.PIPE, text=True)
+ self.address = self.daemon.stdout.readline().strip()
+ flags = Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION
+ self.conn = Gio.DBusConnection.new_for_address_sync(self.address, flags, None, None)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning) # register_object's closure-less form
+ self.conn.register_object("/org/freedesktop/portal/desktop",
+ Gio.DBusNodeInfo.new_for_xml(self.XML).interfaces[0], self.call, None, None)
+ self.conn.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName",
+ GLib.Variant("(su)", ("org.freedesktop.portal.Desktop", 4)), None,
+ Gio.DBusCallFlags.NONE, 3000, None)
+ self.loop = GLib.MainLoop()
+ threading.Thread(target=self.loop.run, daemon=True).start()
+
+ def call(self, conn, sender, _path, _interface, _method, params, invocation):
+ parent, title, index, options = params.unpack()
+ fd = invocation.get_message().get_unix_fd_list().get(index)
+ with os.fdopen(fd, "rb") as document:
+ data = document.read()
+ request = "/org/freedesktop/portal/desktop/request/%s/%s" % (
+ sender[1:].replace(".", "_"), options.get("handle_token", "t"))
+ invocation.return_value(self.GLib.Variant("(o)", (request,)))
+ self.jobs.append({"parent": parent, "title": title, "data": data, "options": options})
+ conn.emit_signal(sender, request, "org.freedesktop.portal.Request", "Response",
+ self.GLib.Variant("(ua{sv})", (self.response, {})))
+
+ def close(self):
+ self.loop.quit()
+ self.conn.close_sync(None)
+ self.daemon.terminate()
+ self.daemon.wait(timeout=5)
+
+
+def print_helper(viewer_pid):
+ """The viewer's unsandboxed print helper process, if it is running."""
+ for entry in Path("/proc").iterdir():
+ try:
+ stat = (entry / "stat").read_text()
+ except (OSError, ValueError):
+ continue
+ fields = stat[stat.rindex(")") + 2:].split()
+ if "(rediwm-pdf-prnt)" in stat and int(fields[1]) == viewer_pid:
+ return int(entry.name)
+ return None
+
+
+def gone(pid):
+ try:
+ return Path(f"/proc/{pid}/stat").read_text().split(") ")[1][0] == "Z"
+ except OSError:
+ return True
+
+
def run(scale: int = 1):
with tempfile.TemporaryDirectory(prefix="rediwm-pdf-") as directory:
tmp = Path(directory)
@@ -131,6 +215,14 @@ def run(scale: int = 1):
key(1)
expect_title("(1/2)")
+ # Printing lives in a helper outside the sandbox. Without a
+ # session bus, Ctrl+P reports that and the viewer carries on.
+ helper = wait_for(lambda: print_helper(pdf_proc.pid), "print helper not running")
+ key(25, ctrl=True)
+ time.sleep(0.5)
+ assert pdf_proc.poll() is None and not gone(helper)
+ key(1)
+
# Take screenshot to verify rendering
shot_path = tmp / "screenshot.png"
ipc.screenshot(path=str(shot_path))
@@ -173,6 +265,62 @@ def run(scale: int = 1):
pdf_proc.wait(timeout=5)
assert pdf_proc.returncode == 0, f"rediwm-pdf exited with code {pdf_proc.returncode}"
+ wait_for(lambda: gone(helper), "print helper outlived the viewer")
+
+ # The Print button hands the opened file to the print portal.
+ portal = FakePrintPortal()
+ try:
+ print_proc = start("rediwm-pdf", str(doc_path), WAYLAND_DISPLAY=display,
+ DBUS_SESSION_BUS_ADDRESS=portal.address)
+ win = wait_for(viewer, "printing viewer did not map")
+ ipc.focus_window(win["id"])
+ expect_title("(1/2)")
+ box = ipc.get_window_debug(win["id"])["client_box"]
+ ipc.move_cursor(int(box["x"] + 612), int(box["y"] + 22))
+ time.sleep(0.1)
+ for pressed in (True, False):
+ ipc.action("pointer_button", {"button": 272, "pressed": pressed})
+ job = wait_for(lambda: portal.jobs and portal.jobs[0], "Print button did not reach the portal")
+ assert job["data"] == doc_path.read_bytes(), "printed bytes differ from the document"
+ assert job["title"] == doc_path.name and job["parent"] == "", job
+ # Answered requests free the helper for the next one.
+ key(25, ctrl=True)
+ wait_for(lambda: len(portal.jobs) == 2, "Ctrl+P did not print again")
+ assert portal.jobs[1]["data"] == job["data"]
+ key(17, ctrl=True)
+ wait_for(lambda: not viewer(), "printing viewer did not close")
+ assert print_proc.wait(timeout=5) == 0
+ finally:
+ portal.close()
+
+ # Tiles are clipped in raster pixels: at any scale each one
+ # shows its own part of the page, not a magnified corner.
+ tall = tmp / "tall.pdf"
+ generate_tall_pdf(tall)
+ tall_proc = start("rediwm-pdf", str(tall), WAYLAND_DISPLAY=display)
+ win = wait_for(viewer, "tall PDF viewer did not map")
+ ipc.focus_window(win["id"])
+ expect_title("(1/1)")
+ key(11) # 0: fit width
+
+ tall_shot = tmp / "tall.png"
+
+ def halves():
+ tall_shot.unlink(missing_ok=True)
+ ipc.screenshot(path=str(tall_shot))
+ box = ipc.get_window_debug(win["id"])["client_box"]
+ with Image.open(tall_shot) as shot:
+ top = shot.convert("RGB").crop(tuple(round(v * scale) for v in (
+ box["x"] + 180, box["y"] + 64, box["x"] + box["width"], box["y"] + 160)))
+ colors = top.getcolors(top.width * top.height) or []
+ blue = sum(n for n, (r, g, b) in colors if b > 200 and r < 60 and g < 60)
+ red = sum(n for n, (r, g, b) in colors if r > 200 and g < 60 and b < 60)
+ return red > 0 and 0.8 < blue / red < 1.25
+
+ wait_for(halves, "fit width does not show the page's own halves")
+ key(17, ctrl=True)
+ wait_for(lambda: not viewer(), "tall PDF viewer did not close")
+ assert tall_proc.wait(timeout=5) == 0
# Files opens PDFs itself, without an installed MIME association.
documents = tmp / "documents"
diff --git a/tests/power_menu.py b/tests/power_menu.py
index 134d28b..4a852fb 100644
--- a/tests/power_menu.py
+++ b/tests/power_menu.py
@@ -16,7 +16,8 @@ from ipc_client import IPCClient, spawn_compositor, stop_process
def run(scale):
with tempfile.TemporaryDirectory(prefix="rediwm-power-test-") as directory:
tmp = Path(directory)
- process, log = spawn_compositor(tmp, scale=scale, env_extra={
+ process, log = spawn_compositor(tmp, scale=scale,
+ config_content='[theme]\nwindow_bg = "rgba(24,30,40,0.70)"\n', env_extra={
"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": directory,
})
try:
@@ -51,13 +52,14 @@ def run(scale):
opened = capture("open")
s = float(scale)
# Sample clear padding after the opening animation settles:
- # 56% neutral tint over the wallpaper and the 45% scrim.
+ # Configured chrome tint/opacity over the wallpaper and
+ # the 45% scrim, independent of the shell glass alpha.
point = (round((box["x"] + 20) * s),
round((box["y"] + box["height"] / 2) * s))
behind = closed.getpixel(point)
actual = opened.getpixel(point)
- expected = tuple(round(bg * .55 * .44 + tint * .56)
- for bg, tint in zip(behind, (38, 45, 55)))
+ expected = tuple(round(bg * .55 * .30 + tint * .70)
+ for bg, tint in zip(behind, (24, 30, 40)))
assert max(abs(a - b) for a, b in zip(actual, expected)) <= 3, (actual, expected)
# Both logical pixels of the idle border must be visible.
x = round((box["x"] + card["x"] + card["width"] / 2) * s)
@@ -65,8 +67,8 @@ def run(scale):
for offset in (.5, 1.5):
point = (x, int((top + offset) * s))
edge = opened.getpixel(point)
- tint_only = tuple(round(bg * .55 * .44 + tint * .56)
- for bg, tint in zip(closed.getpixel(point), (38, 45, 55)))
+ tint_only = tuple(round(bg * .55 * .30 + tint * .70)
+ for bg, tint in zip(closed.getpixel(point), (24, 30, 40)))
assert min(a - b for a, b in zip(edge, tint_only)) >= 4, (edge, tint_only)
if cancel and (preview := os.environ.get("REDIWM_POWER_PREVIEW")):
opened.save(preview)
diff --git a/tests/start_menu.py b/tests/start_menu.py
index 9283dde..32a3849 100644
--- a/tests/start_menu.py
+++ b/tests/start_menu.py
@@ -101,7 +101,10 @@ def run():
for _ in repeated:
key(14)
- hit = client.hit_test(100, 200)
+ # The menu is sized to the output, so aim at its centre (the result list).
+ menu = client.get_shell_state()["start_menu"]["box"]
+ centre = (menu["x"] + menu["width"] // 2, menu["y"] + menu["height"] // 2)
+ hit = client.hit_test(*centre)
assert hit.get("target_type") in ("panel", "widget", "window", "start_menu"), hit
key(30) # Search for 'a', rebuilding and laying out the tree.
@@ -116,7 +119,7 @@ def run():
assert ImageChops.difference(searched, selected).getbbox(), "selection did not repaint"
key(14) # Clear search, then scroll to load a different set of icons.
- client.move_cursor(250, 300)
+ client.move_cursor(*centre)
client.wait_for_frame(timeout_ms=2000)
hovered = capture_now("hovered")
client.scroll(0, 180)
diff --git a/tests/startup.py b/tests/startup.py
index 72f1687..f8ee3e8 100644
--- a/tests/startup.py
+++ b/tests/startup.py
@@ -7,6 +7,7 @@ from pathlib import Path
import json
import re
import socket
+import struct
import tempfile
import time
@@ -235,9 +236,59 @@ def test_stalled_audio_does_not_block():
log.close()
+def test_stalled_wayland_client_recovers():
+ """Queue replies while a client is busy, then consume every reply."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-client-buffer-") as directory:
+ tmp = Path(directory)
+ process, log = spawn_compositor(tmp, config_content='[compositor]\nxwayland = false\n', env_extra={
+ "XDG_DATA_HOME": str(tmp / "data"),
+ "XDG_DATA_DIRS": str(tmp / "empty"),
+ "XDG_CACHE_HOME": str(tmp / "cache"),
+ "DBUS_SESSION_BUS_ADDRESS": "unix:path=" + str(tmp / "missing-bus"),
+ "PULSE_SERVER": "unix:" + str(tmp / "missing-pulse"),
+ "PIPEWIRE_RUNTIME_DIR": str(tmp),
+ })
+ try:
+ with IPCClient(socket_path=tmp, timeout=10) as client:
+ # Each wl_display.sync produces callback.done + delete_id,
+ # 24 bytes total. Withhold reads to exercise backpressure.
+ display = next(p for p in tmp.glob("wayland-*") if p.is_socket())
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
+ peer.settimeout(5)
+ peer.connect(str(display))
+ count = 20_000
+ peer.sendall(b"".join(struct.pack("=III", 1, 12 << 16, i)
+ for i in range(2, count + 2)))
+ client.get_shell_state() # The desktop still responds.
+ received = bytearray()
+ while len(received) < count * 24:
+ data = peer.recv(count * 24 - len(received))
+ assert data, f"busy client disconnected after {len(received)} reply bytes"
+ received.extend(data)
+ for index in range(count):
+ callback, event, _, display_id, delete_event, deleted = struct.unpack_from(
+ "=IIIIII", received, index * 24)
+ assert (callback, event) == (index + 2, 12 << 16)
+ assert (display_id, delete_event, deleted) == (1, (12 << 16) | 1, index + 2)
+ # A subsequent roundtrip proves the connection remains usable.
+ peer.sendall(struct.pack("=III", 1, 12 << 16, 2))
+ reply = bytearray()
+ while len(reply) < 24:
+ data = peer.recv(24 - len(reply))
+ assert data, "client disconnected after draining its backlog"
+ reply.extend(data)
+ assert struct.unpack("=IIIIII", reply)[0] == 2
+ assert "Data too big for buffer" not in (tmp / "compositor.log").read_text()
+ print("startup: stalled Wayland client drained 20,000 callbacks and recovered")
+ finally:
+ stop_process(process)
+ log.close()
+
+
if __name__ == "__main__":
test_responsive_before_publication()
test_cache_then_revalidate()
test_corrupt_cache_falls_back()
test_early_shutdown_joins_workers()
test_stalled_audio_does_not_block()
+ test_stalled_wayland_client_recovers()
diff --git a/tests/taskbar_items.py b/tests/taskbar_items.py
deleted file mode 100644
index 8bf3c9d..0000000
--- a/tests/taskbar_items.py
+++ /dev/null
@@ -1,206 +0,0 @@
-#!/usr/bin/env python3
-"""Move/hide taskbar items through Settings; check live geometry and persistence.
-
-Uses private headless compositors and temporary config files, never the host UI.
-"""
-import tempfile
-import time
-import tomllib
-from pathlib import Path
-
-from ipc_client import IPCClient, spawn_compositor, stop_process
-from ui_driver import UIDriver
-
-
-def wait(predicate, message):
- deadline = time.monotonic() + 8
- while time.monotonic() < deadline:
- if predicate():
- return
- time.sleep(.05)
- raise AssertionError(message)
-
-
-def run(scale):
- with tempfile.TemporaryDirectory(prefix="rediwm-taskbar-items-") as directory:
- root = Path(directory)
- config = '# preserve me\n[compositor]\nxwayland = false\n[input]\ninvert_scroll = false\n'
- expected = None
- for restart in range(2):
- runtime = root / str(restart)
- runtime.mkdir()
- process, log = spawn_compositor(runtime, scale=scale, config_content=config, env_extra={
- "DBUS_SESSION_BUS_ADDRESS": "unix:path=/nonexistent/rediwm-test-bus",
- "PULSE_SERVER": "unix:/nonexistent/rediwm-test-audio",
- "REDIWM_THEME": "",
- "XDG_CACHE_HOME": str(runtime),
- })
- try:
- with IPCClient(runtime, timeout=15) as ipc:
- ipc.wait_for("wallpaper_presented", timeout_ms=10000)
-
- def items():
- return ipc.get_shell_state()["taskbars"][0]["right_items"]
-
- def state():
- return [(item["name"], item["visible"]) for item in items()]
-
- def validate():
- visible = [item for item in items() if item["box"] is not None]
- for a, b in zip(visible, visible[1:]):
- assert a["box"]["x"] + a["box"]["width"] <= b["box"]["x"], visible
- for item in visible:
- box = item["box"]
- hit = ipc.hit_test(box["x"] + box["width"] // 2, box["y"] + box["height"] // 2)
- want = {"clock": "clock", "volume": "tray", "network": "tray", "battery": "battery"}[item["name"]]
- assert hit.get("widget") == want, (item, hit)
-
- def check_position(top):
- bar = ipc.get_shell_state()["taskbars"][0]["box"]
- output = ipc.get_outputs()[0]
- assert bar["y"] == (output["y"] if top else output["y"] + output["logical_height"] - bar["height"]), bar
-
- if restart:
- check_position(True)
- assert state() == expected, (state(), expected)
- validate()
- # Hide every item through a config reload, then restore the defaults.
- path = runtime / "rediwm-config.toml"
- path.write_text('[compositor]\nxwayland = false\ntaskbar_items = ["-clock", "-battery", "-network", "-volume"]\n')
- wait(lambda: all(not i["visible"] and i["box"] is None for i in items()), "hide all on reload")
- path.write_text('[compositor]\nxwayland = false\n')
- wait(lambda: state() == [(n, True) for n in ("battery", "network", "volume", "clock")], "restore defaults on reload")
- check_position(False)
- validate()
- continue
-
- assert state() == [(n, True) for n in ("battery", "network", "volume", "clock")]
- validate()
- ipc.action('open_appearance')
-
- def widgets():
- return ipc.get_widget_tree("control_center")["widgets"]
-
- def row_control(name, control):
- # Scroll until the row is fully inside the settings viewport.
- for _ in range(30):
- tree = widgets()
- row = next(w for w in tree if w["role"] == "text" and w["label"] == name)
- box = ipc.get_shell_state()["control_center"]["box"]
- center = row["box"]["y"] + row["box"]["height"] / 2
- if 140 < center < box["height"] - 35:
- candidates = [w for w in tree if abs(w["box"]["y"] + w["box"]["height"] / 2 - center) < 5]
- return next(w for w in candidates if (w["role"] == "toggle" if control == "toggle" else w["role"] == "button" and w["label"] == control))
- ipc.move_cursor(box["x"] + box["width"] - 20, box["y"] + box["height"] - 90)
- ipc.scroll(0, 130 if center >= box["height"] - 35 else -130)
- time.sleep(.1)
- raise AssertionError(f"could not scroll to {name}")
-
- def click(name, control):
- widget = row_control(name, control)
- box = ipc.get_shell_state()["control_center"]["box"]
- rect = widget["box"]
- ipc.click_at(round(box["x"] + rect["x"] + rect["width"] / 2), round(box["y"] + rect["y"] + rect["height"] / 2))
- time.sleep(.25)
-
- def handle_point(name):
- widget = row_control(name, "Drag to reorder")
- box = ipc.get_shell_state()["control_center"]["box"]
- rect = widget["box"]
- return (round(box["x"] + rect["x"] + rect["width"] / 2),
- round(box["y"] + rect["y"] + rect["height"] / 2))
-
- def drag(name, target, down=False, cancel=False, outside=False):
- # Ensure both rows are visible, then read their final positions.
- handle_point(name)
- tx, ty = handle_point(target)
- sx, sy = handle_point(name)
- ipc.move_cursor(sx, sy)
- ipc.pointer_button(0x110, True)
- before = state()
- ipc.move_cursor(tx, ty + (3 if down else -3))
- assert state() == before, "drag must persist only on release"
- tree = widgets()
- rows = [w["label"] for w in sorted(tree, key=lambda w: w["box"]["y"])
- if w["role"] == "text" and w["label"] in {"Battery", "Network", "Volume", "Clock"}]
- assert rows.index(name) == [i["name"] for i in items()].index(target.lower()), rows
- if outside:
- box = ipc.get_shell_state()["control_center"]["box"]
- ipc.move_cursor(box["x"] + box["width"] + 20, ty + (3 if down else -3))
- if cancel:
- ipc.key_down_up(1) # Escape restores the saved order.
- ipc.pointer_button(0x110, False)
- time.sleep(.25)
- if cancel:
- assert state() == before, "Escape must cancel reordering"
-
- click("Clock", "Drag to reorder")
- assert state() == [(n, True) for n in ("battery", "network", "volume", "clock")]
- drag("Clock", "Battery", cancel=True)
- drag("Clock", "Battery")
- wait(lambda: items()[0]["name"] == "clock", "drag last to first")
- drag("Clock", "Volume", down=True, outside=True)
- wait(lambda: items()[-1]["name"] == "clock", "drag first to last")
- click("Network", "toggle")
- wait(lambda: not next(i for i in items() if i["name"] == "network")["visible"], "hide network")
- drag("Clock", "Volume")
- wait(lambda: [i["name"] for i in items()] == ["battery", "network", "clock", "volume"], "move clock left")
- drag("Network", "Clock", down=True)
- wait(lambda: [i["name"] for i in items()] == ["battery", "clock", "network", "volume"], "move hidden network")
- ipc.key_down_up(103) # Up, then Down on the focused handle.
- wait(lambda: items()[1]["name"] == "network", "keyboard reorder up")
- ipc.key_down_up(108)
- wait(lambda: items()[2]["name"] == "network", "keyboard reorder down")
- click("Network", "toggle")
- wait(lambda: all(i["visible"] for i in items()), "show network")
- click("Volume", "toggle")
- expected = [("battery", True), ("clock", True), ("network", True), ("volume", False)]
- wait(lambda: state() == expected, "hide volume")
- ui = UIDriver(ipc)
- for index in (0, 1, 0):
- widget = ui.scroll_into_view("taskbar_position")
- rect = widget["global_box"]
- ipc.click_at(round(rect["x"] + rect["width"] * (index + .5) / 2), round(rect["y"] + rect["height"] / 2))
- time.sleep(.25)
- check_position(index == 0)
- assert ui.scroll_into_view("taskbar_position")["selected_index"] == index
- assert tomllib.loads((runtime / "rediwm-config.toml").read_text())["compositor"]["taskbar_position"] == ("top" if index == 0 else "bottom")
- preview = Path(f"/tmp/rediwm-taskbar-items-{scale}.png")
- preview.unlink(missing_ok=True)
- ipc.screenshot(str(preview))
- ipc.close_panel("control_center")
- wait(lambda: ipc.get_shell_state().get("control_center") is None, "close settings")
- validate()
- # Menus open below a top taskbar and remain interactive.
- bar = ipc.get_shell_state()["taskbars"][0]
- clock = next(i["box"] for i in items() if i["name"] == "clock")
- ipc.click_at(clock["x"] + clock["width"] // 2, clock["y"] + clock["height"] // 2)
- time.sleep(.25)
- output = ipc.get_outputs()[0]
- hit = ipc.hit_test(output["x"] + output["logical_width"] - 50, bar["box"]["y"] + bar["box"]["height"] + 50)
- assert hit["target_type"] == "calendar", hit
- ipc.key_down_up(1)
- start = bar["start_button_box"]
- ipc.click_at(start["x"] + start["width"] // 2, start["y"] + start["height"] // 2)
- time.sleep(.25)
- menu = ipc.get_shell_state()["start_menu"]["box"]
- assert menu["y"] >= bar["box"]["y"] + bar["box"]["height"], menu
- ipc.key_down_up(1)
- config = (runtime / "rediwm-config.toml").read_text()
- saved = tomllib.loads(config)
- assert saved["compositor"]["taskbar_items"] == ["battery", "clock", "network", "-volume"], saved
- assert "# preserve me" in config and saved["input"]["invert_scroll"] is False
- assert ipc.get_perf()["output_failed_commits"] == 0
- except Exception:
- log.flush()
- print((runtime / "compositor.log").read_text()[-4000:])
- raise
- finally:
- stop_process(process)
- log.close()
- print(f"PASS scale {scale}: taskbar move/hide, hit targets, reload and restart persistence")
-
-
-if __name__ == "__main__":
- for scale in (1, 1.5):
- run(scale)
diff --git a/tests/xwayland.py b/tests/xwayland.py
index 72ff892..079bb1a 100644
--- a/tests/xwayland.py
+++ b/tests/xwayland.py
@@ -678,6 +678,89 @@ def start_x11_client(tmp, display, log_path, *args):
)
+def test_switcher_input(factor=1):
+ """Check X11's actual key state and repeated clicks after switching back."""
+ from desktop_zoom import build_client as build_wayland_client
+ from ipc_client import IPCClient, stop_process
+
+ with tempfile.TemporaryDirectory(prefix="rediwm-xwayland-switcher-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ build_wayland_client(tmp)
+ compositor, log = start_compositor(
+ tmp, f'[compositor]\nxwayland = true\nxwayland_native_scaling = true\nxwayland_scale = {factor}\n[keybinds]\n"alt+tab" = "focus_next"\n',
+ {"XDG_STATE_HOME": str(tmp / "state"), "XDG_DATA_HOME": str(tmp / "data")},
+ )
+ clients = []
+ try:
+ with IPCClient(tmp) as ipc:
+ display = ipc.query('get_runtime_info')["xwayland_display"]
+ client_log = tmp / "x11.log"
+ client = start_x11_client(tmp, display, client_log)
+ clients.append(client)
+ xwin = wait_for(lambda: next((w for w in ipc.get_windows() if w['backend'] == 'xwayland'), None), 'X11 map')
+ with (tmp / 'wayland.log').open('w') as out:
+ clients.append(subprocess.Popen(
+ [str(tmp / 'client'), '--title', 'Wayland peer'],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=wayland_display_name(tmp)),
+ stdout=out, stderr=out,
+ ))
+ wait_for(lambda: len(ipc.get_windows()) == 2, 'Wayland map')
+ def check_keys(label, expected=''):
+ # Xwayland processes Wayland input before answering the X query.
+ time.sleep(.15)
+ client.stdin.write(f'keys {label}\n')
+ client.stdin.flush()
+ line = wait_for(lambda: next((l for l in client_log.read_text().splitlines() if l.startswith(f'keys {label}')), None), 'query X keys')
+ assert line == f'keys {label}{expected}', f'Incorrect X11 keys after focus transfer: {line}'
+
+ for mode in ('tab-first', 'alt-first', 'return'):
+ # Start on X11, switch away, then back with each release order.
+ ipc.action('focus_window', {'id': xwin['id']})
+ ipc.key(56, True)
+ ipc.key_down_up(15)
+ ipc.key(56, False)
+ wait_for(lambda: not next(w for w in ipc.get_windows() if w['id'] == xwin['id'])['is_focused'], 'switch away')
+ ipc.key(56, True)
+ ipc.key(15, True)
+ if mode == 'return':
+ ipc.key_down_up(28)
+ if mode == 'tab-first':
+ ipc.key(15, False)
+ ipc.key(56, False)
+ else:
+ ipc.key(56, False)
+ ipc.key(15, False)
+ wait_for(lambda: next(w for w in ipc.get_windows() if w['id'] == xwin['id'])['is_focused'], 'switch back')
+ check_keys(mode)
+ print('PASS: Alt-Tab release order and Return acceptance leave no stuck X11 keys')
+
+ # Genuine client keys must still be carried across focus changes.
+ peer = next(w for w in ipc.get_windows() if w['id'] != xwin['id'])
+ ipc.action('focus_window', {'id': peer['id']})
+ ipc.key(30, True) # A: evdev 30, X11 38
+ ipc.action('focus_window', {'id': xwin['id']})
+ check_keys('held', ' 38')
+ ipc.key(30, False)
+ check_keys('released')
+
+ box = ipc.query('get_window_debug', {'id': xwin['id']})['client_box']
+ # Scrollbars sit just inside the right edge; repeated clicks must
+ # work without moving away to generate another pointer enter.
+ ipc.move_cursor(box['x'] + box['width'] - 5, box['y'] + 80)
+ for count in range(1, 4):
+ ipc.pointer_button(272, True)
+ ipc.pointer_button(272, False)
+ wait_for(lambda: client_log.read_text().count('button-release 1 ') == count,
+ lambda: f'Repeated right-edge click {count} lost: {client_log.read_text()}', timeout=3)
+ print('PASS: repeated X11 right-edge clicks reach the client after Alt-Tab')
+ finally:
+ for client in clients:
+ stop_process(client)
+ stop_process(compositor)
+ log.close()
+
+
def test_unmapped_window_has_no_chrome():
"""An X11 window that is configured and titled but never mapped must not
show a frame. Its chrome used to be painted and hit-testable at the
@@ -2247,6 +2330,8 @@ def run():
test_server_stop_cleanup()
test_managed_window()
test_native_scaling_managed_window()
+ test_switcher_input()
+ test_switcher_input(factor=2)
test_unmapped_window_has_no_chrome()
test_withdrawn_window_survives_close_animation()
test_gtk_menu_alignment()
diff --git a/tests/xwayland_client.c b/tests/xwayland_client.c
index 8a8d6f7..3602d78 100644
--- a/tests/xwayland_client.c
+++ b/tests/xwayland_client.c
@@ -178,7 +178,16 @@ int main(int argc, char *argv[]) {
if (!fgets(line, sizeof(line), stdin))
break;
line[strcspn(line, "\n")] = 0;
- if (strncmp(line, "urgent ", 7) == 0) {
+ if (strncmp(line, "keys ", 5) == 0) {
+ xcb_query_keymap_reply_t *reply = xcb_query_keymap_reply(conn, xcb_query_keymap(conn), NULL);
+ if (!reply) return 1;
+ printf("keys %s", line + 5);
+ for (int code = 8; code < 256; code++)
+ if (reply->keys[code / 8] & (1u << (code % 8))) printf(" %d", code);
+ free(reply);
+ printf("\n");
+ fflush(stdout);
+ } else if (strncmp(line, "urgent ", 7) == 0) {
uint32_t hints[9] = {0};
hints[0] = atoi(line + 7) ? (1u << 8) : 0;
xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win, XCB_ATOM_WM_HINTS,