Skip to content

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

system monitor

oxydizerd59f0562fce2
diff --git a/data/rediwm-monitor.desktop b/data/rediwm-monitor.desktop
new file mode 100644
index 0000000..4e0ebd6
--- /dev/null
+++ b/data/rediwm-monitor.desktop
@@ -0,0 +1,10 @@
+[Desktop Entry]
+Type=Application
+Name=System Monitor
+Comment=View CPU, memory and processes
+Exec=rediwm-monitor
+Icon=rediwm-monitor
+Terminal=false
+Categories=System;Monitor;
+Keywords=process;task;CPU;memory;performance;
+StartupWMClass=rediwm-monitor
diff --git a/data/rediwm-monitor.svg b/data/rediwm-monitor.svg
new file mode 100644
index 0000000..fabae22
--- /dev/null
+++ b/data/rediwm-monitor.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
+ <rect x="4" y="7" width="56" height="44" rx="9" fill="#223042"/>
+ <rect x="8" y="11" width="48" height="36" rx="5" fill="#101923"/>
+ <path d="M11 32h10l6-13 9 23 7-14h10" fill="none" stroke="#6bc9b6" stroke-linecap="round" stroke-linejoin="round" stroke-width="4"/>
+ <path d="M24 51v6h16v-6M20 58h24" fill="none" stroke="#50677c" stroke-linecap="round" stroke-width="4"/>
+</svg>
diff --git a/docs/plans/capture-lifecycle.md b/docs/plans/capture-lifecycle.md
new file mode 100644
index 0000000..1e068df
--- /dev/null
+++ b/docs/plans/capture-lifecycle.md
@@ -0,0 +1,279 @@
+# Capture sources and session lifecycle plan
+
+Status: draft, 2026-10-17. Implementation has not started. Begin with Phase 0;
+Phases 1 and 2 deliver graceful source cancellation, then Phase 3 reduces
+unnecessary capture work.
+
+Own the lifetime of native window and output capture sources so stopping one
+source ends its streams without disconnecting the client or interrupting its
+other streams. Preserve the standard capture protocols, content isolation and
+lock/authentication policy. Extend the existing owned window renderer and add
+an owned output source manager; keep wlroots' image-copy session machinery
+until a demonstrated requirement needs a narrower replacement.
+
+The main acceptance case is one client capturing two different sources:
+stopping one produces `stopped`, an outstanding frame terminates, the client
+connection remains usable, and the other stream continues delivering pixels.
+
+## Current integration
+
+The assessment uses the wlroots 0.20.2 release pinned by
+[`scripts/build-wlroots.sh`](../../scripts/build-wlroots.sh).
+
+| Existing code | Relevant behavior |
+| --- | --- |
+| [`src/capture/manager.zig`](../../src/capture/manager.zig) | Owns policy, session tracking and the capture indicator's count. Stop all, output loss and window minimize currently disconnect capture clients. |
+| [`src/capture/window_source.zig`](../../src/capture/window_source.zig) | Owns a source per request and renders the selected content subtree into a swapchain. Source destruction already produces graceful session termination through `base.finish()`. Creation renders immediately; later requests always render and report full damage. |
+| [`src/toplevel/lifecycle.zig`](../../src/toplevel/lifecycle.zig) | Retires foreign handles on unmap, but explicitly documents the gap where an unmapped window remains alive and its capture source survives. |
+| [`src/toplevel/chrome_actions.zig`](../../src/toplevel/chrome_actions.zig) | Explicitly stops capture on minimize because hiding the frame does not destroy the content tree. |
+| [`src/Output.zig`](../../src/Output.zig) | Stops monitor capture on idle blank and output destruction. Other disable/power paths need the same lifecycle contract. |
+| [`src/session/lock.zig`](../../src/session/lock.zig) and [`src/polkit/dialog.zig`](../../src/polkit/dialog.zig) | Lock and authentication entry points. Polkit calls Stop all; lock entry needs an explicit capture revocation audit, including existing sessions. |
+| [`tests/capture.py`](../../tests/capture.py), [`tests/capture_client.c`](../../tests/capture_client.c), [`tests/screencast.py`](../../tests/screencast.py) | Existing pixel, source-loss, indicator and picker coverage. Several tests currently expect a disconnected client. |
+
+wlroots exposes source initialization, resource creation and `finish` through
+its [source implementation interface](https://wlroots.pages.freedesktop.org/wlroots/wlr/interfaces/wlr_ext_image_capture_source_v1.h.html).
+In the pinned source, finishing a source ends its sessions, fails pending
+frames and makes remaining source resources inert. There is no public general
+session-stop operation in the pinned
+[`wlr_ext_image_copy_capture_v1.h`](https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/0.20.2/include/wlr/types/wlr_ext_image_copy_capture_v1.h).
+Use that supported source boundary first.
+
+## Scope and behavior
+
+The first release covers `ext-image-copy-capture-v1` over output sources and
+native xdg window sources. A source resource can create multiple sessions:
+source cancellation ends all of those sessions. Stopping a target cancels
+every owned source for that window or output. Selecting one session while
+another session on the same source continues is a separate, conditional step.
+
+| Trigger | Required result |
+| --- | --- |
+| Window close, unmap or minimize | Stop all sources for that window gracefully; preserve other windows, outputs and the client's unrelated Wayland resources. |
+| Output unplug, successful disable, power off or idle blank | Stop sources for that output before its backing objects disappear. A rejected disable must not leave a permanently stopped source solely because an attempted transition failed. |
+| Stop sharing from the taskbar or IPC | Stop every active modern source. Clear active-session accounting through the normal teardown path. |
+| Built-in lock, client session lock or authentication | Revoke capture before further source reads/delivery, including existing sessions and sources created without a session yet. Reject new capture while policy denies it. |
+| Window resize or output format/geometry change | Publish fresh constraints before a frame using them; invalidate old cache contents and validate client buffers against the current constraints. |
+| Occlusion or camera movement | Preserve isolated window content; unrelated windows and desktop pixels never enter its frames. |
+| Restore, remap, wake or unlock | Old stopped resources remain inert. A fresh allowed source/session request can recover. |
+| Client/session/source-resource destruction | Release only the affected references and work. Destroying a factory global or a source descriptor must not prematurely free objects still needed by live sessions. |
+
+Keep the existing native-window content boundary: client content and its
+current subtree semantics, transparent shaped corners, and no server chrome,
+shadows or backdrop glass. Keep the existing logical-resolution window raster
+initially. Higher-density capture, broader popup bounds, X11 window capture,
+new picker UI and a new portal backend are separate work.
+
+Legacy `wlr-screencopy-v1` has frame objects rather than these sessions. Retain
+`guardScreencopy` and the existing fail-closed disconnect fallback where its
+API requires it. The new guarantee of preserving unrelated streams initially
+applies to modern capture; a legacy fallback can still disconnect a mixed
+connection. Replacing the legacy implementation is outside this first release.
+
+## Ownership and lifetime
+
+Introduce a shared owned-source record with a target identity, generation,
+state (`active`, `revoked`, `finished`), pending-work handle, session/resource
+references and a stop reason. Windows use stable window IDs; outputs use an
+owned registration identity/generation with a destroy listener. Reusing a
+pointer or an output name must never revive an earlier source.
+
+Create one owned source per source request. Keep cancellation identities
+separate even if a later optimization shares immutable rendered content for
+the same target. Replace `session.source.toOutput()` with lookup in the owned
+source registry: wlroots' helper recognizes only its own output sources.
+
+The stop path is idempotent and performs no allocation:
+
+1. Mark the source revoked and invalidate its generation synchronously.
+2. Cancel queued render/copy work and block new reads or frame delivery.
+3. Finish the source once, allowing wlroots to terminate its sessions and
+ frames and leave wire resources inert.
+4. Detach listeners, release buffers/locks and free the owner when callbacks
+ and remaining work can no longer access it.
+
+Finishing emits callbacks that can remove session records immediately. Use
+mutation-safe iteration and never retain a session pointer across that call.
+Do not free a source while its own `request_frame`/`copy_frame` callback or a
+wlroots dispatcher is still using it. Defer final destruction when necessary,
+but finish dependent objects and release output locks while the output is
+still valid. A queued completion must check its source generation.
+
+Track resource destruction, active sessions and pending work independently.
+Reclaim sources requested but never used, failed accepts and abandoned cached
+buffers. Ending the last session stops active work; do not rely on a window
+eventually closing to release per-request allocations.
+
+Admission checks belong before source-content rendering, in session start,
+and at render/copy delivery. `new_session` alone is too late: the pinned
+wlroots implementation calls the source's `start` before emitting that event.
+Prepare valid buffer constraints before accepting a source, without reading
+window pixels merely to create the descriptor.
+
+## Implementation phases
+
+### Phase 0: establish the protocol and lifetime baseline
+
+Extend `tests/capture_client.c` to hold named sources and sessions concurrently
+on one Wayland connection. Add commands for creating/destroying descriptors,
+sessions and frames independently, selecting an output, waiting for events,
+and checking connection liveness with `wl_display.sync`. Preserve existing
+fixture commands so current tests remain useful.
+
+Verify the pinned contracts for source finish, outstanding frames, descriptor
+destruction with a live session, duplicate stop, constraints, cursor options
+and disconnect during delivery. Check how to observe resource destruction
+through public libwayland callbacks, and how source start/stop callbacks pair
+when multiple sessions share a source.
+
+Record the current capture suites and the disconnect expectations before
+changing behavior. Use a HEAD worktree to classify existing failures, and
+account separately for unrelated working-tree changes. Establish a baseline
+for static capture, animated content, two consumers and compositor idle cost.
+
+Exit gate: the fixture can prove that stopping one stream did not kill its
+connection or accidentally stop another, and the supported lifetime boundary
+is understood without editing private wlroots session lists.
+
+### Phase 1: graceful window source cancellation
+
+Add the shared lifetime/state helpers and a manager-owned stop path. Route
+minimize, close and unmap through source cancellation, including unmap without
+destruction. Remove the modern window path's client-disconnect fallback.
+
+Separate constraint preparation from rendering. Guard source creation,
+activation and frame delivery; reject unavailable targets without leaving a
+registered source or scheduling a render. Clean up allocation/accept failures
+and unused source requests.
+
+Wire lock and authentication revocation explicitly. Preserve `Lock.announce`
+as the first lock action; establish the capture-denied state and revoke
+sources before lock/authentication content can be sampled. Include client
+session-lock entry. Keep greeter capture globals unavailable. Until output
+sources are migrated, retain their existing fallback during global stops.
+
+Exit gate: minimizing/unmapping one captured window produces `stopped` while
+another stream and ordinary client requests remain usable. Restore/remap
+requires a new source. Repeated stop and target destruction during a pending
+frame are clean under Debug allocation checks.
+
+### Phase 2: own output capture sources
+
+Add `src/capture/output_source.zig` and a small owned factory for
+`ext_output_image_capture_source_manager_v1`. A C bridge is acceptable where
+the pinned Zig bindings lack the public resource helper; keep it under
+`src/capture/` and generate the required protocol bindings in `build.zig`.
+Advertise exactly one output-source manager.
+
+Adapt the pinned output-source logic with retained attribution. Use
+`wlr_ext_image_capture_source_v1_create_resource` so wlroots' retained
+image-copy manager recognizes the resource implementation. Map sessions to
+owned sources explicitly; leave the foreign-toplevel list and compatible
+foreign-toplevel source factory in use.
+
+Preserve output buffer constraints, SHM/DMA-BUF copying, damage, timestamps,
+transforms, pointer-cursor sources and attach-render lock accounting. Pair
+every render/software-cursor lock across start, stop, failure and output loss.
+Qualify concurrent sessions with different `paint_cursors` choices: pixel
+variants must match each session's option, including cursor-only changes.
+Sharing one raster must not silently bake the wrong cursor mode into a stream.
+
+Use the existing output commit/render path. Any additional rendered output
+state goes through `Server.buildOutputState`; real output commits remain on
+`Output.commitFrameState`. Preserve explicit synchronization and buffer locks
+through the copy. Revoke pending sources before their output dependencies are
+destroyed, and audit successful disable/power transitions as well as unplug.
+
+Update Stop all and the capture indicator to operate on the owned registry.
+The existing IPC fields retain their meaning; report source kinds and target
+identities without titles or pixels. Update legacy-disconnect wording in
+touched comments and documentation to describe the remaining scope precisely.
+
+Exit gate: on one client connection, an output stream can stop while a second
+output or window stream continues; client-owned windows survive. Pending
+frames terminate on blank/unplug, and a new source succeeds after wake.
+Phases 1 and 2 are the first shippable milestone.
+
+### Phase 3: render capture only when needed
+
+Observe content changes before output-visibility culling. Screen damage alone
+cannot describe an occluded window's changing content. Connect capture
+invalidation to owned node/buffer changes, subtree structure and capture
+geometry; detach observations before freeing nodes. Start with conservative
+whole-source invalidation for uncertain structural changes.
+
+Honor the source's `schedule_frame` contract. Produce the first frame promptly;
+afterward a waiting capture may remain pending until content changes. Render
+only when a consumer needs a frame and the cached content is stale. Reuse a
+valid snapshot for a lagging consumer without repainting the source. Coalesce
+bursts into bounded work and retain one pending frame per session as required
+by the protocol; use event readiness and real deadlines, not a polling loop.
+
+Keep three histories distinct: source content changes, each owned swapchain
+buffer's paint history, and each consumer's buffer/session damage. Newly
+allocated/resized buffers need a complete valid image. Merge client-reported
+buffer damage correctly, never write a busy buffer, and preserve acquire/release
+fences. Geometry, shape, format and cursor-mode changes invalidate the relevant
+cached content.
+
+Window capture remains rooted at `content_tree` with explicit shape handling.
+For animated occluded windows, verify that frame callbacks still allow the
+client to progress. Integrate any capture-induced callback scheduling with
+`Server.sendFrameDone` so a displayed surface does not receive duplicates.
+
+Exit gate: unchanged content causes no repeated window-render submissions;
+unrelated desktop damage does not repaint an isolated window capture; a
+content change wakes a pending consumer and produces correct pixels. No
+capture-generated timers or render work remain after the final consumer ends.
+Measure per-thread wakeups and CPU/GPU work against the Phase 0 baseline.
+
+### Conditional follow-up: own individual session control
+
+Source ownership is sufficient for the first milestone. Reconsider the
+image-copy session manager only if a concrete requirement needs independent
+cancellation of sessions sharing one source, or the Phase 0/2 cursor and
+lifetime probes demonstrate a public-API gap that source ownership cannot
+handle.
+
+First check whether a small upstream API addition solves the gap. If a local
+implementation is justified, port the pinned session code under a RediWM
+namespace, preserve attribution, and retain protocol validation, cursor
+sessions, constraints and frame failure semantics. Qualify it as a separate
+change; do not make the whole project depend on replacing it preemptively.
+
+## Validation and completion
+
+Extend the existing fixtures and suites rather than add production test hooks.
+
+| Coverage | Required cases |
+| --- | --- |
+| Cancellation isolation | Two outputs, two windows, and output plus window on one connection; multiple sessions sharing one source; unrelated client resources still usable after `stopped`. |
+| Lifetime | Pending frame, duplicate stop, unused source, failed accept, session/source/global destruction in different orders, client disconnect, unmap/remap and output removal. |
+| Policy | Stop all, built-in lock, client session lock, authentication, requests queued across revocation, inert old sources after recovery, legacy/mixed capture paths and greeter exclusion. |
+| Pixels and synchronization | Existing SHM/DMA-BUF cases, premultiplied alpha, shaped corners, occlusion, camera movement, resize, transforms, mixed scales, cursor options and screenshot coexistence. |
+| Damage and scheduling | Buffer rotation, lagging/slow consumers, first frame on an idle source, static source waiting without polling, content changes under full occlusion, invalidation during an in-flight copy and clean final-consumer shutdown. |
+| Desktop integration | Correct IPC session counts, taskbar indicator and Stop sharing behavior; existing picker and portal configuration tests. |
+
+Update the tests that currently expect disconnects to assert protocol events,
+pending-frame completion and a working connection. Extend `tests/screencast.py`
+as well as `tests/capture.py`; keep the pixel-isolation fixtures authoritative.
+Use pure unit tests for state transitions and damage accounting where they
+exercise behavior unavailable through the existing integration fixtures, and
+import them into an actual Zig test root.
+
+For implementation, complete Debug and ReleaseSafe builds, `zig build test`,
+`python3 tests/capture.py` and `python3 tests/screencast.py`. Run the affected
+lock/client-lock/authentication, output-lifecycle and screenshot suites from
+[`TESTING.md`](../../TESTING.md). Changes to render/damage/sync integration also
+require the relevant scene-pass and damage-audit checks. Compare failures with
+HEAD before labeling them regressions.
+
+GLES2/DMA-BUF and explicit-sync qualification need a compatible render node;
+record unavailable hardware coverage separately. Browser/OBS sharing through
+the actual portal is a manual acceptance gate, distinct from direct-protocol
+tests. This work does not itself add native-window selection to a portal that
+does not expose it.
+
+Finish implementation by updating the capture area notes, the relevant
+`TESTING.md` entries and stale capture-contract references in touched files.
+Record which phases and hardware paths passed before changing this plan's
+status to complete.
diff --git a/docs/plans/cpu-usage.md b/docs/plans/cpu-usage.md
new file mode 100644
index 0000000..c78047b
--- /dev/null
+++ b/docs/plans/cpu-usage.md
@@ -0,0 +1,84 @@
+# CPU usage reduction plan
+
+Status: draft, 2026-10-17. Implement four increments in the order below,
+measuring each separately. Reduce unnecessary main-thread work during static
+desktop use, capture and active rendering while preserving responsiveness.
+
+## Baseline
+
+Record ReleaseSafe runs for an empty desktop, static windows, a client that
+requests frame callbacks without changing content, animation/drag/resize, and
+static/animated capture. Include one output and mixed-scale multiple outputs.
+Keep hardware, power settings, renderer and workloads identical.
+
+Measure per-thread CPU time and context switches without performance IPC;
+use a separate instrumented run for frame-stage and GPU timing. Follow
+[`TESTING.md`](../../TESTING.md) and extend the existing performance fixtures.
+
+## 1. Schedule only affected outputs
+
+In [`src/projection.c`](../../src/projection.c), replace the per-commit scan of
+surface feedback with a maintained direct lookup. Track which outputs need
+work for known surfaces, including both old and new bounds when they move.
+Keep conservative scheduling for unknown/new surfaces and global changes.
+Distinguish visual damage from requests that only need frame callbacks.
+
+**Acceptance:** activity on one output does not repeatedly process unrelated
+outputs. New popups, moves across outputs, output changes and captured/hidden
+surfaces still receive the work they require.
+
+## 2. Add a lightweight path for callback-only commits
+
+In [`src/output/frame.zig`](../../src/output/frame.zig) and the surface binding,
+track why a frame was requested. When only callbacks are pending and scene
+state is already resolved, bypass unnecessary shell ticks, window walks and
+render preparation. Route damage, animations, layout changes, cursor/output
+state and capture requests through the appropriate full path.
+
+Preserve paced frame callbacks; do not reply immediately in a loop or delay
+the next real visual update. Add a fixture that alternates empty commits with
+real damage so the optimization cannot strand a client.
+
+**Acceptance:** callback-only workloads cost less CPU without extra output
+commits, animation stalls or increased presentation latency.
+
+## 3. Reuse unchanged capture content
+
+Follow Phase 3 of the [capture lifecycle plan](capture-lifecycle.md), after its
+source ownership and cancellation milestones. Observe source changes before
+visibility culling, render when requested content is stale, and reuse valid
+snapshots. Preserve separate source, swapchain-buffer and consumer damage
+histories, constraints, cursor modes and explicit synchronization.
+
+**Acceptance:** static capture produces no repeated source rendering; changed
+content reaches waiting consumers, including fully occluded windows. The last
+consumer leaving removes capture-generated work and timers.
+
+## 4. Reduce renderer and resource overhead
+
+Profile EGL context transitions, GL state queries, texture uploads/imports and
+readback around [`src/scene_pass.c`](../../src/scene_pass.c). Implement scoped
+batching and resource reuse where the measurements show avoidable work.
+
+If the wlroots renderer boundary remains a significant cost, prototype an
+owned renderer/resource implementation behind its existing interface, keeping
+wlroots' display backends and input machinery. Expand ownership only where an
+A/B comparison justifies it. GL state restoration remains required wherever
+wlroots still draws; preserve buffer release and acquire/release fences.
+
+**Acceptance:** repeatable CPU improvement during active rendering, with
+correct SHM/DMA-BUF imports, external textures, capture, cursors and GPU sync.
+Record the result even if profiling rules out a larger renderer replacement.
+
+## Validation and delivery
+
+Land each increment separately with its before/after measurements. Extend
+existing tests where practical. For implementation, build Debug and
+ReleaseSafe, run `zig build test`, and run affected performance, multi-output,
+capture, screenshot and scene-pass suites. Use damage-audit checks for changes
+to damage or output scheduling; compare existing failures with a HEAD worktree.
+
+Check pixels, callback pacing, input responsiveness, frame latency and idle
+wakeups alongside CPU usage. Record hardware-dependent gaps separately. Mark
+each increment complete only when its behavior checks pass and its measured
+result is documented.
diff --git a/docs/plans/system-monitor.md b/docs/plans/system-monitor.md
new file mode 100644
index 0000000..bb2414b
--- /dev/null
+++ b/docs/plans/system-monitor.md
@@ -0,0 +1,184 @@
+# System Monitor plan
+
+Status: implemented, 2026-10-17. Collector, native monitor window, process
+actions, shortcut and desktop integration are present. See the
+[user guide](../system-monitor.md) for behavior, shortcuts and configuration
+migration, and the validation record below.
+
+Add a native **System Monitor** application, `rediwm-monitor`, opened by
+**Ctrl+Alt+Del**. Use [Mission Center](https://missioncenter.io/) as the feature
+reference for a resource overview and process list, with a small first version
+that follows RediWM's existing app styles.
+
+Run it as a separate Wayland application using RediWM's shared UI and theme.
+Process collection runs independently of the compositor.
+
+## First version
+
+Use one resizable window:
+
+| Area | Content |
+| --- | --- |
+| Top | CPU usage and RAM used/total, each with a simple 60-second history graph. |
+| Toolbar | Search, My processes / All processes, and Pause updates. |
+| Main area | Sortable process list: Name, PID, User, CPU %, Memory, State. |
+| Bottom | Process count, swap usage, and actions for the selected process. |
+
+Default to the current user's processes, sorted by CPU usage. Keep selection
+attached to the process as rows move, and preserve scroll position during
+refreshes.
+
+**End process** requests termination. A separate **Force quit** action handles
+processes that ignore it, with confirmation naming the target. Other users'
+processes are viewable where permitted; v1 manages the current user's own
+processes and protects essential RediWM session components.
+
+GPU monitoring, disk/network charts, per-core views and application grouping
+can follow once this foundation is solid.
+
+## Visual design
+
+Use existing window decorations, fonts, spacing, theme colors, selection
+states, fields, buttons, dialogs and scrollbars. Graphs use the theme accent.
+Support live theme changes and fractional scaling from the start.
+
+Use `ui/cairo.zig`, theme text and color tokens, and the shared controls in
+`ui/widgets/`. Load the effective app theme through `files/settings.zig`
+before the first frame. New controls must follow the shared UI ownership,
+callback and lifetime rules.
+
+## Implementation
+
+### 1. Collector and process model
+
+Add `src/system_monitor/` with process enumeration, CPU sampling, memory
+accounting and bounded history. Read Linux's `/proc` data in a worker and
+deliver snapshots to the UI. System memory uses available memory when
+calculating usage; process memory is labeled as resident memory. Follow the
+[Linux proc filesystem documentation](https://docs.kernel.org/filesystems/proc.html).
+
+The existing sampler in
+[`src/ipc/processes.zig`](../../src/ipc/processes.zig) covers only processes
+owning windows. Extract useful parsing logic while preserving that IPC
+command's behavior. The new collector must also include background processes
+and handle processes disappearing during sampling.
+
+Keep collection and process identity logic independent of compositor types.
+Worker snapshots own their data, and workers do not access Wayland or UI
+objects.
+
+### 2. Native window
+
+Follow the existing app-client patterns, using
+[`src/ui/cairo.zig`](../../src/ui/cairo.zig), shared widgets and
+[`src/files/settings.zig`](../../src/files/settings.zig) for theme loading.
+Refresh once per second, paint visible rows, and support keyboard search and
+navigation.
+
+Stop sampling when paused or closed. Include visibility signaling for
+suspension while minimized: the current client protocol setup does not
+provide that automatically. Add and validate that lifecycle support rather
+than treating loss of keyboard focus as proof that the window is hidden.
+
+### 3. Process actions
+
+Identify selections by PID and process start time, revalidate the target, and
+signal through a pidfd so PID reuse cannot redirect an action. Validate the
+pidfd target against the selected identity before sending a signal. Show
+clear outcomes such as "Process already exited" or "Permission denied".
+Follow the [Linux pidfd signal documentation](https://man7.org/linux/man-pages/man2/pidfd_send_signal.2.html).
+
+End process sends SIGTERM. Force quit sends SIGKILL after explicit
+confirmation naming the selected process. Recheck ownership and protected
+session identities when executing the action, including after a confirmation
+has been open while the process list changes.
+
+### 4. Desktop integration
+
+Add an `open_system_monitor` action that launches the app or restores and
+focuses its existing window. Route launching through the existing app-scope
+machinery. Install a desktop entry and icon for the application launcher.
+
+Both presets now bind Ctrl+Alt+Del to `open_system_monitor`; the canvas
+previously used `poweroff`. Explicit bindings are preserved and require the
+[documented configuration change](../system-monitor.md#existing-shortcut-configuration).
+Existing lock, greeter and shortcut-inhibition rules still apply.
+
+Relevant integration points:
+
+| Existing code | Planned integration |
+| --- | --- |
+| [`src/config/keybinds.zig`](../../src/config/keybinds.zig) | Add the named action. |
+| [`src/config/default.zig`](../../src/config/default.zig) | Change the canvas Ctrl+Alt+Del default. |
+| [`src/config/workspace_defaults.zig`](../../src/config/workspace_defaults.zig) | Add the workspace Ctrl+Alt+Del default. |
+| [`src/config_runtime/actions.zig`](../../src/config_runtime/actions.zig) | Dispatch launch or restore/focus through the existing launch path. |
+| [`src/session/app_scope.zig`](../../src/session/app_scope.zig) | Preserve per-application scope placement. |
+| [`src/control_center/sections/shortcuts.zig`](../../src/control_center/sections/shortcuts.zig) | Add the shortcut description and appropriate grouping. |
+| [`build.zig`](../../build.zig) and `data/` | Build and install the executable, desktop entry and icon. |
+
+### 5. Validation
+
+Extend existing tests where practical and add focused coverage for the new
+collector and application:
+
+* CPU calculations and memory accounting from controlled samples.
+* Disappearing processes, PID reuse, unavailable data and permission errors.
+* Sorting, search, stable selection and scroll position during updates.
+* End process and Force quit using disposable fixture processes, including a
+ fixture that ignores SIGTERM.
+* Shortcut launch, restore/focus, repeated activation and both desktop modes.
+* Existing lock, greeter and shortcut-inhibition behavior.
+* Live theme changes, fractional scaling, keyboard navigation and resizing.
+* Sampling suspension, cancellation and worker lifetime when paused,
+ minimized, restored or closed.
+
+Use isolated headless integration tests as described in
+[`TESTING.md`](../../TESTING.md). Process-action tests must only signal their
+own disposable fixtures.
+
+Before completing implementation, build Debug and ReleaseSafe, run
+`zig build test`, and run the affected integration suites. Compare failures
+against a worktree of HEAD before calling them regressions.
+
+## Delivery order
+
+1. Collector and process model with focused tests.
+2. Usable native monitor window with summaries, history, search and sorting.
+3. Process actions, shortcut integration, launcher packaging and end-to-end
+ validation.
+
+## Implementation and validation record
+
+The collector, bounded history and process model live in `src/system_monitor/`.
+IPC reuses its stat reader and retains the existing window-only sampling
+behavior. The standalone app uses persistent shared widgets, released shm
+buffers, filesystem theme notifications, fractional-scale/viewporter, and an
+eventfd worker. xdg-shell v6 suspension is sent by the compositor when a
+window is minimized and cleared on restore. Process actions validate the
+pidfd, start time, ownership and protected executable at execution. Launcher
+files and the session/release installer lists include the new executable.
+
+Validated on 2026-10-17:
+
+* Debug and ReleaseSafe builds; `zig build test` and `zig build test-monitor`.
+* `tests/system_monitor.py`: canvas and workspaces at scale 1 and 1.5,
+ disposable TERM/KILL targets, confirmation cancel, a target exiting while
+ confirmation is open, protection changing across exec, stable list model,
+ pause, focus loss, minimize/restore, hidden close, resizing and live themes.
+ The canvas suite also passes against the ReleaseSafe compositor and app
+ using `REDIWM_TEST_BINARY=.../zig-out/release-safe/bin/rediwm`.
+* `keyboard_shortcuts.py` and `shortcuts_inhibit.py` in both desktop modes;
+ the latter explicitly checks the monitor chord under an inhibitor.
+* `lock_screen.py`, `greeter.py`, `output_scale.py`, `images_viewer.py`,
+ `files_controls.py --places-only`, and `editor.py`.
+* ReleaseSafe executable strings contain no monitor preview or production
+ `REDIWM_TEST_*` hooks. Installer shell syntax and diff whitespace checks pass.
+ UI action tests use a noninstalled seccomp notification guard that permits
+ signals only to their own recorded child identities, with a separate guard
+ check against an unlisted disposable process.
+
+Two broader suites retain failures reproduced in a detached worktree of
+HEAD (`3170a17`): `wlr_protocols.py` expects `finished` for a second session-lock
+request but receives EOF; `pdf_viewer.py` times out waiting for a double-clicked
+PDF window to close. Workspace inhibition's initial restore-drag assertion
+passed on rerun.
diff --git a/docs/system-monitor.md b/docs/system-monitor.md
new file mode 100644
index 0000000..c098015
--- /dev/null
+++ b/docs/system-monitor.md
@@ -0,0 +1,82 @@
+# System Monitor
+
+Open **System Monitor** from the launcher, with **Ctrl+Alt+Del**, or by
+running `rediwm-monitor`. The shortcut restores and focuses an existing
+window, including one on another workspace.
+
+CPU and RAM summaries have 60-second graphs. System RAM usage is
+`MemTotal - MemAvailable`; process memory is resident memory. A process
+using one CPU core reads 100%, so multithreaded processes can exceed 100%.
+New processes and the first sample after resuming show an em dash until
+there is a second CPU measurement. Unavailable data also shows an em dash.
+Nonlocal account names fall back to their numeric UID.
+
+The list starts with your processes, sorted by CPU usage. Click a column to
+sort; click again to reverse. **My processes / All processes** changes the
+ownership filter. Search matches names, PIDs and users. Selection follows
+the PID and start time as rows move; refreshes preserve the scroll offset.
+
+**End process** sends SIGTERM. **Force quit** requires confirmation naming
+the target before sending SIGKILL. Both actions recheck identity, ownership
+and essential RediWM session protection at execution, including after a
+confirmation has been open. Signals use a validated pidfd. Other users'
+processes can be viewed where `/proc` permits but cannot be managed here.
+The monitor never requests elevated privileges.
+
+| Key | Action |
+| --- | --- |
+| Ctrl+F | Focus search and select its text |
+| Up / Down | Select a process; leave search for the list |
+| Page Up / Page Down | Move by a visible page |
+| Home / End | First / last process when outside search |
+| Tab / Shift+Tab | Navigate controls |
+| Enter / Space | Activate the focused control |
+| Delete | End selected process |
+| Shift+Delete | Open Force quit confirmation |
+| Escape | Cancel confirmation or clear search |
+| Ctrl+Q / Ctrl+W | Close |
+
+Collection runs once per second in a worker in the monitor process.
+**Pause updates** and minimizing suspend collection; restoring respects the
+pause setting. Losing keyboard focus does not suspend collection. The
+worker blocks without periodic wakes when paused or minimized. Closing
+cancels collection and joins it. Minimize signaling uses xdg-shell v6's
+`suspended` state, supplied by RediWM; other compositors must support that
+state for minimize suspension. Live themes use filesystem notifications.
+Fractional scaling uses fractional-scale-v1 and viewporter when available.
+
+## Existing shortcut configuration
+
+Both presets now use `open_system_monitor`. Explicit user bindings are
+preserved. For an older canvas config containing
+`"ctrl+alt+delete" = "poweroff"`, replace that line in
+`~/.config/rediwm/config.toml`:
+
+```toml
+[keybinds]
+"ctrl+alt+delete" = "open_system_monitor"
+```
+
+For explicit workspace overrides, use the existing section:
+
+```toml
+[keybinds.workspace]
+"Ctrl+Alt+Delete" = "open_system_monitor"
+```
+
+Shortcut inhibition and lock/greeter rules still apply. The app gets its
+own application scope when scope management is enabled.
+
+## Building and testing
+
+`zig build` installs the app, desktop entry and icon in the build prefix.
+`zig build monitor` builds just those files. The session installer includes
+them too. `zig build test-monitor` tests accounting, collection, identity,
+process actions, the list model and worker lifetime.
+
+`python3 tests/system_monitor.py` exercises both desktop modes in private
+headless compositors; repeat with `REDIWM_TEST_SCALE=1.5`. All action targets
+are disposable test children. See [TESTING.md](../TESTING.md).
+
+Accounting follows the [Linux proc documentation](https://docs.kernel.org/filesystems/proc.html);
+actions follow the [pidfd signal contract](https://man7.org/linux/man-pages/man2/pidfd_send_signal.2.html).
diff --git a/src/control_center/search.zig b/src/control_center/search.zig
new file mode 100644
index 0000000..88ff6bd
--- /dev/null
+++ b/src/control_center/search.zig
@@ -0,0 +1,321 @@
+//! Global Settings search UI. The field outlives tree rebuilds and results own
+//! their strings/widgets in a separate arena, never in a section's arena.
+const std = @import("std");
+const ui = @import("ui");
+const W = ui.layout.Widget;
+const panel = @import("panel.zig");
+const CC = panel.ControlCenter;
+const index = @import("search_index.zig");
+const gpa = @import("../main.zig").gpa;
+
+pub const State = struct {
+ field: W = .{ .kind = .container },
+ toolbar: W = .{ .kind = .container },
+ toolbar_children: [2]W = undefined,
+ initialized: bool = false,
+ focused: bool = false,
+ request_focus: bool = false,
+ expanded: bool = false,
+ active: bool = false,
+ built_active: bool = false,
+ selected: usize = 0,
+ matches: [index.entries.len]usize = undefined,
+ count: usize = 0,
+ rows: []W = &.{},
+ arena: std.heap.ArenaAllocator = .init(gpa),
+ saved_scroll: ui.layout.ScrollState = .{},
+ restore_scroll: bool = false,
+ pending_result: ?usize = null,
+ destination: ?usize = null,
+ reveal: bool = false,
+ unavailable: bool = false,
+ reset_scroll: bool = false,
+
+ pub fn deinit(s: *State) void {
+ if (s.initialized) gpa.free(s.field.kind.text_input.value);
+ s.arena.deinit();
+ }
+
+ pub fn capture(s: *State) void {
+ s.focused = s.initialized and ui.input.current.focused == &s.field;
+ }
+
+ pub fn buildToolbar(s: *State, cc: *CC) void {
+ if (!s.initialized) {
+ const value = gpa.dupe(u8, "") catch return;
+ s.field = .{ .name = "settings_search", .kind = .{ .text_input = .{
+ .field = .{ .leading_icon = .search, .leading_icon_size = 14 },
+ .placeholder = "Search settings…",
+ .value = value,
+ .owner = cc,
+ .on_change = changed,
+ } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 36 } };
+ s.initialized = true;
+ }
+ s.toolbar_children = .{
+ .{ .kind = .container, .width = .{ .flex = 1 }, .children = (&s.field)[0..1] },
+ .{ .name = "settings_search_clear", .kind = .{ .button = .{ .label = "×", .owner = cc, .on_click = clearClicked } }, .width = .{ .fixed = 30 }, .height = .{ .fixed = 36 } },
+ };
+ s.toolbar = .{ .kind = .container, .direction = .row, .gap = 4, .width = .{ .percent = 1 }, .height = .{ .fixed = 36 }, .children = s.toolbar_children[0..if (s.query().len > 0) @as(usize, 2) else 1] };
+ }
+
+ pub fn query(s: *const State) []const u8 {
+ return if (s.initialized) s.field.kind.text_input.value else "";
+ }
+
+ fn failed(s: *State) W {
+ s.count = 0;
+ s.rows = &.{};
+ return panel.outOfMemory();
+ }
+
+ pub fn build(s: *State, cc: *CC) W {
+ _ = s.arena.reset(.retain_capacity);
+ const a = s.arena.allocator();
+ s.count = 0;
+ var scores: [index.entries.len]u32 = undefined;
+ for (index.entries, 0..) |entry, id| {
+ if (entry.page == .services and (cc.systemd_client == null or !cc.systemd_client.?.available())) continue;
+ const rank = index.score(entry, s.query(), panel.page_labels[@intFromEnum(entry.page)]) orelse continue;
+ var at = s.count;
+ while (at > 0 and scores[at - 1] < rank) : (at -= 1) {
+ scores[at] = scores[at - 1];
+ s.matches[at] = s.matches[at - 1];
+ }
+ scores[at] = rank;
+ s.matches[at] = id;
+ s.count += 1;
+ }
+ s.selected = @min(s.selected, s.count -| 1);
+ s.rows = a.alloc(W, s.count + 1) catch return s.failed();
+ const t = panel.palette();
+ const query_copy = a.dupe(u8, s.query()) catch return s.failed();
+ s.rows[0] = panel.sectionTitle(if (s.count == 0) "No settings found" else "Search results");
+ if (s.count == 0) {
+ const children = a.dupe(W, &.{ s.rows[0], .{ .kind = .{ .text = .{ .content = "Try a setting name, such as volume, wallpaper or scroll.", .font_size = t.settings_description_size, .color = t.dim } } } }) catch return s.failed();
+ return .{ .name = "settings_search_results", .kind = .container, .direction = .column, .gap = 12, .children = children };
+ }
+ for (s.matches[0..s.count], 0..) |id, i| {
+ const entry = index.entries[id];
+ const title = W{ .kind = .{ .text = .{ .content = entry.title, .font_size = t.app_text_size, .weight = 600, .color = t.fg, .highlight_query = query_copy } } };
+ const path = panel.page_labels[@intFromEnum(entry.page)];
+ const subtitle = W{ .kind = .{ .text = .{ .content = if (entry.target.len == 0) "Settings page" else path, .font_size = t.settings_description_size, .color = t.dim, .highlight_query = query_copy } } };
+ const labels = a.dupe(W, &.{ title, subtitle }) catch return s.failed();
+ const children = a.dupe(W, &.{.{ .kind = .container, .direction = .column, .width = .{ .flex = 1 }, .gap = 4, .children = labels }}) catch return s.failed();
+ s.rows[i + 1] = .{ .name = entry.target, .kind = .{ .row = .{ .owner = cc, .id = id, .on_click = resultClicked, .selected = i == s.selected } }, .height = .{ .fixed = 64 }, .width = .{ .percent = 1 }, .padding = ui.layout.Edges.all(10), .children = children };
+ }
+ return .{ .name = "settings_search_results", .kind = .container, .direction = .column, .gap = 6, .width = .{ .percent = 1 }, .children = s.rows };
+ }
+};
+
+pub fn focus(cc: *CC) void {
+ if (cc.is_welcome) return;
+ const s = &cc.search;
+ s.expanded = true;
+ s.request_focus = true;
+ s.active = std.mem.trim(u8, s.query(), " \t\r\n").len > 0;
+ // Focus after the rebuild, whose dispatcher reset would otherwise lose it.
+ s.buildToolbar(cc);
+ cc.relayout();
+ ui.input.current.focus(&cc.root, &s.field);
+ _ = ui.input.current.keyEvent(gpa, .select_all, .{}) catch {};
+ cc.requestWidgetRepaint();
+}
+
+pub fn focusClicked(owner: ?*anyopaque, _: usize) void {
+ const cc: *CC = @ptrCast(@alignCast(owner orelse return));
+ cc.search.expanded = true;
+ cc.search.request_focus = true;
+ cc.search.active = std.mem.trim(u8, cc.search.query(), " \t\r\n").len > 0;
+ cc.refresh();
+}
+
+fn changed(owner: ?*anyopaque, _: usize, value: []const u8) void {
+ const cc: *CC = @ptrCast(@alignCast(owner orelse return));
+ const s = &cc.search;
+ s.active = std.mem.trim(u8, value, " \t\r\n").len > 0;
+ s.selected = 0;
+ s.reset_scroll = true;
+ s.destination = null;
+ s.unavailable = false;
+ cc.refresh();
+}
+
+fn clearClicked(owner: ?*anyopaque, _: usize) void {
+ const cc: *CC = @ptrCast(@alignCast(owner orelse return));
+ clear(cc);
+}
+
+pub fn clear(cc: *CC) void {
+ const s = &cc.search;
+ if (!s.initialized) return;
+ const empty = gpa.dupe(u8, "") catch return;
+ gpa.free(s.field.kind.text_input.value);
+ s.field.kind.text_input.value = empty;
+ s.field.kind.text_input.cursor_pos = 0;
+ s.field.kind.text_input.selection_anchor = null;
+ s.active = false;
+ s.destination = null;
+ s.unavailable = false;
+ s.request_focus = true;
+ cc.refresh();
+}
+
+fn resultClicked(owner: ?*anyopaque, id: usize) void {
+ const cc: *CC = @ptrCast(@alignCast(owner orelse return));
+ cc.search.pending_result = id;
+}
+
+pub fn apply(cc: *CC) void {
+ const s = &cc.search;
+ const id = s.pending_result orelse return;
+ s.pending_result = null;
+ if (id >= index.entries.len) return;
+ s.active = false;
+ s.built_active = false;
+ s.restore_scroll = false;
+ s.focused = false;
+ s.request_focus = false;
+ ui.input.current.focused = null;
+ s.destination = id;
+ s.unavailable = false;
+ s.reveal = true;
+ cc.selectPage(index.entries[id].page);
+}
+
+pub fn key(cc: *CC, k: ui.input.Key, shift: bool) bool {
+ const s = &cc.search;
+ if (cc.is_welcome or !s.initialized) return false;
+ if (s.active and cc.refresh_pending and (k == .up or k == .down or k == .enter or k == .tab)) cc.relayout();
+ const field_focused = ui.input.current.focused == &s.field;
+ if (k == .escape and (s.active or field_focused or s.destination != null)) {
+ if (s.query().len > 0 or s.destination != null) clear(cc) else {
+ s.expanded = false;
+ s.focused = false;
+ ui.input.current.focused = null;
+ cc.refresh();
+ }
+ return true;
+ }
+ if (s.active and (k == .down or k == .up)) {
+ if (s.count > 0) {
+ ui.input.current.focus(&cc.root, &s.field);
+ s.selected = if (k == .down) @min(s.selected + 1, s.count - 1) else s.selected -| 1;
+ for (s.rows[1..], 0..) |*row, i| {
+ row.kind.row.selected = i == s.selected;
+ row.markPaintDirty();
+ }
+ ui.widgets.scroll_container.ensureVisibleChild(&cc.body_children[1], &s.rows[s.selected + 1]);
+ }
+ cc.requestWidgetRepaint();
+ return true;
+ }
+ if (s.active and k == .enter) {
+ // Tab can leave the field: activate the focused clear button, category
+ // or result rather than opening the arrow-key selection unexpectedly.
+ if (!field_focused and ui.input.current.focused != null) {
+ if (ui.input.current.focused) |widget| switch (widget.kind) {
+ .button => |data| {
+ if (data.state != .disabled) if (data.on_click) |callback| callback(data.owner, data.id);
+ },
+ .row => |data| {
+ if (data.state != .disabled) if (data.on_click) |callback| callback(data.owner, data.id);
+ },
+ else => {},
+ };
+ } else if (s.count > 0) s.pending_result = s.matches[s.selected];
+ if (cc.pending_page) |page| {
+ cc.pending_page = null;
+ cc.selectPage(page);
+ } else apply(cc);
+ cc.requestWidgetRepaint();
+ return true;
+ }
+ if (s.active and k == .tab) {
+ _ = ui.input.current.focusNext(&cc.root, shift);
+ cc.requestWidgetRepaint();
+ return true;
+ }
+ if (field_focused) {
+ _ = ui.input.current.keyEvent(gpa, k, .{ .shift = shift }) catch {};
+ cc.requestWidgetRepaint();
+ return true;
+ }
+ return false;
+}
+
+fn find(root: *W, target: []const u8) ?*W {
+ if (target.len == 0) return null;
+ if (target[0] == '@') {
+ if (root.kind == .text and std.mem.eql(u8, root.kind.text.content, target[1..])) return root;
+ } else if (root.name) |name| {
+ if (std.mem.eql(u8, name, target)) return root;
+ }
+ for (root.children) |*child| if (find(child, target)) |found| return found;
+ return null;
+}
+
+/// Called after layout: reveal nested targets from the inside out, and paint
+/// the containing row using the shared renderer. No control receives a click.
+pub fn reveal(cc: *CC) void {
+ const s = &cc.search;
+ if (s.active) return;
+ const id = s.destination orelse return;
+ if (index.entries[id].target.len == 0) return;
+ const target = find(&cc.body_children[1], index.entries[id].target) orelse {
+ // A hardware-dependent control may be absent; its page still explains
+ // the unavailable device. Never redirect to another setting.
+ s.reveal = false;
+ if (!s.unavailable) {
+ s.unavailable = true;
+ cc.refresh();
+ }
+ return;
+ };
+ if (s.unavailable) {
+ s.unavailable = false;
+ cc.refresh();
+ }
+ var row = target;
+ if (target.parent) |parent| {
+ if (parent.direction == .row or target.kind == .text) row = parent;
+ }
+ if (row.computed_height > cc.body_children[1].computed_height and target.kind == .text) row = target;
+ row.underlay = .{ .owner = cc, .paint = paintDestination };
+ if (!s.reveal) return;
+ s.reveal = false;
+ var ancestor = row.parent;
+ while (ancestor) |parent| : (ancestor = parent.parent) {
+ if (parent.kind == .scroll_container) ui.widgets.scroll_container.ensureVisibleChild(parent, row);
+ }
+}
+
+fn paintDestination(_: ?*anyopaque, row: *const W, r: *ui.paint.Renderer) void {
+ const t = r.palette orelse panel.palette();
+ r.fillRect(row.computed_x, row.computed_y, row.computed_width, row.computed_height, .{
+ .color = .{ t.accent[0], t.accent[1], t.accent[2], 0.10 },
+ .radius = t.radius,
+ .border_width = 1,
+ .border_color = .{ t.accent[0], t.accent[1], t.accent[2], 0.7 },
+ });
+}
+
+/// Dismiss the destination marker on the next content interaction without
+/// rebuilding a page or changing a control under the pointer.
+pub fn dismiss(cc: *CC) void {
+ if (cc.search.destination == null) return;
+ cc.search.destination = null;
+ if (cc.search.unavailable) {
+ cc.search.unavailable = false;
+ cc.refresh();
+ }
+ removeMarker(&cc.body_children[1]);
+}
+
+fn removeMarker(root: *W) void {
+ if (root.underlay) |under| if (under.paint == paintDestination) {
+ root.underlay = null;
+ root.markPaintDirty();
+ };
+ for (root.children) |*child| removeMarker(child);
+}
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
new file mode 100644
index 0000000..d03243f
--- /dev/null
+++ b/src/control_center/search_index.zig
@@ -0,0 +1,180 @@
+//! Static setting destinations. Searching never builds pages or queries hardware.
+const std = @import("std");
+pub const Page = enum { general, input, displays, audio, network, appearance, shortcuts, desktop, bluetooth, region, users, printers, services };
+pub const Entry = struct {
+ page: Page,
+ title: []const u8,
+ /// Empty for a page; @ prefixes a visible heading, otherwise a widget name.
+ target: []const u8 = "",
+ keywords: []const u8 = "",
+};
+pub const entries = [_]Entry{
+ .{ .page = .general, .title = "General", .target = "", .keywords = "" },
+ .{ .page = .input, .title = "Input", .target = "", .keywords = "" },
+ .{ .page = .displays, .title = "Displays", .target = "", .keywords = "" },
+ .{ .page = .audio, .title = "Audio", .target = "", .keywords = "" },
+ .{ .page = .network, .title = "Network", .target = "", .keywords = "" },
+ .{ .page = .appearance, .title = "Appearance", .target = "", .keywords = "" },
+ .{ .page = .shortcuts, .title = "Keyboard Shortcuts", .target = "", .keywords = "" },
+ .{ .page = .desktop, .title = "Desktop", .target = "", .keywords = "" },
+ .{ .page = .bluetooth, .title = "Bluetooth", .target = "", .keywords = "" },
+ .{ .page = .region, .title = "Region & Language", .target = "", .keywords = "" },
+ .{ .page = .users, .title = "Users", .target = "", .keywords = "" },
+ .{ .page = .printers, .title = "Printers", .target = "", .keywords = "" },
+ .{ .page = .services, .title = "Services", .target = "", .keywords = "" },
+ .{ .page = .general, .title = "Brightness", .target = "@Brightness", .keywords = "backlight screen light" },
+ .{ .page = .general, .title = "Open files with a single click", .target = "files_single_click_open", .keywords = "double click folders" },
+ .{ .page = .input, .title = "Mouse speed", .target = "mouse_speed", .keywords = "pointer acceleration sensitivity" },
+ .{ .page = .input, .title = "Touchpad speed", .target = "touchpad_speed", .keywords = "trackpad acceleration sensitivity" },
+ .{ .page = .input, .title = "Disable touchpad while typing", .target = "touchpad_disable_while_typing", .keywords = "keyboard trackpad" },
+ .{ .page = .input, .title = "Natural scroll", .target = "natural_scroll", .keywords = "scrolling direction reverse invert mouse touchpad" },
+ .{ .page = .input, .title = "Tap to click", .target = "tap_to_click", .keywords = "touchpad trackpad" },
+ .{ .page = .input, .title = "Canvas pan speed", .target = "pan_speed", .keywords = "desktop panning" },
+ .{ .page = .input, .title = "Keyboard repeat delay", .target = "repeat_delay", .keywords = "typing keys" },
+ .{ .page = .input, .title = "Keyboard repeat rate", .target = "repeat_rate", .keywords = "typing keys speed" },
+ .{ .page = .displays, .title = "Monitor", .target = "monitor", .keywords = "screen output" },
+ .{ .page = .displays, .title = "Display arrangement", .target = "@Arrangement", .keywords = "screen position monitors main display" },
+ .{ .page = .displays, .title = "Resolution", .target = "resolution", .keywords = "screen size pixels" },
+ .{ .page = .displays, .title = "Refresh rate", .target = "refresh_rate", .keywords = "screen frequency hz" },
+ .{ .page = .displays, .title = "Display scale", .target = "scale", .keywords = "screen scaling dpi zoom" },
+ .{ .page = .displays, .title = "Xwayland scale", .target = "xwayland_scale", .keywords = "x11 legacy apps scaling" },
+ .{ .page = .displays, .title = "Rotation", .target = "transform", .keywords = "orientation portrait landscape screen" },
+ .{ .page = .displays, .title = "Night light", .target = "night_light", .keywords = "blue light warm screen" },
+ .{ .page = .displays, .title = "Night light temperature", .target = "night_light_temperature", .keywords = "warmth colour color" },
+ .{ .page = .displays, .title = "Lid close action", .target = "lid_close", .keywords = "laptop suspend sleep" },
+ .{ .page = .audio, .title = "Output volume", .target = "output_volume", .keywords = "sound speakers loudness mute" },
+ .{ .page = .audio, .title = "Microphone volume", .target = "input_volume", .keywords = "sound input recording mute" },
+ .{ .page = .audio, .title = "Output balance", .target = "output_balance", .keywords = "left right speakers" },
+ .{ .page = .audio, .title = "Bass boost", .target = "bass_boost", .keywords = "sound equalizer low frequencies" },
+ .{ .page = .audio, .title = "Treble", .target = "treble", .keywords = "sound equalizer high frequencies" },
+ .{ .page = .audio, .title = "Audio output device", .target = "@Audio output", .keywords = "speakers headphones sound default" },
+ .{ .page = .network, .title = "Wi-Fi", .target = "wifi_card", .keywords = "wireless internet wlan hotspot hidden network" },
+ .{ .page = .network, .title = "Ethernet", .target = "ethernet_card", .keywords = "wired internet adapter" },
+ .{ .page = .appearance, .title = "Wallpaper", .target = "@Wallpaper", .keywords = "background desktop image folder" },
+ .{ .page = .appearance, .title = "Theme", .target = "@Theme", .keywords = "colors colours dark light preset" },
+ .{ .page = .appearance, .title = "Icon theme", .target = "icon_theme", .keywords = "icons pack" },
+ .{ .page = .appearance, .title = "Animations", .target = "animations", .keywords = "effects motion" },
+ .{ .page = .appearance, .title = "Animation speed", .target = "anim_speed", .keywords = "motion duration" },
+ .{ .page = .appearance, .title = "Reduced motion", .target = "reduced_motion", .keywords = "accessibility animations" },
+ .{ .page = .appearance, .title = "Focus zoom", .target = "focus_zoom", .keywords = "window focus" },
+ .{ .page = .appearance, .title = "Drag feedback", .target = "drag_feedback", .keywords = "window moving" },
+ .{ .page = .appearance, .title = "Drag scale", .target = "drag_scale", .keywords = "window moving size" },
+ .{ .page = .appearance, .title = "Font", .target = "font", .keywords = "typeface text" },
+ .{ .page = .appearance, .title = "Cursor theme", .target = "cursor_theme", .keywords = "pointer mouse" },
+ .{ .page = .appearance, .title = "Font size", .target = "font_size", .keywords = "text size accessibility" },
+ .{ .page = .appearance, .title = "Corner radius", .target = "radius", .keywords = "rounded windows" },
+ .{ .page = .appearance, .title = "Window shadow", .target = "shadow", .keywords = "shadows" },
+ .{ .page = .appearance, .title = "Border glow", .target = "border_glow", .keywords = "window borders" },
+ .{ .page = .appearance, .title = "Window opacity", .target = "chrome_opacity", .keywords = "transparency chrome" },
+ .{ .page = .appearance, .title = "Window darkness", .target = "chrome_darkness", .keywords = "chrome tint" },
+ .{ .page = .appearance, .title = "Titlebar height", .target = "chrome_height", .keywords = "window chrome" },
+ .{ .page = .appearance, .title = "Window control spacing", .target = "chrome_control_gap", .keywords = "buttons close maximize minimize" },
+ .{ .page = .appearance, .title = "Inactive window opacity", .target = "inactive_opacity", .keywords = "transparency unfocused" },
+ .{ .page = .appearance, .title = "Terminal opacity", .target = "terminal_opacity", .keywords = "transparency" },
+ .{ .page = .appearance, .title = "Taskbar position", .target = "taskbar_position", .keywords = "panel top bottom" },
+ .{ .page = .appearance, .title = "Taskbar edge gap", .target = "taskbar_edge_gap", .keywords = "panel margin" },
+ .{ .page = .appearance, .title = "Taskbar length", .target = "taskbar_length", .keywords = "panel width" },
+ .{ .page = .appearance, .title = "Taskbar corner radius", .target = "taskbar_radius", .keywords = "panel rounded" },
+ .{ .page = .appearance, .title = "Taskbar items", .target = "@Taskbar", .keywords = "clock battery tray notifications capture" },
+ .{ .page = .appearance, .title = "Bold clock", .target = "clock_bold", .keywords = "time taskbar font" },
+ .{ .page = .appearance, .title = "Italic clock", .target = "clock_italic", .keywords = "time taskbar font" },
+ .{ .page = .appearance, .title = "Start menu size", .target = "start_menu_width", .keywords = "launcher width" },
+ .{ .page = .appearance, .title = "Start menu height", .target = "start_menu_height", .keywords = "launcher size" },
+ .{ .page = .appearance, .title = "Start menu logo", .target = "start_logo_tile", .keywords = "launcher icon image" },
+ .{ .page = .appearance, .title = "Dock", .target = "dock_enabled", .keywords = "enable apps launcher" },
+ .{ .page = .appearance, .title = "Dock position", .target = "dock_position", .keywords = "top bottom left right" },
+ .{ .page = .appearance, .title = "Dock auto hide", .target = "dock_auto_hide", .keywords = "hide automatically" },
+ .{ .page = .appearance, .title = "Dock height", .target = "dock_height", .keywords = "size" },
+ .{ .page = .appearance, .title = "Dock hover zoom", .target = "dock_hover_zoom", .keywords = "magnification mouse" },
+ .{ .page = .appearance, .title = "Dock opacity", .target = "dock_opacity", .keywords = "transparency" },
+ .{ .page = .appearance, .title = "Dock corner radius", .target = "dock_radius", .keywords = "rounded" },
+ .{ .page = .appearance, .title = "Dock active highlight", .target = "dock_active_highlight", .keywords = "running apps indicator" },
+ .{ .page = .appearance, .title = "Dock trash", .target = "dock_show_trash", .keywords = "recycle bin" },
+ .{ .page = .shortcuts, .title = "Keyboard shortcuts", .target = "@Keyboard Shortcuts", .keywords = "hotkeys keybindings bindings terminal screenshot volume brightness workspaces" },
+ .{ .page = .desktop, .title = "Desktop mode", .target = "desktop_mode", .keywords = "canvas workspaces tiling" },
+ .{ .page = .desktop, .title = "Canvas size", .target = "@Canvas Size", .keywords = "rows columns panning area" },
+ .{ .page = .desktop, .title = "Desktop switching", .target = "@Desktop Switching", .keywords = "edge pan transitions" },
+ .{ .page = .desktop, .title = "Mini map", .target = "mini_map_enabled", .keywords = "minimap overview" },
+ .{ .page = .desktop, .title = "Mini map position", .target = "mini_map_position", .keywords = "overview location" },
+ .{ .page = .desktop, .title = "Mini map hide delay", .target = "mini_map_hide_ms", .keywords = "overview timeout" },
+ .{ .page = .desktop, .title = "Fixed desktop icons", .target = "desktop_icons_fixed", .keywords = "keep icons in place" },
+ .{ .page = .desktop, .title = "Workspace layout", .target = "@Workspace layout", .keywords = "tiling master stack" },
+ .{ .page = .desktop, .title = "Window spacing", .target = "@Window spacing", .keywords = "gaps tiling" },
+ .{ .page = .desktop, .title = "Floating apps", .target = "@Floating apps", .keywords = "rules tiling windows" },
+ .{ .page = .bluetooth, .title = "Bluetooth devices", .target = "@Bluetooth", .keywords = "wireless pairing paired headphones mouse keyboard" },
+ .{ .page = .region, .title = "Application language", .target = "language", .keywords = "locale translation" },
+ .{ .page = .region, .title = "Regional formats", .target = "formats", .keywords = "locale numbers currency dates" },
+ .{ .page = .region, .title = "24-hour clock", .target = "clock_24h", .keywords = "time am pm" },
+ .{ .page = .region, .title = "Clock seconds", .target = "clock_show_seconds", .keywords = "time" },
+ .{ .page = .region, .title = "Clock day", .target = "clock_show_day", .keywords = "date weekday" },
+ .{ .page = .region, .title = "First day of week", .target = "first_day_of_week", .keywords = "calendar monday sunday" },
+ .{ .page = .users, .title = "Accounts", .target = "@Accounts", .keywords = "users login password administrator groups" },
+ .{ .page = .users, .title = "Automatic login", .target = "@Automatic login", .keywords = "autologin boot" },
+ .{ .page = .printers, .title = "Printers", .target = "@Printers", .keywords = "printing cups add queue jobs paper driver label" },
+ .{ .page = .services, .title = "Services", .target = "services_search", .keywords = "systemd startup boot daemon unit enabled failed slow" },
+ .{ .page = .general, .title = "Desktop portals", .target = "portal_default", .keywords = "backend gtk kde dialogs" },
+ .{ .page = .general, .title = "File dialogs", .target = "portal_file_chooser", .keywords = "chooser portal" },
+ .{ .page = .general, .title = "Default file manager", .target = "default_file_manager", .keywords = "files folders application" },
+ .{ .page = .general, .title = "Default terminal", .target = "default_terminal", .keywords = "application shell console" },
+ .{ .page = .appearance, .title = "Taskbar theme", .target = "taskbar_theme", .keywords = "panel colors colours" },
+ .{ .page = .appearance, .title = "Dark mode", .target = "dark_mode", .keywords = "light appearance theme" },
+ .{ .page = .appearance, .title = "Apply GTK colors", .target = "apply_gtk_colors", .keywords = "application colours theme" },
+ .{ .page = .appearance, .title = "Apply Qt colors", .target = "apply_qt_colors", .keywords = "application colours theme" },
+ .{ .page = .appearance, .title = "Launch splash", .target = "launch_splash", .keywords = "startup welcome animation" },
+ .{ .page = .appearance, .title = "Dodge file drags", .target = "dodge_file_drags", .keywords = "drag drop windows" },
+ .{ .page = .appearance, .title = "Dim inactive windows", .target = "inactive_dim", .keywords = "unfocused darkness" },
+ .{ .page = .appearance, .title = "Window tabs", .target = "window_tabs", .keywords = "applications titlebar grouping" },
+ .{ .page = .appearance, .title = "Snapped window gap", .target = "@Snapped window gap", .keywords = "spacing tiled margin" },
+ .{ .page = .appearance, .title = "Scrollbar width", .target = "@Scrollbar width", .keywords = "thickness scrolling accessibility" },
+ .{ .page = .appearance, .title = "Taskbar size", .target = "@Taskbar size", .keywords = "panel height" },
+ .{ .page = .appearance, .title = "Window item width", .target = "@Window item width", .keywords = "taskbar chip size" },
+ .{ .page = .appearance, .title = "Window item gap", .target = "@Window item gap", .keywords = "taskbar chip spacing" },
+ .{ .page = .appearance, .title = "Start button gap", .target = "@Start button gap", .keywords = "taskbar launcher spacing" },
+ .{ .page = .appearance, .title = "Start button icon size", .target = "@Start button icon size", .keywords = "logo launcher" },
+ .{ .page = .appearance, .title = "Menu left padding", .target = "@Menu left padding", .keywords = "start menu spacing" },
+ .{ .page = .appearance, .title = "Menu bottom padding", .target = "@Menu bottom padding", .keywords = "start menu spacing" },
+ .{ .page = .appearance, .title = "Icon left padding", .target = "@Icon left padding", .keywords = "start menu spacing" },
+ .{ .page = .appearance, .title = "Icon bottom padding", .target = "@Icon bottom padding", .keywords = "start menu spacing" },
+ .{ .page = .appearance, .title = "Install theme", .target = "theme_install", .keywords = "import pack" },
+ .{ .page = .appearance, .title = "Remove theme", .target = "theme_remove", .keywords = "delete pack" },
+ .{ .page = .appearance, .title = "Save theme", .target = "theme_export", .keywords = "export look" },
+ .{ .page = .appearance, .title = "Reset theme", .target = "theme_reset", .keywords = "defaults restore" },
+};
+
+pub fn contains(haystack: []const u8, needle: []const u8) bool {
+ if (needle.len == 0 or needle.len > haystack.len) return false;
+ for (0..haystack.len - needle.len + 1) |i| {
+ if (std.ascii.eqlIgnoreCase(haystack[i..][0..needle.len], needle)) return true;
+ }
+ return false;
+}
+
+/// All words must match, including words supplied by the page or aliases.
+/// Label matches outrank aliases; longer queries remain allocation-free.
+pub fn score(entry: Entry, query: []const u8, page_label: []const u8) ?u32 {
+ var words = std.mem.tokenizeAny(u8, query, " \t\r\n");
+ var total: u32 = 0;
+ var count: usize = 0;
+ while (words.next()) |word| {
+ count += 1;
+ if (contains(entry.title, word)) total += 8 else if (contains(page_label, word)) total += 2 else if (contains(entry.keywords, word)) total += 1 else return null;
+ }
+ if (count == 0) return null;
+ const trimmed = std.mem.trim(u8, query, " \t\r\n");
+ if (std.ascii.eqlIgnoreCase(entry.title, trimmed)) total += 100;
+ if (entry.target.len > 0) total += 1;
+ return total;
+}
+
+test "settings search ranks labels, combines words and resolves aliases" {
+ const entry: Entry = .{ .page = .input, .title = "Natural scroll", .target = "natural_scroll", .keywords = "reverse direction touchpad" };
+ try std.testing.expect(score(entry, " SCROLL input ", "Input") != null);
+ try std.testing.expect(score(entry, "reverse touchpad", "Input") != null);
+ try std.testing.expect(score(entry, "scroll printer", "Input") == null);
+ try std.testing.expect(score(entry, " ", "Input") == null);
+ try std.testing.expect(score(entry, "natural scroll", "Input").? > score(entry, "direction", "Input").?);
+ // Targets are unique within a page, apart from explicit page entries.
+ for (entries, 0..) |a, i| for (entries[i + 1 ..]) |b| {
+ try std.testing.expect(a.page != b.page or !std.mem.eql(u8, a.target, b.target));
+ };
+}
diff --git a/src/system_monitor/AGENTS.md b/src/system_monitor/AGENTS.md
new file mode 100644
index 0000000..1adf01c
--- /dev/null
+++ b/src/system_monitor/AGENTS.md
@@ -0,0 +1,22 @@
+# System Monitor
+
+* `proc.zig`, `collector.zig`, `model.zig` and `actions.zig` have no compositor
+ or UI dependencies. IPC reuses the stat reader but keeps its window-only,
+ request-driven sampling contract.
+* A snapshot owns its arena. The worker publishes under its mutex through an
+ eventfd; the UI takes ownership. A generation change cancels enumeration and
+ publication, resets CPU baselines, and wakes the worker. Inactive workers
+ block indefinitely. Never use NSS lookups here: a stalled account service
+ would prevent joining the worker. Local passwd names fall back to numeric UIDs.
+* Selections and confirmations own PID + start time, never row indices. Every
+ action opens a pidfd first, checks the proc identity, UIDs and protected exe,
+ verifies the pidfd's fdinfo identity and liveness, then signals that fd.
+ Never fall back to `kill(pid)`. Tests signal only disposable fixtures.
+* `App.ensureWidgets` runs after App has a stable address. Widget trees persist
+ across snapshots so focus, presses and field strings survive. Callbacks set
+ pending actions; modal tree changes happen after dispatch returns.
+* Minimize suspension comes from xdg-shell v6, not keyboard focus. Restore
+ respects Pause. The client uses released shm buffers and fractional-scale +
+ viewporter; theme watches remain live while sampling is stopped.
+* Tests: `zig build test-monitor`, `python3 tests/system_monitor.py`, and the
+ latter with `REDIWM_TEST_SCALE=1.5`. User documentation: `docs/system-monitor.md`.
diff --git a/src/system_monitor/actions.zig b/src/system_monitor/actions.zig
new file mode 100644
index 0000000..24377df
--- /dev/null
+++ b/src/system_monitor/actions.zig
@@ -0,0 +1,62 @@
+//! Action authority is checked again at execution, never trusted from a row.
+const std = @import("std");
+const proc = @import("proc.zig");
+const c = proc.c;
+pub const Kind = enum { end, force };
+
+pub fn execute(identity: proc.Identity, kind: Kind) !void {
+ const rc = std.os.linux.pidfd_open(identity.pid, 0);
+ if (std.os.linux.errno(rc) != .SUCCESS) return signalError(std.os.linux.errno(rc));
+ const pidfd: i32 = @intCast(rc);
+ defer _ = c.close(pidfd);
+ // Open the proc directory AFTER the pidfd. If PID reuse occurs between
+ // them, the old pidfd becomes readable and the final liveness gate fails.
+ const dir = try proc.openProcess(identity.pid);
+ defer _ = c.close(dir);
+ var stat_buf: [4096]u8 = undefined;
+ const stat = proc.parseStat(try proc.readAt(dir, "stat", &stat_buf)) orelse return error.IdentityUnavailable;
+ if (stat.start != identity.start) return error.ProcessExited;
+ var status_buf: [16384]u8 = undefined;
+ const uids = proc.parseUids(try proc.readAt(dir, "status", &status_buf)) orelse return error.IdentityUnavailable;
+ if (!proc.owned(uids, c.getuid())) return error.PermissionDenied;
+ if (try proc.protectedAt(dir, identity.pid)) return error.ProtectedProcess;
+ // fdinfo identifies the task referred to by THIS pidfd, not whichever task
+ // currently occupies /proc/PID. An exited pidfd reports Pid: -1.
+ var path_buf: [64]u8 = undefined;
+ const path = try std.fmt.bufPrintZ(&path_buf, "/proc/self/fdinfo/{d}", .{pidfd});
+ var info_buf: [4096]u8 = undefined;
+ const info = try proc.readAt(c.AT_FDCWD, path, &info_buf);
+ var lines = std.mem.splitScalar(u8, info, '\n');
+ var pid_matches = false;
+ while (lines.next()) |line| {
+ if (std.mem.startsWith(u8, line, "Pid:")) {
+ const pid = std.fmt.parseInt(i32, std.mem.trim(u8, line[4..], " \t"), 10) catch return error.IdentityUnavailable;
+ pid_matches = pid == identity.pid;
+ }
+ }
+ if (!pid_matches) return error.ProcessExited;
+ var fd = c.struct_pollfd{ .fd = pidfd, .events = c.POLLIN, .revents = 0 };
+ if (c.poll(&fd, 1, 0) != 0) return error.ProcessExited;
+ const result = std.os.linux.pidfd_send_signal(pidfd, if (kind == .end) std.posix.SIG.TERM else std.posix.SIG.KILL, null, 0);
+ if (std.os.linux.errno(result) != .SUCCESS) return signalError(std.os.linux.errno(result));
+}
+
+fn signalError(err: std.os.linux.E) error{ ProcessExited, PermissionDenied, PidfdUnavailable, SignalFailed } {
+ return switch (err) {
+ .SRCH, .NOENT => error.ProcessExited,
+ .PERM, .ACCES => error.PermissionDenied,
+ .NOSYS, .INVAL => error.PidfdUnavailable,
+ else => error.SignalFailed,
+ };
+}
+
+pub fn message(err: anyerror) []const u8 {
+ return switch (err) {
+ error.ProcessExited => "Process already exited",
+ error.PermissionDenied => "Permission denied: only your own processes can be managed",
+ error.ProtectedProcess => "This essential RediWM session process is protected",
+ error.PidfdUnavailable => "Safe process actions require Linux pidfd support",
+ error.IdentityUnavailable => "Could not verify the process identity",
+ else => "Could not send the signal",
+ };
+}
diff --git a/src/system_monitor/app.zig b/src/system_monitor/app.zig
new file mode 100644
index 0000000..72a259c
--- /dev/null
+++ b/src/system_monitor/app.zig
@@ -0,0 +1,560 @@
+const std = @import("std");
+const ui = @import("ui");
+const cairo = ui.cairo;
+const theme = ui.theme;
+const W = ui.layout.Widget;
+const Rect = cairo.Rect;
+const c = @import("../files/c.zig").api;
+const collector = @import("collector.zig");
+const model = @import("model.zig");
+const proc = @import("proc.zig");
+const actions = @import("actions.zig");
+const scrollbar = ui.widgets.scrollbar;
+const a = std.heap.c_allocator;
+const row_h: f64 = 32;
+const titles = [_][]const u8{ "Name", "PID", "User", "CPU %", "Memory (resident)", "State" };
+const proportions = [_]f32{ 0.28, 0.10, 0.15, 0.12, 0.21, 0.14 };
+const Pending = enum { none, end, confirm, cancel, force };
+const Confirmation = struct { identity: proc.Identity, name: [256]u8 = undefined, len: usize };
+
+pub const App = struct {
+ worker: *collector.Worker,
+ model: model.Model,
+ history: model.History = .{},
+ w: i32 = 960,
+ h: i32 = 640,
+ scale: i32 = 1,
+ density: f64 = 1,
+ dirty: bool = true,
+ closed: bool = false,
+ ctrl: bool = false,
+ alt: bool = false,
+ shift: bool = false,
+ focused: bool = false,
+ caret_visible: bool = true,
+ caret_moving: bool = false,
+ paused: bool = false,
+ suspended: bool = false,
+ px: f32 = -1,
+ py: f32 = -1,
+ root: W = .{ .kind = .container },
+ sections: [6]W = undefined,
+ toolbar: [3]W = undefined,
+ headers: [6]W = undefined,
+ header_labels: [6][64]u8 = undefined,
+ footer: [3]W = undefined,
+ modal: W = .{ .kind = .container },
+ modal_buttons: [2]W = undefined,
+ initialized: bool = false,
+ dispatcher: ui.input.Dispatcher = .{},
+ pending: Pending = .none,
+ confirmation: ?Confirmation = null,
+ notice: []const u8 = "",
+ bar: scrollbar.Appearance = .{},
+ bar_drag: scrollbar.Drag = .{},
+ last_scroll: f64 = 0,
+
+ pub fn init(io: std.Io) !App {
+ return .{ .worker = try collector.Worker.init(io), .model = .{ .allocator = a, .uid = c.getuid() } };
+ }
+ pub fn deinit(self: *App) void {
+ self.worker.deinit();
+ self.dispatcher.reset();
+ if (self.initialized) a.free(self.toolbar[0].kind.text_input.value);
+ self.model.deinit();
+ }
+ pub fn getTitle(_: *App) [*:0]const u8 {
+ return "System Monitor";
+ }
+ pub fn requestClose(self: *App) void {
+ self.closed = true;
+ self.worker.setActive(false);
+ }
+ pub fn setSuspended(self: *App, suspended: bool) void {
+ if (self.suspended == suspended) return;
+ self.suspended = suspended;
+ self.worker.setActive(!self.paused and !suspended and !self.closed);
+ if (suspended) self.cancelDrag();
+ self.dirty = true;
+ }
+ pub fn start(self: *App) void {
+ self.worker.setActive(!self.paused and !self.suspended and !self.closed);
+ }
+ pub fn sync(self: *App) void {
+ self.applyPending();
+ if (self.worker.take()) |snap| {
+ if (self.paused or self.suspended or self.closed) {
+ snap.deinit();
+ return;
+ }
+ self.history.append(snap);
+ self.model.update(snap) catch {
+ self.notice = "Not enough memory to display every process";
+ };
+ self.clampScroll();
+ self.dirty = true;
+ }
+ }
+ fn button(self: *App, label: []const u8, id: usize, width: f32) W {
+ return .{ .kind = .{ .button = .{ .label = label, .owner = self, .id = id, .on_click = clicked } }, .width = .{ .fixed = width }, .height = .{ .fixed = 34 } };
+ }
+ fn ensureWidgets(self: *App) void {
+ if (self.initialized) return;
+ self.initialized = true;
+ self.toolbar = .{
+ .{ .kind = .{ .text_input = .{ .owner = self, .placeholder = "Search name, PID or user", .value = a.dupe(u8, "") catch unreachable, .on_change = searchChanged, .field = .{ .leading_icon = .search } } }, .width = .{ .flex = 1 }, .height = .{ .fixed = 34 } },
+ self.button("My processes", 0, 148),
+ self.button("Pause updates", 1, 130),
+ };
+ for (&self.headers, titles, proportions, 0..) |*header, title, width, i| {
+ header.* = self.button(title, 10 + i, 0);
+ header.width = .{ .percent = width };
+ header.kind.button.variant = .ghost;
+ }
+ self.footer = .{
+ .{ .kind = .container, .width = .{ .flex = 1 } },
+ self.button("End process", 2, 124),
+ self.button("Force quit…", 3, 124),
+ };
+ self.sections = .{
+ .{ .kind = .container, .height = .{ .fixed = 150 } },
+ .{ .kind = .container, .height = .{ .fixed = 50 }, .padding = .{ .left = 16, .right = 16, .top = 4 }, .gap = 8, .children = &self.toolbar },
+ .{ .kind = .container, .height = .{ .fixed = 36 }, .padding = .{ .left = 16, .right = scrollbar.gutter(theme.global.scrollbar_width) + 16 }, .children = &self.headers },
+ .{ .kind = .container, .height = .{ .flex = 1 } },
+ .{ .kind = .container, .height = .{ .fixed = 46 }, .padding = .{ .left = 16, .right = 16, .top = 6 }, .gap = 8, .children = &self.footer },
+ .{ .kind = .container, .height = .{ .fixed = 28 } },
+ };
+ self.root = .{ .kind = .container, .direction = .column, .children = &self.sections, .@"align" = .stretch };
+ self.modal_buttons = .{ self.button("Cancel", 20, 120), self.button("Force quit", 21, 120) };
+ self.modal_buttons[1].kind.button.variant = .primary;
+ self.modal = .{ .kind = .container, .gap = 12, .children = &self.modal_buttons };
+ self.root.linkParents();
+ self.modal.linkParents();
+ self.layout();
+ }
+ fn layout(self: *App) void {
+ if (!self.initialized) return;
+ self.sections[2].padding.right = scrollbar.gutter(theme.global.scrollbar_width) + 16;
+ ui.measure.measure(&self.root, @floatFromInt(self.w), @floatFromInt(self.h));
+ ui.arrange.arrange(&self.root, 0, 0, @floatFromInt(self.w), @floatFromInt(self.h));
+ const box = self.dialogBox();
+ ui.measure.measure(&self.modal, 252, 34);
+ ui.arrange.arrange(&self.modal, box.x + box.w - 276, box.y + box.h - 50, 252, 34);
+ self.clampScroll();
+ }
+ pub fn resize(self: *App, width: i32, height: i32) void {
+ self.w = @max(640, width);
+ self.h = @max(400, height);
+ self.layout();
+ self.dirty = true;
+ }
+ fn tree(self: *App) *W {
+ return if (self.confirmation != null) &self.modal else &self.root;
+ }
+ fn clicked(owner: ?*anyopaque, id: usize) void {
+ const self: *App = @ptrCast(@alignCast(owner.?));
+ switch (id) {
+ 0 => {
+ self.model.mine = !self.model.mine;
+ self.model.filter() catch {};
+ self.clampScroll();
+ },
+ 1 => {
+ self.paused = !self.paused;
+ self.worker.setActive(!self.paused and !self.suspended and !self.closed);
+ },
+ 2 => self.pending = .end,
+ 3 => self.pending = .confirm,
+ 10...15 => self.model.setSort(@enumFromInt(id - 10)),
+ 20 => self.pending = .cancel,
+ 21 => self.pending = .force,
+ else => {},
+ }
+ self.dirty = true;
+ }
+ fn searchChanged(owner: ?*anyopaque, _: usize, value: []const u8) void {
+ const self: *App = @ptrCast(@alignCast(owner.?));
+ self.model.query = value;
+ self.model.filter() catch {};
+ self.clampScroll();
+ self.dirty = true;
+ }
+ fn manageable(self: *const App) bool {
+ const row = self.model.selectedProcess() orelse return false;
+ return row.uids != null and proc.owned(row.uids.?, self.model.uid) and !row.protected and row.state != 'Z' and row.state != 'X';
+ }
+ fn applyPending(self: *App) void {
+ const pending = self.pending;
+ self.pending = .none;
+ if (pending == .none) return;
+ if (pending == .cancel) {
+ self.dismiss();
+ return;
+ }
+ if (pending == .force) {
+ const confirmation = self.confirmation orelse return;
+ self.dismiss();
+ self.send(confirmation.identity, .force);
+ } else {
+ const row = self.model.selectedProcess() orelse {
+ self.notice = "Select a process first";
+ return;
+ };
+ if (!self.manageable()) {
+ self.notice = if (row.protected) actions.message(error.ProtectedProcess) else actions.message(error.PermissionDenied);
+ return;
+ }
+ if (pending == .end) self.send(row.identity, .end) else {
+ var confirmation: Confirmation = .{ .identity = row.identity, .len = @min(row.name.len, 255) };
+ while (confirmation.len > 0 and !std.unicode.utf8ValidateSlice(row.name[0..confirmation.len])) confirmation.len -= 1;
+ @memcpy(confirmation.name[0..confirmation.len], row.name[0..confirmation.len]);
+ self.confirmation = confirmation;
+ self.cancelDrag();
+ self.dispatcher.reset();
+ self.dispatcher.focus(&self.modal, &self.modal_buttons[0]);
+ }
+ }
+ self.dirty = true;
+ }
+ fn dismiss(self: *App) void {
+ self.confirmation = null;
+ self.dispatcher.reset();
+ self.dirty = true;
+ }
+ fn send(self: *App, identity: proc.Identity, kind: actions.Kind) void {
+ actions.execute(identity, kind) catch |err| {
+ self.notice = actions.message(err);
+ self.dirty = true;
+ return;
+ };
+ self.notice = if (kind == .end) "Termination requested" else "Force quit requested";
+ self.dirty = true;
+ }
+ pub fn cancelDrag(self: *App) void {
+ self.bar_drag.end();
+ self.dispatcher.pressed = null;
+ self.dispatcher.text_drag = null;
+ if (self.initialized) self.dispatcher.pointerLeave(self.tree());
+ }
+ pub fn cursorName(self: *App) [*:0]const u8 {
+ return if (self.dispatcher.overText()) "text" else if (self.dispatcher.hovered != null) "pointer" else "default";
+ }
+ pub fn handleMotion(self: *App, x: f64, y: f64) void {
+ self.ensureWidgets();
+ self.px = @floatCast(x);
+ self.py = @floatCast(y);
+ if (self.confirmation == null and self.bar_drag.active) if (self.barGeometry()) |g| {
+ self.model.scroll = self.bar_drag.offsetAt(g, self.px, self.py);
+ };
+ self.dispatcher.pointerMotion(self.tree(), self.px, self.py);
+ self.dirty = true;
+ }
+ pub fn handleButton(self: *App, code: u32, pressed: bool) void {
+ self.ensureWidgets();
+ if (code != 0x110) return;
+ if (!pressed) {
+ self.bar_drag.end();
+ self.dispatcher.pointerButtonUp(self.tree(), self.px, self.py);
+ self.applyPending();
+ } else {
+ if (self.confirmation == null) {
+ const list = self.listBox();
+ const gutter = scrollbar.gutter(theme.global.scrollbar_width);
+ if (self.barGeometry()) |g| if (scrollbar.press(g, self.px, self.py, @floatCast(self.model.scroll))) |decision| {
+ switch (decision) {
+ .grab => self.bar_drag.begin(g, self.px, self.py, @floatCast(self.model.scroll)),
+ .page => |offset| self.model.scroll = offset,
+ }
+ self.dirty = true;
+ return;
+ };
+ if (self.py >= list.y and self.py < list.y + list.h and self.px >= 16 and self.px < @as(f32, @floatFromInt(self.w)) - gutter - 16) {
+ const index: usize = @intFromFloat(@floor((self.py - list.y + self.model.scroll) / row_h));
+ if (index < self.model.rows.items.len) {
+ self.model.selected = self.model.snapshot.?.processes[self.model.rows.items[index]].identity;
+ self.notice = "";
+ }
+ self.dispatcher.focus(&self.root, null);
+ }
+ }
+ self.dispatcher.pointerButtonDown(self.tree(), self.px, self.py);
+ }
+ self.dirty = true;
+ }
+ pub fn handleScroll(self: *App, value: f64) void {
+ if (self.confirmation != null) return;
+ self.model.scroll += value * 3;
+ self.clampScroll();
+ self.dirty = true;
+ }
+ pub fn handleKey(self: *App, sym: u32, text: []const u8) void {
+ self.ensureWidgets();
+ self.dirty = true;
+ if (self.ctrl and (sym == c.XKB_KEY_q or sym == c.XKB_KEY_w)) {
+ self.requestClose();
+ return;
+ }
+ if (sym == c.XKB_KEY_Tab or sym == c.XKB_KEY_ISO_Left_Tab) {
+ _ = self.dispatcher.focusNext(self.tree(), self.shift or sym == c.XKB_KEY_ISO_Left_Tab);
+ return;
+ }
+ if (self.confirmation != null) {
+ if (sym == c.XKB_KEY_Escape) self.dismiss() else if (sym == c.XKB_KEY_Return or sym == c.XKB_KEY_space) self.activateFocused();
+ return;
+ }
+ if (self.ctrl and sym == c.XKB_KEY_f) {
+ self.dispatcher.focus(&self.root, &self.toolbar[0]);
+ ui.widgets.text_input.selectAll(&self.toolbar[0]);
+ return;
+ }
+ if (sym == c.XKB_KEY_Escape) {
+ if (self.toolbar[0].kind.text_input.value.len > 0) {
+ ui.widgets.text_input.selectAll(&self.toolbar[0]);
+ ui.widgets.text_input.insertText(a, &self.toolbar[0], "") catch {};
+ }
+ self.dispatcher.focus(&self.root, null);
+ return;
+ }
+ const field_focused = self.dispatcher.focused == &self.toolbar[0];
+ if (field_focused and sym != c.XKB_KEY_Down and sym != c.XKB_KEY_Up and sym != c.XKB_KEY_Return) {
+ const key: ?ui.input.Key = switch (sym) {
+ c.XKB_KEY_BackSpace => .backspace,
+ c.XKB_KEY_Delete => .delete,
+ c.XKB_KEY_Left => .left,
+ c.XKB_KEY_Right => .right,
+ c.XKB_KEY_Home => .home,
+ c.XKB_KEY_End => .end,
+ else => if (self.ctrl and sym == c.XKB_KEY_a) .select_all else if (!self.ctrl and !self.alt and text.len > 0) .{ .char = text } else null,
+ };
+ if (key) |k| {
+ const outcome = self.dispatcher.keyEvent(a, k, .{ .shift = self.shift }) catch return;
+ if (outcome.copy) |copy| a.free(copy);
+ }
+ return;
+ }
+ if (sym == c.XKB_KEY_Return or sym == c.XKB_KEY_space) {
+ self.activateFocused();
+ } else if (sym == c.XKB_KEY_Delete and !self.ctrl and !self.alt) {
+ self.pending = if (self.shift) .confirm else .end;
+ self.applyPending();
+ } else if (sym == c.XKB_KEY_Up or sym == c.XKB_KEY_Down or sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down or sym == c.XKB_KEY_Home or sym == c.XKB_KEY_End) {
+ if (self.model.rows.items.len == 0) return;
+ self.dispatcher.focus(&self.root, null);
+ const last = self.model.rows.items.len - 1;
+ const current = self.model.selectedIndex() orelse if (sym == c.XKB_KEY_Up) last else 0;
+ const page: usize = @intFromFloat(@max(1, @floor(self.listBox().h / row_h)));
+ const index = switch (sym) {
+ c.XKB_KEY_Up => current -| 1,
+ c.XKB_KEY_Down => @min(last, current + 1),
+ c.XKB_KEY_Page_Up => current -| page,
+ c.XKB_KEY_Page_Down => @min(last, current + page),
+ c.XKB_KEY_Home => 0,
+ else => last,
+ };
+ self.model.selected = self.model.snapshot.?.processes[self.model.rows.items[index]].identity;
+ const y = @as(f64, @floatFromInt(index)) * row_h;
+ if (y < self.model.scroll) self.model.scroll = y;
+ if (y + row_h > self.model.scroll + self.listBox().h) self.model.scroll = y + row_h - self.listBox().h;
+ self.clampScroll();
+ } else if (!self.ctrl and !self.alt and text.len > 0) {
+ self.dispatcher.focus(&self.root, &self.toolbar[0]);
+ ui.widgets.text_input.insertText(a, &self.toolbar[0], text) catch {};
+ }
+ }
+ fn activateFocused(self: *App) void {
+ const focused = self.dispatcher.focused orelse return;
+ if (focused.kind == .button) ui.widgets.button.press(focused);
+ self.applyPending();
+ }
+ pub fn keyRepeats(self: *App, sym: u32, text: []const u8) bool {
+ if (self.confirmation != null or self.ctrl or self.alt) return false;
+ return sym == c.XKB_KEY_Up or sym == c.XKB_KEY_Down or sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down or sym == c.XKB_KEY_BackSpace or (self.dispatcher.focused == &self.toolbar[0] and text.len > 0);
+ }
+ fn listBox(self: *const App) Rect {
+ return .{ .x = 16, .y = 236, .w = @floatFromInt(self.w - 32), .h = @floatFromInt(@max(0, self.h - 310)) };
+ }
+ fn clampScroll(self: *App) void {
+ self.model.scroll = std.math.clamp(self.model.scroll, 0, @max(0, @as(f64, @floatFromInt(self.model.rows.items.len)) * row_h - self.listBox().h));
+ }
+ fn barGeometry(self: *const App) ?scrollbar.Geometry {
+ const list = self.listBox();
+ const gutter = scrollbar.gutter(theme.global.scrollbar_width);
+ return scrollbar.Geometry.compute(.vertical, .{ .x = list.x + list.w - gutter, .y = list.y, .w = gutter, .h = list.h }, list.h, @as(f32, @floatFromInt(self.model.rows.items.len)) * @as(f32, @floatCast(row_h)), @floatCast(self.model.scroll));
+ }
+ pub fn stepAnimations(self: *App, now: i64) void {
+ const geom = self.barGeometry();
+ const hovered = if (geom) |g| g.overThumb(self.px, self.py) else false;
+ if (self.bar.step(now, self.model.scroll != self.last_scroll, hovered, self.bar_drag.active, geom != null)) self.dirty = true;
+ self.last_scroll = self.model.scroll;
+ if (self.focused and self.dispatcher.focused == &self.toolbar[0]) {
+ const visible = self.dispatcher.caret.visible(now);
+ const moving = self.dispatcher.caret.moving(now);
+ if (visible != self.caret_visible or moving or moving != self.caret_moving) self.dirty = true;
+ self.caret_visible = visible;
+ self.caret_moving = moving;
+ }
+ }
+ pub fn animationTimeout(self: *App, now: i64) ?u32 {
+ if (self.suspended) return null;
+ var timeout: ?u32 = if (self.bar.active) 16 else if (self.bar.deadline) |deadline| @intCast(@min(60000, @max(0, deadline - now))) else null;
+ if (self.focused and self.dispatcher.focused == &self.toolbar[0] and self.dispatcher.caret.animating(now)) {
+ const caret = self.dispatcher.caret;
+ const half: i64 = @max(1, ui.input.caret_config.blink_ms / 2);
+ var wait: u32 = if (caret.moving(now)) 16 else @intCast(half - @mod(now - caret.last_edit_ms, half));
+ if (ui.input.caret_config.blink_timeout_s > 0) {
+ const expiry = caret.last_edit_ms + @as(i64, ui.input.caret_config.blink_timeout_s) * 1000;
+ wait = @min(wait, @as(u32, @intCast(@max(1, expiry - now))));
+ }
+ timeout = if (timeout) |existing| @min(existing, wait) else wait;
+ }
+ return timeout;
+ }
+ pub fn render(self: *App, cr: *c.cairo_t) void {
+ self.ensureWidgets();
+ self.layout();
+ cairo.setSource(cr, theme.global.app_bg);
+ c.cairo_paint(cr);
+ self.paintSummary(cr);
+ self.paintRows(cr);
+ self.toolbar[1].kind.button.label = if (self.model.mine) "My processes" else "All processes";
+ self.toolbar[2].kind.button.label = if (self.paused) "Resume updates" else "Pause updates";
+ for (&self.headers, titles, 0..) |*header, title, i| {
+ header.kind.button.label = std.fmt.bufPrint(&self.header_labels[i], "{s}{s}", .{ title, if (@intFromEnum(self.model.sort) == i) if (self.model.descending) " ↓" else " ↑" else "" }) catch title;
+ }
+ for (self.footer[1..]) |*control| {
+ if (!self.manageable()) control.kind.button.state = .disabled else if (control.kind.button.state == .disabled) control.kind.button.state = .idle;
+ }
+ ui.input.active_dispatcher = &self.dispatcher;
+ defer ui.input.active_dispatcher = null;
+ if (cairo.Layer.begin(cr, .{ .x = 0, .y = 0, .w = @floatFromInt(self.w), .h = @floatFromInt(self.h) })) |value| {
+ var layer = value;
+ ui.paint.paint(&self.root, &layer.renderer);
+ layer.finish();
+ }
+ const foot = self.sections[4];
+ var status_buf: [256]u8 = undefined;
+ const status = if (self.notice.len > 0) self.notice else blk: {
+ const snap = self.model.snapshot orelse break :blk "Collecting processes…";
+ var swap_buf: [80]u8 = undefined;
+ const swap = if (snap.memory) |mem| if (mem.swap_total != null and mem.swap_free != null) bytesPair(&swap_buf, mem.swap_total.? -| mem.swap_free.?, mem.swap_total.?) else "Unavailable" else "Unavailable";
+ break :blk std.fmt.bufPrint(&status_buf, "{d} processes · Swap {s}{s}", .{ self.model.rows.items.len, swap, if (self.paused) " · Paused" else if (snap.failed) " · /proc unavailable" else if (snap.truncated) " · List limited" else if (snap.unavailable > 0) " · Some processes unavailable" else "" }) catch "Processes";
+ };
+ textBox(cr, status, .{ .x = 16, .y = foot.computed_y + 8, .w = @max(0, foot.computed_width - 308), .h = 28 }, cairo.statusSize(), false, theme.global.window_fg);
+ textBox(cr, "CPU: 100% = one core · Memory: resident · Ctrl+F search · Delete end · Shift+Delete force quit", .{ .x = 16, .y = @floatFromInt(self.h - 26), .w = @floatFromInt(self.w - 32), .h = 24 }, cairo.statusSize(), false, theme.global.window_fg);
+ if (self.confirmation) |confirmation| self.paintConfirmation(cr, confirmation);
+ }
+ fn paintSummary(self: *App, cr: *c.cairo_t) void {
+ const gap: f32 = 16;
+ const width = (@as(f32, @floatFromInt(self.w)) - gap * 3) / 2;
+ const snap = self.model.snapshot;
+ for (0..2) |index| {
+ const box: Rect = .{ .x = gap + @as(f32, @floatFromInt(index)) * (width + gap), .y = 14, .w = width, .h = 122 };
+ var buf: [128]u8 = undefined;
+ const label = if (index == 0) if (snap != null and snap.?.cpu_percent != null) std.fmt.bufPrint(&buf, "CPU {d:.1}%", .{snap.?.cpu_percent.?}) catch "CPU" else "CPU —" else if (snap != null and snap.?.memory != null) blk: {
+ var pair_buf: [80]u8 = undefined;
+ const mem = snap.?.memory.?;
+ break :blk std.fmt.bufPrint(&buf, "RAM {s}", .{bytesPair(&pair_buf, mem.used(), mem.total)}) catch "RAM";
+ } else "RAM —";
+ textBox(cr, label, .{ .x = box.x, .y = box.y, .w = box.w, .h = 30 }, cairo.headingSize(), true, theme.global.window_fg);
+ textBox(cr, "60 seconds", .{ .x = box.x, .y = box.y + 30, .w = box.w, .h = 20 }, cairo.statusSize(), false, theme.global.window_fg);
+ const graph: Rect = .{ .x = box.x, .y = box.y + 56, .w = box.w, .h = 64 };
+ cairo.setSource(cr, theme.global.app_divider);
+ c.cairo_set_line_width(cr, 1);
+ for (0..3) |line| {
+ const y = graph.y + graph.h * @as(f32, @floatFromInt(line)) / 2;
+ c.cairo_move_to(cr, graph.x, y);
+ c.cairo_line_to(cr, graph.x + graph.w, y);
+ }
+ c.cairo_stroke(cr);
+ if (snap == null) continue;
+ cairo.setSource(cr, theme.shellPalette().accent);
+ c.cairo_set_line_width(cr, 2);
+ var last: ?u64 = null;
+ for (self.history.points[0..self.history.count]) |point| {
+ const value = if (index == 0) point.cpu else point.memory;
+ const age = snap.?.at_ns -| point.at_ns;
+ if (value == null or age >= 60_000_000_000) {
+ last = null;
+ continue;
+ }
+ const x = graph.x + graph.w * (1 - @as(f64, @floatFromInt(age)) / 60_000_000_000);
+ const y = graph.y + graph.h * (1 - std.math.clamp(value.?, 0, 100) / 100);
+ if (last == null or point.at_ns -| last.? > 2_000_000_000) c.cairo_move_to(cr, x, y) else c.cairo_line_to(cr, x, y);
+ last = point.at_ns;
+ }
+ c.cairo_stroke(cr);
+ }
+ }
+ fn paintRows(self: *App, cr: *c.cairo_t) void {
+ const list = self.listBox();
+ const snap = self.model.snapshot orelse return;
+ c.cairo_save(cr);
+ defer c.cairo_restore(cr);
+ c.cairo_rectangle(cr, list.x, list.y, list.w, list.h);
+ c.cairo_clip(cr);
+ const first: usize = @intFromFloat(@floor(self.model.scroll / row_h));
+ const last = @min(self.model.rows.items.len, first + @as(usize, @intFromFloat(@ceil(list.h / row_h))) + 1);
+ for (first..last) |i| {
+ const row = snap.processes[self.model.rows.items[i]];
+ const y: f32 = @floatCast(list.y + @as(f64, @floatFromInt(i)) * row_h - self.model.scroll);
+ if (self.model.selected != null and row.identity.eql(self.model.selected.?)) {
+ cairo.drawSidebarSelected(cr, .{ .x = list.x, .y = y, .w = list.w - scrollbar.gutter(theme.global.scrollbar_width), .h = row_h });
+ }
+ var pid_buf: [32]u8 = undefined;
+ var cpu_buf: [32]u8 = undefined;
+ var mem_buf: [32]u8 = undefined;
+ const pid = std.fmt.bufPrint(&pid_buf, "{d}", .{row.identity.pid}) catch "—";
+ const cpu = if (row.cpu_percent) |v| std.fmt.bufPrint(&cpu_buf, "{d:.1}%", .{v}) catch "—" else "—";
+ const memory = if (row.resident_bytes) |v| bytesLabel(&mem_buf, v) else "—";
+ const values = [_][]const u8{ row.name, pid, row.user, cpu, memory, model.stateName(row.state) };
+ for (values, self.headers) |value, header| textBox(cr, value, .{ .x = header.computed_x + 8, .y = y, .w = @max(0, header.computed_width - 16), .h = row_h }, cairo.textSize(), false, theme.global.window_fg);
+ }
+ if (self.model.rows.items.len == 0) textBox(cr, if (snap.failed) "Process data unavailable" else "No matching processes", .{ .x = list.x + 8, .y = list.y + 12, .w = list.w - 16, .h = 32 }, cairo.textSize(), false, theme.global.window_fg);
+ if (self.barGeometry()) |g| cairo.drawScrollbar(cr, scrollbar.look(g, self.bar, theme.global.scrollbar_width, theme.global));
+ }
+ fn dialogBox(self: *const App) Rect {
+ return .{ .x = (@as(f32, @floatFromInt(self.w)) - 520) / 2, .y = (@as(f32, @floatFromInt(self.h)) - 232) / 2, .w = 520, .h = 232 };
+ }
+ fn paintConfirmation(self: *App, cr: *c.cairo_t, confirmation: Confirmation) void {
+ cairo.setSource(cr, ui.widgets.dialog.backdropColor());
+ c.cairo_paint(cr);
+ const box = self.dialogBox();
+ if (cairo.Layer.begin(cr, box)) |value| {
+ var layer = value;
+ ui.widgets.dialog.paintFrame(&layer.renderer, layer.local());
+ ui.widgets.dialog.paintHeader(&layer.renderer, 24, 24, box.w - 48, .{ .icon = .close, .title = "Force quit this process?", .subtitle = "Unsaved work will be lost." });
+ layer.finish();
+ }
+ var buf: [512]u8 = undefined;
+ const label = std.fmt.bufPrint(&buf, "{s} (PID {d})", .{ confirmation.name[0..confirmation.len], confirmation.identity.pid }) catch "Selected process";
+ textBox(cr, label, .{ .x = box.x + 24, .y = box.y + 112, .w = box.w - 48, .h = 32 }, cairo.textSize(), true, theme.global.window_fg);
+ if (cairo.Layer.begin(cr, .{ .x = 0, .y = 0, .w = @floatFromInt(self.w), .h = @floatFromInt(self.h) })) |value| {
+ var layer = value;
+ ui.paint.paint(&self.modal, &layer.renderer);
+ layer.finish();
+ }
+ }
+};
+
+fn textBox(cr: *c.cairo_t, text: []const u8, box: Rect, size: f32, bold: bool, color: [4]f32) void {
+ if (box.w <= 0 or box.h <= 0) return;
+ c.cairo_save(cr);
+ defer c.cairo_restore(cr);
+ c.cairo_rectangle(cr, box.x, box.y, box.w, box.h);
+ c.cairo_clip(cr);
+ cairo.setSource(cr, color);
+ const metrics = cairo.fontMetrics(cr, size);
+ cairo.drawText(cr, text, box.x, box.y + (box.h - metrics.ascent - metrics.descent) / 2 + metrics.ascent, size, bold);
+}
+fn bytesLabel(buf: []u8, value: u64) []const u8 {
+ const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };
+ var n: f64 = @floatFromInt(value);
+ var unit: usize = 0;
+ while (n >= 1024 and unit + 1 < units.len) : (unit += 1) n /= 1024;
+ return std.fmt.bufPrint(buf, "{d:.1} {s}", .{ n, units[unit] }) catch "—";
+}
+fn bytesPair(buf: []u8, used: u64, total: u64) []const u8 {
+ var left: [32]u8 = undefined;
+ var right: [32]u8 = undefined;
+ return std.fmt.bufPrint(buf, "{s} / {s}", .{ bytesLabel(&left, used), bytesLabel(&right, total) }) catch "—";
+}
diff --git a/src/system_monitor/client.zig b/src/system_monitor/client.zig
new file mode 100644
index 0000000..7e66b0c
--- /dev/null
+++ b/src/system_monitor/client.zig
@@ -0,0 +1,890 @@
+//! Standalone System Monitor Wayland host. Uses the same decoration, input,
+//! cursor and released-buffer lifecycle as the other native RediWM clients.
+const std = @import("std");
+const ClientCursor = @import("ui").client_cursor;
+const wl = @import("wayland").client.wl;
+const xdg = @import("wayland").client.xdg;
+const wp = @import("wayland").client.wp;
+const zxdg = @import("wayland").client.zxdg;
+const c = @import("../files/c.zig").api;
+const app_mod = @import("app.zig");
+const key_repeat = @import("ui").key_repeat;
+const shell_ui = @import("ui").cairo;
+const ui_theme = @import("ui").theme;
+const a = std.heap.c_allocator;
+const ui = @import("ui");
+
+// A window with no server-side decorations must draw its own titlebar so it
+// stays usable (movable, closable) on compositors that don't implement
+// zxdg-decoration, e.g. GNOME/Mutter. See plan-file-manager.md section 1.
+const CSD_TITLEBAR_H: i32 = 32;
+const RESIZE_MARGIN: f64 = 6;
+
+const DecorationMode = enum { unknown, client_side, server_side };
+
+const OutputInfo = struct {
+ client: *Client,
+ proxy: *wl.Output,
+ name: u32,
+ scale: i32 = 1,
+ logical: ?*zxdg.OutputV1 = null,
+ logical_width: i32 = 0,
+ logical_height: i32 = 0,
+ mode_width: i32 = 0,
+ mode_height: i32 = 0,
+
+ /// Physical pixels per logical pixel. `wl_output.scale` is the integer
+ /// ceiling, so a 1.5 output reads as 2; the mode and the logical size
+ /// give the real factor. Anything outside (scale - 1, scale] (a rotated
+ /// or nested output) falls back to the integer.
+ fn density(self: OutputInfo) f64 {
+ const whole: f64 = @floatFromInt(self.scale);
+ const logical = @max(self.logical_width, self.logical_height);
+ const mode = @max(self.mode_width, self.mode_height);
+ if (logical <= 0 or mode <= 0) return whole;
+ const real = @as(f64, @floatFromInt(mode)) / @as(f64, @floatFromInt(logical));
+ return if (real > whole - 1 and real <= whole + 0.01) real else whole;
+ }
+};
+
+pub const Client = struct {
+ display: *wl.Display,
+ compositor: ?*wl.Compositor = null,
+ shm: ?*wl.Shm = null,
+ output_manager: ?*zxdg.OutputManagerV1 = null,
+ outputs: std.ArrayList(*OutputInfo) = .empty,
+ entered_outputs: std.ArrayList(*OutputInfo) = .empty,
+ scale: i32 = 1,
+ density: f64 = 1,
+ seat: ?*wl.Seat = null,
+ pointer: ?*wl.Pointer = null,
+ keyboard: ?*wl.Keyboard = null,
+ input_serial: u32 = 0,
+ wm_base: ?*xdg.WmBase = null,
+ viewporter: ?*wp.Viewporter = null,
+ viewport: ?*wp.Viewport = null,
+ fractional_manager: ?*wp.FractionalScaleManagerV1 = null,
+ fractional: ?*wp.FractionalScaleV1 = null,
+ preferred_density: ?f64 = null,
+ decoration_manager: ?*zxdg.DecorationManagerV1 = null,
+ surface: *wl.Surface = undefined,
+ xdg_surface: *xdg.Surface = undefined,
+ xdg_toplevel: *xdg.Toplevel = undefined,
+ decoration: ?*zxdg.ToplevelDecorationV1 = null,
+ decoration_mode: DecorationMode = .unknown,
+ pointer_x: f64 = 0,
+ pointer_y: f64 = 0,
+ cursor_shape: ClientCursor = .{},
+ cursor_surface: *wl.Surface = undefined,
+ cursor_theme: ?*wl.CursorTheme = null,
+ cursor_serial: u32 = 0,
+ cursor_name: [*:0]const u8 = "",
+ inside: bool = false,
+ configured: bool = false,
+ running: bool = true,
+ outstanding: usize = 0,
+ buffers: [2]?*Buffer = @splat(null),
+ applied_scale: i32 = 0,
+ xkb_context: ?*c.xkb_context = null,
+ xkb_state: ?*c.xkb_state = null,
+ key_repeat: key_repeat.KeyRepeat = .{},
+ compose: @import("ui").compose.Compose = .{},
+ /// LC_CTYPE of the session; picks the Compose table (´+c is ç in pt_BR).
+ locale: []const u8 = "",
+ app: app_mod.App,
+ close_button: ui.layout.Widget = .{ .kind = .{ .button = .{ .variant = .chrome, .icon = .close, .label = "Close" } } },
+ chrome_input: ui.input.Dispatcher = .{},
+
+ fn arrangeClose(self: *Client) void {
+ self.close_button.kind.button.owner = self;
+ self.close_button.kind.button.on_click = closeClicked;
+ const height: f32 = @floatFromInt(self.titlebarHeight());
+ ui.arrange.arrange(&self.close_button, @as(f32, @floatFromInt(self.app.w)) - height, 0, height, height);
+ }
+
+ fn closeClicked(owner: ?*anyopaque, _: usize) void {
+ const self: *Client = @ptrCast(@alignCast(owner.?));
+ self.app.requestClose();
+ }
+
+ pub fn registryEvent(registry: *wl.Registry, event: wl.Registry.Event, self: *Client) void {
+ switch (event) {
+ .global => |g| {
+ const iface = std.mem.span(g.interface);
+ self.cursor_shape.bind(registry, g.name, iface, g.version);
+ if (std.mem.eql(u8, iface, "wl_compositor")) {
+ self.compositor = registry.bind(g.name, wl.Compositor, @min(g.version, 5)) catch null;
+ } else if (std.mem.eql(u8, iface, "wl_shm")) {
+ self.shm = registry.bind(g.name, wl.Shm, 1) catch null;
+ } else if (std.mem.eql(u8, iface, "wl_output")) {
+ if (registry.bind(g.name, wl.Output, @min(g.version, 4)) catch null) |proxy| {
+ const info = a.create(OutputInfo) catch {
+ proxy.destroy();
+ return;
+ };
+ info.* = .{ .client = self, .proxy = proxy, .name = g.name };
+ self.outputs.append(a, info) catch {
+ proxy.destroy();
+ a.destroy(info);
+ return;
+ };
+ proxy.setListener(*OutputInfo, outputEvent, info);
+ }
+ } else if (std.mem.eql(u8, iface, "zxdg_output_manager_v1")) {
+ self.output_manager = registry.bind(g.name, zxdg.OutputManagerV1, @min(g.version, 3)) catch null;
+ } else if (std.mem.eql(u8, iface, "wl_seat") and self.seat == null) {
+ self.seat = registry.bind(g.name, wl.Seat, @min(g.version, 7)) catch null;
+ if (self.seat) |seat| seat.setListener(*Client, seatEvent, self);
+ } else if (std.mem.eql(u8, iface, "wp_viewporter")) {
+ self.viewporter = registry.bind(g.name, wp.Viewporter, 1) catch null;
+ } else if (std.mem.eql(u8, iface, "wp_fractional_scale_manager_v1")) {
+ self.fractional_manager = registry.bind(g.name, wp.FractionalScaleManagerV1, 1) catch null;
+ } else if (std.mem.eql(u8, iface, "xdg_wm_base")) {
+ self.wm_base = registry.bind(g.name, xdg.WmBase, @min(g.version, 6)) catch null;
+ if (self.wm_base) |wm| wm.setListener(*Client, wmBaseEvent, self);
+ } else if (std.mem.eql(u8, iface, "zxdg_decoration_manager_v1")) {
+ self.decoration_manager = registry.bind(g.name, zxdg.DecorationManagerV1, 1) catch null;
+ }
+ },
+ .global_remove => |ev| {
+ for (self.outputs.items, 0..) |info, i| {
+ if (info.name == ev.name) {
+ _ = self.outputs.swapRemove(i);
+ self.removeEnteredOutput(info);
+ if (info.logical) |logical| logical.destroy();
+ info.proxy.destroy();
+ a.destroy(info);
+ self.recomputeScale();
+ break;
+ }
+ }
+ },
+ }
+ }
+
+ fn close(self: *Client) void {
+ self.app.requestClose();
+ self.running = false;
+ }
+
+ fn fractionalEvent(_: *wp.FractionalScaleV1, event: wp.FractionalScaleV1.Event, self: *Client) void {
+ if (event == .preferred_scale and event.preferred_scale.scale > 0) {
+ self.preferred_density = std.math.clamp(@as(f64, @floatFromInt(event.preferred_scale.scale)) / 120, 0.5, 4);
+ self.recomputeScale();
+ }
+ }
+
+ fn wmBaseEvent(_: *xdg.WmBase, event: xdg.WmBase.Event, self: *Client) void {
+ switch (event) {
+ .ping => |ev| {
+ if (self.wm_base) |wm| wm.pong(ev.serial);
+ },
+ }
+ }
+
+ fn logicalOutputEvent(_: *zxdg.OutputV1, event: zxdg.OutputV1.Event, info: *OutputInfo) void {
+ if (event == .logical_size) {
+ info.logical_width = event.logical_size.width;
+ info.logical_height = event.logical_size.height;
+ info.client.recomputeScale();
+ }
+ }
+
+ fn outputEvent(_: *wl.Output, event: wl.Output.Event, info: *OutputInfo) void {
+ switch (event) {
+ .scale => |ev| {
+ info.scale = std.math.clamp(ev.factor, 1, 4);
+ info.client.recomputeScale();
+ },
+ .mode => |ev| if (ev.flags.current) {
+ info.mode_width = ev.width;
+ info.mode_height = ev.height;
+ info.client.recomputeScale();
+ },
+ else => {},
+ }
+ }
+
+ // The window may span multiple outputs at different scales; use the
+ // largest scale among outputs the surface currently overlaps, per the
+ // usual Wayland client convention. Falls back to 1 before the first
+ // wl_surface.enter is received.
+ fn recomputeScale(self: *Client) void {
+ var new_scale: i32 = 1;
+ var new_density: f64 = 1;
+ for (self.entered_outputs.items) |info| {
+ new_scale = @max(new_scale, info.scale);
+ new_density = @max(new_density, info.density());
+ }
+ if (self.viewport != null) new_density = self.preferred_density orelse new_density;
+ if (new_scale != self.scale or new_density != self.density) {
+ self.scale = new_scale;
+ self.density = new_density;
+ self.app.scale = new_scale;
+ self.app.density = new_density;
+ self.app.dirty = true;
+ }
+ }
+
+ fn removeEnteredOutput(self: *Client, info: *OutputInfo) void {
+ for (self.entered_outputs.items, 0..) |o, i| {
+ if (o == info) {
+ _ = self.entered_outputs.swapRemove(i);
+ return;
+ }
+ }
+ }
+
+ fn surfaceEvent(_: *wl.Surface, event: wl.Surface.Event, self: *Client) void {
+ switch (event) {
+ .enter => |ev| {
+ if (ev.output) |out| {
+ for (self.outputs.items) |info| {
+ if (info.proxy == out) {
+ self.entered_outputs.append(a, info) catch {};
+ self.recomputeScale();
+ break;
+ }
+ }
+ }
+ self.app.dirty = true;
+ },
+ .leave => |ev| {
+ if (ev.output) |out| {
+ for (self.outputs.items) |info| {
+ if (info.proxy == out) {
+ self.removeEnteredOutput(info);
+ self.recomputeScale();
+ break;
+ }
+ }
+ }
+ },
+ }
+ }
+
+ fn seatEvent(seat: *wl.Seat, event: wl.Seat.Event, self: *Client) void {
+ switch (event) {
+ .capabilities => |ev| {
+ if (ev.capabilities.pointer and self.pointer == null) {
+ self.pointer = seat.getPointer() catch null;
+ if (self.pointer) |p| p.setListener(*Client, pointerEvent, self);
+ }
+ if (!ev.capabilities.pointer) {
+ self.cursor_shape.clearPointer();
+ if (self.pointer) |p| p.release();
+ self.pointer = null;
+ self.app.cancelDrag();
+ }
+ if (ev.capabilities.keyboard and self.keyboard == null) {
+ self.keyboard = seat.getKeyboard() catch null;
+ if (self.keyboard) |k| k.setListener(*Client, keyboardEvent, self);
+ }
+ if (!ev.capabilities.keyboard) {
+ if (self.keyboard) |k| k.release();
+ self.keyboard = null;
+ }
+ },
+ else => {},
+ }
+ }
+
+ fn xdgSurfaceEvent(xdg_surf: *xdg.Surface, event: xdg.Surface.Event, self: *Client) void {
+ switch (event) {
+ .configure => |ev| {
+ xdg_surf.ackConfigure(ev.serial);
+ self.configured = true;
+ self.app.dirty = true;
+ },
+ }
+ }
+
+ // Whether this window must draw its own titlebar: either the compositor
+ // never advertised zxdg_decoration_manager_v1 (no configure event will
+ // ever arrive, so self-decorate unconditionally), or it did negotiate a
+ // mode and that mode isn't server_side. Per the xdg-decoration spec, a
+ // mode that hasn't been negotiated yet is assumed to be client_side.
+ fn wantsCsd(self: *const Client) bool {
+ return self.decoration_mode != .server_side;
+ }
+
+ fn titlebarHeight(self: *const Client) i32 {
+ return if (self.wantsCsd()) CSD_TITLEBAR_H else 0;
+ }
+
+ fn decorationEvent(_: *zxdg.ToplevelDecorationV1, event: zxdg.ToplevelDecorationV1.Event, self: *Client) void {
+ switch (event) {
+ .configure => |ev| {
+ self.decoration_mode = switch (ev.mode) {
+ .server_side => .server_side,
+ .client_side => .client_side,
+ else => .client_side,
+ };
+ self.app.dirty = true;
+ },
+ }
+ }
+
+ fn xdgToplevelEvent(_: *xdg.Toplevel, event: xdg.Toplevel.Event, self: *Client) void {
+ switch (event) {
+ .configure => |ev| {
+ const tbh = self.titlebarHeight();
+ if (ev.width > 0 and ev.height > 0) {
+ self.app.resize(ev.width, @max(1, ev.height - tbh));
+ } else if (!self.configured) {
+ var width: i32 = 960;
+ var height: i32 = 640;
+ if (self.outputs.items.len > 0) {
+ const output = self.outputs.items[0];
+ if (output.logical_width > 0) width = std.math.clamp(output.logical_width - 160, 640, 1080);
+ if (output.logical_height > 0) height = std.math.clamp(output.logical_height - 200, 400, 640);
+ }
+ self.app.resize(width, height);
+ }
+ var suspended = false;
+ for (ev.states.slice(u32)) |state| if (state == @intFromEnum(xdg.Toplevel.State.suspended)) {
+ suspended = true;
+ };
+ self.app.setSuspended(suspended);
+ self.xdg_toplevel.setMinSize(640, 400 + tbh);
+ self.app.dirty = true;
+ },
+ .close => {
+ self.app.requestClose();
+ },
+ .configure_bounds, .wm_capabilities => {},
+ }
+ }
+
+ fn pointerEvent(_: *wl.Pointer, event: wl.Pointer.Event, self: *Client) void {
+ switch (event) {
+ .enter => |ev| {
+ self.cursor_serial = ev.serial;
+ self.input_serial = ev.serial;
+ self.inside = true;
+ // Force the next setCursor to reassert the image: another
+ // surface may have changed the shared per-seat pointer
+ // cursor while we weren't hovered.
+ self.cursor_name = "";
+ self.handlePointerMotion(ev.surface_x.toDouble(), ev.surface_y.toDouble());
+ },
+ .leave => {
+ self.inside = false;
+ self.app.cancelDrag();
+ },
+ .motion => |ev| {
+ self.handlePointerMotion(ev.surface_x.toDouble(), ev.surface_y.toDouble());
+ },
+ .button => |ev| {
+ self.input_serial = ev.serial;
+ self.handlePointerButton(ev.button, ev.state == .pressed);
+ },
+ .axis => |ev| {
+ if (ev.axis == .vertical_scroll) {
+ self.app.handleScroll(ev.value.toDouble());
+ }
+ },
+ else => {},
+ }
+ }
+
+ fn edgeAt(x: f64, y: f64, w: f64, h: f64) ?xdg.Toplevel.ResizeEdge {
+ const left = x <= RESIZE_MARGIN;
+ const right = x >= w - RESIZE_MARGIN;
+ const top = y <= RESIZE_MARGIN;
+ const bottom = y >= h - RESIZE_MARGIN;
+ if (top and left) return .top_left;
+ if (top and right) return .top_right;
+ if (bottom and left) return .bottom_left;
+ if (bottom and right) return .bottom_right;
+ if (top) return .top;
+ if (bottom) return .bottom;
+ if (left) return .left;
+ if (right) return .right;
+ return null;
+ }
+
+ fn cursorNameForEdge(edge: xdg.Toplevel.ResizeEdge) [*:0]const u8 {
+ return switch (edge) {
+ .top => "n-resize",
+ .bottom => "s-resize",
+ .left => "w-resize",
+ .right => "e-resize",
+ .top_left => "nw-resize",
+ .top_right => "ne-resize",
+ .bottom_left => "sw-resize",
+ .bottom_right => "se-resize",
+ .none => "default",
+ else => "default",
+ };
+ }
+
+ // Only the CSD titlebar and its resize border are handled here; anything
+ // below is forwarded to the App with the titlebar height subtracted so
+ // its hardcoded content-area layout stays oblivious to decorations.
+ fn updateCursor(self: *Client) void {
+ if (self.wantsCsd()) {
+ const tbh: f64 = @floatFromInt(self.titlebarHeight());
+ if (edgeAt(self.pointer_x, self.pointer_y, @floatFromInt(self.app.w), @as(f64, @floatFromInt(self.app.h)) + tbh)) |edge| {
+ self.setCursor(cursorNameForEdge(edge));
+ return;
+ }
+ if (self.pointer_y < tbh) {
+ self.setCursor("default");
+ return;
+ }
+ }
+ self.setCursor(self.app.cursorName());
+ }
+ fn handlePointerMotion(self: *Client, x: f64, y: f64) void {
+ self.pointer_x = x;
+ self.pointer_y = y;
+ const tbh: f64 = @floatFromInt(self.titlebarHeight());
+ if (tbh > 0) {
+ self.arrangeClose();
+ self.chrome_input.pointerMotion(&self.close_button, @floatCast(x), @floatCast(y));
+ }
+ self.app.handleMotion(x, y - tbh);
+ self.updateCursor();
+ if (tbh > 0 and y < tbh) self.app.dirty = true;
+ }
+
+ fn handlePointerButton(self: *Client, button: u32, pressed: bool) void {
+ if (button == 0x110 and !pressed and self.chrome_input.pressed != null) {
+ self.chrome_input.pointerButtonUp(&self.close_button, @floatCast(self.pointer_x), @floatCast(self.pointer_y));
+ self.app.dirty = true;
+ return;
+ }
+ if (button == 0x110 and pressed and self.wantsCsd()) {
+ const tbh_f: f64 = @floatFromInt(self.titlebarHeight());
+ const w_f: f64 = @floatFromInt(self.app.w);
+ const h_f: f64 = @as(f64, @floatFromInt(self.app.h)) + tbh_f;
+ if (edgeAt(self.pointer_x, self.pointer_y, w_f, h_f)) |edge| {
+ if (self.seat) |seat| self.xdg_toplevel.resize(seat, self.input_serial, edge);
+ return;
+ }
+ if (self.pointer_y < tbh_f) {
+ self.handleTitlebarClick();
+ return;
+ }
+ }
+ self.app.handleButton(button, pressed);
+ self.handlePointerMotion(self.pointer_x, self.pointer_y);
+ }
+
+ fn handleTitlebarClick(self: *Client) void {
+ self.arrangeClose();
+ self.chrome_input.pointerButtonDown(&self.close_button, @floatCast(self.pointer_x), @floatCast(self.pointer_y));
+ if (self.chrome_input.pressed != null) return;
+ if (self.seat) |seat| self.xdg_toplevel.move(seat, self.input_serial);
+ }
+
+ /// One press of evdev `key` through the current XKB state.
+ fn deliverKey(self: *Client, key: u32) void {
+ const state = self.xkb_state orelse return;
+ const sym = c.xkb_state_key_get_one_sym(state, key + 8);
+ var buf: [64]u8 = undefined;
+ const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
+ // Dead keys have no text of their own: sequences resolve here, and a
+ // shortcut modifier abandons a half-typed one.
+ if (!self.app.ctrl and !self.app.alt) {
+ var composed: [64]u8 = undefined;
+ if (self.compose.feed(self.locale, sym, &composed)) |text| {
+ if (text.len > 0) self.app.handleKey(0, text);
+ return;
+ }
+ } else self.compose.reset();
+ self.app.handleKey(sym, buf[0..@intCast(std.math.clamp(n, 0, 63))]);
+ }
+
+ fn appRepeats(self: *Client, key: u32) bool {
+ if (self.compose.consumed) return false;
+ const state = self.xkb_state orelse return false;
+ var buf: [64]u8 = undefined;
+ const n = c.xkb_state_key_get_utf8(state, key + 8, &buf, buf.len);
+ return self.app.keyRepeats(c.xkb_state_key_get_one_sym(state, key + 8), buf[0..@intCast(std.math.clamp(n, 0, 63))]);
+ }
+
+ /// A due repeat of the held key, if the app still takes it where its
+ /// focus is now (a repeat may have opened a dialog or left a field).
+ fn repeatDue(self: *Client) void {
+ const key = self.key_repeat.due(key_repeat.nowMs()) orelse return;
+ if (!self.appRepeats(key)) return self.key_repeat.stop();
+ self.deliverKey(key);
+ }
+
+ fn keyboardEvent(_: *wl.Keyboard, event: wl.Keyboard.Event, self: *Client) void {
+ switch (event) {
+ .enter => {
+ self.app.focused = true;
+ self.app.dirty = true;
+ },
+ .leave => {
+ self.app.focused = false;
+ self.key_repeat.stop();
+ self.compose.reset();
+ self.app.cancelDrag();
+ self.app.ctrl = false;
+ self.app.shift = false;
+ self.app.alt = false;
+ self.app.dirty = true;
+ },
+ .keymap => |ev| {
+ defer _ = c.close(ev.fd);
+ self.key_repeat.stop();
+ if (ev.format != .xkb_v1 or ev.size == 0) return;
+ const memory = c.mmap(null, ev.size, c.PROT_READ, c.MAP_PRIVATE, ev.fd, 0);
+ if (memory == c.MAP_FAILED) return;
+ defer _ = c.munmap(memory, ev.size);
+
+ const bytes: [*]const u8 = @ptrCast(memory);
+ if (bytes[ev.size - 1] != 0) return;
+
+ if (self.xkb_context == null) self.xkb_context = c.xkb_context_new(c.XKB_CONTEXT_NO_FLAGS);
+ const keymap = c.xkb_keymap_new_from_string(
+ self.xkb_context,
+ @ptrCast(memory),
+ c.XKB_KEYMAP_FORMAT_TEXT_V1,
+ c.XKB_KEYMAP_COMPILE_NO_FLAGS,
+ ) orelse return;
+ defer c.xkb_keymap_unref(keymap);
+
+ if (self.xkb_state) |state| c.xkb_state_unref(state);
+ self.xkb_state = c.xkb_state_new(keymap);
+ },
+ .modifiers => |ev| {
+ if (self.xkb_state) |state| {
+ _ = c.xkb_state_update_mask(state, ev.mods_depressed, ev.mods_latched, ev.mods_locked, 0, 0, ev.group);
+ self.app.ctrl = c.xkb_state_mod_name_is_active(state, "Control", c.XKB_STATE_MODS_EFFECTIVE) > 0;
+ self.app.shift = c.xkb_state_mod_name_is_active(state, "Shift", c.XKB_STATE_MODS_EFFECTIVE) > 0;
+ self.app.alt = c.xkb_state_mod_name_is_active(state, "Mod1", c.XKB_STATE_MODS_EFFECTIVE) > 0 or
+ c.xkb_state_mod_name_is_active(state, "Alt", c.XKB_STATE_MODS_EFFECTIVE) > 0;
+ }
+ },
+ .key => |ev| {
+ self.input_serial = ev.serial;
+ if (ev.state == .pressed) {
+ const state = self.xkb_state orelse return;
+ self.deliverKey(ev.key);
+ // Asked after the key, of the state it left: the repeats
+ // go wherever this press put focus.
+ const keymap_repeats = c.xkb_keymap_key_repeats(c.xkb_state_get_keymap(state), ev.key + 8) != 0;
+ self.key_repeat.press(ev.key, keymap_repeats, self.appRepeats(ev.key), key_repeat.nowMs());
+ } else self.key_repeat.release(ev.key);
+ },
+ .repeat_info => |ev| self.key_repeat.setInfo(ev.rate, ev.delay),
+ }
+ }
+
+ fn setCursor(self: *Client, name: [*:0]const u8) void {
+ if (!self.inside) return;
+ if (std.mem.eql(u8, std.mem.span(self.cursor_name), std.mem.span(name))) return;
+ const pointer = self.pointer orelse return;
+ if (self.cursor_shape.set(pointer, self.cursor_serial, std.mem.span(name))) {
+ self.cursor_name = name;
+ return;
+ }
+ const theme_ptr = self.cursor_theme orelse return;
+ const cursor = theme_ptr.getCursor(name) orelse theme_ptr.getCursor("default") orelse theme_ptr.getCursor("left_ptr") orelse return;
+ if (cursor.image_count == 0) return;
+ const img = cursor.images[0];
+ const buffer = img.getBuffer() catch return;
+
+ pointer.setCursor(self.cursor_serial, self.cursor_surface, @intCast(img.hotspot_x), @intCast(img.hotspot_y));
+ self.cursor_surface.attach(buffer, 0, 0);
+ self.cursor_surface.damage(0, 0, @intCast(img.width), @intCast(img.height));
+ self.cursor_surface.commit();
+ self.cursor_name = name;
+ }
+
+ fn acquireBuffer(self: *Client, w: i32, h: i32) !?*Buffer {
+ for (self.buffers) |slot| if (slot) |buffer| {
+ if (!buffer.busy and buffer.w == w and buffer.h == h) return buffer;
+ };
+ for (&self.buffers) |*slot| {
+ if (slot.*) |buffer| {
+ if (buffer.busy) continue;
+ buffer.destroy();
+ slot.* = null;
+ }
+ slot.* = try Buffer.create(self, w, h);
+ return slot.*;
+ }
+ return null;
+ }
+ fn render(self: *Client) !void {
+ self.updateCursor();
+ if (!self.configured or !self.app.dirty or self.app.suspended or self.outstanding >= 2) return;
+
+ const tbh = self.titlebarHeight();
+ const w = self.app.w;
+ const h = self.app.h + tbh;
+ const raster_scale: f64 = if (self.viewport != null) self.density else @floatFromInt(self.scale);
+ const bw: i32 = @intFromFloat(@round(@as(f64, @floatFromInt(w)) * raster_scale));
+ const bh: i32 = @intFromFloat(@round(@as(f64, @floatFromInt(h)) * raster_scale));
+ const buffer = (try self.acquireBuffer(bw, bh)) orelse return;
+
+ const cr = c.cairo_create(buffer.image) orelse return error.CairoFailed;
+ defer c.cairo_destroy(cr);
+
+ c.cairo_scale(cr, @as(f64, @floatFromInt(bw)) / @as(f64, @floatFromInt(w)), @as(f64, @floatFromInt(bh)) / @as(f64, @floatFromInt(h)));
+
+ if (tbh > 0) self.renderTitlebar(cr, w, tbh);
+
+ c.cairo_save(cr);
+ c.cairo_translate(cr, 0, @floatFromInt(tbh));
+ self.app.render(cr);
+ c.cairo_restore(cr);
+
+ c.cairo_surface_flush(buffer.image);
+
+ const buffer_scale: i32 = if (self.viewport != null) 1 else self.scale;
+ if (self.applied_scale != buffer_scale) {
+ self.surface.setBufferScale(buffer_scale);
+ self.applied_scale = buffer_scale;
+ }
+ if (self.viewport) |viewport| viewport.setDestination(w, h);
+ self.xdg_surface.setWindowGeometry(0, 0, w, h);
+ buffer.busy = true;
+ self.outstanding += 1;
+ self.surface.attach(buffer.wl_buffer, 0, 0);
+ self.surface.damage(0, 0, w, h);
+ self.surface.commit();
+ self.app.dirty = false;
+ }
+
+ fn renderTitlebar(self: *Client, cr: *c.cairo_t, w: i32, h: i32) void {
+ shell_ui.setSource(cr, ui_theme.global.window_bg);
+ c.cairo_rectangle(cr, 0, 0, @floatFromInt(w), @floatFromInt(h));
+ c.cairo_fill(cr);
+ shell_ui.setSource(cr, ui_theme.global.window_fg);
+ shell_ui.drawText(cr, "System Monitor", 16, @as(f64, @floatFromInt(h)) / 2 + shell_ui.statusSize() / 3, shell_ui.statusSize(), true);
+ self.arrangeClose();
+ if (shell_ui.Layer.begin(cr, .{ .x = 0, .y = 0, .w = @floatFromInt(w), .h = @floatFromInt(h) })) |value| {
+ var layer = value;
+ ui.paint.paint(&self.close_button, &layer.renderer);
+ layer.finish();
+ }
+ }
+ fn deinit(self: *Client) void {
+ for (self.outputs.items) |info| {
+ if (info.logical) |logical| logical.destroy();
+ info.proxy.destroy();
+ a.destroy(info);
+ }
+ self.outputs.deinit(a);
+ self.entered_outputs.deinit(a);
+ if (self.xkb_state) |state| c.xkb_state_unref(state);
+ if (self.xkb_context) |context| c.xkb_context_unref(context);
+ if (self.pointer) |pointer| pointer.release();
+ if (self.keyboard) |keyboard| keyboard.release();
+ if (self.seat) |seat| seat.release();
+ if (self.output_manager) |manager| manager.destroy();
+ if (self.fractional_manager) |manager| manager.destroy();
+ if (self.viewporter) |manager| manager.destroy();
+ if (self.decoration_manager) |manager| manager.destroy();
+ if (self.wm_base) |wm| wm.destroy();
+ if (self.shm) |shm| shm.destroy();
+ if (self.compositor) |compositor| compositor.destroy();
+ self.cursor_shape.deinit();
+ }
+};
+
+const Buffer = struct {
+ client: *Client,
+ wl_buffer: *wl.Buffer,
+ image: *c.cairo_surface_t,
+ memory: *anyopaque,
+ len: usize,
+ w: i32,
+ h: i32,
+ busy: bool = false,
+
+ fn create(client: *Client, w: i32, h: i32) !*Buffer {
+ if (w <= 0 or h <= 0 or w > 16384 or h > 16384) return error.InvalidSize;
+ const len: usize = @intCast(w * h * 4);
+ const fd = c.memfd_create("rediwm-monitor", c.MFD_CLOEXEC);
+ if (fd < 0) return error.ShmFailed;
+ defer _ = c.close(fd);
+
+ if (c.ftruncate(fd, @intCast(len)) != 0) return error.ShmFailed;
+ const memory = c.mmap(null, len, c.PROT_READ | c.PROT_WRITE, c.MAP_SHARED, fd, 0);
+ if (memory == c.MAP_FAILED) return error.ShmFailed;
+ errdefer _ = c.munmap(memory, len);
+
+ const pool = try client.shm.?.createPool(fd, @intCast(len));
+ defer pool.destroy();
+
+ const buffer = try pool.createBuffer(0, w, h, w * 4, .argb8888);
+ errdefer buffer.destroy();
+
+ const image = c.cairo_image_surface_create_for_data(
+ @ptrCast(memory),
+ c.CAIRO_FORMAT_ARGB32,
+ w,
+ h,
+ w * 4,
+ ) orelse return error.CairoFailed;
+ errdefer c.cairo_surface_destroy(image);
+ if (c.cairo_surface_status(image) != c.CAIRO_STATUS_SUCCESS) return error.CairoFailed;
+
+ const self = try a.create(Buffer);
+ self.* = .{
+ .client = client,
+ .wl_buffer = buffer,
+ .image = image,
+ .memory = memory.?,
+ .len = len,
+ .w = w,
+ .h = h,
+ };
+ buffer.setListener(*Buffer, released, self);
+ return self;
+ }
+
+ fn released(_: *wl.Buffer, _: wl.Buffer.Event, self: *Buffer) void {
+ self.busy = false;
+ self.client.outstanding -= 1;
+ }
+ fn destroy(self: *Buffer) void {
+ self.wl_buffer.destroy();
+ c.cairo_surface_destroy(self.image);
+ _ = c.munmap(self.memory, self.len);
+ a.destroy(self);
+ }
+};
+
+pub fn run(init: std.process.Init) !void {
+ _ = c.signal(c.SIGPIPE, c.SIG_IGN);
+ defer @import("../files/settings.zig").deinitTheme();
+ var watch = try @import("settings_watch.zig").Watch.init(init.io, init.minimal.environ);
+ defer watch.deinit();
+ defer @import("ui").compose.flushTable();
+ const display = try wl.Display.connect(null);
+ defer display.disconnect();
+ var self = Client{ .display = display, .app = try app_mod.App.init(init.io), .locale = @import("ui").compose.localeFromEnviron(init.minimal.environ) };
+ defer self.deinit();
+ defer self.compose.deinit();
+ defer self.app.deinit();
+ defer for (self.buffers) |slot| {
+ if (slot) |buffer| buffer.destroy();
+ };
+
+ const registry = try display.getRegistry();
+ defer registry.destroy();
+ registry.setListener(*Client, Client.registryEvent, &self);
+
+ if (display.roundtrip() != .SUCCESS) return error.DisplayFailed;
+ if (self.compositor == null or self.shm == null or self.wm_base == null) {
+ return error.MissingWaylandGlobals;
+ }
+
+ if (self.output_manager) |manager| {
+ for (self.outputs.items) |info| {
+ info.logical = try manager.getXdgOutput(info.proxy);
+ info.logical.?.setListener(*OutputInfo, Client.logicalOutputEvent, info);
+ }
+ if (display.roundtrip() != .SUCCESS) return error.DisplayFailed;
+ }
+
+ self.surface = try self.compositor.?.createSurface();
+ defer self.surface.destroy();
+ self.surface.setListener(*Client, Client.surfaceEvent, &self);
+
+ self.cursor_surface = try self.compositor.?.createSurface();
+ defer self.cursor_surface.destroy();
+ defer self.cursor_shape.deinit();
+ if (self.cursor_shape.manager == null) self.cursor_theme = ClientCursor.loadFallback(self.shm.?);
+ defer if (self.cursor_theme) |theme_ptr| theme_ptr.destroy();
+
+ if (self.viewporter) |manager| self.viewport = try manager.getViewport(self.surface);
+ defer if (self.viewport) |viewport| viewport.destroy();
+ if (self.fractional_manager) |manager| {
+ self.fractional = try manager.getFractionalScale(self.surface);
+ self.fractional.?.setListener(*Client, Client.fractionalEvent, &self);
+ }
+ defer if (self.fractional) |fractional| fractional.destroy();
+
+ self.xdg_surface = try self.wm_base.?.getXdgSurface(self.surface);
+ defer self.xdg_surface.destroy();
+ self.xdg_surface.setListener(*Client, Client.xdgSurfaceEvent, &self);
+
+ self.xdg_toplevel = try self.xdg_surface.getToplevel();
+ defer self.xdg_toplevel.destroy();
+ self.xdg_toplevel.setListener(*Client, Client.xdgToplevelEvent, &self);
+
+ self.xdg_toplevel.setAppId("rediwm-monitor");
+ self.xdg_toplevel.setTitle(self.app.getTitle());
+ // Real min size is set from xdgToplevelEvent once the decoration mode
+ // (and thus titlebar height) is known; this is just a safe pre-configure
+ // default sized for the worst case (self-decorated).
+ self.xdg_toplevel.setMinSize(640, 400 + CSD_TITLEBAR_H);
+
+ // Prefer server-side decorations; the compositor may still tell us via
+ // decorationEvent to self-decorate (e.g. it has no SSD implementation),
+ // and if zxdg_decoration_manager_v1 isn't advertised at all we already
+ // default to self-decorating (see wantsCsd).
+ if (self.decoration_manager) |mgr| {
+ self.decoration = mgr.getToplevelDecoration(self.xdg_toplevel) catch null;
+ if (self.decoration) |dec| {
+ dec.setListener(*Client, Client.decorationEvent, &self);
+ dec.setMode(.server_side);
+ }
+ }
+ defer if (self.decoration) |dec| dec.destroy();
+
+ // Initial commit to start xdg configuration sequence
+ self.surface.commit();
+
+ self.app.start();
+ while (self.running) {
+ if (watch.poll()) self.app.dirty = true;
+ self.app.sync();
+ self.app.stepAnimations(key_repeat.nowMs());
+ if (self.app.closed) self.close();
+ if (!self.running) break;
+
+ try self.render();
+
+ while (!display.prepareRead()) {
+ if (display.dispatchPending() != .SUCCESS) return error.DisplayFailed;
+ }
+ if (!self.running or self.app.closed) {
+ display.cancelRead();
+ self.close();
+ break;
+ }
+
+ if (self.configured and self.app.dirty and !self.app.suspended and self.outstanding < 2) {
+ display.cancelRead();
+ continue;
+ }
+ const flushed = display.flush();
+ if (flushed != .SUCCESS and flushed != .AGAIN) {
+ display.cancelRead();
+ return error.DisplayFailed;
+ }
+
+ var fds = [_]c.struct_pollfd{
+ .{ .fd = display.getFd(), .events = @intCast(c.POLLIN | @as(c_int, if (flushed == .AGAIN) c.POLLOUT else 0)), .revents = 0 },
+ .{ .fd = self.app.worker.notify_fd, .events = c.POLLIN, .revents = 0 },
+ .{ .fd = watch.fd, .events = c.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;
+ if (self.app.animationTimeout(now)) |wait| timeout = if (timeout < 0) @intCast(wait) else @min(timeout, @as(c_int, @intCast(wait)));
+ if (self.app.suspended) {
+ self.key_repeat.stop();
+ timeout = -1;
+ }
+ const result = c.poll(&fds, fds.len, timeout);
+ if (result > 0 and (fds[0].revents & c.POLLIN != 0)) {
+ if (display.readEvents() != .SUCCESS) return error.DisplayFailed;
+ } else {
+ display.cancelRead();
+ }
+ if ((fds[0].revents & (c.POLLERR | c.POLLHUP)) != 0) return error.DisplayFailed;
+ if (display.dispatchPending() != .SUCCESS) return error.DisplayFailed;
+ self.repeatDue();
+ }
+}
diff --git a/src/system_monitor/collector.zig b/src/system_monitor/collector.zig
new file mode 100644
index 0000000..53132c7
--- /dev/null
+++ b/src/system_monitor/collector.zig
@@ -0,0 +1,228 @@
+//! A single cancellable worker. Snapshots own their arena; only copied data
+//! crosses the mutex. Paused/hidden workers block indefinitely on an eventfd.
+const std = @import("std");
+const proc = @import("proc.zig");
+const c = proc.c;
+const a = std.heap.c_allocator;
+
+pub const Process = struct {
+ identity: proc.Identity,
+ name: []const u8,
+ user: []const u8,
+ uids: ?proc.Uids,
+ state: u8,
+ cpu_ticks: u64,
+ cpu_percent: ?f64 = null,
+ resident_bytes: ?u64,
+ protected: bool,
+};
+pub const Snapshot = struct {
+ arena: std.heap.ArenaAllocator,
+ processes: []Process,
+ at_ns: u64,
+ cpu: ?proc.Cpu,
+ cpu_percent: ?f64 = null,
+ memory: ?proc.Memory,
+ unavailable: usize = 0,
+ truncated: bool = false,
+ failed: bool = false,
+ pub fn deinit(self: *Snapshot) void {
+ self.arena.deinit();
+ a.destroy(self);
+ }
+};
+
+pub fn sample(cancelled: *const std.atomic.Value(u64), generation: u64) !*Snapshot {
+ const snapshot = try a.create(Snapshot);
+ snapshot.* = .{ .arena = .init(a), .processes = &.{}, .at_ns = proc.nowNs(), .cpu = null, .memory = null };
+ errdefer snapshot.deinit();
+ const arena = snapshot.arena.allocator();
+ var buf: [65536]u8 = undefined;
+ if (proc.readAt(c.AT_FDCWD, "/proc/stat", &buf)) |bytes| snapshot.cpu = proc.parseCpu(bytes) else |_| {}
+ if (proc.readAt(c.AT_FDCWD, "/proc/meminfo", &buf)) |bytes| snapshot.memory = proc.parseMemory(bytes) else |_| {}
+ const dir = c.opendir("/proc") orelse {
+ snapshot.failed = true;
+ return snapshot;
+ };
+ defer _ = c.closedir(dir);
+ const page_size = c.sysconf(c._SC_PAGESIZE);
+ var rows: std.ArrayList(Process) = .empty;
+ var users: std.AutoHashMapUnmanaged(u32, []const u8) = .empty;
+ // Avoid NSS here: a directory service outage must never prevent stopping
+ // or joining the collector. Nonlocal accounts are displayed by UID.
+ if (proc.readAt(c.AT_FDCWD, "/etc/passwd", &buf)) |bytes| {
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |line| {
+ var fields = std.mem.splitScalar(u8, line, ':');
+ const user = fields.next() orelse continue;
+ _ = fields.next() orelse continue;
+ const uid = std.fmt.parseInt(u32, fields.next() orelse continue, 10) catch continue;
+ try users.put(arena, uid, try safeName(arena, user));
+ }
+ } else |_| {}
+ while (c.readdir(dir)) |entry| {
+ if (cancelled.load(.acquire) != generation) return error.Cancelled;
+ const name = std.mem.sliceTo(entry.*.d_name[0..], 0);
+ const pid = std.fmt.parseInt(i32, name, 10) catch continue;
+ if (pid <= 0) continue;
+ if (rows.items.len >= 131072) {
+ snapshot.truncated = true;
+ break;
+ }
+ const process_dir = proc.openProcess(pid) catch {
+ snapshot.unavailable += 1;
+ continue;
+ };
+ defer _ = c.close(process_dir);
+ const stat = proc.parseStat(proc.readAt(process_dir, "stat", &buf) catch {
+ snapshot.unavailable += 1;
+ continue;
+ }) orelse continue;
+ const process_name = try safeName(arena, stat.name);
+ const uids = if (proc.readAt(process_dir, "status", &buf)) |bytes| proc.parseUids(bytes) else |_| null;
+ const user = if (uids) |ids| blk: {
+ if (users.get(ids[0])) |value| break :blk value;
+ const value = try std.fmt.allocPrint(arena, "{d}", .{ids[0]});
+ try users.put(arena, ids[0], value);
+ break :blk value;
+ } else "Unavailable";
+ const protected = proc.protectedAt(process_dir, pid) catch true;
+ try rows.append(arena, .{
+ .identity = .{ .pid = pid, .start = stat.start },
+ .name = process_name,
+ .user = user,
+ .uids = uids,
+ .state = stat.state,
+ .cpu_ticks = stat.cpu,
+ .resident_bytes = if (page_size > 0) std.math.mul(u64, stat.rss, @intCast(page_size)) catch null else null,
+ .protected = protected,
+ });
+ }
+ snapshot.processes = rows.items;
+ return snapshot;
+}
+
+fn safeName(allocator: std.mem.Allocator, bytes: []const u8) ![]const u8 {
+ const value = try allocator.dupe(u8, if (std.unicode.utf8ValidateSlice(bytes)) bytes else "Unknown process");
+ for (value) |*byte| if (byte.* < 32 or byte.* == 127) {
+ byte.* = ' ';
+ };
+ return value;
+}
+
+const Baseline = struct { start: u64, cpu: u64 };
+pub const Worker = struct {
+ wake_fd: c_int,
+ notify_fd: c_int,
+ thread: ?std.Thread = null,
+ generation: std.atomic.Value(u64) = .init(0),
+ stopping: std.atomic.Value(bool) = .init(false),
+ active: std.atomic.Value(bool) = .init(false),
+ mutex: std.Io.Mutex = .init,
+ io: std.Io,
+ pending: ?*Snapshot = null,
+
+ pub fn init(io: std.Io) !*Worker {
+ const self = try a.create(Worker);
+ errdefer a.destroy(self);
+ const wake_fd = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ if (wake_fd < 0) return error.EventFdFailed;
+ errdefer _ = c.close(wake_fd);
+ const notify = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);
+ if (notify < 0) return error.EventFdFailed;
+ errdefer _ = c.close(notify);
+ self.* = .{ .wake_fd = wake_fd, .notify_fd = notify, .io = io };
+ self.thread = try std.Thread.spawn(.{}, run, .{self});
+ return self;
+ }
+ pub fn deinit(self: *Worker) void {
+ self.stopping.store(true, .release);
+ _ = self.generation.fetchAdd(1, .acq_rel);
+ wake(self.wake_fd);
+ self.thread.?.join();
+ if (self.pending) |old| old.deinit();
+ _ = c.close(self.wake_fd);
+ _ = c.close(self.notify_fd);
+ a.destroy(self);
+ }
+ pub fn setActive(self: *Worker, active: bool) void {
+ if (self.active.swap(active, .acq_rel) == active) return;
+ _ = self.generation.fetchAdd(1, .acq_rel);
+ self.mutex.lockUncancelable(self.io);
+ if (self.pending) |old| old.deinit();
+ self.pending = null;
+ self.mutex.unlock(self.io);
+ wake(self.wake_fd);
+ }
+ pub fn take(self: *Worker) ?*Snapshot {
+ drain(self.notify_fd);
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ const result = self.pending;
+ self.pending = null;
+ return result;
+ }
+ fn run(self: *Worker) void {
+ var previous: std.AutoHashMapUnmanaged(i32, Baseline) = .empty;
+ defer previous.deinit(a);
+ var last_at: u64 = 0;
+ var last_cpu: ?proc.Cpu = null;
+ var observed: u64 = std.math.maxInt(u64);
+ var deadline: u64 = 0;
+ const hz_raw = c.sysconf(c._SC_CLK_TCK);
+ const hz: u64 = @intCast(@max(0, hz_raw));
+ while (!self.stopping.load(.acquire)) {
+ const generation = self.generation.load(.acquire);
+ if (generation != observed) {
+ observed = generation;
+ previous.clearRetainingCapacity();
+ last_at = 0;
+ last_cpu = null;
+ deadline = 0;
+ }
+ if (self.active.load(.acquire) and proc.nowNs() >= deadline) {
+ const snap = sample(&self.generation, generation) catch {
+ deadline = proc.nowNs() + 1_000_000_000;
+ continue;
+ };
+ if (self.generation.load(.acquire) != generation) {
+ snap.deinit();
+ continue;
+ }
+ if (last_cpu) |before| if (snap.cpu) |after| {
+ snap.cpu_percent = proc.cpuPercent(before, after);
+ };
+ for (snap.processes) |*row| {
+ if (previous.get(row.identity.pid)) |before| {
+ row.cpu_percent = proc.processPercent(.{ .name = "", .state = 0, .cpu = before.cpu, .start = before.start, .rss = 0 }, .{ .name = "", .state = 0, .cpu = row.cpu_ticks, .start = row.identity.start, .rss = 0 }, hz, snap.at_ns -| last_at);
+ }
+ }
+ previous.clearRetainingCapacity();
+ for (snap.processes) |row| previous.put(a, row.identity.pid, .{ .start = row.identity.start, .cpu = row.cpu_ticks }) catch {};
+ last_at = snap.at_ns;
+ last_cpu = snap.cpu;
+ deadline = snap.at_ns + 1_000_000_000;
+ self.mutex.lockUncancelable(self.io);
+ if (self.generation.load(.acquire) == generation and self.active.load(.acquire)) {
+ if (self.pending) |old| old.deinit();
+ self.pending = snap;
+ wake(self.notify_fd);
+ } else snap.deinit();
+ self.mutex.unlock(self.io);
+ }
+ var fd = c.struct_pollfd{ .fd = self.wake_fd, .events = c.POLLIN, .revents = 0 };
+ const timeout: c_int = if (!self.active.load(.acquire)) -1 else @intCast(@min(1000, (deadline -| proc.nowNs() + 999_999) / 1_000_000));
+ _ = c.poll(&fd, 1, timeout);
+ drain(self.wake_fd);
+ }
+ }
+};
+
+pub fn wake(fd: c_int) void {
+ const one: u64 = 1;
+ _ = c.write(fd, &one, @sizeOf(u64));
+}
+pub fn drain(fd: c_int) void {
+ var value: u64 = undefined;
+ _ = c.read(fd, &value, @sizeOf(u64));
+}
diff --git a/src/system_monitor/model.zig b/src/system_monitor/model.zig
new file mode 100644
index 0000000..ff50e0b
--- /dev/null
+++ b/src/system_monitor/model.zig
@@ -0,0 +1,112 @@
+const std = @import("std");
+const collector = @import("collector.zig");
+const proc = @import("proc.zig");
+pub const Sort = enum { name, pid, user, cpu, memory, state };
+pub const Model = struct {
+ allocator: std.mem.Allocator,
+ snapshot: ?*collector.Snapshot = null,
+ rows: std.ArrayList(usize) = .empty,
+ selected: ?proc.Identity = null,
+ scroll: f64 = 0,
+ query: []const u8 = "",
+ mine: bool = true,
+ uid: u32,
+ sort: Sort = .cpu,
+ descending: bool = true,
+
+ pub fn deinit(self: *Model) void {
+ self.rows.deinit(self.allocator);
+ if (self.snapshot) |snap| snap.deinit();
+ }
+ pub fn update(self: *Model, snapshot: *collector.Snapshot) !void {
+ if (self.snapshot) |old| old.deinit();
+ self.snapshot = snapshot;
+ try self.filter();
+ }
+ pub fn filter(self: *Model) !void {
+ self.rows.clearRetainingCapacity();
+ const snap = self.snapshot orelse return;
+ for (snap.processes, 0..) |row, i| {
+ if (self.mine and (row.uids == null or row.uids.?[0] != self.uid)) continue;
+ if (self.query.len > 0) {
+ var pid_buf: [32]u8 = undefined;
+ const pid = std.fmt.bufPrint(&pid_buf, "{d}", .{row.identity.pid}) catch unreachable;
+ if (std.ascii.indexOfIgnoreCase(row.name, self.query) == null and std.ascii.indexOfIgnoreCase(row.user, self.query) == null and std.mem.indexOf(u8, pid, self.query) == null) continue;
+ }
+ try self.rows.append(self.allocator, i);
+ }
+ std.mem.sort(usize, self.rows.items, self, less);
+ if (self.selectedIndex() == null) self.selected = null;
+ // The UI only clamps at the new end. Reordering never scrolls to the
+ // selected process; keyboard navigation explicitly reveals it.
+ }
+ pub fn selectedIndex(self: *const Model) ?usize {
+ const identity = self.selected orelse return null;
+ const snap = self.snapshot orelse return null;
+ for (self.rows.items, 0..) |index, i| if (snap.processes[index].identity.eql(identity)) return i;
+ return null;
+ }
+ pub fn selectedProcess(self: *const Model) ?collector.Process {
+ const index = self.selectedIndex() orelse return null;
+ return self.snapshot.?.processes[self.rows.items[index]];
+ }
+ pub fn setSort(self: *Model, sort: Sort) void {
+ self.descending = if (sort == self.sort) !self.descending else sort == .cpu or sort == .memory;
+ self.sort = sort;
+ self.filter() catch {};
+ }
+ fn less(self: *Model, ai: usize, bi: usize) bool {
+ const a = self.snapshot.?.processes[ai];
+ const b = self.snapshot.?.processes[bi];
+ const order: std.math.Order = switch (self.sort) {
+ .name => std.ascii.orderIgnoreCase(a.name, b.name),
+ .pid => std.math.order(a.identity.pid, b.identity.pid),
+ .user => std.ascii.orderIgnoreCase(a.user, b.user),
+ .cpu => optionalOrder(f64, a.cpu_percent, b.cpu_percent),
+ .memory => optionalOrder(u64, a.resident_bytes, b.resident_bytes),
+ .state => std.math.order(a.state, b.state),
+ };
+ if (order == .eq) return a.identity.pid < b.identity.pid;
+ return if (self.descending) order == .gt else order == .lt;
+ }
+};
+fn optionalOrder(comptime T: type, a: ?T, b: ?T) std.math.Order {
+ if (a == null) return if (b == null) .eq else .lt;
+ if (b == null) return .gt;
+ return std.math.order(a.?, b.?);
+}
+
+pub const Point = struct { at_ns: u64, cpu: ?f64, memory: ?f64 };
+pub const History = struct {
+ points: [60]Point = undefined,
+ count: usize = 0,
+ pub fn append(self: *History, snap: *const collector.Snapshot) void {
+ var keep: usize = 0;
+ for (self.points[0..self.count]) |point| {
+ if (snap.at_ns -| point.at_ns < 60_000_000_000) {
+ self.points[keep] = point;
+ keep += 1;
+ }
+ }
+ self.count = keep;
+ if (self.count == self.points.len) {
+ std.mem.copyForwards(Point, self.points[0..59], self.points[1..60]);
+ self.count -= 1;
+ }
+ self.points[self.count] = .{ .at_ns = snap.at_ns, .cpu = snap.cpu_percent, .memory = if (snap.memory) |mem| if (mem.total > 0) @as(f64, @floatFromInt(mem.used())) * 100 / @as(f64, @floatFromInt(mem.total)) else null else null };
+ self.count += 1;
+ }
+};
+
+pub fn stateName(state: u8) []const u8 {
+ return switch (state) {
+ 'R' => "Running",
+ 'S' => "Sleeping",
+ 'D' => "Disk wait",
+ 'T', 't' => "Stopped",
+ 'Z' => "Zombie",
+ 'I' => "Idle",
+ 'X', 'x' => "Exited",
+ else => "Unknown",
+ };
+}
diff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zig
new file mode 100644
index 0000000..fedca66
--- /dev/null
+++ b/src/system_monitor/proc.zig
@@ -0,0 +1,185 @@
+//! Bounded Linux proc readers. No compositor, Wayland or UI dependencies.
+const std = @import("std");
+pub const c = @cImport({
+ @cUndef("_FORTIFY_SOURCE");
+ @cDefine("_GNU_SOURCE", "1");
+ @cInclude("unistd.h");
+ @cInclude("fcntl.h");
+ @cInclude("dirent.h");
+ @cInclude("pwd.h");
+ @cInclude("poll.h");
+ @cInclude("sys/eventfd.h");
+ @cInclude("time.h");
+});
+
+pub const Identity = struct {
+ pid: i32,
+ start: u64,
+ pub fn eql(a: Identity, b: Identity) bool {
+ return a.pid == b.pid and a.start == b.start;
+ }
+};
+pub const Stat = struct { name: []const u8, state: u8, cpu: u64, start: u64, rss: u64 };
+
+/// comm may contain spaces, newlines and closing parentheses. Field 3 starts
+/// after the LAST closing parenthesis; fields 14/15/22/24 are CPU/start/RSS.
+pub fn parseStat(bytes: []const u8) ?Stat {
+ const begin = std.mem.indexOfScalar(u8, bytes, '(') orelse return null;
+ const end = std.mem.lastIndexOfScalar(u8, bytes, ')') orelse return null;
+ if (end <= begin) return null;
+ var fields = std.mem.tokenizeAny(u8, bytes[end + 1 ..], " \n");
+ var out: Stat = .{ .name = bytes[begin + 1 .. end], .state = '?', .cpu = 0, .start = 0, .rss = 0 };
+ var index: usize = 0;
+ while (fields.next()) |field| : (index += 1) switch (index) {
+ 0 => {
+ if (field.len != 1) return null;
+ out.state = field[0];
+ },
+ 11, 12 => out.cpu +|= std.fmt.parseInt(u64, field, 10) catch return null,
+ 19 => out.start = std.fmt.parseInt(u64, field, 10) catch return null,
+ 21 => {
+ const rss = std.fmt.parseInt(i64, field, 10) catch return null;
+ out.rss = @intCast(@max(0, rss));
+ return out;
+ },
+ else => {},
+ };
+ return null;
+}
+
+pub fn readAt(dir: c_int, path: [*:0]const u8, buf: []u8) ![]const u8 {
+ const fd = c.openat(dir, path, c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);
+ if (fd < 0) return switch (std.posix.errno(fd)) {
+ .ACCES, .PERM => error.PermissionDenied,
+ .NOENT, .SRCH => error.ProcessExited,
+ else => error.ReadFailed,
+ };
+ defer _ = c.close(fd);
+ var len: usize = 0;
+ while (len < buf.len) {
+ const n = c.read(fd, buf.ptr + len, buf.len - len);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n < 0) return error.ReadFailed;
+ if (n == 0) return buf[0..len];
+ len += @intCast(n);
+ }
+ return error.DataTooLarge;
+}
+
+pub fn openProcess(pid: i32) !c_int {
+ if (pid <= 0) return error.ProcessExited;
+ var buf: [64]u8 = undefined;
+ const path = try std.fmt.bufPrintZ(&buf, "/proc/{d}", .{pid});
+ const fd = c.open(path, c.O_DIRECTORY | c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW);
+ if (fd < 0) return switch (std.posix.errno(fd)) {
+ .ACCES, .PERM => error.PermissionDenied,
+ .NOENT, .SRCH => error.ProcessExited,
+ else => error.ReadFailed,
+ };
+ return fd;
+}
+
+pub fn readStat(pid: i32, buf: []u8) ?Stat {
+ const dir = openProcess(pid) catch return null;
+ defer _ = c.close(dir);
+ return parseStat(readAt(dir, "stat", buf) catch return null);
+}
+
+pub const Uids = [4]u32;
+pub fn parseUids(bytes: []const u8) ?Uids {
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |line| {
+ if (!std.mem.startsWith(u8, line, "Uid:")) continue;
+ var values = std.mem.tokenizeAny(u8, line[4..], " \t");
+ var out: Uids = undefined;
+ for (&out) |*uid| uid.* = std.fmt.parseInt(u32, values.next() orelse return null, 10) catch return null;
+ return out;
+ }
+ return null;
+}
+
+pub fn owned(uids: Uids, uid: u32) bool {
+ for (uids) |value| if (value != uid) return false;
+ return true;
+}
+
+pub fn protectedName(name: []const u8) bool {
+ const clean = if (std.mem.endsWith(u8, name, " (deleted)")) name[0 .. name.len - " (deleted)".len] else name;
+ const base = std.fs.path.basename(clean);
+ inline for (.{ "rediwm", "rediwm-session", "rediwm-dm", "rediwm-accounts-helper", "rediwm-polkit-agent" }) |protected| {
+ if (std.mem.eql(u8, base, protected)) return true;
+ }
+ return false;
+}
+
+pub fn protectedAt(dir: c_int, pid: i32) !bool {
+ if (pid <= 1 or pid == c.getpid()) return true;
+ var buf: [4096]u8 = undefined;
+ const n = c.readlinkat(dir, "exe", &buf, buf.len);
+ if (n < 0 or n == buf.len) return error.IdentityUnavailable;
+ return protectedName(buf[0..@intCast(n)]);
+}
+
+pub const Cpu = struct { total: u64, idle: u64 };
+pub fn parseCpu(bytes: []const u8) ?Cpu {
+ var fields = std.mem.tokenizeAny(u8, bytes[0 .. std.mem.indexOfScalar(u8, bytes, '\n') orelse bytes.len], " \t");
+ if (!std.mem.eql(u8, fields.next() orelse return null, "cpu")) return null;
+ var out: Cpu = .{ .total = 0, .idle = 0 };
+ var count: usize = 0;
+ // guest and guest_nice are already included in user/nice.
+ while (fields.next()) |field| : (count += 1) {
+ if (count == 8) break;
+ const ticks = std.fmt.parseInt(u64, field, 10) catch return null;
+ out.total +|= ticks;
+ if (count == 3 or count == 4) out.idle +|= ticks;
+ }
+ return if (count >= 4) out else null;
+}
+pub fn cpuPercent(before: Cpu, after: Cpu) ?f64 {
+ if (after.total <= before.total or after.idle < before.idle) return null;
+ const total = after.total - before.total;
+ return @as(f64, @floatFromInt(total -| (after.idle - before.idle))) * 100 / @as(f64, @floatFromInt(total));
+}
+/// Process CPU uses one core = 100%, and may exceed 100% for threaded apps.
+pub fn processPercent(before: Stat, after: Stat, hz: u64, elapsed_ns: u64) ?f64 {
+ if (before.start != after.start or after.cpu < before.cpu or hz == 0 or elapsed_ns == 0) return null;
+ return @as(f64, @floatFromInt(after.cpu - before.cpu)) * 100 * 1_000_000_000 /
+ (@as(f64, @floatFromInt(hz)) * @as(f64, @floatFromInt(elapsed_ns)));
+}
+
+pub const Memory = struct {
+ total: u64,
+ available: u64,
+ swap_total: ?u64,
+ swap_free: ?u64,
+ pub fn used(self: Memory) u64 {
+ return self.total -| self.available;
+ }
+};
+pub fn parseMemory(bytes: []const u8) ?Memory {
+ var total: ?u64 = null;
+ var available: ?u64 = null;
+ var swap_total: ?u64 = null;
+ var swap_free: ?u64 = null;
+ var lines = std.mem.splitScalar(u8, bytes, '\n');
+ while (lines.next()) |line| {
+ var fields = std.mem.tokenizeAny(u8, line, " \t");
+ const key = fields.next() orelse continue;
+ const relevant = std.mem.eql(u8, key, "MemTotal:") or std.mem.eql(u8, key, "MemAvailable:") or std.mem.eql(u8, key, "SwapTotal:") or std.mem.eql(u8, key, "SwapFree:");
+ if (!relevant) continue;
+ const kb = std.fmt.parseInt(u64, fields.next() orelse return null, 10) catch return null;
+ if (!std.mem.eql(u8, fields.next() orelse return null, "kB")) return null;
+ const value = std.math.mul(u64, kb, 1024) catch return null;
+ if (std.mem.eql(u8, key, "MemTotal:")) total = value;
+ if (std.mem.eql(u8, key, "MemAvailable:")) available = value;
+ if (std.mem.eql(u8, key, "SwapTotal:")) swap_total = value;
+ if (std.mem.eql(u8, key, "SwapFree:")) swap_free = value;
+ }
+ return .{ .total = total orelse return null, .available = available orelse return null, .swap_total = swap_total, .swap_free = swap_free };
+}
+
+pub fn nowNs() u64 {
+ var ts: c.struct_timespec = undefined;
+ if (c.clock_gettime(c.CLOCK_MONOTONIC, &ts) != 0) return 0;
+ return @as(u64, @intCast(ts.tv_sec)) * 1_000_000_000 + @as(u64, @intCast(ts.tv_nsec));
+}
diff --git a/src/system_monitor/settings_watch.zig b/src/system_monitor/settings_watch.zig
new file mode 100644
index 0000000..ee27d09
--- /dev/null
+++ b/src/system_monitor/settings_watch.zig
@@ -0,0 +1,52 @@
+//! Theme changes wake the UI through inotify, including while sampling is
+//! paused or suspended. Watch parent directories so atomic saves work too.
+const std = @import("std");
+const c = @import("../files/c.zig").api;
+const settings = @import("../files/settings.zig");
+const a = std.heap.c_allocator;
+pub const Watch = struct {
+ fd: c_int,
+ settings: settings.Settings,
+ io: std.Io,
+ pub fn init(io: std.Io, env: std.process.Environ) !Watch {
+ const fd = c.inotify_init1(c.IN_NONBLOCK | c.IN_CLOEXEC);
+ if (fd < 0) return error.ThemeWatchFailed;
+ errdefer _ = c.close(fd);
+ var self: Watch = .{ .fd = fd, .settings = try settings.Settings.init(a, env), .io = io };
+ self.arm();
+ _ = self.apply();
+ return self;
+ }
+ pub fn deinit(self: *Watch) void {
+ self.settings.deinit(a);
+ _ = c.close(self.fd);
+ }
+ fn arm(self: *Watch) void {
+ for ([_]?[:0]const u8{ self.settings.config_path, self.settings.theme_path }) |maybe_path| {
+ var parent = std.fs.path.dirname(maybe_path orelse continue) orelse continue;
+ while (true) {
+ var buf: [4096]u8 = undefined;
+ const path = std.fmt.bufPrintZ(&buf, "{s}", .{parent}) catch break;
+ if (c.inotify_add_watch(self.fd, path, c.IN_CLOSE_WRITE | c.IN_MOVED_TO | c.IN_CREATE | c.IN_DELETE | c.IN_DELETE_SELF | c.IN_MOVE_SELF) >= 0) break;
+ parent = std.fs.path.dirname(parent) orelse break;
+ }
+ }
+ }
+ fn apply(self: *Watch) bool {
+ self.settings.last_second = -1;
+ if (self.settings.poll(a, self.io)) |update| {
+ update.apply();
+ @import("ui").anim.applySettings(self.settings.animations);
+ return true;
+ }
+ return false;
+ }
+ pub fn poll(self: *Watch) bool {
+ var buf: [8192]u8 = undefined;
+ var changed = false;
+ while (c.read(self.fd, &buf, buf.len) > 0) changed = true;
+ if (!changed) return false;
+ self.arm();
+ return self.apply();
+ }
+};
diff --git a/src/system_monitor_main.zig b/src/system_monitor_main.zig
new file mode 100644
index 0000000..61d8164
--- /dev/null
+++ b/src/system_monitor_main.zig
@@ -0,0 +1,18 @@
+const std = @import("std");
+pub fn main(init: std.process.Init) !void {
+ defer {
+ if (@import("memory").deinit()) std.log.err("System Monitor memory leaks reported above", .{});
+ }
+ defer @import("ui").text.deinit();
+ defer @import("ui").shell_icons.deinit();
+ const args = init.minimal.args.vector;
+ if (args.len > 1) {
+ const arg = std.mem.span(args[1]);
+ if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
+ std.debug.print("Usage: rediwm-monitor\n\nSystem Monitor for RediWM.\nCtrl+F: search Arrows: select Delete: end process\nShift+Delete: force quit (confirmation) Ctrl+Q: close\n", .{});
+ return;
+ }
+ return error.UnexpectedArgument;
+ }
+ try @import("system_monitor/client.zig").run(init);
+}
diff --git a/src/system_monitor_tests.zig b/src/system_monitor_tests.zig
new file mode 100644
index 0000000..c736038
--- /dev/null
+++ b/src/system_monitor_tests.zig
@@ -0,0 +1,161 @@
+const std = @import("std");
+const proc = @import("system_monitor/proc.zig");
+const model = @import("system_monitor/model.zig");
+const collector = @import("system_monitor/collector.zig");
+const actions = @import("system_monitor/actions.zig");
+
+test "monitor stat parsing preserves tricky names and rejects partial data" {
+ const stat = proc.parseStat("123 (a ) strange\nname) S 1 2 3 4 5 6 7 8 9 10 100 50 0 0 20 0 1 0 987654 10000 42\n").?;
+ try std.testing.expectEqualStrings("a ) strange\nname", stat.name);
+ try std.testing.expectEqual(@as(u64, 150), stat.cpu);
+ try std.testing.expectEqual(@as(u64, 987654), stat.start);
+ try std.testing.expectEqual(@as(u64, 42), stat.rss);
+ try std.testing.expect(proc.parseStat("123 (gone) S 1 2") == null);
+ try std.testing.expect(proc.parseStat("garbage") == null);
+}
+test "monitor CPU excludes guest accounting and rejects reset counters and PID reuse" {
+ const before = proc.parseCpu("cpu 100 20 30 400 50 10 20 10 90 10\ncpu0 1").?;
+ const after = proc.parseCpu("cpu 120 20 40 440 60 10 30 20 100 10\n").?;
+ try std.testing.expectEqual(@as(u64, 640), before.total);
+ try std.testing.expectApproxEqAbs(@as(f64, 50), proc.cpuPercent(before, after).?, 0.001);
+ try std.testing.expect(proc.cpuPercent(after, before) == null);
+ var first: proc.Stat = .{ .name = "", .state = 'R', .cpu = 100, .start = 10, .rss = 0 };
+ var second = first;
+ second.cpu = 350;
+ try std.testing.expectApproxEqAbs(@as(f64, 250), proc.processPercent(first, second, 100, 1_000_000_000).?, 0.001);
+ first.start = 11;
+ try std.testing.expect(proc.processPercent(first, second, 100, 1_000_000_000) == null);
+}
+test "monitor memory uses available rather than free and bounds missing values" {
+ const mem = proc.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 400 kB\nSwapTotal: 500 kB\nSwapFree: 250 kB\n").?;
+ try std.testing.expectEqual(@as(u64, 600 * 1024), mem.used());
+ try std.testing.expectEqual(@as(u64, 500 * 1024), mem.swap_total.?);
+ try std.testing.expect(proc.parseMemory("MemTotal: 1000 kB\nMemFree: 100 kB\n") == null);
+ try std.testing.expect(proc.parseMemory("MemTotal: 18446744073709551615 kB\nMemAvailable: 1 kB") == null);
+}
+fn fixture(pid: i32, start: u64, name: []const u8, uid: u32, cpu: f64) collector.Process {
+ return .{ .identity = .{ .pid = pid, .start = start }, .name = name, .user = "alex", .uids = .{ uid, uid, uid, uid }, .state = 'S', .cpu_ticks = 0, .cpu_percent = cpu, .resident_bytes = 4096, .protected = false };
+}
+test "monitor sort search selection and scroll survive updates without following reused PIDs" {
+ var snap: collector.Snapshot = .{ .arena = .init(std.testing.allocator), .processes = &.{}, .at_ns = 0, .cpu = null, .memory = null };
+ defer snap.arena.deinit();
+ var rows = [_]collector.Process{ fixture(21, 1, "alpha", 1000, 1), fixture(22, 2, "beta", 1000, 10), fixture(23, 3, "root", 0, 20) };
+ snap.processes = &rows;
+ var m: model.Model = .{ .allocator = std.testing.allocator, .snapshot = &snap, .uid = 1000, .scroll = 36 };
+ defer m.rows.deinit(std.testing.allocator);
+ try m.filter();
+ try std.testing.expectEqualSlices(usize, &.{ 1, 0 }, m.rows.items);
+ m.selected = rows[0].identity;
+ rows[0].cpu_percent = 50;
+ try m.filter();
+ try std.testing.expectEqual(@as(usize, 0), m.selectedIndex().?);
+ try std.testing.expectEqual(@as(f64, 36), m.scroll);
+ m.setSort(.name);
+ try std.testing.expectEqualSlices(usize, &.{ 0, 1 }, m.rows.items);
+ m.setSort(.name);
+ try std.testing.expectEqualSlices(usize, &.{ 1, 0 }, m.rows.items);
+ try std.testing.expectEqual(@as(usize, 1), m.selectedIndex().?);
+ m.query = "BETA";
+ try m.filter();
+ try std.testing.expectEqualSlices(usize, &.{1}, m.rows.items);
+ try std.testing.expect(m.selected == null);
+ m.query = "";
+ m.mine = false;
+ try m.filter();
+ try std.testing.expectEqual(@as(usize, 3), m.rows.items.len);
+ m.selected = rows[0].identity;
+ rows[0].identity.start = 99;
+ try m.filter();
+ try std.testing.expect(m.selected == null);
+}
+test "monitor history holds only the last 60 seconds including pause gaps" {
+ var history: model.History = .{};
+ var snap: collector.Snapshot = .{ .arena = .init(std.testing.allocator), .processes = &.{}, .at_ns = 0, .cpu = null, .memory = null };
+ defer snap.arena.deinit();
+ for (0..100) |i| {
+ snap.at_ns = i * 1_000_000_000;
+ history.append(&snap);
+ }
+ try std.testing.expectEqual(@as(usize, 60), history.count);
+ snap.at_ns += 61_000_000_000;
+ history.append(&snap);
+ try std.testing.expectEqual(@as(usize, 1), history.count);
+}
+test "monitor action authority rejects changed identities and protects session executables" {
+ try std.testing.expect(proc.protectedName("/usr/bin/rediwm-session"));
+ try std.testing.expect(proc.protectedName("/usr/bin/rediwm (deleted)"));
+ try std.testing.expect(!proc.protectedName("/usr/bin/rediwm-files"));
+ try std.testing.expect(!proc.owned(.{ 1000, 0, 0, 1000 }, 1000));
+ var buf: [4096]u8 = undefined;
+ const own = proc.readStat(proc.c.getpid(), &buf).?;
+ try std.testing.expectError(error.ProcessExited, actions.execute(.{ .pid = proc.c.getpid(), .start = own.start + 1 }, .end));
+ try std.testing.expectError(error.ProtectedProcess, actions.execute(.{ .pid = proc.c.getpid(), .start = own.start }, .force));
+}
+test "monitor real collection includes its background worker owner and cancels" {
+ var generation = std.atomic.Value(u64).init(0);
+ const snap = try collector.sample(&generation, 0);
+ defer snap.deinit();
+ var found = false;
+ for (snap.processes) |row| if (row.identity.pid == proc.c.getpid()) {
+ found = true;
+ };
+ try std.testing.expect(found);
+ generation.store(1, .release);
+ try std.testing.expectError(error.Cancelled, collector.sample(&generation, 0));
+}
+
+test "monitor pidfd actions terminate only disposable fixtures and force a TERM-ignoring fixture" {
+ const io = std.testing.io;
+ var child = try std.process.spawn(io, .{ .argv = &.{ "/bin/sleep", "30" } });
+ defer child.kill(io);
+ var buf: [4096]u8 = undefined;
+ const stat = proc.readStat(child.id.?, &buf).?;
+ try actions.execute(.{ .pid = child.id.?, .start = stat.start }, .end);
+ const term = try child.wait(io);
+ try std.testing.expectEqual(std.posix.SIG.TERM, term.signal);
+
+ var stubborn = try std.process.spawn(io, .{ .argv = &.{ "/bin/sh", "-c", "trap '' TERM; echo ready; exec sleep 30" }, .stdout = .pipe });
+ defer stubborn.kill(io);
+ var ready: [16]u8 = undefined;
+ try std.testing.expect(proc.c.read(stubborn.stdout.?.handle, &ready, ready.len) > 0);
+ const identity = proc.Identity{ .pid = stubborn.id.?, .start = proc.readStat(stubborn.id.?, &buf).?.start };
+ const rc = std.os.linux.pidfd_open(identity.pid, 0);
+ try std.testing.expectEqual(std.os.linux.E.SUCCESS, std.os.linux.errno(rc));
+ const fd: i32 = @intCast(rc);
+ defer _ = proc.c.close(fd);
+ try actions.execute(identity, .end);
+ var pollfd = proc.c.struct_pollfd{ .fd = fd, .events = proc.c.POLLIN, .revents = 0 };
+ try std.testing.expectEqual(@as(c_int, 0), proc.c.poll(&pollfd, 1, 100));
+ try actions.execute(identity, .force);
+ const killed = try stubborn.wait(io);
+ try std.testing.expectEqual(std.posix.SIG.KILL, killed.signal);
+ try std.testing.expectError(error.ProcessExited, actions.execute(identity, .force));
+}
+
+test "monitor worker pause cancels publication and resume starts a fresh CPU interval" {
+ const worker = try collector.Worker.init(std.testing.io);
+ defer worker.deinit();
+ var fd = proc.c.struct_pollfd{ .fd = worker.notify_fd, .events = proc.c.POLLIN, .revents = 0 };
+ try std.testing.expectEqual(@as(c_int, 0), proc.c.poll(&fd, 1, 100));
+ worker.setActive(true);
+ try std.testing.expect(proc.c.poll(&fd, 1, 3000) > 0);
+ const first = worker.take().?;
+ try std.testing.expect(first.cpu_percent == null);
+ first.deinit();
+ worker.setActive(false);
+ if (worker.take()) |unexpected| {
+ unexpected.deinit();
+ return error.PublishedWhilePaused;
+ }
+ try std.testing.expectEqual(@as(c_int, 0), proc.c.poll(&fd, 1, 1200));
+ worker.setActive(true);
+ try std.testing.expect(proc.c.poll(&fd, 1, 3000) > 0);
+ const resumed = worker.take().?;
+ defer resumed.deinit();
+ try std.testing.expect(resumed.cpu_percent == null);
+ for (resumed.processes) |row| try std.testing.expect(row.cpu_percent == null);
+ // Exercise cancellation while enumeration may already be in progress.
+ worker.setActive(false);
+ worker.setActive(true);
+ worker.setActive(false);
+}
diff --git a/tests/system_monitor.py b/tests/system_monitor.py
new file mode 100644
index 0000000..b11a03b
--- /dev/null
+++ b/tests/system_monitor.py
@@ -0,0 +1,325 @@
+#!/usr/bin/env python3
+"""System Monitor input, disposable process actions and worker lifetime.
+
+Every signal target is a child created here, selected by a unique comm value.
+Compositors, themes, state and application databases stay in a private session.
+"""
+import os
+from pathlib import Path
+import signal
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+from PIL import Image, ImageChops
+from files_browser import wait_for
+from ipc_client import IPCClient, ROOT, spawn_compositor, stop_process
+
+
+def switches(pid):
+ total = 0
+ for status in Path(f"/proc/{pid}/task").glob("*/status"):
+ try:
+ for line in status.read_text().splitlines():
+ if line.startswith(("voluntary_ctxt_switches:", "nonvoluntary_ctxt_switches:")):
+ total += int(line.split()[1])
+ except FileNotFoundError:
+ pass
+ return total
+
+
+def check_signal_guard(tmp, guard, targets):
+ """Prove the guard with two disposable children, before using the UI."""
+ probe_dir = tmp / "guard-probe"
+ probe_dir.mkdir()
+ source = probe_dir / "probe.c"
+ source.write_text('''#define _GNU_SOURCE
+#include <errno.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+int main(int argc, char **argv) {
+ if (argc != 3) return 1;
+ int denied = syscall(SYS_pidfd_open, atoi(argv[2]), 0);
+ int allowed = syscall(SYS_pidfd_open, atoi(argv[1]), 0);
+ if (denied < 0 || allowed < 0) return 2;
+ if (syscall(SYS_pidfd_send_signal, denied, SIGTERM, 0, 0) != -1 || errno != EPERM) return 3;
+ if (syscall(SYS_pidfd_send_signal, allowed, SIGTERM, 0, 0) != 0) return 4;
+ close(denied); close(allowed);
+ return 0;
+}
+''')
+ binary = probe_dir / "rediwm-monitor"
+ subprocess.run(["cc", "-Wall", "-Wextra", "-Werror", str(source), "-o", str(binary)], check=True)
+ allowed = subprocess.Popen(["/bin/sleep", "120"])
+ denied = subprocess.Popen(["/bin/sleep", "120"])
+ try:
+ start = Path(f"/proc/{allowed.pid}/stat").read_text().rsplit(")", 1)[1].split()[19]
+ targets.write_text(f"{os.getpid()}\n{allowed.pid} {start}\n")
+ subprocess.run([str(binary), str(allowed.pid), str(denied.pid)], check=True, timeout=10,
+ env=dict(os.environ, LD_PRELOAD=str(guard), REDIWM_TEST_MONITOR_TARGETS=str(targets)))
+ assert allowed.wait(timeout=5) == -signal.SIGTERM
+ assert denied.poll() is None, "signal guard did not protect the unlisted fixture"
+ finally:
+ for child in (allowed, denied):
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=5)
+ targets.write_text(f"{os.getpid()}\n")
+
+
+def run(scale, workspace):
+ with tempfile.TemporaryDirectory(prefix="rediwm-monitor-") as directory:
+ tmp = Path(directory)
+ config = ('[compositor]\nxwayland = false\n' +
+ ('desktop_mode = "workspaces"\n' if workspace else '') +
+ '[theme]\napp_bg = "#203040"\n')
+ env = {"HOME": directory, "XDG_CONFIG_HOME": str(tmp / "config"),
+ "XDG_DATA_HOME": str(tmp / "data"), "XDG_CACHE_HOME": str(tmp / "cache"),
+ "DBUS_SESSION_BUS_ADDRESS": "", "REDIWM_FILES_DEVICES": "0"}
+ guard = tmp / "monitor-guard.so"
+ subprocess.run(["cc", "-shared", "-fPIC", "-Wall", "-Wextra", "-Werror", "-pthread",
+ str(ROOT / "tests/system_monitor_guard.c"), "-o", str(guard)], check=True)
+ targets = tmp / "signal-targets"
+ targets.write_text(f"{os.getpid()}\n")
+ check_signal_guard(tmp, guard, targets)
+ env.update(LD_PRELOAD=str(guard), REDIWM_TEST_MONITOR_TARGETS=str(targets))
+ compositor, log = spawn_compositor(tmp, scale=str(scale), config_content=config, env_extra=env,
+ binary=os.environ.get("REDIWM_TEST_BINARY"))
+ fixtures = []
+ monitor_pid = None
+ try:
+ with IPCClient(tmp, timeout=20) as ipc:
+ def windows():
+ return [w for w in ipc.get_windows() if w["app_id"] == "rediwm-monitor"]
+
+ def monitor():
+ return next(iter(windows()), None)
+
+ def chord(*codes):
+ for code in codes:
+ ipc.key(code, True)
+ for code in reversed(codes):
+ ipc.key(code, False)
+
+ def settled():
+ ipc.wait_for("window_geometry_settled", window_id=monitor()["id"])
+ ipc.wait_for_frame()
+
+ def box():
+ return ipc.get_window_debug(monitor()["id"])["client_box"]
+
+ def click(x, y):
+ b = box()
+ ipc.click_at(round(b["x"] + x), round(b["y"] + y))
+
+ def shot(name, graph=False):
+ path = tmp / f"{name}.png"
+ ipc.wait_for_frame()
+ ipc.screenshot(path=str(path))
+ with Image.open(path) as image:
+ b = box()
+ output = ipc.get_outputs()[0]
+ factor = image.width / output["logical_width"]
+ region = ((b["x"] + 16, b["y"] + 68, b["x"] + b["width"] - 16, b["y"] + 134)
+ if graph else (b["x"], b["y"], b["x"] + b["width"], b["y"] + b["height"]))
+ return image.convert("RGB").crop(tuple(round(v * factor) for v in region))
+
+ def idle(label):
+ time.sleep(.4) # finish pending buffer release and hover transitions
+ before = switches(monitor_pid)
+ time.sleep(2.2)
+ delta = switches(monitor_pid) - before
+ assert delta <= 2, f"{label}: monitor kept waking ({delta} context switches)"
+
+ for _ in range(3):
+ chord(29, 56, 111) # Ctrl+Alt+Delete, including activation while starting
+ ipc.wait_for("window_mapped", app_id="rediwm-monitor", timeout_ms=15000)
+ settled()
+ assert len(windows()) == 1, windows()
+ window_id = monitor()["id"]
+ monitor_pid = monitor()["pid"]
+ time.sleep(1.2)
+ debug = ipc.get_window_debug(window_id)
+ assert debug["buffer_scale"] == 1, debug
+ assert abs(debug["buffer_width"] - round(debug["client_box"]["width"] * scale)) <= 1, debug
+ assert shot("initial").getpixel((4, 4)) == (32, 48, 64)
+
+ # Background collection follows visibility, independently of keyboard focus.
+ ipc.open_control_center()
+ before = switches(monitor_pid)
+ time.sleep(2.2)
+ assert switches(monitor_pid) - before >= 3, "collection stopped on focus loss"
+ settings = next(w for w in ipc.get_windows() if w["backend"] == "shell")
+ ipc.close_window(settings["id"])
+ ipc.focus_window(window_id)
+ settled()
+
+ # Pause has no recurring worker or theme-stat timer.
+ click(box()["width"] - 80, 171)
+ idle("paused")
+ paused = shot("paused", True)
+ time.sleep(1.2)
+ assert ImageChops.difference(paused, shot("still-paused", True)).getbbox() is None
+
+ # Atomic theme replacement still wakes a paused app.
+ changed = tmp / "theme-new.toml"
+ changed.write_text(config.replace("#203040", "#304050"))
+ changed.replace(tmp / "rediwm-config.toml")
+ wait_for(lambda: shot("theme").getpixel((4, 4)) == (48, 64, 80), "live app theme did not update")
+ click(box()["width"] - 80, 171)
+ time.sleep(1.2)
+
+ # Minimize is a real xdg-shell v6 suspended configure. Restore
+ # starts a fresh interval and repeated activation keeps this ID.
+ ipc.minimize(window_id)
+ idle("minimized")
+ for _ in range(2):
+ chord(29, 56, 111)
+ wait_for(lambda: monitor() and not monitor()["is_minimized"], "shortcut did not restore monitor")
+ settled()
+ assert len(windows()) == 1 and monitor()["id"] == window_id
+ before = switches(monitor_pid)
+ time.sleep(2.2)
+ assert switches(monitor_pid) - before >= 3, "restored monitor did not resume"
+ if workspace:
+ ipc.action("switch_workspace", {"workspace": 9})
+ chord(29, 56, 111)
+ ipc.wait_for("window_focused", window_id=window_id)
+ assert monitor()["id"] == window_id and len(windows()) == 1
+
+ # Resize through maximize and return; the controls remain usable.
+ ipc.maximize(window_id)
+ settled()
+ assert box()["width"] > 640
+ ipc.maximize(window_id)
+ settled()
+
+ def fixture(ignore_term, replace_with=None):
+ name = f"rmon{os.getpid()}-{len(fixtures)}"[:15]
+ program = ('import ctypes,signal,time,sys;'
+ f'ctypes.CDLL(None).prctl(15,{name.encode()!r},0,0,0);' +
+ ('signal.signal(signal.SIGTERM,signal.SIG_IGN);' if ignore_term else '') +
+ 'print("ready",flush=True);' +
+ ('sys.stdin.readline();import os;os.execv(sys.argv[1],["rediwm","120"])'
+ if replace_with else 'time.sleep(120)'))
+ argv = [sys.executable, "-c", program]
+ if replace_with:
+ argv.append(str(replace_with))
+ child = subprocess.Popen(argv, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True)
+ fixtures.append(child)
+ assert child.stdout.readline().strip() == "ready"
+ stat = Path(f"/proc/{child.pid}/stat").read_text().rsplit(")", 1)[1].split()
+ with targets.open("a") as allowed:
+ allowed.write(f"{child.pid} {stat[19]}\n")
+ time.sleep(1.2) # next collector snapshot contains this fixture
+ chord(29, 33) # Ctrl+F
+ chord(29, 30) # Ctrl+A
+ ipc.type_text(name)
+ time.sleep(.2)
+ chord(102) # Home edits the field; Down transfers to the process list
+ chord(108)
+ time.sleep(.15)
+ return child
+
+ normal = fixture(False)
+ chord(111) # Delete sends TERM only to the selected fixture
+ wait_for(lambda: normal.poll() is not None, "End process did not terminate fixture")
+ assert normal.returncode == -signal.SIGTERM
+
+ stubborn = fixture(True)
+ chord(111)
+ time.sleep(.25)
+ assert stubborn.poll() is None, "fixture did not ignore SIGTERM"
+ chord(42, 111) # Shift+Delete opens the named confirmation
+ time.sleep(.2)
+ confirmation = shot("force-confirm")
+ assert stubborn.poll() is None, "force quit ran before confirmation"
+ chord(1) # Escape cancels
+ time.sleep(.2)
+ assert stubborn.poll() is None
+ assert ImageChops.difference(confirmation, shot("cancelled")).getbbox()
+ chord(42, 111)
+ time.sleep(.15)
+ chord(15) # Cancel is focused first; Tab focuses Force quit
+ chord(28)
+ wait_for(lambda: stubborn.poll() is not None, "confirmed Force quit did not terminate fixture")
+ assert stubborn.returncode == -signal.SIGKILL
+
+ # A confirmation owns its identity even after the target exits.
+ gone = fixture(True)
+ chord(42, 111)
+ time.sleep(.15)
+ gone.kill()
+ gone.wait(timeout=5)
+ time.sleep(1.2) # list refresh clears selection while confirmation keeps its identity
+ chord(15)
+ chord(28)
+ time.sleep(.15)
+ assert monitor()["id"] == window_id
+
+ # Recheck protection at execution: this disposable process
+ # execs a protected executable name while confirmation is open.
+ protected_exe = tmp / "rediwm"
+ shutil.copyfile("/bin/sleep", protected_exe)
+ protected_exe.chmod(0o700)
+ protected = fixture(True, protected_exe)
+ chord(42, 111)
+ protected.stdin.write("exec\n")
+ protected.stdin.flush()
+ wait_for(lambda: Path(f"/proc/{protected.pid}/exe").resolve() == protected_exe,
+ "fixture did not exec the protected name")
+ time.sleep(1.2)
+ chord(15)
+ chord(28)
+ time.sleep(.15)
+ assert protected.poll() is None, "confirmation bypassed refreshed session protection"
+
+ # Close joins the worker, even if a sample has just started.
+ chord(29, 16) # Ctrl+Q
+ ipc.wait_for("window_closed", window_id=window_id)
+ wait_for(lambda: not Path(f"/proc/{monitor_pid}").exists(), "monitor worker outlived its window")
+ assert not windows()
+ # A paused app stays paused across minimize/restore, and a
+ # hidden app must still consume close and join its worker.
+ chord(29, 56, 111)
+ ipc.wait_for("window_mapped", app_id="rediwm-monitor")
+ settled()
+ window_id = monitor()["id"]
+ monitor_pid = monitor()["pid"]
+ click(box()["width"] - 80, 171)
+ ipc.minimize(window_id)
+ chord(29, 56, 111)
+ wait_for(lambda: not monitor()["is_minimized"], "paused monitor did not restore")
+ settled()
+ idle("restored while paused")
+ ipc.minimize(window_id)
+ ipc.close_window(window_id)
+ ipc.wait_for("window_closed", window_id=window_id)
+ wait_for(lambda: not Path(f"/proc/{monitor_pid}").exists(), "hidden monitor did not stop")
+ print(f"System Monitor: scale={scale} mode={'workspaces' if workspace else 'canvas'} passed", flush=True)
+ finally:
+ for child in fixtures:
+ if child.poll() is None:
+ child.kill()
+ child.wait(timeout=5)
+ if child.stdout:
+ child.stdout.close()
+ if child.stdin:
+ child.stdin.close()
+ stop_process(compositor)
+ log.close()
+ errors = (tmp / "compositor.log").read_text()
+ if "panic" in errors or "error(gpa)" in errors:
+ print(errors[-6000:], file=sys.stderr)
+ raise AssertionError("compositor or monitor reported a panic/leak")
+
+
+if __name__ == "__main__":
+ os.umask(0o077)
+ scale = float(os.environ.get("REDIWM_TEST_SCALE", "1"))
+ run(scale, False)
+ run(scale, True)
diff --git a/tests/system_monitor_guard.c b/tests/system_monitor_guard.c
new file mode 100644
index 0000000..33714b2
--- /dev/null
+++ b/tests/system_monitor_guard.c
@@ -0,0 +1,126 @@
+/* Noninstalled LD_PRELOAD fixture. Supervise real signal syscalls so a UI
+ * selection regression cannot signal anything except this test's children.
+ * The production monitor contains no test hooks and still uses real pidfds. */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/filter.h>
+#include <linux/seccomp.h>
+#include <pthread.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/prctl.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+extern char *program_invocation_short_name;
+static const char *targets;
+static int listener;
+
+static int allowed_target(int pid) {
+ FILE *file = fopen(targets, "re");
+ if (!file) return 0;
+ int owner = 0, candidate = 0;
+ unsigned long long start = 0, wanted = 0;
+ if (fscanf(file, "%d", &owner) != 1) { fclose(file); return 0; }
+ while (fscanf(file, "%d %llu", &candidate, &start) == 2) {
+ if (candidate == pid) { wanted = start; break; }
+ }
+ fclose(file);
+ if (!wanted || owner <= 0 || pid <= 1) return 0;
+
+ char path[80], stat[4096];
+ snprintf(path, sizeof(path), "/proc/%d/stat", pid);
+ int fd = open(path, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) return 0;
+ ssize_t n = read(fd, stat, sizeof(stat) - 1);
+ close(fd);
+ if (n <= 0) return 0;
+ stat[n] = 0;
+ char *fields = strrchr(stat, ')');
+ if (!fields) return 0;
+ fields++;
+ char *save = NULL;
+ int parent = 0;
+ start = 0;
+ for (int i = 0; i <= 19; i++) {
+ char *field = strtok_r(i ? NULL : fields, " \n", &save);
+ if (!field) return 0;
+ if (i == 1) parent = (int)strtol(field, NULL, 10);
+ if (i == 19) start = strtoull(field, NULL, 10);
+ }
+ /* Parent and start time also reject any reused fixture PID. */
+ return parent == owner && start == wanted;
+}
+
+static int pidfd_target(int tid, int fd) {
+ char path[96], line[256];
+ snprintf(path, sizeof(path), "/proc/%d/fdinfo/%d", tid, fd);
+ FILE *file = fopen(path, "re");
+ if (!file) return -1;
+ int pid = -1;
+ while (fgets(line, sizeof(line), file)) {
+ if (sscanf(line, "Pid: %d", &pid) == 1) break;
+ }
+ fclose(file);
+ return pid;
+}
+
+static void *supervise(void *unused) {
+ (void)unused;
+ for (;;) {
+ struct seccomp_notif request = {0};
+ struct seccomp_notif_resp response = {0};
+ if (ioctl(listener, SECCOMP_IOCTL_NOTIF_RECV, &request) < 0) {
+ if (errno == EINTR || errno == ENOENT) continue;
+ _exit(125); /* Fail closed if supervision stops. */
+ }
+ int permit = 0;
+ int nr = request.data.nr;
+ if (nr == __NR_pidfd_send_signal) {
+ int sig = (int)request.data.args[1];
+ int pid = pidfd_target((int)request.pid, (int)request.data.args[0]);
+ permit = (sig == SIGTERM || sig == SIGKILL) && allowed_target(pid);
+ } else if (nr == __NR_kill) {
+ int pid = (int)request.data.args[0];
+ permit = pid == getpid() || allowed_target(pid);
+ } else if (nr == __NR_tgkill) {
+ /* Permit a runtime to signal its own threads, never another app. */
+ permit = (int)request.data.args[0] == getpid();
+ }
+ response.id = request.id;
+ if (permit) response.flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE;
+ else response.error = -EPERM;
+ if (ioctl(listener, SECCOMP_IOCTL_NOTIF_SEND, &response) < 0 && errno != ENOENT)
+ _exit(125);
+ }
+ return NULL;
+}
+
+__attribute__((constructor)) static void install_guard(void) {
+ if (strcmp(program_invocation_short_name, "rediwm-monitor") != 0) return;
+ targets = getenv("REDIWM_TEST_MONITOR_TARGETS");
+ if (!targets) _exit(125);
+ struct sock_filter filter[] = {
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_pidfd_send_signal, 4, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_kill, 3, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tgkill, 2, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tkill, 1, 0),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_USER_NOTIF),
+ };
+ struct sock_fprog program = { .len = sizeof(filter) / sizeof(filter[0]), .filter = filter };
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) _exit(125);
+ listener = (int)syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_NEW_LISTENER, &program);
+ if (listener < 0) _exit(125);
+ if (fcntl(listener, F_SETFD, FD_CLOEXEC) != 0) _exit(125);
+ pthread_t thread;
+ if (pthread_create(&thread, NULL, supervise, NULL) != 0) _exit(125);
+ pthread_detach(thread);
+}