RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
updates
oxydizer85eb8294e6f0
diff --git a/README.md b/README.mdindex 7069b14..a72a4c0 100644--- a/README.md+++ b/README.md@@ -47,8 +47,8 @@ curl -fsSL https://rediwm.redios.org/install.sh | sh # add `-s -- --dm` for r| <img width="100%" alt="Screenshot 1" src="https://github.com/user-attachments/assets/b4cbd48c-ccab-452e-8457-2d1b8c096def" /> | <img width="100%" alt="Screenshot 2" src="https://github.com/user-attachments/assets/10f9becc-bcd9-4089-872b-4a03d1dba818" /> || <img width="100%" alt="Screenshot 3" src="https://github.com/user-attachments/assets/a0ccd5f3-7476-4171-80c5-5f74a751e6b7" /> | <img width="100%" alt="Screenshot 4" src="https://github.com/user-attachments/assets/dd0cdae7-4c4d-401c-9624-80895897d0de" /> |-`scripts/install.sh` installs the prebuilt release for your distro (Arch,-Debian, Ubuntu and Fedora).+`scripts/install.sh` installs the prebuilt release for your distro (Arch+and derivatives such as Artix and CachyOS, Debian, Ubuntu and Fedora).Installing never replaces your login manager## Building and runningdiff --git a/docs/agent-notes/dock.md b/docs/agent-notes/dock.mdnew file mode 100644index 0000000..406f240--- /dev/null+++ b/docs/agent-notes/dock.md@@ -0,0 +1,48 @@+# Dock implementation notes++Read when changing `src/Dock.zig`, `src/dock_drag.zig`, or their output,+taskbar, OSD and input integration. General rules remain in+[AGENTS.md](../../AGENTS.md); integration coverage is in `tests/dock.py`.++* **The dock repaints cells, not itself** (`Dock.zig`). It keeps its last+ raster and, when only some items' looks changed (hover zoom, pills), clears+ and repaints just their `itemCell`s (each item at the largest hover zoom, across+ the dock's thickness) under a clip, publishing that damage alone. Dock-wide+ state (theme, scale, count, drop slot, hover zoom, active-app highlight, the+ background `Dock.background` makes of `dock_opacity`) is `base_key` and+ repaints all. Draw nothing outside an item's cell without keying it in+ `base_key`, or it goes stale. `tests/dock.py` compares an animated dock with a+ whole repaint. The icon tooltip waits `tooltip_delay_ms` on its own one-shot+ timer, re-armed only when the hovered icon changes. Icons use `drawImageSmooth` (area average): `drawImageCover`+ samples the nearest pixel and shows stair-steps at the dock's fractional+ downscale.++* Hover zoom keeps the screen-edge side fixed and grows toward the desktop.+ Its spring (`dock_hover`) is underdamped: `zoomRange` gives the overshoot+ headroom that rasters, icon size and cells are sized for, so never clamp a+ look to `dock_hover_zoom` itself.+ `rasterBox` pads the painted buffer for overflow; `glass_anchor` keeps the+ background's extent. Input uses tree-local coordinates and `input_root`+ covers the expanded icons. Item cells span the expanded raster's thickness.++* **The dock reserves space only when it doesn't auto-hide.** `Output.usableBox`+ is `dockAreaBox` (output less the taskbar) less `Dock.reservedStrip`, a pure+ function of config and that box (`Dock.fits`), so it never flips with a lock+ or fullscreen window. The dock and the taskbar's popups/menus are placed in+ `dockAreaBox`, never `usableBox`. A setting that changes the strip calls+ `applyTaskbarPosition` (`Dock.reserves` before/after). The OSD keeps clear+ of `Dock.footprint` (the resting dock, auto-hiding or not) on the bottom+ edge. Auto-hide fades and slides the node (`reveal`, opacity + position, no+ repaint; the glass opacity follows it too) and parks it (no rebuilds, no+ frames) once away; reveal/hide wait on one `wl` timer+ (`Dock.pointerAt` from `Input.processCursorMotion`, `retime`).++* **Compositor-internal drags** (`dock_drag.zig`: start menu app -> dock pin,+ and a pinned dock icon -> another place among the pins) are not wl_data_device+ ones: a press arms, motion past a threshold starts, and starting rebuilds the+ menu so its release is no click. A pinned icon acts on release (`Dock.clickPin`)+ so a drag can start from it. Closing the menu or Escape (`cancelDrag`; for a+ dock icon `Keyboard.zig` takes it ahead of every shell panel, for a menu app+ before the menu's own Escape) abandons it. A dock+ holds resolved pins as copies (`pin_arena`); `config_index` maps a slot back+ into `dock_pinned_apps`, which also lists apps no longer installed.diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdnew file mode 100644index 0000000..9123165--- /dev/null+++ b/docs/agent-notes/rendering.md@@ -0,0 +1,135 @@+# Rendering implementation notes++Read when changing projection, the output pass, glass, window shapes,+chrome, capture, or retained panel painting. General rules remain in+[AGENTS.md](../../AGENTS.md); test commands are in [TESTING.md](../../TESTING.md).++* **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.+* **Window frames are shapes** (`docs/plans/scene-graph-stage4.md`).+ `Toplevel.applyShape` gives `frame_tree` one rounded clip carrying the ring+ colour (× window opacity); the pass composites the ring over the body, so+ something must be drawn under every ring pixel: the titlebar `ChromeBuffer`+ (a plain band) on top and the three `frame_fills` rects beside and below the+ client. The footer is `frame_border`. `shadow_tree`, the resize-grab tree and+ every xdg popup carry `setTreeUnclipped` (a new node that hangs outside the+ window needs it too). The shadow is analytic (`setTreeShadow` on+ `shadow_tree`, the CPU formula's smoothstep); its leaf `shadow_node` has no+ buffer and carries footprint, opacity and input only, so the projection+ damages that footprint itself. CSD windows have no shape and keep the+ `border_rects` outline. A changed clip damages its rim itself+ (`projection.c`); a point the shape cuts away is declined by the pick+ (`pick_world`), so the pick falls to what is below. Window capture draws the client alone and is+ handed the shape explicitly. The ring is one `max(1, round(border * scale))`.+ Without the shaped programs (`chrome.shapes` false) windows are square, with+ no ring or shadow.+* **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.+* **Glass is drawn by the output pass** (stage 5, `docs/plans/scene-graph-stage5.md`).+ `glass.c` only registers effects: a bufferless node just below its target, to+ which resolve gives the target's box. When an effect re-blurs, `scene_output.c`+ redirects the pass (`rediwm_scene_pass_begin_backdrop`) and draws the items+ below it into an image a quarter of the logical size of its padded extent+ (target + 3 sigma), blurs that and composites it through the shape (shaped+ program mode 3), keeping one blur per effect and output. A kept blur is+ re-taken only when a damage event from a leaf painted *below* the effect, or+ damage no event explains, meets that extent, or the region or sigma changed.+ Only leaves that put pixels on screen have damage events (an input-only node+ must not, or it reads as a change below glass), and the software cursor's+ damage counts as explained. Damage a new kind of change through the+ projection's events or it counts as below (safe, slower). Collect keeps items an+ effect reads even where surfaces above hide them (`reads`). Holds (a dragged+ titlebar at ≥ 0.98 opacity, camera motion) carry the blur and re-take it once+ released. Per output, so mixed scales stay idle (`glass_hold.py`); attribution+ is checked by `glass_reblur.py`.+* **Owned GL beside wlroots:** wlroots draws with client-side vertex arrays, so+ any GL work of ours must put `GL_ARRAY_BUFFER` (and the rest of the state it+ touched) back before a wlroots pass runs, as `scene_pass.c`'s `leave()` does; a quad+ VBO left bound makes wlroots draw half a rectangle. A border is drawn in the+ same pass as its body, never over it (`docs/plans/scene-graph-stage1.md`).+* **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.+ Build output state through `Server.buildOutputState`, including capture: the+ owned GLES2 pass is the only presenter (the session requires GLES2) and keeps+ one swapchain damage history. It reads graph geometry and the buffers,+ textures and wait points of the source nodes+ (`docs/plans/scene-graph-stage3.md`, `scene-graph-stage6.md`).+* **Shapes in the owned pass** (`scene_pass.h`): a window's rounded clip, ring+ and shadow are `rediwm_scene_pass_add_*_shaped` calls, device pixels, snapped by+ the caller. The programs cost the driver about 430 KiB (a GL program costs+ 130-150 KiB whatever its size), so `enable_shapes` builds them on request, never+ with the renderer; before it a shaped draw fails the pass. Blend NONE is only+ valid inside `rediwm_clip_opaque`, minus the ring (`scene_output.c` draws a+ clipped item's ring-free core plain and the rest through the shape). The+ distance ramp is not area coverage (up to 18 of 208 levels at one pixel of a+ curved edge): that is expected.+* **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; a buffer from `PanelBuffer.createRetained`+ carries a stamp, so only what it missed is copied in, and only the damage+ back out — pass null when drawing over the retained image); 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.+* **Projection is resolve, then present** (`projection.c`, `scene_graph.h`).+ `resolve` turns the source tree into typed items (kind, unrounded+ layout-space edges, composed scale, content) listed in paint order per group+ and shows nothing; `present` rounds once (`rediwm_edges_snap`, edges not+ origin+size) and turns what changed into damage events and screen damage.+ Geometry is derived only in `resolve`: a new rule (clip, opacity, fractional+ placement) is a field on the item, not a computation in `present_leaf`. A leaf+ or group leaves its `paint` list before the head is freed (`detach`,+ `destroy_group`). Buffer identity and damage are read from the source node by+ `present`, textures, single-pixel colours, wait points and opaque regions by+ the pass. A tree's rounded clip (`rediwm_projection_set_tree_clip`) is a field+ on each item (`item.clip`), resolved after the tree's own zoom and scale; an+ xdg popup lives under its parent's tree and must carry+ `rediwm_projection_set_tree_unclipped`.+* **The world has no second tree** (`docs/plans/scene-graph-stage6.md`). The+ source tree is disabled, so wlroots computes no outputs, frame callbacks,+ damage or picks for it; the graph does, with wlroots' own rules on our data.+ *Feedback* (`rediwm_projection_feedback_*`, called by the pass's `collect`):+ per build, the pixels of each client surface that nothing above hides, over+ every output; an output is active when it shows more than a tenth of that, the+ primary one shows most (the later wins a tie); `outputs_update` and+ `output_enter/leave` go out on the *source* buffer, again when an active+ output's scale, transform or subpixel changed. Frame callbacks of the world+ come from `Server.sendFrameDone`, never `wlr_scene_output_send_frame_done`+ alone; the pass emits `output_sample` on the source buffer. A layer-shell+ surface below the world (background, bottom) is no longer occluded by windows+ in wlroots' eyes: it keeps frame callbacks while covered. *Damage*: every+ change reaches `p->pending` through `damage_box` and goes to the outputs once,+ at the end of each sync. A change of what a leaf itself shows is cut to what+ was visible of it at the last build (`l->visible`); a move, restyle or removal+ damages the old box (cut) and the new one; a restack damages what moved+ (`damage_restacked`), shadow footprints included; a destroyed node applies at+ once, because a capture can build before the next sync. A new kind of change+ that moves no leaf has to damage itself there (clip rims and shadows do).+ *Picks*: `rediwm_projection_node_at` (graph for the world, wlroots for the+ layout trees), never `wlr_scene_node_at` on the root. GLES2 lets go of a+ plain buffer once uploaded, so "has content" is a buffer, a texture or a+ single-pixel colour (`present_leaf`, `collect`).+* **The veil** (`rediwm_scene_output_set_veil`, driven by `reveal.zig`) is+ black drawn over every entry and under the software cursor: the session's+ fade in from black and the greeter's fade out. It exists only on DRM and+ nested outputs. A change damages the whole output and counts as explained+ damage, so glass does not re-blur for it; scan-out waits until it is 0.+* **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.diff --git a/scripts/AGENTS.md b/scripts/AGENTS.mdindex 235fb34..1b0faaf 100644--- a/scripts/AGENTS.md+++ b/scripts/AGENTS.md@@ -12,6 +12,13 @@libraries don't match, `unresolved_libs` (missing libs or too-new glibcsymbol versions) or a failed package install falls back to a source build.A checksum mismatch never falls back: it dies.+* **Derivatives are matched by name when `os-release` doesn't say:** Artix has+ no `ID_LIKE`. Artix also has no systemd, so `pkg_install` maps the+ release's `systemd-libs` to `libudev`; otherwise pacman satisfies it with+ `artix-archlinux-support`, a dummy that enables the Arch repositories.+ `make-release.sh` verifies the Arch tarball on Artix and CachyOS too+ (`derivatives_of`); their pacman hooks print errors under rootless podman+ (no network sandbox, no systemd), which are harmless.* **`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`diff --git a/scripts/install.sh b/scripts/install.shindex 2d97cc0..5cbb1df 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -45,6 +45,7 @@ if [ "$(id -u)" -eq 0 ]; then SUDO=""; else SUDO="sudo"; fi# Our own flags are consumed here; everything else goes to install-session.sh.BUILD=noDEPS_ONLY=no+DM=non=$#while [ "$n" -gt 0 ]; doarg=$1; shift; n=$((n - 1))@@ -52,6 +53,7 @@ while [ "$n" -gt 0 ]; do--build) BUILD=yes ;;# For scripts/release-build.sh: install what a release build needs.--build-deps-only) BUILD=yes; DEPS_ONLY=yes ;;+ --dm) DM=yes; set -- "$@" "$arg" ;;*) set -- "$@" "$arg" ;;esacdone@@ -66,22 +68,29 @@ fi[ -r /etc/os-release ] || die "cannot detect distro: /etc/os-release is missing". /etc/os-release+# Artix leaves ID_LIKE unset; CachyOS sets it, but is named in case that changes.case " ${ID:-} ${ID_LIKE:-} " in- *' arch '*) FAMILY=arch ;;+ *' arch '*|*' artix '*|*' cachyos '*) FAMILY=arch ;;*' fedora '*) FAMILY=fedora ;;*' debian '*|*' ubuntu '*) FAMILY=debian ;;*' opensuse'*|*' suse '*) FAMILY=opensuse ;;*' gentoo '*) FAMILY=gentoo ;;- *) die "unsupported distro '${PRETTY_NAME:-${ID:-unknown}}' (supported: Arch, Fedora, openSUSE, Gentoo, Debian, Ubuntu). Install the packages listed in README.md's Requirements section by hand, then run scripts/install-session.sh directly." ;;+ *) die "unsupported distro '${PRETTY_NAME:-${ID:-unknown}}' (supported: Arch and derivatives such as Artix and CachyOS, Fedora, openSUSE, Gentoo, Debian, Ubuntu). Install the packages listed in README.md's Requirements section by hand, then run scripts/install-session.sh directly." ;;esaclog "Detected ${PRETTY_NAME:-$ID} -> $FAMILY"+if [ "$DM" = yes ] && [ ! -d /run/systemd/system ]; then+ log "rediwm-dm is a systemd service and this system doesn't run systemd: it is installed but can't be enabled here"+fi# Releases are built per distro because the libraries differ in ways one binary# can't span (libjpeg is libjpeg.so.8 on Arch and Ubuntu, .so.62 on Debian and# Fedora, with a different struct layout). A derivative uses its parent's.RELEASE_ID=""for id in ${ID:-} ${ID_LIKE:-}; do- case "$id" in arch|debian|ubuntu|fedora) RELEASE_ID=$id; break ;; esac+ case "$id" in+ arch|artix|cachyos) RELEASE_ID=arch; break ;;+ debian|ubuntu|fedora) RELEASE_ID=$id; break ;;+ esacdone# Installs packages with the distro's package manager. Returns non-zero on@@ -89,6 +98,14 @@ donepkg_install() {case "$FAMILY" inarch)+ # Artix is Arch without systemd: libudev.so.1 comes from its+ # `libudev`, and the name `systemd-libs` is provided only by+ # artix-archlinux-support, which enables the Arch repositories+ # instead of installing the library.+ if [ "${ID:-}" = artix ]; then+ # shellcheck disable=SC2046 # word-split the package list+ set -- $(printf '%s\n' "$@" | sed 's/^systemd-libs$/libudev/')+ fi# Install only what is missing and never refresh the sync databases:# `-Sy pkg` is a partial upgrade, which breaks exact-version split# packages (e.g. a newer pipewire vs installed pipewire-pulse).diff --git a/scripts/make-release.sh b/scripts/make-release.shindex 33d1a1d..74db22c 100755--- a/scripts/make-release.sh+++ b/scripts/make-release.sh@@ -10,7 +10,8 @@# never leak in; --src DIR builds that directory instead. DIR (default# ./release) ends up holding rediwm-FAMILY-x86_64.tar.gz for each family built,# plus SHA256SUMS over every tarball in it. Each tarball is then installed by-# the real install.sh in a fresh container (--no-verify skips that).+# the real install.sh in a fresh container, and the Arch one also on Artix and+# CachyOS, which install.sh points at it (--no-verify skips that).## Upload the tarballs and SHA256SUMS to a GitHub release (a tag named v<version># from build.zig.zon); install.sh reads releases/latest/download/. Tests are@@ -49,6 +50,15 @@ image_for() {debian) echo docker.io/library/debian:13 ;;ubuntu) echo docker.io/library/ubuntu:24.04 ;;fedora) echo docker.io/library/fedora:latest ;;+ artix) echo docker.io/artixlinux/artixlinux:latest ;;+ cachyos) echo docker.io/cachyos/cachyos:latest ;;+ esac+}++# Derivatives that install.sh gives a family's tarball, verified with it.+derivatives_of() {+ case "$1" in+ arch) echo artix cachyos ;;esac}@@ -76,8 +86,10 @@ fi# Each build writes into its tree (zig-out), so each family gets its own copy.# Rootless podman maps root in the container to this user, so what it writes to# a bind mount is already ours; docker's root-owned files are handed back.-# run_args: extra engine options for the next run() (the verify step's render node).+# run_args: extra engine options for the next run() (the verify step's render+# node); run_image: the image to use instead of the family's own.run_args=""+run_image=""run() { # family script args...family=$1; shiftrc=0@@ -88,7 +100,7 @@ run() { # family script args...-e REDIWM_ZIG_DIR=/cache/zig -e ZIG_GLOBAL_CACHE_DIR=/cache/zig-global \-e REDIWM_REVISION="$revision" -e ZIG_JOBS="${ZIG_JOBS:-}" \-e OWNER="$([ "$engine" = docker ] && echo "$(id -u):$(id -g)")" \- "$(image_for "$family")" sh -c '"$@"; rc=$?; [ -z "$OWNER" ] || chown -R "$OWNER" /work /out /cache; exit $rc' sh "$@" || rc=$?+ "${run_image:-$(image_for "$family")}" sh -c '"$@"; rc=$?; [ -z "$OWNER" ] || chown -R "$OWNER" /work /out /cache; exit $rc' sh "$@" || rc=$?return $rc}@@ -98,14 +110,18 @@ for family in $families; docp -a "$src/." "$work/$family/"run "$family" sh /work/scripts/release-build.sh "$family" /outif [ "$verify" = yes ]; then- log "Verifying $family in a fresh container"# The compositor needs GLES2, which needs a DRM render node even for# llvmpipe, and a bare container has none: hand it the host's.node=${REDIWM_RENDER_NODE:-$(ls /dev/dri/renderD* 2>/dev/null | head -n 1)}[ -n "$node" ] || die "no /dev/dri/renderD* on this machine for the verify step (set REDIWM_RENDER_NODE, or use --no-verify)"run_args="--device $node"- run "$family" sh /work/scripts/release-verify.sh "$family" /out+ for target in "$family" $(derivatives_of "$family"); do+ log "Verifying $family in a fresh $target container"+ run_image=$(image_for "$target")+ run "$family" sh /work/scripts/release-verify.sh "$family" /out+ donerun_args=""+ run_image=""firm -rf -- "$work/$family"donediff --git a/src/Input.zig b/src/Input.zigindex 7ea8825..b168c36 100644--- a/src/Input.zig+++ b/src/Input.zig@@ -27,6 +27,7 @@ const snap = @import("snap.zig");const scene_data = @import("scene_data.zig");const CursorSerial = @import("input/cursor_serial.zig");const ClientWheel = @import("input/client_wheel.zig");+const WheelDebounce = @import("input/wheel_debounce.zig");const PointerConstraints = @import("input/pointer_constraints.zig");const ShortcutsInhibit = @import("input/shortcuts_inhibit.zig");const Touch = @import("input/touch.zig");@@ -149,6 +150,9 @@ cursor_button: wl.Listener(*wlr.Pointer.event.Button) = .init(cursorButton),cursor_axis: wl.Listener(*wlr.Pointer.event.Axis) = .init(cursorAxis),/// Acceleration and optional smoothing for wheel notches sent to clients.client_wheel: ClientWheel = .{},+/// Drops stray clicks from bouncing wheel encoders, per axis, before anything+/// sees them.+wheel_debounce: [2]WheelDebounce = .{ .{}, .{} },cursor_frame: wl.Listener(*wlr.Cursor) = .init(cursorFrame),cursor_swipe_begin: wl.Listener(*wlr.Pointer.event.SwipeBegin) = .init(cursorSwipeBegin),@@ -2336,9 +2340,20 @@ fn cursorAxis() void {const input: *Input = @fieldParentPtr("cursor_axis", listener);if (input.blockedVirtual(event.device)) return;- if (input.zoom_device != event.device) input.zoom_scroll.reset();+ if (input.zoom_device != event.device) {+ input.zoom_scroll.reset();+ input.wheel_debounce = .{ .{}, .{} };+ }input.zoom_device = event.device;- input.processAxis(event.time_msec, event.orientation, event.delta, event.delta_discrete, event.source);+ var delta = event.delta;+ var delta_discrete = event.delta_discrete;+ if (event.source == .wheel and delta_discrete != 0) {+ const debounce = &input.wheel_debounce[@intCast(@intFromEnum(event.orientation))];+ const notch = debounce.feed(event.time_msec, delta, delta_discrete, input.server.config.input.wheel_debounce_ms) orelse return;+ delta = notch.delta;+ delta_discrete = notch.discrete;+ }+ input.processAxis(event.time_msec, event.orientation, delta, delta_discrete, event.source);}pub fn processAxis(diff --git a/src/config/default.zig b/src/config/default.zigindex 49fb3bd..06fc042 100644--- a/src/config/default.zig+++ b/src/config/default.zig@@ -87,6 +87,8 @@ pub const source =\\# smooth_scroll_exclude = ["brave", "chromium", "google-chrome", "microsoft-edge", "vivaldi",\\# "opera", "firefox", "librewolf", "floorp", "zen"] # default: browsers,\\# # which smooth wheel scrolling themselves+ \\wheel_debounce_ms = 60 # 0-200; ignore a wheel click against the run this soon after+ \\ # the last one (worn wheels bounce); 0 = off\\tap_to_click = true\\tap_drag = true\\disable_while_typing = truediff --git a/src/config/loader.zig b/src/config/loader.zigindex 06475b7..1f4e6d9 100644--- a/src/config/loader.zig+++ b/src/config/loader.zig@@ -81,6 +81,9 @@ pub const InputConfig = struct {// wheel scrolling are excluded, so it is not smoothed twice.smooth_scroll: bool = false,smooth_scroll_exclude: []const []const u8 = &default_smooth_scroll_exclude,+ // A wheel click against the run this soon after its last click is held+ // as a likely encoder bounce (`input/wheel_debounce.zig`). 0 disables.+ wheel_debounce_ms: u32 = 60,tap_to_click: bool = true,tap_drag: bool = true,disable_while_typing: bool = true,@@ -1044,6 +1047,7 @@ const input_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(InputConfig), Fi.wheel_acceleration_exclude = .string_list,.smooth_scroll = .boolean,.smooth_scroll_exclude = .string_list,+ .wheel_debounce_ms = .{ .uint = .{ .min = 0, .max = 200 } },.tap_to_click = .boolean,.tap_drag = .boolean,.disable_while_typing = .boolean,diff --git a/src/input/AGENTS.md b/src/input/AGENTS.mdindex c03a7c7..05e7609 100644--- a/src/input/AGENTS.md+++ b/src/input/AGENTS.md@@ -25,5 +25,9 @@`directInputReachesClients()`; otherwise they emulate the pointer (send yourown `pointerNotifyFrame`). Touchscreens map to `output_name` or the built-inpanel.+* **Wheel debounce** (`wheel_debounce.zig`) runs in `cursorAxis`, before+ `processAxis`, on detented `.wheel` events only. IPC `scroll` and+ automation sequences (`virtual.zig`) enter `processAxis` as `.continuous`+ and never reach it, so cover it with unit tests.* **Lid:** a closed lid hides built-in panels only while another display ison; undocked, logind owns the lid.diff --git a/src/input/wheel_debounce.zig b/src/input/wheel_debounce.zignew file mode 100644index 0000000..12d5639--- /dev/null+++ b/src/input/wheel_debounce.zig@@ -0,0 +1,114 @@+//! Drops stray clicks from bouncing mouse-wheel encoders. A worn or dusty+//! encoder sends a click the wrong way while it spins, as it stops, or as it+//! starts (2-40 ms after a real click, about one in sixteen on the mouse this+//! was measured on). Wheel glides read any reversal as the hand turning+//! round, so one stray click stops the glide dead and steps it back.+//!+//! A click against the run, within `window_ms` of the run's last click, is+//! held: no hand turns a detented wheel round that fast. If the run comes+//! back it bounced and is dropped; if nothing follows it is dropped too (a+//! bounce as the wheel settles). If clicks keep coming the new way past the+//! window, the held ones were a real reversal and go out with the click that+//! shows it. A wheel that never bounces never reaches the hold.+const std = @import("std");++const WheelDebounce = @This();++/// Sign of the run; 0 before the first click.+dir: i32 = 0,+/// When the run's last click was delivered.+last_ms: u32 = 0,+/// Clicks against the run, summed, and when the last of them came.+held: Notch = .{ .delta = 0, .discrete = 0 },+held_ms: u32 = 0,++pub const Notch = struct {+ delta: f64,+ discrete: i32,+};++/// Feeds one detented wheel event (value120 in `discrete`, nonzero). Returns+/// what to deliver now, or null when the event is held or dropped.+pub fn feed(self: *WheelDebounce, time_msec: u32, delta: f64, discrete: i32, window_ms: u32) ?Notch {+ const notch: Notch = .{ .delta = delta, .discrete = discrete };+ const dir = std.math.sign(discrete);+ if (window_ms == 0 or dir == 0) return notch;+ if (dir == self.dir) {+ // The run came back: whatever was held against it bounced.+ self.held = .{ .delta = 0, .discrete = 0 };+ self.last_ms = time_msec;+ return notch;+ }+ if (self.dir != 0 and time_msec -% self.last_ms < window_ms) {+ self.held.delta += delta;+ self.held.discrete += discrete;+ self.held_ms = time_msec;+ return null;+ }+ // A new run. Clicks held just before it, the same way, were its start.+ var out = notch;+ if (self.held.discrete != 0 and time_msec -% self.held_ms < window_ms) {+ out.delta += self.held.delta;+ out.discrete += self.held.discrete;+ }+ self.held = .{ .delta = 0, .discrete = 0 };+ self.dir = dir;+ self.last_ms = time_msec;+ return out;+}++/// Feeds whole clicks (`+1`/`-1` per entry) at the given times and returns+/// the value120 delivered for each, 0 when nothing was.+fn run(comptime n: usize, clicks: [n]struct { u32, i32 }, window_ms: u32) [n]i32 {+ var d: WheelDebounce = .{};+ var out: [n]i32 = undefined;+ for (clicks, &out) |click, *o| {+ const notch = d.feed(click[0], @floatFromInt(click[1] * 15), click[1] * 120, window_ms);+ o.* = if (notch) |got| got.discrete else 0;+ }+ return out;+}++test "a stray click inside a run is dropped" {+ // Recorded: v 27v 50v 6v 5^ 16v+ const got = run(6, .{ .{ 0, -1 }, .{ 27, -1 }, .{ 77, -1 }, .{ 83, -1 }, .{ 88, 1 }, .{ 104, -1 } }, 60);+ try std.testing.expectEqual([6]i32{ -120, -120, -120, -120, 0, -120 }, got);+}++test "two stray clicks in a row are dropped" {+ // Recorded: v 17v 15^ 9^ 35v+ const got = run(5, .{ .{ 0, -1 }, .{ 17, -1 }, .{ 32, 1 }, .{ 41, 1 }, .{ 76, -1 } }, 60);+ try std.testing.expectEqual([5]i32{ -120, -120, 0, 0, -120 }, got);+}++test "a stray click as the wheel stops is dropped, a later turn is not" {+ // Recorded: v 13v 17v 6^, then the hand scrolls up 300 ms later.+ const got = run(5, .{ .{ 0, -1 }, .{ 13, -1 }, .{ 30, -1 }, .{ 36, 1 }, .{ 336, 1 } }, 60);+ try std.testing.expectEqual([5]i32{ -120, -120, -120, 0, 120 }, got);+}++test "a deliberate reversal goes out at once" {+ const got = run(3, .{ .{ 0, -1 }, .{ 25, -1 }, .{ 215, 1 } }, 60);+ try std.testing.expectEqual([3]i32{ -120, -120, 120 }, got);+}++test "clicks that keep going the new way are delivered, not lost" {+ // Recorded: a run starting with a wrong-way click, ^ 14v 19v 21v 6v. The+ // stray ^ has already gone out; the real run must not be eaten.+ const got = run(5, .{ .{ 0, 1 }, .{ 14, -1 }, .{ 33, -1 }, .{ 54, -1 }, .{ 60, -1 } }, 60);+ try std.testing.expectEqual([5]i32{ 120, 0, 0, 0, -480 }, got);+}++test "window 0 passes everything through" {+ const got = run(3, .{ .{ 0, -1 }, .{ 5, 1 }, .{ 10, -1 } }, 0);+ try std.testing.expectEqual([3]i32{ -120, 120, -120 }, got);+}++test "held deltas travel with their clicks" {+ var d: WheelDebounce = .{};+ _ = d.feed(0, 15, 120, 60);+ try std.testing.expect(d.feed(10, -15, -120, 60) == null);+ const out = d.feed(65, -15, -120, 60).?;+ try std.testing.expectEqual(@as(i32, -240), out.discrete);+ try std.testing.expectEqual(@as(f64, -30), out.delta);+}diff --git a/src/session/lock.zig b/src/session/lock.zigindex d97ab4e..a65fe19 100644--- a/src/session/lock.zig+++ b/src/session/lock.zig@@ -21,6 +21,7 @@ const anim = @import("ui").anim;const greeter_mod = @import("greeter.zig");const ClientLock = @import("client_lock.zig").ClientLock;const lock_controls = @import("lock_controls.zig");+const power_cmd = @import("power.zig");const Controls = lock_controls.Controls;const CaretOverlay = @import("../caret_overlay.zig").CaretOverlay;const Greeter = greeter_mod.Greeter;@@ -644,10 +645,11 @@ pub const Lock = struct {return;}self.confirm = null;- // systemctl delegates to logind/polkit; no privileged syscall or- // shell interpolation. Never request an interactive auth agent- // behind the locked screen.- var child = std.process.spawn(self.server.io, .{ .argv = &.{ "systemctl", if (reboot) "reboot" else "poweroff", "--no-ask-password", "--no-block" } }) catch {+ // systemctl/loginctl delegate to logind/polkit; no privileged+ // syscall or shell interpolation. Never request an interactive+ // auth agent behind the locked screen.+ var argv: [4][]const u8 = undefined;+ var child = std.process.spawn(self.server.io, .{ .argv = power_cmd.commandArgv(&argv, if (reboot) .reboot else .poweroff, false, true) }) catch {self.status = "Power service unavailable";return;};diff --git a/src/session/power.zig b/src/session/power.zigindex 5f8edc2..e22fde2 100644--- a/src/session/power.zig+++ b/src/session/power.zig@@ -1,4 +1,5 @@-//! Poweroff/reboot through systemctl (like DMS); suspend through logind.+//! Poweroff/reboot through systemctl (like DMS), or loginctl where systemd is+//! not init (elogind, e.g. Artix); suspend through logind.//! Capability probes and preparation signals still use the system bus.//! Requests run as the logged-in user, with normal authorization and inhibitor//! checks. Automatic power commands use --no-ask-password. Suspend uses@@ -100,6 +101,27 @@ pub const Request = struct {interactive: bool,};+/// The poweroff/reboot command line, written into `buf`. systemctl needs+/// systemd as init (sd_booted's `/run/systemd/system` test); elogind systems+/// have these verbs in loginctl, which only asks logind and never waits for+/// the job, so it has no --no-block.+pub fn commandArgv(buf: *[4][]const u8, kind: Kind, ask_password: bool, no_block: bool) []const []const u8 {+ std.debug.assert(kind != .@"suspend");+ const systemd = std.posix.system.access("/run/systemd/system", std.posix.F_OK) == 0;+ buf[0] = if (systemd) "systemctl" else "loginctl";+ buf[1] = @tagName(kind);+ var len: usize = 2;+ if (!ask_password) {+ buf[len] = "--no-ask-password";+ len += 1;+ }+ if (no_block and systemd) {+ buf[len] = "--no-block";+ len += 1;+ }+ return buf[0..len];+}+/// Only one request may be in flight; a second action while one is/// pending is reported and dropped rather than queued. There is no automatic/// retry after a lost connection — the next explicit user action reconnects.@@ -120,6 +142,8 @@ pub const Manager = struct {want_probe: bool = false,pending: ?Request = null,command_child: ?*Child = null,+ /// argv[0] of `command_child`, for its log lines.+ command_tool: []const u8 = "",closing: bool = false,lid_fd: ?std.posix.fd_t = null,lid_pending: bool = false,@@ -575,22 +599,20 @@ pub const Manager = struct {}fn startCommand(self: *Manager, req: Request) void {- const action = if (req.kind == .reboot) "reboot" else "poweroff";- const argv: []const []const u8 = if (req.interactive)- &.{ "systemctl", action }- else- &.{ "systemctl", action, "--no-ask-password" };+ var buf: [4][]const u8 = undefined;+ const argv = commandArgv(&buf, req.kind, req.interactive, false);var child = std.process.spawn(self.server.io, .{.argv = argv,.stdin = .ignore,.stdout = .ignore,- // Preserve systemctl's detailed refusal/inhibitor reason in the+ // Preserve the tool's detailed refusal/inhibitor reason in the// session log. Completion is delivered by the pidfd watcher.}) catch |err| {self.pending = null;self.failed(req.kind, "Could not start the power command.", err);return;};+ self.command_tool = argv[0];self.command_child = Child.watch(self.allocator, self.server.wl_server.getEventLoop(), child.id.?, self, commandExited) catch |err| {child.kill(self.server.io);self.pending = null;@@ -605,9 +627,9 @@ pub const Manager = struct {const req = self.pending orelse return;self.pending = null;if (status != null and status.? == 0) {- log.info("{s} requested via systemctl", .{req.kind.label()});+ log.info("{s} requested via {s}", .{ req.kind.label(), self.command_tool });} else {- log.warn("{s}: systemctl failed (wait status {?d})", .{ req.kind.label(), status });+ log.warn("{s}: {s} failed (wait status {?d})", .{ req.kind.label(), self.command_tool, status });self.report(req.kind, "Power request failed. Check permissions and applications blocking shutdown.");}}diff --git a/src/ui_tests.zig b/src/ui_tests.zigindex 632357a..9180cb2 100644--- a/src/ui_tests.zig+++ b/src/ui_tests.zig@@ -8,6 +8,7 @@ test {_ = @import("desktop/grid.zig");_ = @import("config").keymap;_ = @import("input/repeat_keys.zig");+ _ = @import("input/wheel_debounce.zig");_ = @import("ui").key_repeat;_ = @import("ui").hover_glide;_ = @import("input/ime_placement.zig");diff --git a/tests/power.py b/tests/power.pyindex c380419..827433d 100644--- a/tests/power.py+++ b/tests/power.py@@ -4,9 +4,11 @@Runs on a private dbus-run-session, pointed at by DBUS_SYSTEM_BUS_ADDRESS sothe compositor's power manager never reaches the host's real system bus(plan-power-session.md stages 1 and 2). Every test prepends a fake systemctl-to PATH so no test can invoke host reboot/poweroff. Covers:+and loginctl to PATH so no test can invoke host reboot/poweroff. Covers:- Poweroff/reboot command arguments, completion, refusal, missing executable,duplicate rejection, and retries without logging out.+- loginctl instead of systemctl when systemd isn't init (elogind), with+ /run/systemd hidden in a user namespace.- Explicit suspend requests invoking SuspendWithFlags withSD_LOGIND_ROOT_CHECK_INHIBITORS and interactive authorization allowed.- Fallback to legacy Suspend when WithFlags is unsupported or@@ -179,12 +181,14 @@ Gio.bus_own_name_on_connection(conn, "org.freedesktop.login1", Gio.BusNameOwnerFGLib.MainLoop().run()'''-FAKE_SYSTEMCTL = r'''import json, os, sys, time+# Installed as both systemctl and loginctl; files are named after the command.+FAKE_POWER_TOOL = r'''import json, os, sys, timefrom pathlib import Path-tmp = Path(os.environ["FAKE_SYSTEMCTL_DIR"])-config = tmp / "systemctl-config.json"+tmp = Path(os.environ["FAKE_POWER_TOOL_DIR"])+name = Path(sys.argv[0]).name+config = tmp / f"{name}-config.json"options = json.loads(config.read_text()) if config.exists() else {}-with (tmp / "systemctl-calls.jsonl").open("a") as calls:+with (tmp / f"{name}-calls.jsonl").open("a") as calls:calls.write(json.dumps(sys.argv[1:]) + "\n")time.sleep(options.get("delay", 0))if options.get("error"):@@ -320,17 +324,27 @@ def is_pid_running(pid):return True+def without_systemd(argv):+ """argv run as this user with /run/systemd hidden, as on an elogind system:+ the outer user namespace mounts over it, the inner one maps back."""+ script = 'uid=$1 gid=$2; shift 2; mount -t tmpfs none /run/systemd && exec unshare --user --map-user="$uid" --map-group="$gid" "$@"'+ return ["unshare", "--user", "--map-root-user", "--mount", "sh", "-c", script, "sh",+ str(os.getuid()), str(os.getgid()), *argv]++def spawn(tmp, system_bus_address, config=CONFIG, env_extra=None):- # Every compositor in this suite gets a harmless systemctl, even in tests- # intended to exercise only D-Bus. Never fall through to the host command.+ # Every compositor in this suite gets a harmless systemctl and loginctl,+ # even in tests intended to exercise only D-Bus. Never fall through to the+ # host command.bin_dir = tmp / "bin"bin_dir.mkdir(exist_ok=True)- command = bin_dir / "systemctl"- command.write_text("#!/usr/bin/python3\n" + FAKE_SYSTEMCTL)- command.chmod(0o755)+ for name in ("systemctl", "loginctl"):+ command = bin_dir / name+ command.write_text("#!/usr/bin/python3\n" + FAKE_POWER_TOOL)+ command.chmod(0o755)return spawn_compositor(tmp, config_content=config, env_extra={"PATH": str(bin_dir) + os.pathsep + os.environ.get("PATH", ""),- "FAKE_SYSTEMCTL_DIR": str(tmp),+ "FAKE_POWER_TOOL_DIR": str(tmp),"DBUS_SESSION_BUS_ADDRESS": "","DBUS_SYSTEM_BUS_ADDRESS": system_bus_address,**(env_extra or {}),@@ -376,35 +390,54 @@ def test_normal_request_calls_with_flags_and_checks_inhibitors(system_bus_addresprint("power: explicit request calls WithFlags with SD_LOGIND_ROOT_CHECK_INHIBITORS and interactive auth allowed")-def test_systemctl_power_commands():- # No logind connection is needed in the compositor to launch systemctl.+def test_power_commands():+ # No logind connection is needed in the compositor to launch the command.unavailable_bus = "unix:path=/nonexistent-rediwm-power-test-bus"+ tool, other = ("systemctl", "loginctl") if Path("/run/systemd/system").is_dir() else ("loginctl", "systemctl")for action in ("poweroff", "reboot", "poweroff_auto", "reboot_auto"):- with tempfile.TemporaryDirectory(prefix="rediwm-systemctl-") as directory:+ with tempfile.TemporaryDirectory(prefix=f"rediwm-{tool}-") as directory:tmp = Path(directory)- (tmp / "systemctl-config.json").write_text(json.dumps({"delay": 0.4}))+ (tmp / f"{tool}-config.json").write_text(json.dumps({"delay": 0.4}))process, log = spawn(tmp, unavailable_bus)try:with IPCClient(tmp, timeout=15) as ipc:ipc.wait_for("wallpaper_presented", timeout_ms=10000)press(ipc, action)- calls = tmp / "systemctl-calls.jsonl"- wait_for(lambda: calls.exists() and calls.stat().st_size > 0, "systemctl invoked")+ calls = tmp / f"{tool}-calls.jsonl"+ wait_for(lambda: calls.exists() and calls.stat().st_size > 0, f"{tool} invoked")expected = [action.removesuffix("_auto")]if action.endswith("_auto"):expected.append("--no-ask-password")assert json.loads(calls.read_text()) == expectedpress(ipc, "suspend")wait_for(lambda: "is already pending" in log_text(tmp), "duplicate rejected")- wait_for(lambda: "requested via systemctl" in log_text(tmp), "command reaped by SIGCHLD")+ wait_for(lambda: f"requested via {tool}" in log_text(tmp), "command reaped by SIGCHLD")assert len(calls.read_text().splitlines()) == 1+ assert not (tmp / f"{other}-calls.jsonl").exists()assert process.poll() is None, log_text(tmp)assert "terminating compositor session" not in log_text(tmp)assert "requested via logind" not in log_text(tmp)finally:stop_process(process)log.close()- print("power: poweroff/reboot use systemctl directly, without force flags or early logout")+ print(f"power: poweroff/reboot use {tool} directly, without force flags or early logout")+++def test_power_commands_without_systemd():+ """Reruns test_power_commands with /run/systemd hidden, where it must use+ loginctl. The test client shares the compositor's user namespace: the IPC+ server treats a peer whose /proc it can't read as sandboxed."""+ if not Path("/run/systemd/system").is_dir():+ return # test_power_commands already used loginctl+ try:+ usable = subprocess.run(without_systemd(["true"]), stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL).returncode == 0+ except FileNotFoundError:+ usable = False+ if not usable:+ print("power: SKIP loginctl commands (cannot hide /run/systemd in a user namespace)")+ return+ subprocess.run(without_systemd([sys.executable, __file__, "--power-commands"]), check=True)def test_systemctl_failure_and_retry():@@ -1172,6 +1205,9 @@ def test_logind_lock_and_locked_hint(system_bus_address):def main():+ if sys.argv[1:] == ["--power-commands"]:+ test_power_commands()+ returnif "--private" not in sys.argv:sys.exit(subprocess.call(["dbus-run-session", "--", sys.executable, __file__, "--private"]))system_bus_address = os.environ["DBUS_SESSION_BUS_ADDRESS"]@@ -1179,7 +1215,8 @@ def main():test_lid_inhibitor_late_reply_and_denial(system_bus_address)test_lock_on_suspend(system_bus_address)test_logind_lock_and_locked_hint(system_bus_address)- test_systemctl_power_commands()+ test_power_commands()+ test_power_commands_without_systemd()test_systemctl_failure_and_retry()test_systemctl_missing()test_normal_request_calls_with_flags_and_checks_inhibitors(system_bus_address)