RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
print settings update
oxydizer299fb0aabaa9
diff --git a/README.md b/README.mdindex 4fa2d8f..2638a71 100644--- a/README.md+++ b/README.md@@ -60,7 +60,11 @@ libseccomp, libarchive, libjpeg, libpng, libwebp and GNU Readline. Files embedsthe pinned libvterm 0.3.3 source (downloaded by Zig; no system libvterm needed). Optional:Xwayland, `foot`, `brightnessctl`, `gio`/`xdg-open`, `git` (optional).-Printer support uses an existing CUPS server (`cups`).+Printer support links against `libcups` (CUPS development headers are needed to+build). Settings → Printers uses `cups-pk-helper` when installed, or talks directly+to the local CUPS server and prompts for a CUPS administrator account when needed.+The CUPS server and helper are optional runtime packages. RediWM does not install+printer drivers or change USB rules.Run from a checkout, `scripts/install.sh` builds that checkout (dependencies,then `install-session.sh` with the arguments you give it).diff --git a/TESTING.md b/TESTING.mdindex 1656606..9230e4a 100644--- a/TESTING.md+++ b/TESTING.md@@ -34,7 +34,10 @@ compiler, `wayland-scanner` and wayland-protocols; D-Bus suites need PyGObject,`tests/printers.py` against the real headless Settings page. It needs the regularintegration dependencies above, `wl-paste` (`wl-clipboard`), PyGObject/Gio/GLib,`dbus-daemon`, and a C compiler capable of a small shared `LD_PRELOAD` fixture.-It does not require installed CUPS, cups-pk-helper or a printer.+It needs libcups and its development headers, but does not require a running+CUPS server, cups-pk-helper or a printer. `tests/printers_direct.py` also exercises+the native backend against private schedulers: queue operations, PPD editing,+rename, authentication retry, password cancellation and page teardown.```shzig build test-printers@@ -323,7 +326,8 @@ actions against disposable children, and worker pause/resume/cancellation.`python3 tests/system_monitor.py` covers shortcut launch and restore in bothdesktop modes, search, keyboard actions, named force-quit confirmation,disappearing targets, resize, live theme updates while paused, focus loss,-minimize/restore and idle worker lifetime. Repeat with `REDIWM_TEST_SCALE=1.5`.+minimize/restore, Files-style row hover/selection, pointer leave and idle worker+lifetime. Repeat with `REDIWM_TEST_SCALE=1.5`.The noninstalled preload fixture uses seccomp user notifications to permitsignals only to recorded disposable child identities, and verifies that gateagainst an unlisted disposable child before exercising UI actions. These testsdiff --git a/build.zig b/build.zigindex 9a780b7..163ed8c 100644--- a/build.zig+++ b/build.zig@@ -145,6 +145,8 @@ pub fn build(b: *std.Build) void {compositor.root_module.addImport("wlroots", wlroots);compositor.root_module.addImport("pixman", pixman);compositor.root_module.linkSystemLibrary("wayland-server", .{});+ compositor.root_module.linkSystemLibrary("cups", .{});+ compositor.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });compositor.root_module.linkSystemLibrary("xkbcommon", .{});compositor.root_module.linkSystemLibrary("pixman-1", .{});compositor.root_module.linkSystemLibrary("freetype2", .{});@@ -477,6 +479,8 @@ pub fn build(b: *std.Build) void {ui_tests_module.addImport("wlroots", wlroots);ui_tests_module.addImport("pixman", pixman);ui_tests_module.linkSystemLibrary("wayland-server", .{});+ ui_tests_module.linkSystemLibrary("cups", .{});+ ui_tests_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });ui_tests_module.linkSystemLibrary("xkbcommon", .{});ui_tests_module.linkSystemLibrary("pixman-1", .{});ui_tests_module.linkSystemLibrary("freetype2", .{});@@ -527,6 +531,8 @@ pub fn build(b: *std.Build) void {printing_tests.root_module.addImport("dbus", dbus_mod);printing_tests.root_module.addImport("wayland", wayland);printing_tests.root_module.linkSystemLibrary("wayland-server", .{});+ printing_tests.root_module.linkSystemLibrary("cups", .{});+ printing_tests.root_module.addCSourceFile(.{ .file = b.path("src/printing/direct.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-deprecated-declarations" } });const run_printing_tests = b.addRunArtifact(printing_tests);test_step.dependOn(&run_printing_tests.step);const printers_integration = b.addSystemCommand(&.{"python3"});@@ -535,6 +541,10 @@ pub fn build(b: *std.Build) void {const printers_step = b.step("test-printers", "Test printer diagnostics and private CUPS page lifecycle");printers_step.dependOn(&run_printing_tests.step);printers_step.dependOn(&printers_integration.step);+ const printers_direct = b.addSystemCommand(&.{"python3"});+ printers_direct.addFileArg(b.path("tests/printers_direct.py"));+ printers_direct.step.dependOn(&printers_integration.step);+ printers_step.dependOn(&printers_direct.step);// Dependency-module tests are not collected by the executable's test root.const shared_ui_tests = b.addTest(.{ .root_module = ui_mod });const shared_config_tests = b.addTest(.{ .root_module = config_mod });diff --git a/docs/plans/printers-direct-cups.md b/docs/plans/printers-direct-cups.mdnew file mode 100644index 0000000..60064de--- /dev/null+++ b/docs/plans/printers-direct-cups.md@@ -0,0 +1,65 @@+# Direct CUPS administration++Add a local libcups administration backend when cups-pk-helper is absent.+Keep the established helper path when available; backend selection happens+before a request, never by retrying a failed mutation against another backend.+The existing canonical-local-server gate remains in force. Remote/TLS inventory+support is separate work and must not silently redirect to the local scheduler.++Implementation sequence:++1. Add a page-owned native worker with an eventfd completion/challenge channel,+ bounded local connection/I/O, cancellation, and thread-local libcups state.+ Keep the existing validated actions and chained add/PPD cleanup state machine.+2. Map the helper-independent operations to IPP: discovery, creation, deletion,+ enable/accept, default, description, device, defaults and PPD editing. Rename+ must preserve settings/PPD and reject active jobs/collisions before clone/delete;+ report uncertain or partial changes and refresh instead of automatic rollback.+3. Add username/password controls backed by locked and wiped storage. Only show+ them in response to a CUPS challenge, bound retries, cancel on page hide, and+ never retain passwords between operations or log server-provided prompts.+4. Extend isolated tests for helper-absent administration, challenge/retry/cancel,+ denial, discovery filtering, partial operations, and responsive page teardown.+ Existing helper tests remain regression coverage.+5. Update package/build guidance and subsystem notes. Run Debug and ReleaseSafe+ builds, zig build test, and printer integration tests. Compare failures against+ HEAD in an isolated worktree before attributing regressions.++No production test environment switches, automatic package installation, host+queue changes, or test print jobs are part of this work. Hardware printing and+stock CUPS authentication policy still require separate qualification.++Implementation status: the helper-absent backend, secure credentials controls,+IPP operations, PPD default editing and guarded clone/delete rename are now+implemented. Helper-present behavior remains covered by the original suite.+The private libcups suite covers successful operations, collisions, permission+denial, wrong-password retries and exhaustion, partial rename, active-job refusal,+and cancellation during both I/O and a password challenge. The Settings test+checks actual secret widgets, fresh authentication on subsequent operations,+cancel and hide. No real printer has been exercised.++The direct backend follows the public+[CUPS authentication and request APIs](https://openprinting.github.io/cups/doc/cupspm.html).+PPD support intentionally uses CUPS 2.x compatibility APIs, as the existing+printer page exposes legacy driver controls. Build/install dependencies now+include libcups headers. A real private cupsd check could not run here because+the installed cupsd executable is not executable by this user; synthetic tests+must not be described as stock scheduler/policy qualification.++Direct rename refuses queues in CUPS classes before mutating them; the page+does not model class membership and must not silently discard it.++Validation completed:++- Debug and ReleaseSafe builds passed.+- `zig build test` passed on the final source.+- `zig build test-printers --summary all` and+ `zig build test-printers -Doptimize=ReleaseSafe --summary all` both passed:+ 59/59 build steps, 73/73 printing unit tests, the existing helper integration+ suite, and the new native/Settings integration suite.+- Native tests include the 20-second I/O deadline, class-member rename refusal,+ PPD preservation, and no timed wakeups in either idle administration thread.+- `git diff --check`, Python syntax checks and installer shell syntax passed.++These are isolated software checks, not evidence of physical paper output or+stock CUPS authentication policy on a deployed desktop.diff --git a/docs/plans/printers.md b/docs/plans/printers.mdindex 3a1777f..488ed74 100644--- a/docs/plans/printers.md+++ b/docs/plans/printers.md@@ -14,7 +14,8 @@ Implemented scope:cleartext TCP CUPS endpoints. System/user `client.conf`, `CUPS_SERVER` andencryption preferences are checked without falling back to a differentserver. TLS, authentication and escaped configuration syntax are unsupported.-* Local-default-server administration uses `cups-pk-helper`: discovery, queue+* Local-default-server administration uses `cups-pk-helper` when available,+ or a direct libcups worker with CUPS authentication: discovery, queuecreation, enabling/disabling, accepting/rejecting jobs, descriptions, queuerename/removal, connection changes and the system default. Custom Unix andremote schedulers remain read-only for these actions. CUPS service start uses@@ -25,13 +26,13 @@ Implemented scope:and raw queues/third-party driver guidance are explicit. Vendor backends mustcome from the current CUPS discovery result, never arbitrary typed input.* Queue-name collisions are checked before administration. Removal and queue- rename require separate named confirmations. Rename is the helper's+ rename require separate named confirmations. Rename is anon-atomic clone/delete operation, with known-job guards, refreshed queuechecks and migration of personal defaults/private observations after success.* Supported IPP values and bounded PPD UI declarations provide media,resolution, colour, duplex, quality and exposed label controls. Driver choices- use the PPD-aware helper API and are refreshed for verification. CUPS can- report conflicting IPP/PPD defaults; an accepted request is not presented as+ use the PPD-aware helper API or direct PPD editing and are refreshed for+ verification. CUPS can report conflicting IPP/PPD defaults; an accepted request is not presented asa verified setting when the resulting value cannot be established.* Per-user defaults preserve existing `~/.cups/lpoptions` options, destinations,instances and comments through atomic replacement. `LPDEST`/`PRINTER` overridesdiff --git a/docs/system-monitor.md b/docs/system-monitor.mdindex c098015..aaabac6 100644--- a/docs/system-monitor.md+++ b/docs/system-monitor.md@@ -23,6 +23,10 @@ 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.+Process rows use Files' rounded hover and selection cards. The hover fades in+and glides between rows; selection fades use the accent outline. Both follow+the theme and animation settings and stop requesting frames when settled.+| Key | Action || --- | --- || Ctrl+F | Focus search and select its text |@@ -48,7 +52,9 @@ Fractional scaling uses fractional-scale-v1 and viewporter when available.## Existing shortcut configurationBoth presets now use `open_system_monitor`. Explicit user bindings are-preserved. For an older canvas config containing+preserved. Existing canvas shortcut lists inherit Ctrl+Alt+Delete when that+key is unassigned, so **Open System Monitor** also appears under **System**+in Settings → Keyboard Shortcuts. For an older canvas config containing`"ctrl+alt+delete" = "poweroff"`, replace that line in`~/.config/rediwm/config.toml`:diff --git a/scripts/install.sh b/scripts/install.shindex a860378..12e4f9e 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -215,7 +215,7 @@ case "$FAMILY" inarch)deps="wayland wayland-protocols pixman libxkbcommon \freetype2 harfbuzz fontconfig librsvg cairo pango libinput poppler-glib libseccomp \- libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam mesa pkgconf git python readline \+ libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam libcups mesa pkgconf git python readline \xorg-xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"if [ "$PRIVATE_WLROOTS" = no ]; thendeps="wlroots0.20 $deps"@@ -238,13 +238,13 @@ case "$FAMILY" inlibxcb-res0-dev libxcb-xfixes0-dev libxcb-dri3-dev libxcb-present-dev \libxcb-render-util0-dev libxcb-shm0-dev libxcb-xinput-dev xwayland \libfreetype-dev libharfbuzz-dev libfontconfig-dev librsvg2-dev libcairo2-dev libpango1.0-dev libgdk-pixbuf-2.0-dev \- libglib2.0-dev libarchive-dev libwebp-dev libpng-dev libjpeg-dev libpulse-dev libpipewire-0.3-dev libpam0g-dev libpoppler-glib-dev libseccomp-dev libreadline-dev \+ libglib2.0-dev libarchive-dev libwebp-dev libpng-dev libjpeg-dev libpulse-dev libpipewire-0.3-dev libpam0g-dev libcups2-dev libpoppler-glib-dev libseccomp-dev libreadline-dev \xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk";;fedora)deps="wayland-devel wayland-protocols-devel pixman-devel libxkbcommon-devel \freetype-devel harfbuzz-devel fontconfig-devel librsvg2-devel cairo-devel pango-devel libinput-devel \- libarchive-devel libwebp-devel libpng-devel libjpeg-turbo-devel pulseaudio-libs-devel pipewire-devel pam-devel poppler-glib-devel libseccomp-devel \+ libarchive-devel libwebp-devel libpng-devel libjpeg-turbo-devel pulseaudio-libs-devel pipewire-devel pam-devel cups-devel poppler-glib-devel libseccomp-devel \mesa-libEGL-devel mesa-libGLES-devel glibc-devel readline-devel \pkgconf-pkg-config git python3 \xorg-x11-server-Xwayland \@@ -261,7 +261,7 @@ case "$FAMILY" inopensuse)deps="wlroots-devel wayland-devel wayland-protocols-devel libpixman-1-0-devel libxkbcommon-devel \freetype2-devel harfbuzz-devel fontconfig-devel librsvg-devel cairo-devel pango-devel libinput-devel \- libarchive-devel libwebp-devel libpng16-devel libjpeg8-devel libpulse-devel pipewire-devel pam-devel libpoppler-glib-devel libseccomp-devel \+ libarchive-devel libwebp-devel libpng16-devel libjpeg8-devel libpulse-devel pipewire-devel pam-devel cups-devel libpoppler-glib-devel libseccomp-devel \Mesa-libEGL-devel Mesa-libGLESv2-devel glibc-devel readline-devel \pkg-config git python3 \xwayland \@@ -270,7 +270,7 @@ case "$FAMILY" ingentoo)deps="gui-libs/wlroots dev-libs/wayland dev-libs/wayland-protocols x11-libs/pixman x11-libs/libxkbcommon \media-libs/freetype media-libs/harfbuzz media-libs/fontconfig gnome-base/librsvg x11-libs/cairo x11-libs/pango dev-libs/libinput \- app-arch/libarchive media-libs/libwebp media-libs/libpng media-libs/libjpeg-turbo media-libs/libpulse media-video/pipewire sys-libs/pam \+ app-arch/libarchive media-libs/libwebp media-libs/libpng media-libs/libjpeg-turbo media-libs/libpulse media-video/pipewire sys-libs/pam net-print/cups \media-libs/mesa sys-libs/readline \virtual/pkgconfig dev-vcs/git dev-lang/python \x11-base/xwayland \diff --git a/src/config/loader.zig b/src/config/loader.zigindex 7fd1d3e..8ed874e 100644--- a/src/config/loader.zig+++ b/src/config/loader.zig@@ -739,13 +739,13 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config}if (seen_keybinds) {- // Keep laptop controls, nested-session switching and the way out of- // an inhibiting client available in existing configs too. Explicit- // bindings (including noop) always take precedence over these defaults.+ // Keep laptop controls, System Monitor, nested-session switching and+ // the way out of an inhibiting client available in existing configs too.+ // Explicit bindings (including noop) always take precedence.const defaults = try parseKeybindsOnly(cfg.arena.allocator(), default_file.source);for (defaults) |bind| {const nested_switcher = bind.modifiers.ctrl and (bind.action == .focus_next or bind.action == .focus_prev);- if (!keybinds.isHardwareAction(bind.action) and !nested_switcher and bind.action != .restore_shortcuts) continue;+ if (!keybinds.isHardwareAction(bind.action) and !nested_switcher and bind.action != .restore_shortcuts and bind.action != .open_system_monitor) continue;const key = keybinds.pack(bind.modifiers, bind.sym);var overridden = false;for (bind_list.items) |custom| {diff --git a/src/config/loader_tests.zig b/src/config/loader_tests.zigindex 101462b..823e46d 100644--- a/src/config/loader_tests.zig+++ b/src/config/loader_tests.zig@@ -93,12 +93,25 @@ test "empty config keeps built-in zoom steps and default keybinds" {}test "System Monitor defaults preserve explicit canvas and workspace shortcut overrides" {+ const binding = try keybinds.parseKeybind("Ctrl+Alt+Delete");+ for ([_][]const u8{+ "[keybinds]\n",+ "[keybinds]\n\"Super+q\" = \"close_window\"\n\"Ctrl+Alt+Shift+Delete\" = \"poweroff\"\n",+ }) |source| {+ var existing = try parse(std.testing.allocator, source, "mem");+ defer existing.deinit();+ try std.testing.expectEqual(Action.open_system_monitor, existing.lookupKeybind(binding.modifiers, binding.sym).?);+ existing.compositor.desktop_mode = .workspaces;+ try std.testing.expectEqual(Action.open_system_monitor, existing.lookupKeybind(binding.modifiers, binding.sym).?);+ }var cfg = try parse(std.testing.allocator, "[keybinds]\n\"Ctrl+Alt+Delete\" = \"poweroff\"\n[keybinds.workspace]\n\"Ctrl+Alt+Delete\" = \"noop\"\n", "mem");defer cfg.deinit();- const binding = try keybinds.parseKeybind("Ctrl+Alt+Delete");try std.testing.expectEqual(Action.poweroff, cfg.lookupKeybind(binding.modifiers, binding.sym).?);cfg.compositor.desktop_mode = .workspaces;try std.testing.expectEqual(Action.noop, cfg.lookupKeybind(binding.modifiers, binding.sym).?);+ var disabled_cfg = try parse(std.testing.allocator, "[keybinds]\n\"Ctrl+Alt+Delete\" = \"noop\"\n", "mem");+ defer disabled_cfg.deinit();+ try std.testing.expectEqual(Action.noop, disabled_cfg.lookupKeybind(binding.modifiers, binding.sym).?);}test "the desktop follows its section, then a legacy rediwm-desktop autostart" {diff --git a/src/config/shortcut_save.zig b/src/config/shortcut_save.zigindex 25e3bca..f1db1e1 100644--- a/src/config/shortcut_save.zig+++ b/src/config/shortcut_save.zig@@ -1,5 +1,5 @@//! Persist the effective bindings, including inherited defaults. A noop at the-//! previous key prevents the loader from restoring an inherited hardware bind.+//! previous key prevents the loader from restoring an inherited binding.const std = @import("std");const loader = @import("loader.zig");const keys = @import("keybinds.zig");@@ -103,35 +103,37 @@ pub fn saveMode(a: std.mem.Allocator, io: std.Io, path: []const u8, binds: []contry std.Io.Dir.rename(.cwd(), tmp, .cwd(), path, io);}-test "moving inherited hardware shortcuts persists and old keys can be reused" {- const a = std.testing.allocator;- const original = "# keep me\n[input]\npointer_speed = 0.4\n";- var cfg = try loader.parse(a, original, "test");- defer cfg.deinit();- var index: usize = 0;- for (cfg.keybinds, 0..) |bind, i| {- if (bind.action == .volume_up) {- index = i;- break;+test "moving inherited shortcuts persists and old keys can be reused" {+ for ([_]keys.Action{ .volume_up, .open_system_monitor }) |action| {+ const a = std.testing.allocator;+ const original = "# keep me\n[input]\npointer_speed = 0.4\n";+ var cfg = try loader.parse(a, original, "test");+ defer cfg.deinit();+ var index: usize = 0;+ for (cfg.keybinds, 0..) |bind, i| {+ if (keys.actionEql(bind.action, action)) {+ index = i;+ break;+ }}+ const key = try keys.parseKeybind("Super+F12");+ const replacement: keys.Keybind = .{ .sym = key.sym, .modifiers = key.modifiers, .action = action };+ const updated = try patch(a, original, cfg.keybinds, index, replacement);+ defer a.free(updated);+ var parsed = try loader.parse(a, updated, "test");+ defer parsed.deinit();+ try std.testing.expectEqual(@as(f32, 0.4), parsed.input.pointer_speed);+ try std.testing.expect(std.mem.indexOf(u8, updated, "# keep me") != null);+ const old = cfg.keybinds[index];+ try std.testing.expectEqual(keys.Action.noop, parsed.lookupKeybind(old.modifiers, old.sym).?);+ try std.testing.expectEqual(action, parsed.lookupKeybind(key.modifiers, key.sym).?);+ const restored = try patch(a, updated, parsed.keybinds, index, old);+ defer a.free(restored);+ var again = try loader.parse(a, restored, "test");+ defer again.deinit();+ try std.testing.expectEqual(action, again.lookupKeybind(old.modifiers, old.sym).?);+ try std.testing.expectEqual(@as(?keys.Action, null), again.lookupKeybind(key.modifiers, key.sym));}- const key = try keys.parseKeybind("Super+F12");- const replacement: keys.Keybind = .{ .sym = key.sym, .modifiers = key.modifiers, .action = .volume_up };- const updated = try patch(a, original, cfg.keybinds, index, replacement);- defer a.free(updated);- var parsed = try loader.parse(a, updated, "test");- defer parsed.deinit();- try std.testing.expectEqual(@as(f32, 0.4), parsed.input.pointer_speed);- try std.testing.expect(std.mem.indexOf(u8, updated, "# keep me") != null);- const old = cfg.keybinds[index];- try std.testing.expectEqual(keys.Action.noop, parsed.lookupKeybind(old.modifiers, old.sym).?);- try std.testing.expectEqual(keys.Action.volume_up, parsed.lookupKeybind(key.modifiers, key.sym).?);- const restored = try patch(a, updated, parsed.keybinds, index, old);- defer a.free(restored);- var again = try loader.parse(a, restored, "test");- defer again.deinit();- try std.testing.expectEqual(keys.Action.volume_up, again.lookupKeybind(old.modifiers, old.sym).?);- try std.testing.expectEqual(@as(?keys.Action, null), again.lookupKeybind(key.modifiers, key.sym));}test "moving Files restores ordinary keys and removes obsolete non-inherited noops" {diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.mdindex 5d7300e..a627af4 100644--- a/src/control_center/AGENTS.md+++ b/src/control_center/AGENTS.md@@ -49,9 +49,12 @@ Settings is an ordinary window with a compositor-drawn body (`Backend.shell`).the authority. Reports omit identities and arbitrary status messages.USB libusb queues do not require a usblp node. Read `docs/plans/printers.md`for the unqualified hardware and distribution-policy acceptance gates.- Discovered backend URIs must match the current helper catalog exactly;+ Discovered backend URIs must match the current administration catalog exactly;arbitrary typed vendor/file backends are not allowed. PPD settings use- `PrinterAddOption` after clearing stale IPP defaults, followed by readback.+ `PrinterAddOption` or direct PPD editing after clearing stale IPP defaults,+ followed by readback. Direct CUPS authentication uses the shared secret widget+ over locked storage, clears it on submit/cancel/hide, and never stores passwords+ in the section arena. Hiding also cancels any native authentication wait.* Global search uses `search_index.zig` destinations (widget names or `@` plusvisible label text), without building hidden sections. Add an index entrydiff --git a/src/control_center/sections/printers.zig b/src/control_center/sections/printers.zigindex 9e15c02..7904eae 100644--- a/src/control_center/sections/printers.zig+++ b/src/control_center/sections/printers.zig@@ -13,13 +13,14 @@ const preferences = @import("../../printing/preferences.zig");const known = @import("../../printing/known_devices.zig");const notifier = @import("../../printing/notifier.zig");const driver_options = @import("../../printing/options.zig");+const secure = @import("../../network/secure_allocator.zig").allocator;const gpa = @import("../../main.zig").gpa;const W = ui.layout.Widget;const A = std.mem.Allocator;const Form = enum { none, add, connection, remove, test_confirm, test_result, queue_rename };const Disclosure = enum { history, more_options, manage, troubleshooting, label_tools, devices };-const Field = enum { address, name, rename, loaded_width, loaded_height, measured_width, measured_height, raw_dpi, queue_name };-const field_names = [_][]const u8{ "printers_address", "printers_name", "printers_rename", "printers_loaded_width", "printers_loaded_height", "printers_measured_width", "printers_measured_height", "printers_raw_dpi", "printers_queue_name" };+const Field = enum { address, name, rename, loaded_width, loaded_height, measured_width, measured_height, raw_dpi, queue_name, auth_user };+const field_names = [_][]const u8{ "printers_address", "printers_name", "printers_rename", "printers_loaded_width", "printers_loaded_height", "printers_measured_width", "printers_measured_height", "printers_raw_dpi", "printers_queue_name", "printers_auth_user" };const Input = struct { widget: ?*W = null, data: ?ui.layout.TextInputData = null };const RangeDraft = struct { name: [128]u8 = undefined, len: usize = 0, range: cups.ipp.Range = .{ .lower = 0, .upper = 0 }, value: f32 = 0 };const PendingAdd = struct {@@ -38,6 +39,8 @@ pub const Section = struct {root: W = undefined,client: ?*printing.Client = null,administration: ?*admin.Manager = null,+ password: ui.widgets.secret_input.Input = .{ .storage = @constCast(&[_]u8{}) },+ password_focus: bool = false,listener: ?*notifier.Listener = null,listener_attempted: bool = false,admin_generation: u64 = 0,@@ -78,7 +81,9 @@ pub const Section = struct {copied: bool = false,pub fn capture(self: *Section) void {self.focused_field = null;+ self.password_focus = false;if (ui.input.current.focused) |focused| {+ if (focused.name) |name| self.password_focus = std.mem.eql(u8, name, "printers_auth_password");for (self.fields, 0..) |field, i| if (field.widget == focused) {self.focused_field = @enumFromInt(i);};@@ -91,6 +96,7 @@ pub const Section = struct {}}pub fn restoreFocus(self: *Section, cc: *panel.ControlCenter) void {+ if (self.password_focus) if (findNamed(&self.root, "printers_auth_password")) |widget| ui.input.current.focus(&cc.root, widget);if (self.focused_field) |id| if (self.fields[@intFromEnum(id)].widget) |widget| ui.input.current.focus(&cc.root, widget);if (self.reveal_target) |name| {if (findNamed(&self.root, name)) |widget| ui.widgets.scroll_container.ensureVisibleChild(&cc.body_children[1], widget);@@ -98,6 +104,8 @@ pub const Section = struct {}}pub fn hide(self: *Section) void {+ self.password.clear();+ self.password_focus = false;self.saveFields();if (self.pending_add) |pending| pending.destroy();self.pending_add = null;@@ -119,6 +127,7 @@ pub const Section = struct {pub fn deinit(self: *Section) void {self.hide();for (self.fields) |field| if (field.data) |data| gpa.free(data.value);+ if (self.password.storage.len != 0) secure.free(self.password.storage);self.arena.deinit();}};@@ -197,6 +206,29 @@ fn adminChanged(raw: *anyopaque) void {if (cc.printers.pending_option) |*pending| pending.after_admin = true;if (cc.printers.client) |client| client.act(.refresh) catch client.invalidate();};+ if (cc.printers.administration) |manager| if (!manager.authentication) {+ cc.printers.password.clear();+ };+ cc.refresh();+}+fn authenticateClicked(raw: ?*anyopaque, _: usize) void {+ const cc = owner(raw);+ const self = &cc.printers;+ const manager = self.administration orelse return;+ manager.authenticate(fieldValue(self, .auth_user), self.password.value()) catch {+ self.message = "Enter a valid CUPS administrator username and password.";+ self.password.clear();+ cc.refresh();+ return;+ };+ self.password.clear();+ self.message = "";+ cc.refresh();+}+fn cancelAuthenticationClicked(raw: ?*anyopaque, _: usize) void {+ const cc = owner(raw);+ cc.printers.password.clear();+ if (cc.printers.administration) |manager| manager.cancelAuthentication();cc.refresh();}fn cupsChanged(raw: *anyopaque) void {@@ -303,14 +335,31 @@ fn tree(self: *Section, cc: *panel.ControlCenter, a: A) !W {if (self.message.len > 0) try content.append(a, text(self.message, false));if (self.administration) |manager| {if (!std.mem.eql(u8, manager.status, "Printer administration is available; authorization may be required.")) try content.append(a, text(manager.status, true));- } else try content.append(a, text("Printer setup requires the local default CUPS server and cups-pk-helper.", true));+ if (manager.authentication) {+ if (self.password.storage.len == 0) {+ self.password.storage = try secure.alloc(u8, 4095);+ @memset(self.password.storage, 0);+ }+ const username = try cups.user(a);+ try content.append(a, try card(a, &.{+ text("Authorize printer administration", false),+ text("Enter an account permitted to administer the local CUPS server.", true),+ try entry(self, cc, a, .auth_user, "Username", username),+ .{ .name = "printers_auth_password", .kind = .{ .secret_input = .{ .placeholder = "Password", .input = &self.password } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 36 } },+ try actionRow(a, cc, &.{+ button(cc, "printers_auth_submit", "Authenticate", 0, false, authenticateClicked),+ button(cc, "printers_auth_cancel", "Cancel", 0, false, cancelAuthenticationClicked),+ }),+ }));+ }+ } else try content.append(a, text("Printer setup requires the local default CUPS server.", true));if (state) |snapshot| {if (snapshot.action_error) |err| try content.append(a, text(cups.failure(err), false));if (snapshot.failure != null) {try content.append(a, text(snapshot.platform.missing_cups, true));try content.append(a, button(cc, "printers_start", "Start CUPS", 0, !snapshot.admin_local or busy(self) or self.administration == null, startClicked));}- if (self.administration) |manager| if (manager.availability == .missing) try content.append(a, text(snapshot.platform.missing_helper, true));+if (self.form == .add or self.form == .connection) try content.append(a, try addForm(self, cc, a, snapshot));if (snapshot.cups) |data| {if (data.printers.len == 0) {diff --git a/src/files/app_items.zig b/src/files/app_items.zigindex f761af1..71d8f10 100644--- a/src/files/app_items.zig+++ b/src/files/app_items.zig@@ -36,12 +36,7 @@ pub fn renderFileItems(self: *App, cr: *c.cairo_t, viewport_h: i32) void {const glide = self.item_hover.frame;if (glide.alpha > 0) {const box = self.itemHighlight(glide);- roundedRect(cr, box.x, box.y, box.w, box.h, 6);- setSource(cr, withAlpha(ui_theme.global.app_item_hover, glide.alpha));- c.cairo_fill_preserve(cr);- setSource(cr, withAlpha(ui_theme.global.app_item_border, glide.alpha));- c.cairo_set_line_width(cr, 1);- c.cairo_stroke(cr);+ shell_ui.drawItemHighlight(cr, .{ .x = box.x, .y = box.y, .w = box.w, .h = box.h }, false, glide.alpha, glide.alpha);}var index = first;while (index < last) : (index += 1) {@@ -54,14 +49,7 @@ pub fn renderFileItems(self: *App, cr: *c.cairo_t, viewport_h: i32) void {// Items sit on the list itself; only selection and keyboard focus// draw a card here (hover is the glide above).if (item.selection_fill.alpha > 0 or item.selection_border.alpha > 0) {- roundedRect(cr, x, y, width, @floatFromInt(self.cardHeight()), 6);- if (item.selection_fill.alpha > 0) {- setSource(cr, withAlpha(ui_theme.global.app_item_selected, item.selection_fill.alpha));- c.cairo_fill_preserve(cr);- }- setSource(cr, withAlpha(accent, item.selection_border.alpha));- c.cairo_set_line_width(cr, 1);- c.cairo_stroke(cr);+ shell_ui.drawItemHighlight(cr, .{ .x = x, .y = y, .w = width, .h = @floatFromInt(self.cardHeight()) }, true, item.selection_fill.alpha, item.selection_border.alpha);}if (self.folder_drop == idx) {roundedRect(cr, x, y, width, @floatFromInt(self.cardHeight()), 6);diff --git a/src/files/app_model.zig b/src/files/app_model.zigindex 9640886..3844511 100644--- a/src/files/app_model.zig+++ b/src/files/app_model.zig@@ -89,20 +89,7 @@ pub const SizeState = union(enum) {},};-pub const SelectionFade = struct {- animation: anim.Anim = .{ .property = .opacity },- alpha: f32 = 0,-- pub fn step(self: *SelectionFade, now: i64, visible: bool) bool {- const target: f32 = if (visible) 1 else 0;- if (self.animation.to != target) self.animation.retargetTo(now, target, anim.curveFor(.start_glide_fade));- const value = self.animation.value(now);- const next = if (self.animation.settled(now)) value else @round(value / anim.rasterAlphaQuantum()) * anim.rasterAlphaQuantum();- const changed = next != self.alpha;- self.alpha = next;- return changed;- }-};+pub const SelectionFade = @import("ui").hover_glide.Fade;// Titlebar timing, with a rectangle that also fits labelled toolbar buttons.pub const ToolbarHover = struct {diff --git a/src/printing/AGENTS.md b/src/printing/AGENTS.mdindex 58d4099..7d8b6fe 100644--- a/src/printing/AGENTS.md+++ b/src/printing/AGENTS.md@@ -3,8 +3,16 @@* `cups.zig` queries the configured Unix or cleartext TCP CUPS endpoint. TLS andauthentication are explicit unsupported states; never fall back to adifferent server. Configuration read failures are not missing files.- cups-pk-helper targets its local default server: allow its actions only with- the canonical local socket, never a custom Unix or remote CUPS endpoint.+ Both administration backends target the canonical local socket, never a+ custom Unix or remote endpoint. `admin.zig` selects the helper when present,+ otherwise `direct.zig`/`direct.c` use libcups in a page-owned worker. Never+ retry an uncertain mutation through another backend. The native worker alone+ uses libcups (including its thread-local authentication state); UI credentials+ use locked storage and are wiped on submit/cancel/hide. A chain may reuse its+ CUPS connection, but completion closes it and wipes the worker password.+ The deadline watcher owns a duplicated socket descriptor, never a borrowed+ descriptor that libcups could close/reuse during authentication. It has no+ timed wakeups while idle or waiting for user input.* IPP and HTTP replies are untrusted and bounded. Socket operations share anabsolute deadline and include the worker cancellation fd in every wait.* `cups.Snapshot` owns an arena. Parser helpers allocate into that arena;diff --git a/src/printing/admin.zig b/src/printing/admin.zigindex 58ac493..bd53315 100644--- a/src/printing/admin.zig+++ b/src/printing/admin.zig@@ -1,9 +1,10 @@-//! Page-owned asynchronous printer administration. The installed cups-pk-helper-//! owns policy and privileged CUPS calls; RediWM never becomes root or runs a-//! shell. Destruction closes outstanding requests before releasing their owner.+//! Page-owned asynchronous printer administration. Use the installed helper+//! for polkit authorization, or a local libcups worker for CUPS authentication.+//! RediWM never becomes root or runs a shell. Destruction closes outstanding requests before releasing their owner.const std = @import("std");const dbus = @import("dbus");const wl = @import("wayland").server.wl;+const direct = @import("direct.zig");const setup = @import("setup.zig");const cups = @import("cups.zig");const wire = dbus.wire;@@ -58,6 +59,9 @@ pub const Manager = struct {owner: *anyopaque,changed: *const fn (*anyopaque) void,bus: ?*dbus.Connection = null,+ loop: ?*wl.EventLoop = null,+ worker: ?*direct.Worker = null,+ authentication: bool = false,closing: bool = false,availability: Availability = .loading,busy: bool = true,@@ -82,19 +86,15 @@ pub const Manager = struct {pub fn create(loop: *wl.EventLoop, env: std.process.Environ, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Manager {const self = try a.create(Manager);errdefer a.destroy(self);- self.* = .{ .owner = owner, .changed = changed };+ self.* = .{ .owner = owner, .changed = changed, .loop = loop };self.bus = dbus.Connection.openSystem(a, loop, env) catch {- self.availability = .missing;- self.busy = false;- self.status = "System bus unavailable; printer administration is unavailable.";+ self.useDirect();return self;};_ = self.bus.?.hello(self, hello) catch {self.bus.?.destroy();self.bus = null;- self.availability = .missing;- self.busy = false;- self.status = "Could not connect to the system bus.";+ self.useDirect();};if (self.bus) |bus| bus.on_disconnect = .{ .owner = self, .callback = disconnected };return self;@@ -102,6 +102,7 @@ pub const Manager = struct {pub fn destroy(self: *Manager) void {self.closing = true;+ if (self.worker) |worker| worker.destroy();if (self.bus) |bus| bus.destroy();self.option_body.deinit();self.arena.deinit();@@ -115,6 +116,7 @@ pub const Manager = struct {fn disconnected(owner: ?*anyopaque) void {const self: *Manager = @ptrCast(@alignCast(owner.?));if (self.closing) return;+ if (self.worker != null) return;self.stage = .idle;self.unavailable("System bus connection lost. Reopen Printers to reconnect.");}@@ -123,17 +125,17 @@ pub const Manager = struct {const self: *Manager = @ptrCast(@alignCast(owner.?));if (self.closing) return;const msg = result catch {- self.unavailable("Could not connect to the system bus.");+ self.useDirect();return;};if (msg.kind != .method_return) {- self.unavailable("Could not connect to the system bus.");+ self.useDirect();return;}var body: wire.Writer = .{ .allocator = a };defer body.deinit();_ = bus.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListActivatableNames", "", &body, self, activatable, 5000) catch {- self.unavailable("Could not check cups-pk-helper availability.");+ self.useDirect();};}@@ -141,7 +143,7 @@ pub const Manager = struct {const self: *Manager = @ptrCast(@alignCast(owner.?));if (self.closing) return;const msg = result catch {- self.unavailable("Could not check cups-pk-helper availability.");+ self.useDirect();return;};if (msg.kind == .method_return and std.mem.eql(u8, msg.headers.signature, "as")) {@@ -171,11 +173,11 @@ pub const Manager = struct {var body: wire.Writer = .{ .allocator = a };defer body.deinit();body.string(helper_name) catch {- self.unavailable("Could not check cups-pk-helper availability.");+ self.useDirect();return;};_ = bus.call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", "s", &body, self, hasOwner, 5000) catch {- self.unavailable("Could not check cups-pk-helper availability.");+ self.useDirect();};}@@ -183,7 +185,7 @@ pub const Manager = struct {const self: *Manager = @ptrCast(@alignCast(owner.?));if (self.closing) return;const msg = result catch {- self.unavailable("Could not check cups-pk-helper availability.");+ self.useDirect();return;};if (msg.kind == .method_return and std.mem.eql(u8, msg.headers.signature, "b")) {@@ -198,7 +200,84 @@ pub const Manager = struct {return;}}- self.unavailable("Install cups-pk-helper to add or configure printers.");+ self.useDirect();+ }++ fn useDirect(self: *Manager) void {+ if (self.worker == null) {+ const loop = self.loop orelse {+ self.unavailable("Could not start CUPS administration.");+ return;+ };+ self.worker = direct.Worker.create(loop, self, directReady) catch {+ self.unavailable("Could not start CUPS administration.");+ return;+ };+ }+ self.available();+ }++ fn send(self: *Manager, method: Method, body: *wire.Writer, reset: bool) !void {+ if (self.worker) |worker| return worker.submit(method.member, method.signature, body.bytes.items, reset);+ const bus = self.bus orelse return error.Disconnected;+ _ = try bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, body, self, reply, 120000, wire.flag_allow_interactive_authorization);+ }++ fn directReady(raw: *anyopaque) void {+ const self: *Manager = @ptrCast(@alignCast(raw));+ if (self.closing) return;+ const worker = self.worker.?;+ switch (worker.state()) {+ 1 => {+ self.authentication = true;+ self.status = "CUPS requires an administrator username and password.";+ self.notify();+ },+ 2 => {+ self.authentication = false;+ const result = worker.result();+ if (result != 0) {+ self.fail(switch (result) {+ 2 => "Printer administration was cancelled.",+ 3 => "CUPS authentication failed after three attempts. Check the administrator account and permissions.",+ 4 => "Queue rename only partly completed. Refresh and check both queues before retrying.",+ 5 => "This printer belongs to a CUPS class. Manage its class membership before renaming it here.",+ else => "CUPS refused or could not complete the request. Check authorization and refresh before retrying.",+ });+ return;+ }+ if (self.stage == .discovery) {+ var body: wire.Writer = .{ .allocator = a };+ defer body.deinit();+ worker.devices(&body) catch {+ self.fail("Invalid or oversized printer discovery reply.");+ return;+ };+ var reader: wire.Reader = .{ .bytes = body.bytes.items };+ self.readDevices(&reader) catch {+ self.fail("Invalid or oversized printer discovery reply.");+ return;+ };+ worker.finish();+ self.stage = .idle;+ self.busy = false;+ self.status = if (self.devices.len == 0) "CUPS discovered no supported printer addresses. You can enter a network address." else "Printer discovery complete.";+ self.notify();+ } else self.advance();+ },+ else => {},+ }+ }++ pub fn authenticate(self: *Manager, user: []const u8, password: []const u8) !void {+ if (!self.authentication) return error.NoChallenge;+ try self.worker.?.credentials(user, password);+ self.authentication = false;+ self.status = "Authenticating with CUPS…";+ }+ pub fn cancelAuthentication(self: *Manager) void {+ if (self.worker) |worker| worker.cancel();+ self.authentication = false;}fn available(self: *Manager) void {@@ -224,7 +303,7 @@ pub const Manager = struct {.device => |device| try self.requireDiscovered(device.uri, device.discovered),else => {},}- const bus = self.bus orelse return error.Disconnected;+ if (self.bus == null and self.worker == null) return error.Disconnected;if (action != .start_service and self.availability != .available) return error.HelperUnavailable;var body: wire.Writer = .{ .allocator = a };defer body.deinit();@@ -272,19 +351,23 @@ pub const Manager = struct {else => "Applying printer change; authorization may be required…",};if (action == .start_service) {+ const bus = self.bus orelse {+ self.fail("The system service manager is unavailable.");+ return error.Disconnected;+ };_ = bus.callWithFlags("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", method.member, method.signature, &body, self, reply, 120000, 4) catch |err| {self.fail("Could not request CUPS start.");return err;};} else {- _ = bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, &body, self, reply, 120000, 4) catch |err| {+ self.send(method, &body, true) catch |err| {self.fail("Could not send printer administration request.");return err;};}}- fn reply(owner: ?*anyopaque, bus: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {+ fn reply(owner: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {const self: *Manager = @ptrCast(@alignCast(owner.?));if (self.closing) return;const msg = result catch |err| {@@ -295,7 +378,7 @@ pub const Manager = struct {const error_name = msg.headers.error_name orelse "";if (std.mem.eql(u8, error_name, "org.freedesktop.DBus.Error.ServiceUnknown") or std.mem.eql(u8, error_name, "org.freedesktop.DBus.Error.NameHasNoOwner")) {if (self.stage != .start_service) self.availability = .missing;- self.fail(if (self.stage == .start_service) "The system service manager is unavailable; start CUPS using your distribution's service tools." else "Install cups-pk-helper to add or configure printers.");+ self.fail(if (self.stage == .start_service) "The system service manager is unavailable; start CUPS using your distribution's service tools." else "Printer authorization helper unavailable. Refresh before trying again.");} else if (std.mem.indexOf(u8, error_name, "NotPrivileged") != null or std.mem.indexOf(u8, error_name, "AccessDenied") != null or std.mem.indexOf(u8, error_name, "NotAuthorized") != null or std.mem.indexOf(u8, error_name, "InteractiveAuthorizationRequired") != null) {self.fail("Printer administration was not authorized or was cancelled.");} else self.fail("Printer administration failed; refresh and check the printer status.");@@ -351,14 +434,18 @@ pub const Manager = struct {self.fail("Invalid cups-pk-helper reply.");return;};+ self.advance();+ }++ fn advance(self: *Manager) void {switch (self.stage) {.add => {self.stage = .enable_added;- self.sendAdded(bus, .{ .enabled = .{ .name = self.added_name[0..self.added_len], .value = true } });+ self.sendAdded(.{ .enabled = .{ .name = self.added_name[0..self.added_len], .value = true } });},.enable_added => {self.stage = .accept_added;- self.sendAdded(bus, .{ .accepting = .{ .name = self.added_name[0..self.added_len], .value = true } });+ self.sendAdded(.{ .accepting = .{ .name = self.added_name[0..self.added_len], .value = true } });},.accept_added => self.succeed("Printer added, enabled and accepting jobs."),.rename => self.succeed("Queue rename request completed. Check the refreshed queues and options."),@@ -366,29 +453,29 @@ pub const Manager = struct {.clear_ppd_override => {if (self.option_alias != null) {self.stage = .clear_ppd_alias;- self.clearOptionAlias(bus);+ self.clearOptionAlias();} else {self.stage = .ppd_option;- self.sendPpdOption(bus);+ self.sendPpdOption();}},.clear_ppd_alias => {self.stage = .ppd_option;- self.sendPpdOption(bus);+ self.sendPpdOption();},.ppd_option => self.succeed("Printer option applied."),else => self.succeed("Printer change applied."),}}- fn sendAdded(self: *Manager, bus: *dbus.Connection, action: Action) void {+ fn sendAdded(self: *Manager, action: Action) void {var body: wire.Writer = .{ .allocator = a };defer body.deinit();const method = encode(&body, action) catch {self.fail("Printer was added, but could not be enabled. Refresh and resume it.");return;};- _ = bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, &body, self, reply, 120000, 4) catch {+ self.send(method, &body, false) catch {self.fail("Printer was added, but could not be enabled. Refresh and resume it.");};}@@ -399,13 +486,13 @@ pub const Manager = struct {return error.UntrustedDevice;}- fn sendPpdOption(self: *Manager, bus: *dbus.Connection) void {- _ = bus.callWithFlags(helper_name, helper_path, helper_name, "PrinterAddOption", "ssas", &self.option_body, self, reply, 120000, wire.flag_allow_interactive_authorization) catch {+ fn sendPpdOption(self: *Manager) void {+ self.send(.{ .member = "PrinterAddOption", .signature = "ssas" }, &self.option_body, false) catch {self.fail("Could not apply the printer option.");};}- fn clearOptionAlias(self: *Manager, bus: *dbus.Connection) void {+ fn clearOptionAlias(self: *Manager) void {var body: wire.Writer = .{ .allocator = a };defer body.deinit();const method = encode(&body, .{ .clear_option = .{@@ -415,12 +502,15 @@ pub const Manager = struct {self.fail("Could not clear the canonical default override.");return;};- _ = bus.callWithFlags(helper_name, helper_path, helper_name, method.member, method.signature, &body, self, reply, 120000, wire.flag_allow_interactive_authorization) catch {+ self.send(method, &body, false) catch {self.fail("Could not clear the canonical default override.");};}fn fail(self: *Manager, status: []const u8) void {+ self.authentication = false;+ if (self.worker) |worker| worker.finish();+ if (self.worker != null and self.stage == .mutation) self.generation +%= 1;// A chained add may already have changed CUPS; force an inventory reload// and describe its partial result rather than deleting anyone's queue.const partial = self.stage == .enable_added or self.stage == .accept_added;@@ -446,6 +536,8 @@ pub const Manager = struct {}fn succeed(self: *Manager, status: []const u8) void {+ self.authentication = false;+ if (self.worker) |worker| worker.finish();self.generation +%= 1;self.status = status;self.busy = false;diff --git a/src/printing/direct.c b/src/printing/direct.cnew file mode 100644index 0000000..71ddef8--- /dev/null+++ b/src/printing/direct.c@@ -0,0 +1,492 @@+#define _GNU_SOURCE+#include "direct.h"+#include <cups/cups.h>+#include <cups/adminutil.h>+#include <cups/ppd.h>+#include <pthread.h>+#include <stdatomic.h>+#include <sys/eventfd.h>+#include <sys/mman.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <unistd.h>+#include <errno.h>+#include <fcntl.h>+#include <stdlib.h>+#include <string.h>+#include <strings.h>+#include <time.h>++/* The worker is the only thread using libcups. Its default server and password+ * callback are thread-local. No subprocess, elevated uid, or host fallback. */+struct rediwm_cups {+ pthread_t thread, watchdog;+ pthread_mutex_t mutex;+ pthread_cond_t condition;+ int fd, state, result, queued, reset, close_idle, password_ready;+ atomic_int stop, cancelled;+ char *method, *args[68];+ int argc, active_fd, timeout_sent;+ http_t *http;+ double deadline;+ int attempts;+ char user[256];+ char *password; /* One locked page, wiped after a logical operation. */+ char *devices[128][5];+ int count, overflow;+};+static double now(void) {+ struct timespec t;+ clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec / 1e9;+}+static void wake(struct rediwm_cups *w) {+ uint64_t one = 1;+ ssize_t n = write(w->fd, &one, sizeof(one));+ (void)n;+}+static int timeout_cb(http_t *http, void *data) {+ struct rediwm_cups *w = data;+ pthread_mutex_lock(&w->mutex);+ int fd = fcntl(httpGetFd(http), F_DUPFD_CLOEXEC, 0);+ if (w->active_fd >= 0) close(w->active_fd);+ w->active_fd = fd;+ pthread_cond_broadcast(&w->condition);+ pthread_mutex_unlock(&w->mutex);+ return !atomic_load(&w->stop) && !atomic_load(&w->cancelled) && now() < w->deadline;+}+static const char *password_cb(const char *prompt, http_t *http,+ const char *method, const char *resource, void *data) {+ (void)prompt; (void)http; (void)method; (void)resource;+ struct rediwm_cups *w = data;+ pthread_mutex_lock(&w->mutex);+ explicit_bzero(w->password, 4096);+ if (++w->attempts > 3 || atomic_load(&w->stop) || atomic_load(&w->cancelled)) {+ pthread_mutex_unlock(&w->mutex);+ return NULL;+ }+ w->password_ready = 0;+ w->state = 1;+ wake(w);+ pthread_cond_broadcast(&w->condition);+ struct timespec end;+ clock_gettime(CLOCK_MONOTONIC, &end);+ end.tv_sec += 120;+ while (!w->password_ready && !atomic_load(&w->stop) && !atomic_load(&w->cancelled)) {+ if (pthread_cond_timedwait(&w->condition, &w->mutex, &end) == ETIMEDOUT) {+ atomic_store(&w->cancelled, 1);+ break;+ }+ }+ w->state = 0;+ w->deadline = now() + 20;+ int ok = w->password_ready && !atomic_load(&w->stop) && !atomic_load(&w->cancelled);+ if (ok) cupsSetUser(w->user);+ pthread_mutex_unlock(&w->mutex);+ return ok ? w->password : NULL;+}+static ipp_t *request(ipp_op_t op, const char *name) {+ ipp_t *r = ippNewRequest(op);+ char uri[1024];+ if (name) {+ httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL, "localhost", 0, "/printers/%s", name);+ ippAddString(r, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri);+ }+ ippAddString(r, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());+ return r;+}+static int prepare(struct rediwm_cups *w) {+ if (atomic_load(&w->stop) || atomic_load(&w->cancelled) || now() >= w->deadline) return 0;+ if (httpGetFd(w->http) < 0 && httpReconnect2(w->http, 1000, NULL)) return 0;+ return timeout_cb(w->http, w);+}+static int send_request(struct rediwm_cups *w, ipp_t *r, const char *file) {+ if (!prepare(w)) { ippDelete(r); return 1; }+ ipp_t *reply = file ? cupsDoFileRequest(w->http, r, "/admin/", file) : cupsDoRequest(w->http, r, "/admin/");+ int failed = !reply || ippGetStatusCode(reply) > IPP_STATUS_OK_EVENTS_COMPLETE;+ ippDelete(reply);+ return failed;+}+static void devices_clear(struct rediwm_cups *w) {+ for (int i = 0; i < w->count; i++) for (int j = 0; j < 5; j++) {+ free(w->devices[i][j]); w->devices[i][j] = NULL;+ }+ w->count = w->overflow = 0;+}+static void device_cb(const char *kind, const char *id, const char *info,+ const char *model, const char *uri, const char *location, void *data) {+ (void)location;+ struct rediwm_cups *w = data;+ if (w->count >= 128) { w->overflow = 1; return; }+ const char *values[] = {uri, info, model, id, kind};+ int n = w->count++;+ for (int j = 0; j < 5; j++) {+ const char *v = values[j] ? values[j] : "";+ if (strlen(v) > 8192 || !(w->devices[n][j] = strdup(v))) w->overflow = 1;+ }+}+/* Rewrite only a declared PPD default. Values were validated in Zig; using+ * the PPD parser ensures custom sizes and PageSize/PageRegion stay consistent. */+static int ppd_option(struct rediwm_cups *w, const char *name, const char *key, const char *value) {+ if (!prepare(w)) return 1;+ const char *download = cupsGetPPD2(w->http, name);+ if (!download) return 1;+ char path[1024];+ snprintf(path, sizeof(path), "%s", download);+ struct stat st;+ if (stat(path, &st) || !S_ISREG(st.st_mode) || st.st_size > 4 * 1024 * 1024) { unlink(path); return 1; }+ ppd_file_t *ppd = ppdOpenFile(path);+ if (!ppd) { unlink(path); return 1; }+ ppdMarkDefaults(ppd);+ ppd_option_t *option = ppdFindOption(ppd, key);+ if (!option || (!ppdFindChoice(option, value) && strncmp(value, "Custom.", 7))) {+ ppdClose(ppd); unlink(path); return 1;+ }+ if (ppdMarkOption(ppd, key, value)) { ppdClose(ppd); unlink(path); return 1; }+ char output[] = "/tmp/rediwm-cups-XXXXXX";+ int fd = mkostemp(output, O_CLOEXEC);+ FILE *out = fd >= 0 ? fdopen(fd, "w") : NULL;+ FILE *in = fopen(path, "re");+ int failed = !out || !in;+ if (out && in) {+ char *line = NULL;+ size_t cap = 0, total = 0;+ ssize_t len;+ while ((len = getline(&line, &cap, in)) >= 0) {+ total += (size_t)len;+ if (total > 4 * 1024 * 1024) { failed = 1; break; }+ char keyword[128];+ if (sscanf(line, "*Default%127[^:]:", keyword) == 1) {+ int size_default = !strcmp(keyword, "PageSize") || !strcmp(keyword, "PageRegion") ||+ !strcmp(keyword, "PaperDimension") || !strcmp(keyword, "ImageableArea");+ ppd_choice_t *choice = ppdFindMarkedChoice(ppd, size_default ? "PageSize" : keyword);+ if (!choice && size_default) choice = ppdFindMarkedChoice(ppd, "PageRegion");+ if (choice) {+ const char *selected = choice->choice;+ if (!strcmp(selected, "Custom")) {+ if (!strcmp(keyword, key) || (size_default && (!strcmp(key, "PageSize") || !strcmp(key, "PageRegion")))) selected = value;+ else { fputs(line, out); continue; }+ }+ fprintf(out, "*Default%s: %s\n", keyword, selected);+ continue;+ }+ }+ if (fwrite(line, 1, (size_t)len, out) != (size_t)len) { failed = 1; break; }+ }+ if (ferror(in)) failed = 1;+ free(line);+ }+ if (in) fclose(in);+ if (out) { if (fclose(out)) failed = 1; } else if (fd >= 0) close(fd);+ ppdClose(ppd);+ unlink(path);+ if (!failed) failed = send_request(w, request(IPP_OP_CUPS_ADD_MODIFY_PRINTER, name), output);+ unlink(output);+ return failed;+}+static ipp_t *get_printer(struct rediwm_cups *w, const char *name) {+ if (!prepare(w)) return NULL;+ return cupsDoRequest(w->http, request(IPP_OP_GET_PRINTER_ATTRIBUTES, name), "/");+}+/* Do not silently detach a queue from a CUPS class. Class membership editing+ * is outside this page's model; refuse this rename before creating anything. */+static int class_member(struct rediwm_cups *w, const char *name) {+ if (!prepare(w)) return -1;+ ipp_t *classes = cupsDoRequest(w->http, request(IPP_OP_CUPS_GET_CLASSES, NULL), "/");+ if (!classes) return -1;+ ipp_status_t status = ippGetStatusCode(classes);+ if (status == IPP_STATUS_ERROR_NOT_FOUND) { ippDelete(classes); return 0; }+ if (status > IPP_STATUS_OK_EVENTS_COMPLETE) { ippDelete(classes); return -1; }+ int member = 0;+ for (ipp_attribute_t *attr = ippFirstAttribute(classes); attr; attr = ippNextAttribute(classes)) {+ const char *key = ippGetName(attr);+ if (!key || strcmp(key, "member-names") || ippGetValueTag(attr) != IPP_TAG_NAME) continue;+ for (int i = 0; i < ippGetCount(attr); i++) {+ const char *value = ippGetString(attr, i, NULL);+ if (value && !strcasecmp(value, name)) member = 1;+ }+ }+ ippDelete(classes);+ return member;+}+/* CUPS has no rename transaction. Recheck names/jobs, clone settings and PPD,+ * then delete only after the new queue has been accepted. Never roll back an+ * uncertain creation: the page refreshes both identities and reports partial. */+static int rename_printer(struct rediwm_cups *w, const char *old, const char *name) {+ int membership = class_member(w, old);+ if (membership) return membership > 0 ? 5 : 1;+ ipp_t *existing = get_printer(w, name);+ int absent = existing && ippGetStatusCode(existing) == IPP_STATUS_ERROR_NOT_FOUND;+ ippDelete(existing);+ if (!absent) return 1;+ ipp_t *jobs = request(IPP_OP_GET_JOBS, old);+ ippAddString(jobs, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "which-jobs", NULL, "not-completed");+ if (!prepare(w)) { ippDelete(jobs); return 1; }+ ipp_t *reply = cupsDoRequest(w->http, jobs, "/");+ int blocked = !reply || ippGetStatusCode(reply) > IPP_STATUS_OK_EVENTS_COMPLETE || ippFindAttribute(reply, "job-id", IPP_TAG_INTEGER);+ ippDelete(reply);+ if (blocked) return 1;+ ipp_t *source = get_printer(w, old);+ if (!source || ippGetStatusCode(source) > IPP_STATUS_OK_EVENTS_COMPLETE) { ippDelete(source); return 1; }+ ipp_t *add = request(IPP_OP_CUPS_ADD_MODIFY_PRINTER, name);+ const char *copy[] = {"device-uri", "printer-info", "printer-location", "printer-is-shared", "printer-error-policy", "printer-op-policy", "requesting-user-name-allowed", "requesting-user-name-denied", "job-quota-period", "job-k-limit", "job-page-limit", "port-monitor"};+ for (ipp_attribute_t *attr = ippFirstAttribute(source); attr; attr = ippNextAttribute(source)) {+ const char *key = ippGetName(attr);+ if (!key || ippGetGroupTag(attr) != IPP_TAG_PRINTER) continue;+ size_t len = strlen(key);+ int keep = len > 8 && !strcmp(key + len - 8, "-default");+ for (size_t i = 0; i < sizeof(copy)/sizeof(copy[0]); i++) if (!strcmp(key, copy[i])) keep = 1;+ if (keep) ippCopyAttribute(add, attr, 0);+ }+ ipp_attribute_t *state = ippFindAttribute(source, "printer-state", IPP_TAG_ENUM);+ ipp_attribute_t *accepting = ippFindAttribute(source, "printer-is-accepting-jobs", IPP_TAG_BOOLEAN);+ ipp_attribute_t *type = ippFindAttribute(source, "printer-type", IPP_TAG_ENUM);+ int enabled = state && ippGetInteger(state, 0) != IPP_PSTATE_STOPPED;+ int accept = accepting && ippGetBoolean(accepting, 0);+ int is_default = type && (ippGetInteger(type, 0) & CUPS_PRINTER_DEFAULT);+ ippDelete(source);+ if (!prepare(w)) { ippDelete(add); return 1; }+ const char *download = cupsGetPPD2(w->http, old);+ char path[1024] = "";+ if (download) snprintf(path, sizeof(path), "%s", download);+ else if (cupsLastError() != IPP_STATUS_ERROR_NOT_FOUND) { ippDelete(add); return 1; }+ struct stat st;+ if (*path && (stat(path, &st) || !S_ISREG(st.st_mode) || st.st_size > 4 * 1024 * 1024)) { unlink(path); ippDelete(add); return 1; }+ int failed = send_request(w, add, *path ? path : NULL);+ if (*path) unlink(path);+ if (failed) return 4;+ if (enabled && send_request(w, request(IPP_OP_RESUME_PRINTER, name), NULL)) return 4;+ if (accept && send_request(w, request(IPP_OP_CUPS_ACCEPT_JOBS, name), NULL)) return 4;+ if (is_default && send_request(w, request(IPP_OP_CUPS_SET_DEFAULT, name), NULL)) return 4;+ ipp_t *created = get_printer(w, name);+ int verified = created && ippGetStatusCode(created) <= IPP_STATUS_OK_EVENTS_COMPLETE &&+ ippFindAttribute(created, "printer-name", IPP_TAG_NAME);+ ippDelete(created);+ if (!verified) return 4;+ jobs = request(IPP_OP_GET_JOBS, old);+ ippAddString(jobs, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "which-jobs", NULL, "not-completed");+ if (!prepare(w)) { ippDelete(jobs); return 4; }+ reply = cupsDoRequest(w->http, jobs, "/");+ blocked = !reply || ippGetStatusCode(reply) > IPP_STATUS_OK_EVENTS_COMPLETE || ippFindAttribute(reply, "job-id", IPP_TAG_INTEGER);+ ippDelete(reply);+ if (blocked) return 4;+ if (send_request(w, request(IPP_OP_CUPS_DELETE_PRINTER, old), NULL)) return 4;+ return 0;+}+static int execute(struct rediwm_cups *w) {+ const char *m = w->method, *name = w->argc ? w->args[0] : NULL;+ if (!strcmp(m, "DevicesGet")) {+ devices_clear(w);+ int result = cupsGetDevices(w->http, 10, NULL, "file,smb,smbs,pdf,pipe,exec,command,beh,hpfax,mailto", device_cb, w);+ return result > IPP_STATUS_OK_EVENTS_COMPLETE || w->overflow;+ }+ if (!strcmp(m, "PrinterRename")) return rename_printer(w, name, w->args[1]);+ if (!strcmp(m, "PrinterAddOption")) return w->argc == 3 ? ppd_option(w, name, w->args[1], w->args[2]) : 1;+ ipp_op_t op = IPP_OP_CUPS_ADD_MODIFY_PRINTER;+ if (!strcmp(m, "PrinterDelete")) op = IPP_OP_CUPS_DELETE_PRINTER;+ else if (!strcmp(m, "PrinterSetDefault")) op = IPP_OP_CUPS_SET_DEFAULT;+ else if (!strcmp(m, "PrinterSetEnabled")) op = !strcmp(w->args[1], "true") ? IPP_OP_RESUME_PRINTER : IPP_OP_PAUSE_PRINTER;+ else if (!strcmp(m, "PrinterSetAcceptJobs")) op = !strcmp(w->args[1], "true") ? IPP_OP_CUPS_ACCEPT_JOBS : IPP_OP_CUPS_REJECT_JOBS;+ ipp_t *r = request(op, name);+ if (!strcmp(m, "PrinterAdd")) {+ /* Check again at the worker boundary; ADD_MODIFY itself is an upsert. */+ ipp_t *existing = get_printer(w, name);+ int absent = existing && ippGetStatusCode(existing) == IPP_STATUS_ERROR_NOT_FOUND;+ ippDelete(existing);+ if (!absent) { ippDelete(r); return 1; }+ ippAddString(r, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL, w->args[1]);+ ippAddString(r, IPP_TAG_PRINTER, IPP_TAG_NAME, "ppd-name", NULL, w->args[2]);+ ippAddString(r, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, w->args[3]);+ ippAddString(r, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-location", NULL, w->args[4]);+ } else if (!strcmp(m, "PrinterSetInfo")) ippAddString(r, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, w->args[1]);+ else if (!strcmp(m, "PrinterSetDevice")) ippAddString(r, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL, w->args[1]);+ else if (!strcmp(m, "PrinterDeleteOptionDefault")) {+ char key[256];+ snprintf(key, sizeof(key), "%s-default", w->args[1]);+ ippAddOutOfBand(r, IPP_TAG_PRINTER, IPP_TAG_DELETEATTR, key);+ } else if (!strcmp(m, "PrinterAddOptionDefault")) {+ char key[256], value[65536] = "";+ snprintf(key, sizeof(key), "%s-default", w->args[1]);+ for (int i = 2; i < w->argc; i++) {+ if (i > 2) strcat(value, ",");+ if (strlen(value) + strlen(w->args[i]) >= sizeof(value)) { ippDelete(r); return 1; }+ strcat(value, w->args[i]);+ }+ cups_option_t *options = NULL;+ int count = cupsAddOption(key, value, 0, &options);+ cupsEncodeOptions2(r, count, options, IPP_TAG_PRINTER);+ cupsFreeOptions(count, options);+ }+ return send_request(w, r, NULL);+}+static void close_connection(struct rediwm_cups *w) {+ if (w->active_fd >= 0) close(w->active_fd);+ w->active_fd = -1;+ if (w->http) { httpClose(w->http); w->http = NULL; }+ explicit_bzero(w->password, 4096);+ w->attempts = 0;+ cupsSetUser(NULL);+}+static void *run(void *data) {+ struct rediwm_cups *w = data;+ pthread_setname_np(pthread_self(), "rediwm-cups");+ cupsSetServer("/run/cups/cups.sock");+ cupsSetPasswordCB2(password_cb, w);+ pthread_mutex_lock(&w->mutex);+ while (!atomic_load(&w->stop)) {+ while (!w->queued && !w->close_idle && !atomic_load(&w->stop)) pthread_cond_wait(&w->condition, &w->mutex);+ if (atomic_load(&w->stop)) break;+ if (w->reset || w->close_idle) { close_connection(w); w->reset = w->close_idle = 0; }+ if (!w->queued) continue;+ w->queued = 0;+ w->deadline = now() + 20;+ pthread_mutex_unlock(&w->mutex);+ if (!w->http) w->http = httpConnect2("/run/cups/cups.sock", 631, NULL, AF_UNIX, HTTP_ENCRYPTION_NEVER, 1, 1000, NULL);+ int result = 1;+ if (w->http) {+ pthread_mutex_lock(&w->mutex);+ if (w->active_fd >= 0) close(w->active_fd);+ w->active_fd = fcntl(httpGetFd(w->http), F_DUPFD_CLOEXEC, 0);+ pthread_cond_broadcast(&w->condition);+ pthread_mutex_unlock(&w->mutex);+ httpSetTimeout(w->http, 0.2, timeout_cb, w);+ result = execute(w);+ }+ pthread_mutex_lock(&w->mutex);+ w->result = atomic_load(&w->cancelled) ? 2 : result;+ if (result && w->attempts >= 3) w->result = 3;+ w->state = 2;+ pthread_cond_broadcast(&w->condition);+ wake(w);+ }+ close_connection(w);+ pthread_mutex_unlock(&w->mutex);+ return NULL;+}+/* An absolute deadline also stops a peer that drip-feeds bytes and therefore+ * never triggers libcups' inactivity timeout. This thread sleeps on a condition+ * with no deadline when idle or awaiting user input. */+static void *watchdog(void *data) {+ struct rediwm_cups *w = data;+ pthread_setname_np(pthread_self(), "rediwm-cups-io");+ pthread_mutex_lock(&w->mutex);+ while (!atomic_load(&w->stop)) {+ if (w->state != 0 || w->active_fd < 0 || w->timeout_sent) {+ pthread_cond_wait(&w->condition, &w->mutex);+ continue;+ }+ struct timespec end = { .tv_sec = (time_t)w->deadline,+ .tv_nsec = (long)((w->deadline - (time_t)w->deadline) * 1e9) };+ if (pthread_cond_timedwait(&w->condition, &w->mutex, &end) == ETIMEDOUT &&+ w->state == 0 && w->active_fd >= 0 && now() >= w->deadline) {+ w->timeout_sent = 1;+ shutdown(w->active_fd, SHUT_RDWR);+ }+ }+ pthread_mutex_unlock(&w->mutex);+ return NULL;+}+struct rediwm_cups *rediwm_cups_create(void) {+ struct rediwm_cups *w = calloc(1, sizeof(*w));+ if (!w) return NULL;+ w->password = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);+ if (w->password == MAP_FAILED) { free(w); return NULL; }+ if (mlock(w->password, 4096)) { munmap(w->password, 4096); free(w); return NULL; }+ madvise(w->password, 4096, MADV_DONTDUMP);+ w->fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);+ if (w->fd < 0) goto fail;+ if (pthread_mutex_init(&w->mutex, NULL)) goto fail_fd;+ pthread_condattr_t attr;+ pthread_condattr_init(&attr);+ pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);+ int err = pthread_cond_init(&w->condition, &attr);+ pthread_condattr_destroy(&attr);+ if (err) goto fail_mutex;+ w->state = 2;+ w->active_fd = -1;+ if (pthread_create(&w->thread, NULL, run, w)) goto fail_condition;+ if (pthread_create(&w->watchdog, NULL, watchdog, w)) {+ atomic_store(&w->stop, 1);+ pthread_mutex_lock(&w->mutex);+ pthread_cond_broadcast(&w->condition);+ pthread_mutex_unlock(&w->mutex);+ pthread_join(w->thread, NULL);+ goto fail_condition;+ }+ return w;+fail_condition: pthread_cond_destroy(&w->condition);+fail_mutex: pthread_mutex_destroy(&w->mutex);+fail_fd: close(w->fd);+fail: munlock(w->password, 4096); munmap(w->password, 4096); free(w); return NULL;+}+void rediwm_cups_cancel(struct rediwm_cups *w) {+ atomic_store(&w->cancelled, 1);+ pthread_mutex_lock(&w->mutex);+ if (w->active_fd >= 0) shutdown(w->active_fd, SHUT_RDWR);+ pthread_cond_broadcast(&w->condition);+ pthread_mutex_unlock(&w->mutex);+}+void rediwm_cups_destroy(struct rediwm_cups *w) {+ atomic_store(&w->stop, 1);+ rediwm_cups_cancel(w);+ pthread_join(w->thread, NULL);+ pthread_join(w->watchdog, NULL);+ free(w->method);+ for (int i = 0; i < w->argc; i++) free(w->args[i]);+ devices_clear(w);+ close(w->fd);+ pthread_cond_destroy(&w->condition);+ pthread_mutex_destroy(&w->mutex);+ munlock(w->password, 4096); munmap(w->password, 4096);+ free(w);+}+int rediwm_cups_fd(struct rediwm_cups *w) { return w->fd; }+int rediwm_cups_state(struct rediwm_cups *w) {+ pthread_mutex_lock(&w->mutex); int state = w->state; pthread_mutex_unlock(&w->mutex); return state;+}+int rediwm_cups_result(struct rediwm_cups *w) { return w->result; }+const char *rediwm_cups_device(struct rediwm_cups *w, int i, int field) {+ return i < w->count && field < 5 ? w->devices[i][field] : NULL;+}+int rediwm_cups_submit(struct rediwm_cups *w, const char *method, int argc, const char *const *args, int reset) {+ if (argc < 0 || argc > 68) return -1;+ char *m = strdup(method), *copy[68] = {0};+ int ok = m != NULL;+ for (int i = 0; i < argc; i++) if (!(copy[i] = strdup(args[i]))) ok = 0;+ if (!ok) { free(m); for (int i = 0; i < argc; i++) free(copy[i]); return -1; }+ pthread_mutex_lock(&w->mutex);+ if (w->state != 2) {+ pthread_mutex_unlock(&w->mutex);+ free(m);+ for (int i = 0; i < argc; i++) free(copy[i]);+ return -1;+ }+ free(w->method); w->method = m;+ for (int i = 0; i < w->argc; i++) free(w->args[i]);+ memcpy(w->args, copy, sizeof(copy)); w->argc = argc;+ w->state = 0; w->queued = 1; w->reset = reset; w->timeout_sent = 0;+ w->deadline = now() + 20;+ atomic_store(&w->cancelled, 0);+ pthread_cond_broadcast(&w->condition);+ pthread_mutex_unlock(&w->mutex);+ return 0;+}+void rediwm_cups_credentials(struct rediwm_cups *w, const char *user, const char *password, unsigned long len) {+ pthread_mutex_lock(&w->mutex);+ if (w->state == 1 && len < 4096 && strlen(user) < sizeof(w->user)) {+ snprintf(w->user, sizeof(w->user), "%s", user);+ explicit_bzero(w->password, 4096);+ memcpy(w->password, password, len);+ w->password_ready = 1;+ w->state = 0;+ w->deadline = now() + 20;+ pthread_cond_broadcast(&w->condition);+ }+ pthread_mutex_unlock(&w->mutex);+}+void rediwm_cups_finish(struct rediwm_cups *w) {+ pthread_mutex_lock(&w->mutex);+ w->close_idle = 1;+ pthread_cond_broadcast(&w->condition);+ pthread_mutex_unlock(&w->mutex);+}diff --git a/src/printing/direct.h b/src/printing/direct.hnew file mode 100644index 0000000..28e82bc--- /dev/null+++ b/src/printing/direct.h@@ -0,0 +1,15 @@+#ifndef REDIWM_PRINT_DIRECT_H+#define REDIWM_PRINT_DIRECT_H+struct rediwm_cups;+struct rediwm_cups *rediwm_cups_create(void);+void rediwm_cups_destroy(struct rediwm_cups *);+int rediwm_cups_fd(struct rediwm_cups *);+/* All commands and results are copied. state: 0 working, 1 password, 2 done. */+int rediwm_cups_submit(struct rediwm_cups *, const char *, int, const char *const *, int);+int rediwm_cups_state(struct rediwm_cups *);+int rediwm_cups_result(struct rediwm_cups *);+void rediwm_cups_credentials(struct rediwm_cups *, const char *, const char *, unsigned long);+void rediwm_cups_cancel(struct rediwm_cups *);+void rediwm_cups_finish(struct rediwm_cups *);+const char *rediwm_cups_device(struct rediwm_cups *, int, int);+#endifdiff --git a/src/printing/direct.zig b/src/printing/direct.zignew file mode 100644index 0000000..f38ee10--- /dev/null+++ b/src/printing/direct.zig@@ -0,0 +1,106 @@+//! Adapter for the private native libcups worker. The validated helper-shaped+//! arguments are an internal command format, not a D-Bus dependency.+const std = @import("std");+const wire = @import("dbus").wire;+const wl = @import("wayland").server.wl;+const a = std.heap.c_allocator;+const Native = opaque {};+extern fn rediwm_cups_create() ?*Native;+extern fn rediwm_cups_destroy(*Native) void;+extern fn rediwm_cups_fd(*Native) c_int;+extern fn rediwm_cups_submit(*Native, [*:0]const u8, c_int, [*]const [*:0]const u8, c_int) c_int;+extern fn rediwm_cups_state(*Native) c_int;+extern fn rediwm_cups_result(*Native) c_int;+extern fn rediwm_cups_device(*Native, c_int, c_int) ?[*:0]const u8;+extern fn rediwm_cups_credentials(*Native, [*:0]const u8, [*]const u8, c_ulong) void;+extern fn rediwm_cups_cancel(*Native) void;+extern fn rediwm_cups_finish(*Native) void;+extern "c" fn read(c_int, *anyopaque, usize) isize;++pub const Worker = struct {+ native: *Native,+ source: *wl.EventSource,+ owner: *anyopaque,+ callback: *const fn (*anyopaque) void,+ discovery: bool = false,++ pub fn create(loop: *wl.EventLoop, owner: *anyopaque, callback: *const fn (*anyopaque) void) !*Worker {+ const self = try a.create(Worker);+ errdefer a.destroy(self);+ const native = rediwm_cups_create() orelse return error.WorkerFailed;+ errdefer rediwm_cups_destroy(native);+ self.* = .{ .native = native, .source = undefined, .owner = owner, .callback = callback };+ self.source = try loop.addFd(*Worker, rediwm_cups_fd(native), .{ .readable = true }, ready, self);+ return self;+ }+ pub fn destroy(self: *Worker) void {+ self.source.remove();+ rediwm_cups_destroy(self.native);+ a.destroy(self);+ }+ fn ready(fd: c_int, _: wl.EventMask, self: *Worker) c_int {+ var value: u64 = 0;+ _ = read(fd, &value, @sizeOf(u64));+ self.callback(self.owner);+ return 0;+ }+ pub fn state(self: *Worker) c_int {+ return rediwm_cups_state(self.native);+ }+ pub fn result(self: *Worker) c_int {+ return rediwm_cups_result(self.native);+ }+ pub fn cancel(self: *Worker) void {+ rediwm_cups_cancel(self.native);+ }+ pub fn finish(self: *Worker) void {+ rediwm_cups_finish(self.native);+ }+ pub fn credentials(self: *Worker, user: []const u8, password: []const u8) !void {+ if (user.len == 0 or user.len > 255 or password.len >= 4096) return error.InvalidCredentials;+ for (user) |ch| if (ch < 0x21 or ch == 0x7f) return error.InvalidCredentials;+ if (std.mem.indexOfScalar(u8, password, 0) != null) return error.InvalidCredentials;+ const name = try a.dupeZ(u8, user);+ defer a.free(name);+ rediwm_cups_credentials(self.native, name, password.ptr, password.len);+ }+ pub fn submit(self: *Worker, method: []const u8, signature: []const u8, bytes: []const u8, reset: bool) !void {+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const mem = arena.allocator();+ var args: std.ArrayList([*:0]const u8) = .empty;+ var reader: wire.Reader = .{ .bytes = bytes };+ self.discovery = std.mem.eql(u8, method, "DevicesGet");+ if (!self.discovery) {+ var i: usize = 0;+ while (i < signature.len) : (i += 1) switch (signature[i]) {+ 's' => try args.append(mem, try mem.dupeZ(u8, try reader.string())),+ 'b' => try args.append(mem, if (try reader.boolean()) "true" else "false"),+ 'a' => {+ i += 1;+ if (i >= signature.len or signature[i] != 's') return error.InvalidSignature;+ var values = try reader.array(4);+ while (values.offset < values.bytes.len) try args.append(mem, try mem.dupeZ(u8, try values.string()));+ },+ else => return error.InvalidSignature,+ };+ try reader.done();+ }+ if (rediwm_cups_submit(self.native, try mem.dupeZ(u8, method), @intCast(args.items.len), args.items.ptr, @intFromBool(reset)) != 0) return error.OutOfMemory;+ }+ pub fn devices(self: *Worker, writer: *wire.Writer) !void {+ const dict = try writer.beginArray(8);+ const names = [_][]const u8{ "device-uri", "device-info", "device-make-and-model", "device-id", "device-class" };+ for (0..128) |i| {+ if (rediwm_cups_device(self.native, @intCast(i), 0) == null) break;+ for (names, 0..) |name, j| {+ const value = rediwm_cups_device(self.native, @intCast(i), @intCast(j)) orelse return error.InvalidReply;+ var key: [64]u8 = undefined;+ try writer.alignTo(8);+ try writer.string(try std.fmt.bufPrint(&key, "{s}:{d}", .{ name, i }));+ try writer.string(std.mem.span(value));+ }+ }+ try writer.endArray(dict);+ }+};diff --git a/src/printing/platform.zig b/src/printing/platform.zigindex bbf3c2b..7282cc6 100644--- a/src/printing/platform.zig+++ b/src/printing/platform.zig@@ -15,7 +15,7 @@ pub const Info = struct {// never evidence that the daemon is running/enabled. null means inaccessible.daemon_installed: ?bool = null,missing_cups: []const u8 = "Printing needs CUPS. Ask your distribution's package manager for its CUPS print-server package, then start the print service.",- missing_helper: []const u8 = "Printer administration needs the optional cups-pk-helper package and an authorization policy that permits the action.",+ missing_helper: []const u8 = "Printer administration uses CUPS authentication when the optional cups-pk-helper package is unavailable.",pub fn deinit(self: *Info, a: A) void {a.free(self.id);@@ -90,9 +90,9 @@ pub fn parse(a: A, bytes: []const u8) !Info {.generic => info.missing_cups,};info.missing_helper = switch (distro) {- .arch, .cachyos, .artix => "Install the optional cups-pk-helper package for authorized printer setup and configuration. Printing and user-level status do not require it.",- .debian, .ubuntu => "Install the optional cups-pk-helper package for authorized printer setup and configuration. Printing and user-level status do not require it.",- .fedora => "Install the optional cups-pk-helper package for authorized printer setup and configuration. Printing and user-level status do not require it.",+ .arch, .cachyos, .artix => "The optional cups-pk-helper package provides polkit authorization. Without it, printer setup uses CUPS administrator credentials.",+ .debian, .ubuntu => "The optional cups-pk-helper package provides polkit authorization. Without it, printer setup uses CUPS administrator credentials.",+ .fedora => "The optional cups-pk-helper package provides polkit authorization. Without it, printer setup uses CUPS administrator credentials.",.opensuse => "Look for the optional cups-pk-helper package in your openSUSE repositories. Availability and authorization depend on the release and local policy.",.generic => info.missing_helper,};diff --git a/src/system_monitor/app.zig b/src/system_monitor/app.zigindex 72a259c..52ee336 100644--- a/src/system_monitor/app.zig+++ b/src/system_monitor/app.zig@@ -16,6 +16,7 @@ const titles = [_][]const u8{ "Name", "PID", "User", "CPU %", "Memory (resident)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 };+const Selection = struct { identity: proc.Identity, fade: ui.hover_glide.Fade = .{} };pub const App = struct {worker: *collector.Worker,@@ -53,6 +54,8 @@ pub const App = struct {bar: scrollbar.Appearance = .{},bar_drag: scrollbar.Drag = .{},last_scroll: f64 = 0,+ row_hover: ui.hover_glide.Glide = .{},+ selections: std.ArrayList(Selection) = .empty,pub fn init(io: std.Io) !App {return .{ .worker = try collector.Worker.init(io), .model = .{ .allocator = a, .uid = c.getuid() } };@@ -62,6 +65,7 @@ pub const App = struct {self.dispatcher.reset();if (self.initialized) a.free(self.toolbar[0].kind.text_input.value);self.model.deinit();+ self.selections.deinit(a);}pub fn getTitle(_: *App) [*:0]const u8 {return "System Monitor";@@ -231,6 +235,8 @@ pub const App = struct {self.dirty = true;}pub fn cancelDrag(self: *App) void {+ self.px = -1;+ self.py = -1;self.bar_drag.end();self.dispatcher.pressed = null;self.dispatcher.text_drag = null;@@ -258,8 +264,6 @@ pub const App = struct {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)),@@ -268,12 +272,9 @@ pub const App = struct {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 = "";- }+ if (self.processAt()) |index| {+ self.model.selected = self.model.snapshot.?.processes[self.model.rows.items[index]].identity;+ self.notice = "";self.dispatcher.focus(&self.root, null);}}@@ -373,6 +374,18 @@ pub const App = struct {fn listBox(self: *const App) Rect {return .{ .x = 16, .y = 236, .w = @floatFromInt(self.w - 32), .h = @floatFromInt(@max(0, self.h - 310)) };}+ fn processAt(self: *const App) ?usize {+ if (self.confirmation != null or self.suspended or self.bar_drag.active) return null;+ const list = self.listBox();+ const right = list.x + list.w - scrollbar.gutter(theme.global.scrollbar_width);+ if (self.px < list.x or self.px >= right or self.py < list.y or self.py >= list.y + list.h) return null;+ const index: usize = @intFromFloat(@floor((self.py - list.y + self.model.scroll) / row_h));+ return if (index < self.model.rows.items.len) index else null;+ }+ fn rowBox(self: *const App, row: f32) cairo.ItemBox {+ const list = self.listBox();+ return .{ .x = list.x + 1, .y = list.y + @as(f64, row) * row_h - self.model.scroll + 1, .w = list.w - scrollbar.gutter(theme.global.scrollbar_width) - 2, .h = row_h - 2 };+ }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));}@@ -382,9 +395,33 @@ pub const App = struct {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 index = self.processAt();+ const hovered = if (index) |i| blk: {+ const identity = self.model.snapshot.?.processes[self.model.rows.items[i]].identity;+ if (self.model.selected) |selected| if (identity.eql(selected)) break :blk null;+ break :blk @as(?ui.hover_glide.Cell, .{ .col = 0, .row = @intCast(i) });+ } else null;+ self.row_hover.setTarget(now, hovered);+ const pixel = ui.anim.rasterPixelQuantum(@floatCast(self.density));+ if (self.row_hover.step(now, pixel, pixel / @as(f32, row_h))) self.dirty = true;+ if (self.model.selected) |identity| {+ const found = for (self.selections.items) |selection| {+ if (selection.identity.eql(identity)) break true;+ } else false;+ if (!found) self.selections.append(a, .{ .identity = identity }) catch {};+ }+ var i: usize = 0;+ while (i < self.selections.items.len) {+ const selection = &self.selections.items[i];+ const selected = if (self.model.selected) |identity| identity.eql(selection.identity) else false;+ if (selection.fade.step(now, selected)) self.dirty = true;+ if (!selected and selection.fade.alpha == 0 and selection.fade.animation.settled(now)) {+ _ = self.selections.swapRemove(i);+ } else i += 1;+ }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;+ const thumb_hovered = if (geom) |g| g.overThumb(self.px, self.py) else false;+ if (self.bar.step(now, self.model.scroll != self.last_scroll, thumb_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);@@ -397,6 +434,11 @@ pub const App = struct {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.row_hover.animating(now)) timeout = 16;+ for (self.selections.items) |selection| if (!selection.fade.animation.settled(now)) {+ timeout = if (timeout) |existing| @min(existing, 16) else 16;+ break;+ };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);@@ -494,12 +536,15 @@ pub const App = struct {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);+ const hover = self.row_hover.frame;+ if (hover.alpha > 0) cairo.drawItemHighlight(cr, self.rowBox(hover.row), false, hover.alpha, hover.alpha);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 });- }+ for (self.selections.items) |selection| if (selection.identity.eql(row.identity)) {+ cairo.drawItemHighlight(cr, self.rowBox(@floatFromInt(i)), true, selection.fade.alpha, selection.fade.alpha);+ break;+ };var pid_buf: [32]u8 = undefined;var cpu_buf: [32]u8 = undefined;var mem_buf: [32]u8 = undefined;diff --git a/src/ui/cairo.zig b/src/ui/cairo.zigindex bff43c3..1e9fa91 100644--- a/src/ui/cairo.zig+++ b/src/ui/cairo.zig@@ -60,6 +60,27 @@ pub fn setSource(cr_any: *anyopaque, color: [4]f32) void {c.cairo_set_source_rgba(@ptrCast(cr_any), color[0], color[1], color[2], color[3]);}+/// File and process rows share the same rounded hover/selection card.+/// Keep double-precision geometry for Cairo's fractional raster positions.+pub const ItemBox = struct { x: f64, y: f64, w: f64, h: f64 };++pub fn drawItemHighlight(cr_any: *anyopaque, box: ItemBox, selected: bool, fill_alpha: f32, border_alpha: f32) void {+ if (box.w <= 0 or box.h <= 0 or (fill_alpha <= 0 and border_alpha <= 0)) return;+ const cr: *c.cairo_t = @ptrCast(cr_any);+ roundedPath(cr, box.x, box.y, box.w, box.h, @min(6, @min(box.w, box.h) / 2));+ if (fill_alpha > 0) {+ var fill = if (selected) theme.global.app_item_selected else theme.global.app_item_hover;+ fill[3] *= fill_alpha;+ setSource(cr, fill);+ c.cairo_fill_preserve(cr);+ }+ var border = if (selected) theme.shellPalette().accent else theme.global.app_item_border;+ border[3] *= border_alpha;+ setSource(cr, border);+ c.cairo_set_line_width(cr, 1);+ c.cairo_stroke(cr);+}+/// Sidebar hover: a plain rounded fill at `alpha`.pub fn drawSidebarHover(cr_any: *anyopaque, box: Rect, alpha: f32) void {if (box.w <= 0 or box.h <= 0 or alpha <= 0) return;diff --git a/src/ui/hover_glide.zig b/src/ui/hover_glide.zigindex d90c883..601857e 100644--- a/src/ui/hover_glide.zig+++ b/src/ui/hover_glide.zig@@ -11,6 +11,22 @@const std = @import("std");const anim = @import("anim.zig");+/// Selection fades use the same timing and raster sampling as the hover.+pub const Fade = struct {+ animation: anim.Anim = .{ .property = .opacity },+ alpha: f32 = 0,++ pub fn step(self: *Fade, now: i64, visible: bool) bool {+ const target: f32 = if (visible) 1 else 0;+ if (self.animation.to != target) self.animation.retargetTo(now, target, anim.curveFor(.start_glide_fade));+ const value = self.animation.value(now);+ const next = if (self.animation.settled(now)) value else @round(value / anim.rasterAlphaQuantum()) * anim.rasterAlphaQuantum();+ const changed = next != self.alpha;+ self.alpha = next;+ return changed;+ }+};+/// A grid cell; a plain list uses column 0.pub const Cell = struct { col: i32, row: i32 };diff --git a/tests/keyboard_shortcuts.py b/tests/keyboard_shortcuts.pyindex bb2056f..32386c4 100644--- a/tests/keyboard_shortcuts.py+++ b/tests/keyboard_shortcuts.py@@ -42,6 +42,8 @@ def run():click("Keyboard Shortcuts")assert has("Window Management") and has("Launcher")+ assert has("Open System Monitor"), "existing shortcuts omitted System Monitor"+ assert has("Ctrl+Alt+Delete")click("Super+q")chord("f")time.sleep(.15)diff --git a/tests/printers.py b/tests/printers.pyindex b2b18bc..1414906 100644--- a/tests/printers.py+++ b/tests/printers.py@@ -78,7 +78,13 @@ def request_attributes(body):offset += 2value = body[offset:offset + length]offset += length- fields[name] = struct.unpack('!i', value)[0] if tag in (0x21, 0x23) else bool(value[0]) if tag == 0x22 else value.decode()+ if tag == 0x32:+ x, y, units = struct.unpack('!iiB', value)+ fields[name] = f'{x}x{y}' + ('dpi' if units == 3 else 'dpcm')+ elif tag == 0x16:+ fields[name] = None # delete-attribute+ else:+ fields[name] = struct.unpack('!i', value)[0] if tag in (0x21, 0x23) else bool(value[0]) if tag == 0x22 else value.decode()return fields@@ -1174,14 +1180,14 @@ def setup_and_tools(scale, queue_rename=True, preview=False):click('printers_remove_confirm')wait_for(lambda: called('PrinterDelete', lambda args: args == [remove_name]), 'confirmed queue removal')wait_for(lambda: set(scheduler.state()['queues']) == before_remove - {remove_name}, 'confirmed queue removal commit')- # A missing helper is an explicit read-only state. Disappearance- # during the page's lifetime cannot fall back to direct admin.+ # Helper disappearance during a request must not retry the+ # mutation through another backend. Refresh selects anew.helper.terminate()helper.wait(timeout=5)select_printer(ipc, ui, 0)click('printers_disable')- wait_for(lambda: any('cups-pk-helper' in label and ('install' in label.lower() or 'unavailable' in label.lower()) for label in labels()), 'missing helper guidance')- assert named('printers_add')['is_disabled'] and named('printers_disable')['is_disabled'] and named('printers_connection')['is_disabled'], 'missing helper must disable privileged controls'+ wait_for(lambda: 'printer authorization helper unavailable. refresh before trying again.' in ' '.join(labels()).lower(), 'lost helper requires explicit refresh')+ assert named('printers_add')['is_disabled'] and named('printers_disable')['is_disabled'] and named('printers_connection')['is_disabled'], 'a failed helper request must disable administration until refresh'assert scheduler.state()['queues']['Office_Test']['enabled'], scheduler.state()click('shortcuts')assert not printer_workers(process), 'setup page hide must release worker'diff --git a/tests/printers_direct.py b/tests/printers_direct.pynew file mode 100644index 0000000..be32fb5--- /dev/null+++ b/tests/printers_direct.py@@ -0,0 +1,368 @@+#!/usr/bin/env python3+"""Direct libcups against private scripted schedulers, never the host CUPS.++The native API checks exercise actual libcups HTTP/IPP and authentication. The+UI check runs the real Settings page with no helper on its private system bus.+"""+import base64+import ctypes+import json+import os+from pathlib import Path+import select+import socketserver+import struct+import subprocess+import sys+import tempfile+import time++from printers import (SetupScheduler, CUPS_CONNECT_HOOK, request_attributes,+ attribute, cups_ready, IPCClient, UIDriver, spawn_compositor,+ stop_process, wait_for)+++class DirectHandler(socketserver.StreamRequestHandler):+ def handle(self):+ try:+ line = self.rfile.readline().decode().split()+ if not line:+ return+ method, path = line[:2]+ headers = {}+ while True:+ line = self.rfile.readline()+ if line in (b'\r\n', b'\n', b''):+ break+ key, value = line.decode().split(':', 1)+ headers[key.lower()] = value.strip()+ protected = path.startswith('/admin')+ # Inventory GET/POST remains available to the independent reader.+ if self.server.auth and protected and headers.get('authorization') != 'Basic ' + base64.b64encode(b'fixture-admin:fixture-secret').decode():+ self.server.challenges += 1+ self.wfile.write(b'HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm="private fixture"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')+ return+ if headers.get('expect', '').lower() == '100-continue':+ self.wfile.write(b'HTTP/1.1 100 Continue\r\n\r\n')+ self.wfile.flush()+ if method == 'GET':+ name = path.rsplit('/', 1)[-1].removesuffix('.ppd')+ if name not in self.server.state()['queues']:+ status, response = 404, b''+ else:+ status, ipp = self.server.reply(0x400f, {'_request_id': 1, 'printer-uri': 'ipp://localhost/printers/' + name})+ response = ipp[ipp.index(b'*PPD-Adobe'):]+ # libcups' PPD parser expects these required headers.+ response = response.replace(b'*OpenGroup:', b'*FormatVersion: "4.3"\n*FileVersion: "1.0"\n*LanguageVersion: English\n*LanguageEncoding: ISOLatin1\n*PCFileName: "FIXTURE.PPD"\n*Manufacturer: "Fixture"\n*Product: "(Fixture)"\n*ModelName: "Fixture"\n*NickName: "Fixture"\n*PSVersion: "(3010) 0"\n*OpenGroup:', 1)+ else:+ if headers.get('transfer-encoding') == 'chunked':+ chunks = []+ while True:+ size = int(self.rfile.readline().strip(), 16)+ if not size:+ self.rfile.readline()+ break+ chunks.append(self.rfile.read(size))+ self.rfile.read(2)+ body = b''.join(chunks)+ else:+ body = self.rfile.read(int(headers.get('content-length', '0')))+ fields = request_attributes(body)+ fields['_request_id'] = struct.unpack_from('!I', body, 4)[0]+ operation = struct.unpack_from('!H', body, 2)[0]+ if self.server.stall and path.startswith('/admin'):+ self.server.release.wait(30)+ status, response = self.server.reply(operation, fields)+ self.wfile.write(f'HTTP/1.1 {status} Fixture\r\nContent-Type: application/ipp\r\nContent-Length: {len(response)}\r\nConnection: close\r\n\r\n'.encode() + response)+ except (BrokenPipeError, ConnectionResetError, TimeoutError):+ pass+++class DirectScheduler(SetupScheduler):+ def __init__(self, path, state):+ self.auth = False+ self.challenges = 0+ self.stall = False+ self.deny = None+ self.class_member = False+ super().__init__(path, state)+ self.RequestHandlerClass = DirectHandler++ def reply(self, operation, fields):+ state = self.state()+ name = fields.get('printer-uri', '').rsplit('/', 1)[-1]+ status = 0+ if operation == self.deny:+ status = 0x403+ elif operation == 0x000b and name not in state['queues']:+ status = 0x406+ elif operation in (0x4003, 0x4004, 0x400a, 0x10, 0x11, 0x4008, 0x4009):+ with self.lock:+ self.events.append((operation, dict(fields)))+ if operation == 0x4004:+ state['queues'].pop(name, None)+ elif operation == 0x400a:+ state['default'] = name+ else:+ queue = state['queues'].setdefault(name, {'uri': '', 'options': {}, 'enabled': False, 'accepting': False})+ if operation == 0x4003:+ if 'device-uri' in fields: queue['uri'] = fields['device-uri']+ if 'printer-info' in fields: queue['info'] = fields['printer-info']+ for key, value in fields.items():+ if key.endswith('-default'):+ if value is None: queue['options'].pop(key[:-8], None)+ else: queue['options'][key[:-8]] = value+ document = fields.get('_document', b'')+ if document:+ for line in document.decode().splitlines():+ if line.startswith('*Default'):+ key, value = line[8:].split(':', 1)+ queue['options'][key] = value.strip()+ elif operation in (0x10, 0x11): queue['enabled'] = operation == 0x11+ elif operation in (0x4008, 0x4009): queue['accepting'] = operation == 0x4008+ self.state_path.write_text(json.dumps(state))+ else:+ if operation not in (0x400b, 0x4005):+ return super().reply(operation, fields)+ response = struct.pack('!BBHI', 2, 0, status, fields['_request_id'])+ response += b'\x01' + attribute(0x47, 'attributes-charset', 'utf-8') + attribute(0x48, 'attributes-natural-language', 'en')+ if operation == 0x4005 and self.class_member:+ response += b'\x04' + attribute(0x42, 'printer-name', 'FixtureClass') + attribute(0x42, 'member-names', 'Label_Test')+ if operation == 0x400b and not status:+ for uri in ('usb://Fixture/Label?serial=direct', 'file:/tmp/forbidden'):+ response += b'\x04' + attribute(0x45, 'device-uri', uri)+ response += attribute(0x41, 'device-info', 'Direct fixture')+ response += attribute(0x41, 'device-make-and-model', 'Fixture Label')+ response += attribute(0x41, 'device-id', 'MFG:Fixture;MDL:Label;')+ response += attribute(0x44, 'device-class', 'direct')+ return 200, response + b'\x03'+++def fixture(tmp):+ state = tmp / 'queues.json'+ state.write_text(json.dumps({'queues': {'Label_Test': {'uri': 'usb://Fixture/Label?serial=existing', 'enabled': False, 'accepting': False, 'info': 'Fixture', 'options': {}}}, 'default': 'Label_Test'}))+ source = tmp / 'connect.c'+ source.write_text(CUPS_CONNECT_HOOK)+ hook = tmp / 'connect.so'+ subprocess.run(['cc', '-shared', '-fPIC', '-o', str(hook), str(source), '-ldl'], check=True)+ return DirectScheduler(tmp / 'cups.sock', state), hook+++def native_child(library):+ lib = ctypes.CDLL(library)+ ptr = ctypes.c_void_p+ lib.rediwm_cups_create.restype = ptr+ for name in ('destroy', 'fd', 'state', 'result', 'cancel', 'finish'):+ getattr(lib, 'rediwm_cups_' + name).argtypes = [ptr]+ lib.rediwm_cups_submit.argtypes = [ptr, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_char_p), ctypes.c_int]+ lib.rediwm_cups_credentials.argtypes = [ptr, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong]+ worker = lib.rediwm_cups_create()+ assert worker+ try:+ def command(method, args=(), reset=1, auth=False):+ argv = (ctypes.c_char_p * len(args))(*(x.encode() for x in args))+ assert lib.rediwm_cups_submit(worker, method.encode(), len(args), argv, reset) == 0+ fd = lib.rediwm_cups_fd(worker)+ challenges = 0+ while True:+ assert select.select([fd], [], [], 25)[0], (method, 'no worker result')+ os.read(fd, 8)+ state = lib.rediwm_cups_state(worker)+ if state == 1:+ challenges += 1+ assert auth, method+ password = b'wrong' if challenges == 1 or mode == 'bad-auth' else b'fixture-secret'+ lib.rediwm_cups_credentials(worker, b'fixture-admin', password, len(password))+ elif state == 2:+ result = lib.rediwm_cups_result(worker)+ lib.rediwm_cups_finish(worker)+ return result+ mode = sys.argv[3]+ if mode == 'class':+ assert command('PrinterRename', ['Label_Test', 'ClassBlocked']) == 5+ elif mode == 'denied':+ assert command('PrinterSetInfo', ['Label_Test', 'Must not change']) != 0+ elif mode == 'partial':+ assert command('PrinterRename', ['Label_Test', 'Partial']) == 4+ elif mode == 'active-jobs':+ assert command('PrinterRename', ['Label_Test', 'Blocked']) != 0+ elif mode == 'bad-auth':+ assert command('PrinterSetInfo', ['Label_Test', 'Must not change'], auth=True) != 0+ elif mode == 'auth':+ assert command('PrinterSetInfo', ['Label_Test', 'Authenticated'], auth=True) == 0+ elif mode == 'cancel':+ argv = (ctypes.c_char_p * 2)(b'Label_Test', b'cancelled')+ assert lib.rediwm_cups_submit(worker, b'PrinterSetInfo', 2, argv, 1) == 0+ assert select.select([lib.rediwm_cups_fd(worker)], [], [], 5)[0]+ os.read(lib.rediwm_cups_fd(worker), 8)+ assert lib.rediwm_cups_state(worker) == 1+ start = time.monotonic()+ lib.rediwm_cups_destroy(worker)+ worker = None+ assert time.monotonic() - start < 1+ elif mode == 'deadline':+ start = time.monotonic()+ assert command('PrinterSetInfo', ['Label_Test', 'Uncertain']) != 0+ assert 18 < time.monotonic() - start < 24, 'CUPS I/O must have an absolute deadline'+ elif mode == 'stall':+ argv = (ctypes.c_char_p * 2)(b'Label_Test', b'stalled')+ assert lib.rediwm_cups_submit(worker, b'PrinterSetInfo', 2, argv, 1) == 0+ time.sleep(.3)+ start = time.monotonic()+ lib.rediwm_cups_destroy(worker)+ worker = None+ assert time.monotonic() - start < 2+ else:+ assert command('DevicesGet') == 0+ assert command('PrinterAdd', ['Direct', 'usb://Fixture/Label?serial=direct', 'raw', 'Direct fixture', '']) == 0+ assert command('PrinterAdd', ['Direct', 'usb://Fixture/other', 'raw', 'Collision', '']) != 0+ for method, args in (+ ('PrinterSetEnabled', ['Direct', 'true']),+ ('PrinterSetAcceptJobs', ['Direct', 'true', '']),+ ('PrinterSetDefault', ['Direct']),+ ('PrinterSetInfo', ['Direct', 'Renamed description']),+ ('PrinterSetDevice', ['Direct', 'socket://127.0.0.1:9100']),+ ('PrinterAddOptionDefault', ['Direct', 'printer-resolution', '203dpi']),+ ('PrinterDeleteOptionDefault', ['Direct', 'printer-resolution']),+ ('PrinterAddOption', ['Direct', 'Darkness', '12']),+ ('PrinterRename', ['Direct', 'Cloned']),+ ('PrinterDelete', ['Cloned']),+ ):+ assert command(method, args) == 0, method+ if method == 'PrinterAddOption':+ state = json.loads((Path(os.environ['HOME']) / 'queues.json').read_text())+ assert state['queues']['Direct']['options']['Darkness'] == '12'+ if method == 'PrinterRename':+ state = json.loads((Path(os.environ['HOME']) / 'queues.json').read_text())+ assert 'Direct' not in state['queues']+ assert state['default'] == 'Cloned'+ assert state['queues']['Cloned']['options']['Darkness'] == '12'+ finally:+ if worker: lib.rediwm_cups_destroy(worker)+++def native_tests():+ with tempfile.TemporaryDirectory(prefix='rediwm-direct-native-') as directory:+ tmp = Path(directory)+ scheduler, hook = fixture(tmp)+ lib = tmp / 'direct.so'+ subprocess.run(['cc', '-shared', '-fPIC', '-g', '-Wno-deprecated-declarations', '-o', str(lib), 'src/printing/direct.c', '-lcups', '-lpthread'], check=True)+ env = {**os.environ, 'HOME': str(tmp), 'LD_PRELOAD': str(hook), 'PRINTER_FIXTURE_CUPS_SOCKET': str(tmp / 'cups.sock'), 'CUPS_USER': 'fixture-admin'}+ try:+ for mode in ('operations', 'auth', 'bad-auth', 'cancel', 'denied', 'class', 'active-jobs', 'partial', 'stall', 'deadline'):+ scheduler.auth = mode in ('auth', 'bad-auth', 'cancel')+ scheduler.deny = 0x4003 if mode == 'denied' else 0x4004 if mode == 'partial' else None+ scheduler.active_job = mode == 'active-jobs'+ scheduler.class_member = mode == 'class'+ scheduler.stall = mode in ('stall', 'deadline')+ subprocess.run([sys.executable, __file__, '--native-child', str(lib), mode], env=env, check=True, timeout=60)+ assert 'Cloned' not in scheduler.state()['queues']+ assert 'Partial' in scheduler.state()['queues']+ assert 'Blocked' not in scheduler.state()['queues']+ assert 'ClassBlocked' not in scheduler.state()['queues']+ assert scheduler.state()['queues']['Label_Test']['info'] == 'Authenticated'+ finally:+ scheduler.release.set()+ scheduler.close()+ print('Direct libcups operations, authentication retry and cancellation passed', flush=True)+++def ui_test(scale):+ with tempfile.TemporaryDirectory(prefix='rediwm-direct-ui-') as directory:+ tmp = Path(directory)+ scheduler, hook = fixture(tmp)+ bus = subprocess.Popen(['dbus-daemon', '--session', '--nofork', '--print-address=1'], stdout=subprocess.PIPE, text=True)+ process = log = None+ try:+ assert select.select([bus.stdout], [], [], 10)[0]+ address = bus.stdout.readline().strip()+ process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n', env_extra={+ 'CUPS_SERVER': '/run/cups/cups.sock', 'CUPS_ENCRYPTION': 'Never',+ 'LD_PRELOAD': str(hook), 'PRINTER_FIXTURE_CUPS_SOCKET': str(tmp / 'cups.sock'),+ 'HOME': str(tmp), 'XDG_CONFIG_HOME': str(tmp / 'config'), 'XDG_DATA_HOME': str(tmp / 'data'), 'XDG_CACHE_HOME': str(tmp / 'cache'),+ 'DBUS_SESSION_BUS_ADDRESS': '', 'DBUS_SYSTEM_BUS_ADDRESS': address,+ 'PIPEWIRE_RUNTIME_DIR': str(tmp), 'PULSE_SERVER': 'unix:/nonexistent-rediwm-printers-test-pulse',+ })+ with IPCClient(tmp, timeout=15) as ipc:+ ui = UIDriver(ipc)+ def click(name):+ wait_for(lambda: not ui.find(name, panel='control_center')['is_disabled'], name, timeout=15)+ ui.click(ui.scroll_into_view(name, panel='control_center'), panel='control_center')+ ui.wait_settled('control_center')+ ipc.open_control_center()+ ui.wait_settled('control_center')+ click('printers')+ wait_for(lambda: cups_ready(ui), 'direct page loaded', timeout=15)+ click('printers_resume')+ wait_for(lambda: scheduler.state()['queues']['Label_Test']['enabled'], 'helper-absent resume')+ wait_for(lambda: cups_ready(ui), 'refresh after resume')+ scheduler.auth = True+ click('printers_manage')+ click('printers_accepting')+ wait_for(lambda: any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'CUPS password UI')+ click('printers_auth_user')+ ipc.key(29, True); ipc.key_press('a'); ipc.key(29, False)+ ipc.type_text('fixture-admin')+ click('printers_auth_password')+ ipc.type_text('fixture-secret')+ assert 'fixture-secret' not in json.dumps(ui.widgets()), 'secret must not be exposed by widget inspection'+ click('printers_auth_submit')+ wait_for(lambda: scheduler.state()['queues']['Label_Test']['accepting'], 'authenticated administration')+ wait_for(lambda: cups_ready(ui), 'inventory refresh')+ click('printers_accepting')+ wait_for(lambda: any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'new operation must request fresh credentials')+ click('printers_auth_cancel')+ wait_for(lambda: not any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'cancel clears prompt')+ # Hide while a second prompt is outstanding; worker joins promptly.+ click('printers_accepting')+ wait_for(lambda: any(w.get('name') == 'printers_auth_password' for w in ui.widgets()), 'hide challenge')+ start = time.monotonic()+ click('general')+ assert time.monotonic() - start < 3+ assert scheduler.state()['queues']['Label_Test']['accepting']+ scheduler.auth = False+ click('printers')+ wait_for(lambda: cups_ready(ui), 'reopened direct page')+ click('printers_add')+ click('printers_discover')+ wait_for(lambda: any(w.get('name') == 'printers_device_0' for w in ui.widgets()), 'direct discovery')+ assert not any(w.get('name') == 'printers_device_1' for w in ui.widgets()), 'unsafe backend URI must be filtered'+ click('printers_device_0')+ click('printers_name')+ ipc.key(29, True); ipc.key_press('a'); ipc.key(29, False)+ ipc.type_text('Ui_Direct')+ click('printers_create')+ wait_for(lambda: scheduler.state()['queues'].get('Ui_Direct', {}).get('accepting'), 'direct add/enable/accept chain')+ created = scheduler.state()['queues']['Ui_Direct']+ assert created['enabled'] and created['uri'] == 'usb://Fixture/Label?serial=direct'+ assert not scheduler.printed, 'administration must not print a document'+ wait_for(lambda: cups_ready(ui), 'direct add refreshed')+ # Both native threads must sleep without timed wakes at idle.+ def counters():+ result = {}+ for task in Path(f'/proc/{process.pid}/task').iterdir():+ try:+ if task.joinpath('comm').read_text().strip() not in ('rediwm-cups', 'rediwm-cups-io'): continue+ fields = dict(line.split(':', 1) for line in task.joinpath('status').read_text().splitlines())+ result[task.name] = int(fields['voluntary_ctxt_switches'])+ except FileNotFoundError: pass+ return result+ time.sleep(.3)+ before = counters()+ time.sleep(.6)+ assert len(before) == 2 and counters() == before, 'native administration must not poll at idle'+ finally:+ if process: stop_process(process)+ if log: log.close()+ bus.terminate(); bus.wait(timeout=5)+ scheduler.close()+ print('Helper-absent Settings and secure CUPS challenge lifecycle passed at scale', scale, flush=True)+++if __name__ == '__main__':+ os.umask(0o077)+ if len(sys.argv) > 1 and sys.argv[1] == '--native-child':+ native_child(sys.argv[2])+ else:+ native_tests()+ ui_test(os.environ.get('REDIWM_TEST_SCALE', '1'))diff --git a/tests/system_monitor.py b/tests/system_monitor.pyindex b11a03b..437ec19 100644--- a/tests/system_monitor.py+++ b/tests/system_monitor.py@@ -76,7 +76,8 @@ def run(scale, workspace):tmp = Path(directory)config = ('[compositor]\nxwayland = false\n' +('desktop_mode = "workspaces"\n' if workspace else '') +- '[theme]\napp_bg = "#203040"\n')+ '[theme]\napp_bg = "#203040"\napp_item_hover = "#4a6076"\n'+ 'app_item_selected = "#62768a"\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"}@@ -165,6 +166,37 @@ def run(scale, workspace):time.sleep(1.2)assert ImageChops.difference(paused, shot("still-paused", True)).getbbox() is None+ # Files' rounded hover and selection fills, with no idle timer.+ def move(x, y):+ b = box()+ ipc.move_cursor(round(b["x"] + x), round(b["y"] + y))++ def row_pixel(name, y):+ image = shot(name)+ factor = image.width / box()["width"]+ return image.getpixel((round(20 * factor), round(y * factor)))++ assert row_pixel("row-idle", 252) == (32, 48, 64)+ move(40, 252)+ time.sleep(.6)+ assert row_pixel("row-hover", 252) == (74, 96, 118)+ idle("hover settled")+ move(40, 284)+ time.sleep(.6)+ assert row_pixel("row-glide", 284) == (74, 96, 118)+ assert row_pixel("row-glide-old", 252) == (32, 48, 64)+ click(40, 284)+ time.sleep(.6)+ assert row_pixel("row-selected", 284) == (98, 118, 138)+ # Leaving the surface fades hover away without dropping selection.+ move(40, 316)+ time.sleep(.6)+ ipc.move_cursor(0, 0)+ time.sleep(.6)+ assert row_pixel("row-left", 316) == (32, 48, 64)+ assert row_pixel("row-selection-kept", 284) == (98, 118, 138)+ idle("row feedback settled")+# Atomic theme replacement still wakes a paused app.changed = tmp / "theme-new.toml"changed.write_text(config.replace("#203040", "#304050"))