RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Region and recent-files work, UI and settings polish, test updates
oxydizerc42718d18113
diff --git a/README.md b/README.mdindex cda2073..e7756ee 100644--- a/README.md+++ b/README.md@@ -6,14 +6,12 @@### A Wayland compositor with its own desktop shell, built in Zig-<!-- badges go here -->-</div>-RediWM is a [wlroots](https://gitlab.freedesktop.org/wlroots/wlroots) compositor+RediWM is a single process [wlroots](https://gitlab.freedesktop.org/wlroots/wlroots) compositorthat draws its whole shell itself: taskbar, start menu, settings, lock and loginscreens, notifications and OSDs, all in one process, benchmarked against-[labwc](https://labwc.github.io/) to stay as lean.+[labwc](https://labwc.github.io/) to stay as lean (192mb idle ram usage, <1% CPU usage)https://github.com/user-attachments/assets/60bc1190-694c-4fb7-b2bc-d90e5e9faa90@@ -39,26 +37,19 @@ curl -fsSL https://raw.githubusercontent.com/oxydizer/rediwm/HEAD/scripts/instal````scripts/install.sh` installs the prebuilt release for your distro (Arch,-Debian, Ubuntu and Fedora on x86_64, and their derivatives): the compositor,-the apps and the exact wlroots 0.20 they were tested with, including the-[window-title patch](patches/wlroots/README.md). Installing never replaces your login manager. SDDM, GDM and the-like keep working, and RediWM only appears as a session in their picker. The-`rediwm-dm` login manager is installed only with `--dm`, and even then it is-not enabled (see below).+Debian, Ubuntu and Fedora).+Installing never replaces your login manager## Building and running-Requirements: Zig 0.16, wlroots 0.20 (`scripts/install.sh --build` builds it-into a private prefix on Debian/Ubuntu, and `REDIWM_PRIVATE_WLROOTS=1` does so-on Arch and Fedora), and the development files for Wayland,+Requirements: Zig 0.16, wlroots 0.20, and the development files for Wayland,wayland-protocols, xkbcommon, pixman, FreeType, HarfBuzz, Fontconfig,librsvg/GdkPixbuf, PangoCairo, libinput, PAM, libpulse, libpipewire-0.3, Poppler GLib,libseccomp, libjpeg and libpng. Optional:-Xwayland, `foot`, `brightnessctl`, `gio`/`xdg-open`, `git` (Files repository status).+Xwayland, `foot`, `brightnessctl`, `gio`/`xdg-open`, `git` (optional).-Runtime portals: `xdg-desktop-portal`, `xdg-desktop-portal-wlr` for screen-sharing, and `xdg-desktop-portal-gtk` for fallback portals. `scripts/install.sh`-installs all three.+Run from a checkout, `scripts/install.sh` builds that checkout (dependencies,+then `install-session.sh` with the arguments you give it).```shzig build run -- foot # nested in your current Wayland session@@ -67,9 +58,6 @@ sh scripts/install-session.sh # install and restart the running sesssh scripts/install-session.sh --no-restart --dm # install only, plus rediwm-dm```-Run from a checkout, `scripts/install.sh` builds that checkout (dependencies,-then `install-session.sh` with the arguments you give it).-### Releasing`scripts/make-release.sh` builds each distro's tarball (`rediwm-<distro>-x86_64.tar.gz`)@@ -97,65 +85,17 @@ RediWM); it refuses to parse a document if isolation cannot be established.| Super+Z | undo the last window move or resize || Super+Shift+E | quit |-All bindings live in `[keybinds]` (`"noop"` disables one).--- Alt+drag moves windows, Alt+right-drag resizes. **Super+Alt+mouse** or a- middle-button drag pans the desktop; **Super+Alt+scroll** zooms it, and- **Alt+scroll** over a window zooms just that window. Ordinary desktop zoom scales all- windows together around the pointer, up to 100%, without changing their- world positions. Desktop icons stay fixed by default; the taskbar stays fixed.- The shared volume/brightness OSD also shows the desktop zoom percentage.-- **Window switching zoom** in Settings → Appearance controls Alt+Tab,- directional focus and taskbar activation. **Boost window** (the default)- temporarily brings the selected floating window to 100% on-screen size- while preserving desktop zoom, its position and its saved window zoom.- Switching away restores its original scale. **Keep zoom** only pans;- **Focus camera** zooms the desktop to the selected window's depth, fading- windows that would grow beyond full size. In that mode, desktop zoom also- steps through the depths of open windows above 100%. Configure this with- `[compositor] focus_zoom = "boost"`, `"keep"`, or `"camera"`.- Window reveals ease over 320 ms, and titlebar scrolling uses the same- eased window zoom as Alt+scroll. Animation speed and reduced motion apply- to these transitions; `[animations.camera_reveal]` can override the pan.-- **Window tabs** in Settings → Appearance lets you enable tabs per app using- RediWM chrome (XDG, KDE or X11 decorations). Open an app once to list it.- **+** opens another window as a tab in that frame; ordinary launches stay- separate. Each tab has a close button, and the outer close button closes- the group while respecting app confirmation dialogs. Disabling tabs restores- separate windows. App IDs are saved in `[compositor] window_tab_apps`.- Arrow buttons and scrolling over the strip switch tabs; Alt+scroll still- zooms the window. Apps need a desktop entry with a usable launch command;- launches that only activate an existing window do not create a tab.-- **Settings** (start menu cog) is a regular window covering display modes,- scale and night light, input, audio, appearance, shortcuts and the desktop- canvas. Changes are saved to the config with its comments intact.-- The lock screen covers every output; Escape clears the field and never- unlocks. It engages before the system sleeps, and sleep waits until it is- on screen (`[compositor] lock_on_suspend`, on by default), and on- `loginctl lock-session`. RediWM doesn't lock on idle itself: run- `swayidle -w timeout 300 'swaylock -f'` from `[[autostart]]`.-- Desktop icons run a `.desktop` launcher only if it is installed, owned by- root, executable, or an exact copy of an installed entry. Any other- launcher shows as the file it is until you choose **Allow Launching** from- its menu.-- `rediwm-dm` runs the greeter as an unprivileged user on its own VT. After- installing, disable your current display manager, `sudo systemctl enable- rediwm-dm` and reboot; options live in `/etc/rediwm/dm.conf`.-- In `rediwm-files`, **Space** opens images, PDFs and text files. **Text Editor**- (`rediwm-editor [FILE ...]`) opens text files in tabs in one window per display.- Use **Ctrl+N** for a new tab, **Ctrl+O** to open, **Ctrl+S** to save,- **Ctrl+Shift+S** for the existing Save As dialog, **Ctrl+Page Up/Down** to- switch tabs, **Ctrl+W** to close a tab, and **Ctrl+F** / **F3** to find text.- It supports UTF-8 files up to 16 MiB, preserves BOM and line endings, and- prompts before discarding changes. Files, Images and Text Editor also run- on other Wayland compositors.-- Games get pointer lock and relative motion. VMs and remote desktops can- capture shortcuts; **Super+Escape** takes them back.-- The desktop renders before autostart; session environment publication and- audio connection do not block frames or input. Xwayland starts on the first- X11 connection, including with native scaling.-- X11 limits of wlroots 0.20: X11→Wayland drag-and-drop- doesn't start, and X11 pointer input on a second output doesn't arrive.+All bindings live in `[keybinds]`; `"noop"` disables one.++- **Mouse:** Alt+drag moves windows, Alt+right-drag resizes. Super+Alt+drag (or middle-drag) pans the desktop, Super+Alt+scroll zooms it, and Alt+scroll zooms a single window.+- **Zoom on window switch:** `[compositor] focus_zoom` (also in Settings → Appearance) controls what Alt+Tab, directional focus and taskbar activation do. `"boost"` (default) shows the window at 100% until you switch away, `"keep"` only pans, and `"camera"` zooms the desktop to the window's depth.+- **Window tabs:** enable per app in Settings → Appearance (saved in `[compositor] window_tab_apps`). **+** opens a new window as a tab. The app needs a desktop entry with a launch command.+- **Lock screen:** covers every output and engages before suspend (`[compositor] lock_on_suspend`) and on `loginctl lock-session`. There's no idle lock; add `swayidle -w timeout 300 'swaylock -f'` to `[[autostart]]`.+- **Desktop icons:** a `.desktop` launcher only runs if it's installed, root-owned, executable, or an exact copy of an installed entry. Otherwise, choose **Allow Launching** from its menu.+- **`rediwm-dm`:** disable your current display manager, run `sudo systemctl enable rediwm-dm`, and reboot. Options are in `/etc/rediwm/dm.conf`.+- **Text editor:** `rediwm-editor [FILE ...]` opens UTF-8 files in tabs, from tiny notes to logs of hundreds of megabytes (up to 4 GiB, if they fit in free memory). Ctrl+N new, Ctrl+O open, Ctrl+S save, Ctrl+Shift+S save as, Ctrl+W close tab, Ctrl+PgUp/PgDn switch tabs, Ctrl+F or F3 find. In `rediwm-files`, Space previews images, PDFs and text.+- **Games and VMs:** games get pointer lock and relative motion. If a VM or remote desktop grabs your shortcuts, Super+Escape takes them back.+- **Known issues (wlroots 0.20):** X11→Wayland drag-and-drop doesn't start, and X11 pointer input on a second output doesn't arrive.## Protocols@@ -186,9 +126,6 @@ previous config. Sections: `[theme]`, `[input]`, `[input_method]`,`[polkit]`, `[ipc]`, `[keybinds]`, `[[outputs]]`, `[[autostart]]`,`[[window_rules]]`, `[[notification_rules]]` and `[[sandbox_allow]]`.-The `.toml` files use a **line-based TOML subset**, including standalone theme-files.-Window rules match by globs; for each property the last matching rule wins:```tomldiff --git a/TESTING.md b/TESTING.mdindex 58181c5..a6ace1e 100644--- a/TESTING.md+++ b/TESTING.md@@ -37,6 +37,8 @@ compiler, `wayland-scanner` and wayland-protocols; D-Bus suites need PyGObject,layout autosave and saved window sizes.- Files lists the host's removable and external disks from UDisks2, so everyFiles-launching suite sets `REDIWM_FILES_DEVICES=0`. Do the same in new ones.+- Files records opened files in shared recent history; set a scratch+ `XDG_DATA_HOME` in suites that open files so they never update the host's history.- `REDIWM_TEST_RENDERER=gles2`: GPU rendering (needs a render node; pick onewith `WLR_RENDER_DRM_DEVICE=/dev/dri/renderD128` on multi-GPU machines).GLES2 frees CPU scene buffers after upload, so `DumpBuffer` checks run on@@ -178,7 +180,8 @@ a JSON result on stdout.**Desktop, Files, Images**: `desktop_icons.py`, `desktop_damage.py`,`files_browser.py` (file-path selection; with `REDIWM_FORCE_DBUS=1` on a private`dbus-run-session` bus, also checks `FileManager1.ShowItems`), `files_controls.py`, `files_decoration.py`,-`files_thumbnails.py` (draws real pictures and reads thumbnail pixels back: shape,+`files_controls.py --places-only` isolates navigation, Recent history and sidebar+controls from the Git checks. `files_thumbnails.py` (draws real pictures and reads thumbnail pixels back: shape,colour, EXIF rotation, the shared freedesktop cache read and write, a 240-picturefolder, the `REDIWM_FILES_THUMBNAILS=0` switch and idle wakeups; it sets a scratch`XDG_CACHE_HOME`), `files_fixes.py` (wl-clipboard), `files_associations.py` (private MIME/app@@ -193,9 +196,11 @@ back on drop or Escape; also camera zoom, the setting off and nothing to uncoverthemed cursor pixels, live theme reload and client cursor serials).**Text editor**: `zig build test-editor` (document history, Unicode boundaries,-file classification and safe saving), `python3 tests/editor.py` (Files Space,-tab reuse and activation, typing, undo/redo, clipboard, Save As, unsaved-close-prompts and external-change protection). `python3 tests/editor_visuals.py` checks+line segmentation and folding, the scrolling view, file classification, loading+and safe saving), `python3 tests/editor.py` (Files Space, tab reuse and+activation, typing, undo/redo, clipboard, Save As, unsaved-close prompts,+external-change protection, and a 46 MiB file opened, edited at its end and+saved exactly). `python3 tests/editor_visuals.py` checkscaret blinking and idle wakeups, and title glyph dimensions across resizes(`REDIWM_EDITOR_DRAG=1` exercises pointer resizing). Supports `REDIWM_TEST_SCALE`,`REDIWM_TEST_RENDERER`, and `REDIWM_EDITOR_PREVIEW=/tmp/editor.png`.diff --git a/data/rediwm-files.desktop b/data/rediwm-files.desktopindex b5c368f..6a8bd32 100644--- a/data/rediwm-files.desktop+++ b/data/rediwm-files.desktop@@ -5,6 +5,7 @@ Name=RediWM FilesGenericName=File ManagerComment=Browse, open and manage local files and foldersExec=rediwm-files %f+MimeType=inode/directory;Icon=redi-fm-iconTerminal=falseStartupWMClass=rediwm-filesdiff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.mdindex 7ed9792..cd08b6f 100644--- a/docs/wiki/Configuration.md+++ b/docs/wiki/Configuration.md@@ -36,9 +36,9 @@ built-in default. Appearance preserves these overrides when it saves.## Region & Language-Settings → Region & Language shows the login session's language, regional-formats and time zone. These system settings are read-only; RediWM's interface-currently uses English. Format examples use the session's locale categories.+Settings → Region & Language lets you choose a personal language, regional+formats and time zone. Empty choices inherit the login environment; system+defaults are unchanged. RediWM's interface currently uses English.Personal clock and calendar preferences apply immediately and are saved in`[region]`:@@ -46,10 +46,16 @@ Personal clock and calendar preferences apply immediately and are saved in```toml[region]clock_24h = false+clock_show_seconds = false+clock_show_day = truefirst_day_of_week = "sunday"````clock_24h` applies to the taskbar, calendar and built-in lock screen.+`clock_show_seconds` adds seconds to the taskbar time. `clock_show_day` shows+the date line beneath it, using the selected regional format (`formats`, or+the inherited locale). Both lines are centered; hiding the date centers the+time vertically. These two options apply only to the taskbar clock.`first_day_of_week` accepts any lowercase weekday name, and changes both theweekday headings and date positions in the taskbar calendar. Existing configskeep 12-hour time and Sunday first until changed.diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.mdindex 01a9091..659e158 100644--- a/docs/wiki/Theme.md+++ b/docs/wiki/Theme.md@@ -10,6 +10,19 @@ RediWM Light uses 75% window chrome opacity and teal selection accents.`start_button_logo_color` optionally tints the bundled R logo; Light uses adark tint for contrast. Custom start-button icons retain their own colours.+Appearance also has a **Taskbar theme** picker under Theme, with the same+presets plus "Same as theme". It gives the taskbar the preset's colours and+leaves every other surface on the theme above. It is saved as a+`[taskbar_theme]` section holding only these keys: `taskbar_bg`,+`taskbar_surface`, `taskbar_hover`, `taskbar_border`, `border_soft`,+`surface_hover`, `window_fg`, `window_dim`, `danger`, `window_close_hover`,+`start_button_hover`, `start_button_indicator`, `start_button_logo_color` and+the `battery_*` colours. Unlisted keys are ignored, so a whole theme file's+body can be pasted under that header; keys it leaves out take the built-in+defaults, not the main theme's. The section's presence selects the taskbar+theme (an empty one is the built-in colours); without it the taskbar follows+`[theme]`. Sizes, gaps and radii always come from `[theme]`.+Colors accept `"#rrggbb"`, `"#rrggbbaa"`, or `"rgba(r,g,b,a)"` with RGBchannels from 0 to 255 and alpha from 0 to 1. Numbers must be finite andnonnegative. Sizes are logical pixels. The tables describe appearance tokens;@@ -59,6 +72,12 @@ the current built-in radii, Sharp caps them at 4 px (the minimap's default),and Round uses 1.3 times the defaults. Individual theme radii remain editable.Cursor styling is `[input].cursor_theme` and `[input].cursor_size`; animation behavior belongs in `[animations]`.+Set `[theme].chrome_round_buttons = true` for circular window controls and+pill-shaped window tabs. Tab close, new-tab and overflow controls follow the+same setting. It defaults to `false`, preserving the existing corner radii,+and reloads live from the main config or the `REDIWM_THEME` file. Button sizes+and hit targets stay the same; `radius_lg` still controls the window frame.+The lock's background always paints opaque, even if `lock_bg` supplies alpha;`lock_wallpaper_opacity` controls its wallpaper overlay. Actual image pixels,PDF paper/content, application-provided icons and fixed layout/hit-test@@ -314,3 +333,7 @@ fit their available space. The scrollbar reserves room for its maximum width;| `font` | `"Manrope"` | Compositor's preferred proportional font family || `mono_font` | `"JetBrains Mono"` | Compositor's preferred monospace font family || `start_button_icon` | `""` | Bundled Redi logo; otherwise an absolute image path |++In **Settings → Appearance → Start menu**, **Choose file…** selects a PNG or+SVG for the Start button logo and applies it immediately. **Reset to default**+restores the bundled R logo. Both choices are saved with the theme.diff --git a/scripts/make-release.sh b/scripts/make-release.shold mode 100644new mode 100755diff --git a/src/Input.zig b/src/Input.zigindex cb642b2..c9c14d0 100644--- a/src/Input.zig+++ b/src/Input.zig@@ -1412,11 +1412,22 @@ pub fn processCursorMotion(input: *Input, time_msec: u32) void {}fn passthroughMotion(input: *Input, time_msec: u32) void {+ // Shell controls keep receiving motion until release, just like a client's+ // implicit grab. A scrollbar drag may leave the whole window or panel.if (input.open_control_center) |cc| {- if (cc.appearance.item_drag != null) {+ if (cc.pointer_down) {const local = cc.localPoint(input.cursor.x, input.cursor.y);control_center.pointerMotion(cc, local.x, local.y);- input.setNamedCursor("grabbing");+ if (cc.appearance.item_drag != null) input.setNamedCursor("grabbing") else input.setShellCursor(ui_input.current.overText());+ input.seat.pointerClearFocus();+ return;+ }+ }+ if (input.open_start_menu) |menu| {+ if (menu.dispatcher.scroll_drag != null) {+ const local = scene_data.toNodeLocal(&menu.buffer_node.node, input.cursor.x, input.cursor.y);+ menu.pointerMotion(local.x, local.y);+ input.setDefaultCursor();input.seat.pointerClearFocus();return;}diff --git a/src/Server.zig b/src/Server.zigindex 88f4a32..6421afb 100644--- a/src/Server.zig+++ b/src/Server.zig@@ -377,6 +377,7 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:loaded.polkit.enable = false;}ui_theme.global = loaded.theme;+ ui_theme.taskbar_override = if (loaded.taskbar_theme) |chosen| ui_theme.taskbarTokens(chosen) else null;@import("ui").text.setPreferredFamilies(ui_theme.global.font, ui_theme.global.mono_font);// Caret timings are process-wide UI-engine state, like the theme, and the// panels paint before any input device exists to carry them in.@@ -421,6 +422,10 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:.greeter_mode = greeter,};+ if (!greeter) @import("config_runtime/region.zig").applyTimezone(@import("main.zig").gpa, loaded.region.timezone, environ.getPosix("TZ")) catch |err| {+ log.warn("could not apply personal timezone: {}", .{err});+ };+// The syncobj global itself is created with the other globals below.// REDIWM_NO_EXPLICIT_SYNC=1 withholds it, to tell driver sync bugs apart.if (environ.getPosix("REDIWM_NO_EXPLICIT_SYNC") == null and explicit_sync.supported(renderer, backend)) {@@ -671,6 +676,7 @@ pub fn applyChildEnvWithToken(server: *Server, map: *child_env.Map, token: ?[]cotry map.put("PATH", path);try child_env.apply(map, .{+ .region = server.config.region,.input_method = server.config.input_method.env,.wayland_display = server.wl_server_socket_name,.ipc_socket = server.ipc_socket_path,diff --git a/src/Taskbar.zig b/src/Taskbar.zigindex 6a12fe8..c7dce7d 100644--- a/src/Taskbar.zig+++ b/src/Taskbar.zig@@ -15,6 +15,7 @@ const wlr = @import("wlroots");const col = @import("color.zig");const c_time = @cImport({+ @cInclude("locale.h");@cInclude("time.h");});@@ -192,7 +193,9 @@ audio_volume: f32 = 0,audio_muted: bool = false,clock_time: [16]u8 = [_]u8{0} ** 16,-clock_date: [16]u8 = [_]u8{0} ** 16,+clock_date: [128]u8 = [_]u8{0} ** 128,+clock_locale: c_time.locale_t = null,+clock_minute: c_time.time_t = 0,// Layout and every tick ask for these; shaping them each time showed up in// idle profiles. The clock's is dropped when its strings change.clock_width: MeasuredWidth = .{},@@ -289,7 +292,7 @@ const ChipMemo = struct {.radius = t.radius,.title_size = t.taskbar_title_size,.font = t.font,- .colors = .{ t.taskbar_surface, t.taskbar_hover, t.surface_hover, t.taskbar_border, t.border_soft, t.window_fg },+ .colors = .{ ui_theme.taskbar(.taskbar_surface), ui_theme.taskbar(.taskbar_hover), ui_theme.taskbar(.surface_hover), ui_theme.taskbar(.taskbar_border), ui_theme.taskbar(.border_soft), ui_theme.taskbar(.window_fg) },};}};@@ -384,6 +387,7 @@ pub fn create(server: *Server, wlr_output: *wlr.Output) !*Taskbar {.capture_node = capture_node,.battery_node = battery_node,.battery_state = battery.read(server.io, gpa),+ .clock_minute = @divFloor(c_time.time(null), 60),.timer = undefined,};bar.node_data = .{ .role = .{ .taskbar = bar } };@@ -402,6 +406,7 @@ pub fn create(server: *Server, wlr_output: *wlr.Output) !*Taskbar {bar.refreshStartLogo();bar.timer = try server.wl_server.getEventLoop().addTimer(*Taskbar, onTick, bar);errdefer bar.timer.remove();+ bar.updateClockLocale();_ = bar.updateClockStrings();bar.scheduleClockTick();return bar;@@ -411,6 +416,7 @@ pub fn destroy(bar: *Taskbar) void {if (bar.server.tray) |tray_mgr| tray_mgr.closeMenu();bar.server.input.detachTaskbar(bar);bar.timer.remove();+ if (bar.clock_locale) |locale| c_time.freelocale(locale);if (bar.start_logo) |e| bar.server.iconRelease(e.id);for (bar.chips.items) |chip| {if (chip.raster) |raster| raster.base.drop();@@ -442,18 +448,17 @@ pub fn applyBattery(bar: *Taskbar, next: battery.State) void {}fn onTick(bar: *Taskbar) c_int {- // Plug events arrive through Server's uevent socket; this catches the- // capacity changes firmware does not announce.- bar.applyBattery(battery.read(bar.server.io, gpa));- if (bar.updateClockStrings()) {- bar.clock_dirty = true;- bar.markDirty(paint_clock);- bar.wlr_output.scheduleFrame();- stats.recordTaskbarClockFrameRequest();- }- if (Output.fromWlr(bar.wlr_output)) |output| {- if (output.calendar) |calendar| calendar.refresh();+ // Seconds only repaint the clock. Keep expensive sysfs reads and the+ // calendar on their minute cadence; plug events have their own uevent.+ const minute = @divFloor(c_time.time(null), 60);+ if (minute != bar.clock_minute) {+ bar.clock_minute = minute;+ bar.applyBattery(battery.read(bar.server.io, gpa));+ if (Output.fromWlr(bar.wlr_output)) |output| {+ if (output.calendar) |calendar| calendar.refresh();+ }}+ bar.refreshClock();bar.scheduleClockTick();return 0;}@@ -476,41 +481,52 @@ pub fn markDirty(bar: *Taskbar, cause: u8) void {}fn scheduleClockTick(bar: *Taskbar) void {- var raw: c_time.time_t = c_time.time(null);- var tm_storage: c_time.struct_tm = undefined;- const tm = c_time.localtime_r(&raw, &tm_storage) orelse {+ var now: c_time.struct_timespec = undefined;+ if (c_time.clock_gettime(c_time.CLOCK_REALTIME, &now) != 0) {bar.timer.timerUpdate(1000) catch |err| {- log.err("scheduleClockTick: localtime failed: {}", .{err});- };- return;- };-- const tm_sec = tm.*.tm_sec;- if (tm_sec < 0 or tm_sec > 59) {- bar.timer.timerUpdate(1000) catch |err| {- log.err("scheduleClockTick: invalid tm_sec {}: {}", .{ tm_sec, err });+ log.err("scheduleClockTick: clock_gettime failed: {}", .{err});};return;}-- // Keep updates aligned to the displayed minute boundary to avoid one-second- // frame requests when the shown strings did not change. Battery capacity- // shares this wakeup instead of adding its own.- const delay_ms: c_int = @intCast((60 - tm_sec) * 1000 + 25);+ // Wake just after the next displayed boundary, without accumulating drift.+ // A hidden clock only needs the shared minute wake for battery/calendar.+ const interval: c_time.time_t = if (bar.server.config.region.clock_show_seconds and bar.itemShown(.clock)) 1 else 60;+ const delay_ms: c_int = @intCast((interval - @mod(now.tv_sec, interval)) * 1000 - @divTrunc(now.tv_nsec, 1_000_000) + 25);bar.timer.timerUpdate(delay_ms) catch |err| {log.err("scheduleClockTick: could not reschedule clock timer: {}", .{err});};}-pub fn refreshClock(bar: *Taskbar) void {+fn updateClockLocale(bar: *Taskbar) void {+ const name = gpa.dupeZ(u8, bar.server.config.region.formats) catch return;+ defer gpa.free(name);+ // Keep a private locale: changing the process locale would affect workers.+ const locale = c_time.newlocale(c_time.LC_TIME_MASK, name, null);+ if (bar.clock_locale) |old| c_time.freelocale(old);+ bar.clock_locale = locale;+}++pub fn refreshClockSettings(bar: *Taskbar) void {+ bar.updateClockLocale();+ bar.refreshClock();+ bar.scheduleClockTick();+}++fn refreshClock(bar: *Taskbar) void {+ const previous_width = bar.clockColumnWidth();if (!bar.updateClockStrings()) return;bar.clock_dirty = true;- // A wider/narrower clock moves every item to its left, including the tray.- bar.tray_dirty = .{ true, true };- bar.capture_dirty = true;- const chips_changed = bar.reconcile(nowMs());- bar.markDirty(paint_clock | paint_tray | paint_capture | (if (chips_changed) paint_chips else @as(u8, 0)));+ var causes: u8 = paint_clock;+ if (previous_width != bar.clockColumnWidth()) {+ // A wider/narrower clock moves every item to its left, including the tray.+ bar.tray_dirty = .{ true, true };+ bar.capture_dirty = true;+ const chips_changed = bar.reconcile(nowMs());+ causes |= paint_tray | paint_capture | (if (chips_changed) paint_chips else @as(u8, 0));+ }+ bar.markDirty(causes);bar.wlr_output.scheduleFrame();+ stats.recordTaskbarClockFrameRequest();}fn updateClockStrings(bar: *Taskbar) bool {@@ -519,9 +535,16 @@ fn updateClockStrings(bar: *Taskbar) bool {const tm = c_time.localtime_r(&raw, &tm_storage) orelse return false;var next_time: [16]u8 = undefined;- var next_date: [16]u8 = undefined;- if (c_time.strftime(&next_time, next_time.len, bar.server.config.region.timeFormat(), tm) == 0) return false;- if (c_time.strftime(&next_date, next_date.len, "%a, %b %-d", tm) == 0) return false;+ var next_date: [128]u8 = @splat(0);+ const prefs = bar.server.config.region;+ if (c_time.strftime(&next_time, next_time.len, prefs.taskbarTimeFormat(), tm) == 0) return false;+ if (prefs.clock_show_day) {+ const len = if (bar.clock_locale) |locale|+ c_time.strftime_l(&next_date, next_date.len, "%x", tm, locale)+ else+ c_time.strftime(&next_date, next_date.len, "%x", tm);+ if (len == 0) return false;+ }const prev_time = std.mem.sliceTo(&bar.clock_time, 0);const prev_date = std.mem.sliceTo(&bar.clock_date, 0);@@ -560,6 +583,7 @@ pub fn relayout(bar: *Taskbar, output_box: wlr.Box) void {bar.battery_dirty = true;for (bar.chips.items) |*chip| chip.dirty = true;bar.render(now_ms, paint_start | paint_chips | paint_tray | paint_clock);+ bar.scheduleClockTick();bar.dirty = false;bar.paint_causes = 0;if (Output.fromWlr(bar.wlr_output)) |output| if (output.wifi_popup) |popup| {@@ -589,10 +613,10 @@ fn clockColumnWidth(bar: *Taskbar) f32 {if (bar.clock_width.get(scale)) |width| return width;const time_str = std.mem.trimStart(u8, std.mem.sliceTo(&bar.clock_time, 0), " ");const date_str = std.mem.sliceTo(&bar.clock_date, 0);- // Reserve room for the widest usual clock/date to keep the tray stable.+ // Fit the displayed lines so unused column space cannot widen the left gap.const time_w = text.measureWidth(time_str, .manrope, 14, scale) catch null;const date_w = text.measureWidth(date_str, .manrope, 11, scale) catch null;- const width: f32 = @floatFromInt(@max(80, @max(time_w orelse 0, date_w orelse 0) + 1));+ const width: f32 = @floatFromInt(@max(time_w orelse 0, date_w orelse 0) + 1);// A failed measurement is retried next time rather than remembered.if (time_w == null or date_w == null) return width;return bar.clock_width.put(scale, width);@@ -1191,38 +1215,38 @@ const Color = struct {// Exact CSS tints; glass.c supplies the filtered backdrop underneath.fn bar_fill() Color {- return fromRgba(ui_theme.global.taskbar_bg);+ return fromRgba(ui_theme.taskbar(.taskbar_bg));}fn hairline() Color {- return fromRgba(ui_theme.global.border_soft);+ return fromRgba(ui_theme.taskbar(.border_soft));}fn chip_idle() Color {- return fromRgba(ui_theme.global.taskbar_surface);+ return fromRgba(ui_theme.taskbar(.taskbar_surface));}fn hover_fill() Color {- return fromRgba(ui_theme.global.surface_hover);+ return fromRgba(ui_theme.taskbar(.surface_hover));}fn active_fill() Color {- return fromRgba(ui_theme.global.taskbar_hover).scaled(2.8);+ return fromRgba(ui_theme.taskbar(.taskbar_hover)).scaled(2.8);}pub fn fromRgba(c: [4]f32) Color {return .{ .r = c[0], .g = c[1], .b = c[2], .a = c[3] };}fn chip_title_idle() text.Color {- return textColor(fromRgba(ui_theme.global.window_fg));+ return textColor(fromRgba(ui_theme.taskbar(.window_fg)));}fn tray_icon() Color {- return fromRgba(ui_theme.global.window_fg);+ return fromRgba(ui_theme.taskbar(.window_fg));}fn tray_icon_hover() Color {- return fromRgba(ui_theme.global.window_fg);+ return fromRgba(ui_theme.taskbar(.window_fg));}const glyph = Color{ .r = 1, .g = 1, .b = 1, .a = 0.96 };fn clock_time() text.Color {- return textColor(fromRgba(ui_theme.global.window_fg));+ return textColor(fromRgba(ui_theme.taskbar(.window_fg)));}fn clock_date() text.Color {- return textColor(fromRgba(ui_theme.global.window_dim));+ return textColor(fromRgba(ui_theme.taskbar(.window_dim)));}pub fn over(source: Color, destination: Color) Color {@@ -1523,7 +1547,7 @@ fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_y: iif (part == .tray) {const i = part.tray;const color = if (i == @intFromEnum(TrayKind.volume) and bar.audio_muted)- Color.fromRgba(ui_theme.global.danger)+ Color.fromRgba(ui_theme.taskbar(.danger))elseColor.lerp(Color.tray_icon(), Color.tray_icon_hover(), hover);const size = 20 * press;@@ -1568,7 +1592,7 @@ fn paintPartPixel(bar: *Taskbar, sampled_start: start_button.Paint, hover: f32,if (ix >= 0 and ix < icon.size and iy >= 0 and iy < icon.size) {var sample = Color.fromPremultiplied(icon.pixels[@intCast(iy * icon.size + ix)]);if (ui_theme.global.start_button_icon.len == 0) {- if (ui_theme.global.start_button_logo_color) |tint| sample = Color.fromRgba(tint).scaled(sample.a);+ if (ui_theme.taskbar(.start_button_logo_color)) |tint| sample = Color.fromRgba(tint).scaled(sample.a);}color = sample.over(color);}@@ -1592,7 +1616,7 @@ fn paintBatteryPixel(bar: *Taskbar, x: f32, py: f32, scale: f32, progress: f32).plugged = bar.battery_state.plugged,.shimmer = progress,.height = trh,- }, battery_badge.Colors.of(ui_theme.global));+ }, battery_badge.Colors.taskbar());return .{ .r = c.r, .g = c.g, .b = c.b, .a = c.a };}@@ -1605,7 +1629,7 @@ fn paintCapturePixel(bar: *Taskbar, hover: f32, press: f32, tx: f32, tw: f32, pxvar color = Color{ .r = 0, .g = 0, .b = 0, .a = 0 };const cov = edgeCoverage(chrome.sdRoundedBox(lx, ly, tx, tray_y, tw, @floatFromInt(trayHit()), tray_radius), scale);if (cov > 0) {- const fill = Color.lerp(Color.fromRgba(ui_theme.global.danger), Color.fromRgba(ui_theme.global.window_close_hover), hover);+ const fill = Color.lerp(Color.fromRgba(ui_theme.taskbar(.danger)), Color.fromRgba(ui_theme.taskbar(.window_close_hover)), hover);color = fill.scaled(cov).over(color);}return color;@@ -1623,7 +1647,7 @@ const ChipPaint = struct {const active = chip.toplevel == bar.server.world.toplevels.first();const hover = chip.hover.value(now_ms);const press_strength = std.math.clamp((1 - chip.press.value(now_ms)) / (1 - press_scale), 0, 1);- const style = @import("taskbar/chip_style.zig").look(Color, active, chip.toplevel.needs_attention, hover, press_strength);+ const style = @import("taskbar/chip_style.zig").lookFrom(Color, .taskbar, active, chip.toplevel.needs_attention, hover, press_strength);var paint: ChipPaint = .{.chip = chip,.x = chip.renderX(now_ms),@@ -1837,22 +1861,20 @@ fn drawPartText(bar: *Taskbar, now_ms: i64, part: Part, buf: *BarBuffer, ox: i32.start => if (bar.start_logo == null) {const btn_size = buttonSize();const w = text.measureWidth("R", .mono_bold, start_button.glyph_size_px, scale) catch 0;- drawCenteredText(buf.pixels, buf.width, buf.height, local(startButtonLeft() + @divTrunc(btn_size - w, 2), @intFromFloat(@round(start_button.top(bar.box.height, btn_size))), btn_size, btn_size, ox, oy), "R", textColor(Color.fromRgba(ui_theme.global.start_button_logo_color orelse .{ 1, 1, 1, 1 })), scale, .mono_bold, start_button.glyph_size_px) catch {};+ drawCenteredText(buf.pixels, buf.width, buf.height, local(startButtonLeft() + @divTrunc(btn_size - w, 2), @intFromFloat(@round(start_button.top(bar.box.height, btn_size))), btn_size, btn_size, ox, oy), "R", textColor(Color.fromRgba(ui_theme.taskbar(.start_button_logo_color) orelse .{ 1, 1, 1, 1 })), scale, .mono_bold, start_button.glyph_size_px) catch {};},.clock => {const time = std.mem.trimStart(u8, std.mem.sliceTo(&bar.clock_time, 0), " ");const date = std.mem.sliceTo(&bar.clock_date, 0);const tw = text.measureWidth(time, .manrope, 14, scale) catch 0;const dw = text.measureWidth(date, .manrope, 11, scale) catch 0;- // Keep both lines left-aligned, with the wider line at the column's- // right edge rather than leaving the reserved width empty there.- const right: i32 = @intFromFloat(@round(bar.clockX() + bar.clockColumnWidth()));- const left = right - @max(tw, dw) - 1;- const clock_h: i32 = 37;+ const left: i32 = @intFromFloat(@round(bar.clockX()));+ const width: i32 = @intFromFloat(bar.clockColumnWidth());+ const clock_h: i32 = if (date.len == 0) 20 else 37;const time_y = @divTrunc(bar.box.height - clock_h, 2);const date_y = time_y + 21;- drawCenteredText(buf.pixels, buf.width, buf.height, local(left, time_y, tw + 1, 20, ox, oy), time, Color.clock_time(), scale, .manrope, 14) catch {};- drawCenteredText(buf.pixels, buf.width, buf.height, local(left, date_y, dw + 1, 16, ox, oy), date, Color.clock_date(), scale, .manrope, 11) catch {};+ drawCenteredText(buf.pixels, buf.width, buf.height, local(left + @divTrunc(width - tw - 1, 2), time_y, tw + 1, 20, ox, oy), time, Color.clock_time(), scale, .manrope, 14) catch {};+ if (date.len != 0) drawCenteredText(buf.pixels, buf.width, buf.height, local(left + @divTrunc(width - dw - 1, 2), date_y, dw + 1, 16, ox, oy), date, Color.clock_date(), scale, .manrope, 11) catch {};},.chip => |chip| {const cx: i32 = @intFromFloat(@round(chip.renderX(now_ms)));diff --git a/src/child_env.zig b/src/child_env.zigindex 12278c4..a91657d 100644--- a/src/child_env.zig+++ b/src/child_env.zig@@ -13,6 +13,7 @@ pub const session_type = "wayland";pub const InputMethod = @import("config").types.InputMethod;pub const Spec = struct {+ region: @import("config").loader.RegionConfig = .{},input_method: InputMethod = .none,wayland_display: ?[]const u8 = null,ipc_socket: ?[]const u8 = null,@@ -29,6 +30,7 @@ pub const Spec = struct {};pub fn apply(map: *Map, spec: Spec) !void {+ try applyRegion(map, spec.region);// Private supervisor authority must never escape to descendant launches.inline for (.{ "REDIWM_SESSION_FD", "REDIWM_LOGIN_SESSION", "REDIWM_SESSION_PRIMARY" }) |key| _ = map.swapRemove(key);switch (spec.input_method) {@@ -73,6 +75,30 @@ pub fn apply(map: *Map, spec: Spec) !void {}}+pub const format_categories = [_][]const u8{ "LC_TIME", "LC_NUMERIC", "LC_MONETARY", "LC_MEASUREMENT", "LC_PAPER", "LC_ADDRESS", "LC_TELEPHONE", "LC_NAME" };++pub fn applyRegion(map: *Map, prefs: @import("config").loader.RegionConfig) !void {+ if (prefs.timezone.len != 0) try map.put("TZ", prefs.timezone);+ if (prefs.language.len == 0 and prefs.formats.len == 0) return;+ // Preserve LC_ALL's inherited categories before removing its precedence.+ if (map.get("LC_ALL")) |all| {+ const copy = try map.allocator.dupe(u8, all);+ defer map.allocator.free(copy);+ if (copy.len != 0) {+ inline for (.{ "LC_MESSAGES", "LC_CTYPE", "LC_COLLATE", "LC_TIME", "LC_NUMERIC", "LC_MONETARY", "LC_MEASUREMENT", "LC_PAPER", "LC_ADDRESS", "LC_TELEPHONE", "LC_NAME", "LC_IDENTIFICATION" }) |key| try map.put(key, copy);+ }+ _ = map.swapRemove("LC_ALL");+ }+ if (prefs.language.len != 0) {+ try map.put("LANG", prefs.language);+ try map.put("LC_MESSAGES", prefs.language);+ try map.put("LC_CTYPE", prefs.language);+ // gettext's LANGUAGE would otherwise override LC_MESSAGES.+ _ = map.swapRemove("LANGUAGE");+ }+ for (format_categories) |key| if (prefs.formats.len != 0) try map.put(key, prefs.formats);+}+fn stripHostX11(map: *Map) void {// Host DISPLAY/XAUTHORITY would send X clients to the nested backend's// parent session. Clearing both is what "Xwayland disabled" means.@@ -139,6 +165,17 @@ test "child env overwrites a host XDG_CURRENT_DESKTOP" {try apply(&map, .{ .wayland_display = "wayland-1" });try std.testing.expectEqualStrings(desktop_name, map.get("XDG_CURRENT_DESKTOP").?);try std.testing.expectEqualStrings(session_type, map.get("XDG_SESSION_TYPE").?);+ try map.put("LC_ALL", "en_US.utf8");+ try map.put("LANGUAGE", "de:fr");+ try apply(&map, .{ .region = .{ .timezone = "Pacific/Auckland", .language = "C.utf8", .formats = "en_NZ.utf8" } });+ try std.testing.expect(map.get("LC_ALL") == null);+ try std.testing.expect(map.get("LANGUAGE") == null);+ try std.testing.expectEqualStrings("C.utf8", map.get("LANG").?);+ try std.testing.expectEqualStrings("C.utf8", map.get("LC_MESSAGES").?);+ try std.testing.expectEqualStrings("C.utf8", map.get("LC_CTYPE").?);+ try std.testing.expectEqualStrings("en_US.utf8", map.get("LC_COLLATE").?);+ for (format_categories) |key| try std.testing.expectEqualStrings("en_NZ.utf8", map.get(key).?);+ try std.testing.expectEqualStrings("Pacific/Auckland", map.get("TZ").?);}test "activation_token sets XDG_ACTIVATION_TOKEN and DESKTOP_STARTUP_ID" {diff --git a/src/chrome.zig b/src/chrome.zigindex 881bc45..b78c89c 100644--- a/src/chrome.zig+++ b/src/chrome.zig@@ -313,6 +313,7 @@ pub const TitlebarMemo = struct {title_size: f32,chrome_height: f32 = 46,chrome_control_gap: f32 = 4,+ chrome_round_buttons: bool = false,pub fn capture(width: i32, height: i32, title_ptr: ?[*:0]const u8, state: ChromeState) TitlebarMemo {const t = theme.global;@@ -344,6 +345,7 @@ pub const TitlebarMemo = struct {.title_size = t.title_size,.chrome_height = t.chrome_height,.chrome_control_gap = t.chrome_control_gap,+ .chrome_round_buttons = t.chrome_round_buttons,};}@@ -380,7 +382,7 @@ pub const TitlebarMemo = struct {inline for (.{ "glass", "border", "border_soft", "fg", "dim", "border_hover", "surface_hover", "danger", "close_fg" }) |field| {if (!rgbaEql(@field(a, field), @field(b, field))) return false;}- return a.close_hover_alpha == b.close_hover_alpha and a.title_size == b.title_size and a.chrome_height == b.chrome_height and a.chrome_control_gap == b.chrome_control_gap;+ return a.close_hover_alpha == b.close_hover_alpha and a.title_size == b.title_size and a.chrome_height == b.chrome_height and a.chrome_control_gap == b.chrome_control_gap and a.chrome_round_buttons == b.chrome_round_buttons;}};@@ -1382,7 +1384,7 @@ fn paintControls() Color {var color = base;- // .win-btn:hover chip, 4px radius, drawn under the glyph. One chip+ // Window-control hover chip, drawn under the glyph. One chip// slides between the buttons; its rect and red-ness are interpolated// from the slot coordinate.if (chip_alpha > 0) {@@ -1391,15 +1393,17 @@ fn paintControls(const a_btn = if (from_max) max_btn else min_btn;const b_btn = if (from_max) close_btn else max_btn;const t = if (from_max) pos - 1 else pos;+ const chip_width = mix(@floatFromInt(a_btn.w), @floatFromInt(b_btn.w), t);+ const chip_height = mix(@floatFromInt(a_btn.h), @floatFromInt(b_btn.h), t);const fill = Color.lerp(Color.control_hover(), Color.close_hover(), clamp01(pos - 1));const chip = edgeCoverage(sdRoundedBox(px,py,mix(@floatFromInt(a_btn.x), @floatFromInt(b_btn.x), t),mix(@floatFromInt(a_btn.y), @floatFromInt(b_btn.y), t),- mix(@floatFromInt(a_btn.w), @floatFromInt(b_btn.w), t),- mix(@floatFromInt(a_btn.h), @floatFromInt(b_btn.h), t),- btn_radius * density,+ chip_width,+ chip_height,+ window_chrome.cornerRadius(theme.global.chrome_round_buttons, chip_width, chip_height, btn_radius * density),), scale);if (chip > 0) color = fill.scaled(chip * clamp01(chip_alpha)).over(color);}@@ -1635,6 +1639,11 @@ test "chrome geometry changes invalidate retained titlebar pixels" {theme.global.chrome_height += 1;const taller = TitlebarMemo.capture(400, 320, null, .{ .radius = 10 });try std.testing.expect(!before.reusableFor(taller));+ theme.global.chrome_height = saved.chrome_height;+ theme.global.chrome_round_buttons = !saved.chrome_round_buttons;+ const round = TitlebarMemo.capture(400, 320, null, .{ .radius = 10 });+ try std.testing.expect(!before.eql(round));+ try std.testing.expect(!before.reusableFor(round));}test "chrome controls fit and stay centered at every supported height and density" {diff --git a/src/chrome_tabs.zig b/src/chrome_tabs.zigindex 21703fb..3a882f3 100644--- a/src/chrome_tabs.zig+++ b/src/chrome_tabs.zig@@ -6,6 +6,7 @@ const button = @import("ui").widgets.button;const style = @import("taskbar/chip_style.zig");const icon_service = @import("icon_service.zig");const chrome = @import("chrome.zig");+const window_chrome = @import("ui").window_chrome;const Rect = button.Rect;pub const Tab = struct { id: u64, title: []const u8, active: bool, attention: bool };@@ -101,7 +102,7 @@ fn hashImpl(strip: Strip, include_titles: bool) u64 {h.update(std.mem.asBytes(&t.attention));}// The shared painter's palette is independent of the chrome palette.- inline for (.{ "taskbar_surface", "taskbar_hover", "taskbar_border", "surface_hover", "danger", "window_fg", "radius", "taskbar_title_size" }) |field| h.update(std.mem.asBytes(&@field(theme.global, field)));+ inline for (.{ "taskbar_surface", "taskbar_hover", "taskbar_border", "surface_hover", "danger", "window_fg", "radius", "taskbar_title_size", "chrome_round_buttons" }) |field| h.update(std.mem.asBytes(&@field(theme.global, field)));return h.final();}@@ -114,6 +115,7 @@ pub fn paint(comptime C: type, pixels: []u32, width: i32, height: i32, logical_wconst clip_right: usize = if (clip) |c| @intFromFloat(@max(0, @round(@as(f32, @floatFromInt(c.x + c.w)) * scale))) else @intCast(width);for (strip.tabs[g.first..][0..g.count], 0..) |t, i| {const rect = g.tab(i);+ const radius = window_chrome.cornerRadius(theme.global.chrome_round_buttons, rect.w, rect.h, theme.global.radius * density * 0.8);const look = style.look(C, t.active, t.attention, if (strip.hover == key(.{ .tab = t.id })) 1 else 0, 0);const x0: usize = @max(clip_left, @as(usize, @intFromFloat(@max(0, @floor(rect.x * scale)))));const x1: usize = @min(clip_right, @as(usize, @intFromFloat(@min(@as(f32, @floatFromInt(width)), @ceil((rect.x + rect.w) * scale)))));@@ -121,7 +123,7 @@ pub fn paint(comptime C: type, pixels: []u32, width: i32, height: i32, logical_wconst y1: usize = @intFromFloat(@min(@as(f32, @floatFromInt(height)), @ceil((rect.y + rect.h) * scale)));if (x1 > x0 and y1 > y0) for (y0..y1) |y| for (x0..x1) |x| {const index = y * @as(usize, @intCast(width)) + x;- const c = style.pixel(C, (@as(f32, @floatFromInt(x)) + 0.5) / scale, (@as(f32, @floatFromInt(y)) + 0.5) / scale, rect.x, rect.y, rect.w, rect.h, theme.global.radius * density * 0.8, scale, look.fill, look.border);+ const c = style.pixel(C, (@as(f32, @floatFromInt(x)) + 0.5) / scale, (@as(f32, @floatFromInt(y)) + 0.5) / scale, rect.x, rect.y, rect.w, rect.h, radius, scale, look.fill, look.border);pixels[index] = c.over(C.fromPremultiplied(pixels[index])).argb();};const size = @min(20 * density, rect.h - 6);@@ -138,7 +140,11 @@ pub fn paint(comptime C: type, pixels: []u32, width: i32, height: i32, logical_w});button.paint(&renderer, close, .{ .variant = .chrome, .size = .sm, .icon = .close, .icon_scale = 0.39, .label = "Close tab" }, .{ .pointer = if (strip.hover == key(.{ .close = t.id })) .hover else .idle });}- button.paint(&renderer, g.plus, .{ .variant = .ghost, .size = .sm, .icon = .plus, .label = "New tab" }, .{ .pointer = if (strip.notice == .opening) .disabled else if (strip.hover == key(.plus)) .hover else .idle });- if (g.previous) |r| button.paint(&renderer, r, .{ .variant = .ghost, .size = .sm, .icon = .chevron_left }, .{ .pointer = if (strip.hover == key(.previous)) .hover else .idle });- if (g.next) |r| button.paint(&renderer, r, .{ .variant = .ghost, .size = .sm, .icon = .chevron_right }, .{ .pointer = if (strip.hover == key(.next)) .hover else .idle });+ button.paint(&renderer, g.plus, .{ .variant = .ghost, .size = .sm, .icon = .plus, .label = "New tab", .radius = navigationRadius(g.plus) }, .{ .pointer = if (strip.notice == .opening) .disabled else if (strip.hover == key(.plus)) .hover else .idle });+ if (g.previous) |r| button.paint(&renderer, r, .{ .variant = .ghost, .size = .sm, .icon = .chevron_left, .radius = navigationRadius(r) }, .{ .pointer = if (strip.hover == key(.previous)) .hover else .idle });+ if (g.next) |r| button.paint(&renderer, r, .{ .variant = .ghost, .size = .sm, .icon = .chevron_right, .radius = navigationRadius(r) }, .{ .pointer = if (strip.hover == key(.next)) .hover else .idle });+}++fn navigationRadius(rect: Rect) f32 {+ return window_chrome.cornerRadius(theme.global.chrome_round_buttons, rect.w, rect.h, theme.global.radius);}diff --git a/src/config/default.zig b/src/config/default.zigindex 8c3d848..8bc03ae 100644--- a/src/config/default.zig+++ b/src/config/default.zig@@ -17,6 +17,7 @@ pub const source =\\chrome_height = 46.0 # window titlebar height, 28–84px; scales icons and controls\\chrome_control_gap = 4.0 # gap between window controls, 0–24px\\radius = 5.0 # --r-sm base+ \\chrome_round_buttons = false # true: circular window controls and pill-shaped tabs\\bg = "#090b18" # shell background\\fg = "#eef1fb" # --text\\dim = "#9aa2c4" # --text-dim@@ -141,10 +142,15 @@ pub const source =\\lock_on_suspend = true # lock before the system sleeps (menu, lid, idle or another program)\\\\# ───────────────────────────────────────────────- \\# Region & Language — personal shell preferences; system locale is inherited+ \\# Region & Language — this user's RediWM session only, not system defaults\\# ───────────────────────────────────────────────\\[region]+ \\timezone = "" # empty inherits login; e.g. Pacific/Auckland+ \\language = "" # installed locale for new apps; e.g. en_NZ.utf8+ \\formats = "" # installed locale for regional date/number/currency formats\\clock_24h = false # taskbar, calendar and lock screen+ \\clock_show_seconds = false # taskbar clock only+ \\clock_show_day = true # taskbar date line, in regional format\\first_day_of_week = "sunday" # any lowercase weekday name\\\\# ───────────────────────────────────────────────diff --git a/src/config/loader.zig b/src/config/loader.zigindex 68bb39f..fd87fab 100644--- a/src/config/loader.zig+++ b/src/config/loader.zig@@ -95,14 +95,24 @@ pub const InputConfig = struct {caret_motion_ms: u32 = 80,};-/// Personal shell clock/calendar preferences; system locale stays inherited.+/// Personal session preferences. Empty strings inherit the login environment.pub const RegionConfig = struct {+ timezone: []const u8 = "",+ language: []const u8 = "",+ formats: []const u8 = "",clock_24h: bool = false,+ clock_show_seconds: bool = false,+ clock_show_day: bool = true,first_day_of_week: enum { sunday, monday, tuesday, wednesday, thursday, friday, saturday } = .sunday,pub fn timeFormat(self: RegionConfig) [:0]const u8 {return if (self.clock_24h) "%H:%M" else "%l:%M %p";}++ pub fn taskbarTimeFormat(self: RegionConfig) [:0]const u8 {+ if (!self.clock_show_seconds) return self.timeFormat();+ return if (self.clock_24h) "%H:%M:%S" else "%l:%M:%S %p";+ }};pub const TaskbarItems = @import("taskbar_items.zig").Config;@@ -245,6 +255,9 @@ pub const NotificationRule = struct {pub const Config = struct {theme: Theme = .{},+ /// `[taskbar_theme]`: the taskbar's own colours over the main theme's.+ /// Null (no section) follows the main theme. Only taskbar tokens are set.+ taskbar_theme: ?Theme = null,input: InputConfig = .{},input_method: struct { env: types.InputMethod = .none } = .{},keyboard_keymap: ?*xkb.Keymap = null,@@ -305,51 +318,75 @@ pub const resolvePath = @import("path.zig").resolvePath;/// section and any leading comments. Used by the control center so appearance/// edits don't clobber keybinds/input.pub fn replaceThemeSection(allocator: Allocator, io: Io, path: []const u8, t: Theme) void {+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(allocator);+ theme_mod.writeInto(allocator, &buf, t) catch return;+ rewriteSection(allocator, io, path, "[theme]", buf.items);+}++/// Rewrites `[taskbar_theme]` to `t`'s taskbar tokens, or drops the section+/// for null so the taskbar follows the main theme again.+pub fn replaceTaskbarThemeSection(allocator: Allocator, io: Io, path: []const u8, t: ?Theme) void {+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(allocator);+ if (t) |tokens| theme_mod.writeTaskbarInto(allocator, &buf, tokens) catch return;+ rewriteSection(allocator, io, path, "[taskbar_theme]", if (t == null) null else buf.items);+}++/// Replaces the section starting with `header` by `body` (a whole section,+/// header line included), or removes it for null, leaving everything else as+/// it was. A section that is not there yet goes at the end.+fn rewriteSection(allocator: Allocator, io: Io, path: []const u8, header: []const u8, body: ?[]const u8) void {const existing = Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(1 << 20)) catch {- var buf: std.ArrayList(u8) = .empty;- defer buf.deinit(allocator);- theme_mod.writeInto(allocator, &buf, t) catch return;- Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = buf.items }) catch return;+ const text = body orelse return;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }) catch return;return;};defer allocator.free(existing);var out: std.ArrayList(u8) = .empty;defer out.deinit(allocator);+ spliceSection(allocator, &out, existing, header, body) catch return;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = out.items }) catch |err| {+ log.warn("rewrite '{s}' in '{s}': {}", .{ header, path, err });+ };+}- var in_theme = false;+/// `rewriteSection` on text: appends `existing` to `out` with the section+/// replaced (or removed for a null `body`).+fn spliceSection(allocator: Allocator, out: *std.ArrayList(u8), existing: []const u8, header: []const u8, body: ?[]const u8) !void {+ var in_section = false;var replaced = false;var lines = std.mem.splitScalar(u8, existing, '\n');while (lines.next()) |raw| {+ // The piece after the file's final newline is not a line; keeping it+ // would add a blank line to the file on every save.+ if (raw.len == 0 and lines.peek() == null) break;const trimmed = std.mem.trim(u8, raw, " \t\r");if (trimmed.len > 0 and trimmed[0] == '[') {- const is_theme = std.mem.startsWith(u8, trimmed, "[theme]");- if (in_theme) {- in_theme = false;- }- if (is_theme) {+ const is_section = std.mem.startsWith(u8, trimmed, header);+ in_section = false;+ if (is_section) {if (!replaced) {- theme_mod.writeInto(allocator, &out, t) catch return;- if (out.items.len == 0 or out.items[out.items.len - 1] != '\n') {- out.append(allocator, '\n') catch return;+ if (body) |text| {+ try out.appendSlice(allocator, text);+ if (out.items.len == 0 or out.items[out.items.len - 1] != '\n') try out.append(allocator, '\n');}replaced = true;}- in_theme = true;+ in_section = true;continue;}}- if (in_theme) continue;- out.appendSlice(allocator, raw) catch return;- out.append(allocator, '\n') catch return;+ if (in_section) continue;+ try out.appendSlice(allocator, raw);+ try out.append(allocator, '\n');}if (!replaced) {- if (out.items.len > 0 and out.items[out.items.len - 1] != '\n') out.append(allocator, '\n') catch return;- theme_mod.writeInto(allocator, &out, t) catch return;+ const text = body orelse return;+ if (out.items.len > 0 and out.items[out.items.len - 1] != '\n') try out.append(allocator, '\n');+ try out.appendSlice(allocator, text);}- Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = out.items }) catch |err| {- log.warn("replaceThemeSection '{s}': {}", .{ path, err });- };}pub fn generateDefault(io: Io, path: []const u8) !void {@@ -453,6 +490,8 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configreturn error.InvalidConfig;};if (section == .keybinds) seen_keybinds = true;+ // Its presence alone chooses a taskbar theme, even with no keys.+ if (section == .taskbar_theme and cfg.taskbar_theme == null) cfg.taskbar_theme = .{};continue;}@@ -472,6 +511,13 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Config};if (std.mem.eql(u8, key, "radius_lg")) seen_frame_radius = true;},+ .taskbar_theme => {+ // Other theme keys are ignored, so a whole theme file's body can be pasted in.+ _ = theme_mod.applyTaskbarKey(cfg.arena.allocator(), &cfg.taskbar_theme.?, key, value) catch |err| {+ fail(path, line_no, "invalid taskbar_theme field '{s}': {s}", .{ key, @errorName(err) });+ return error.InvalidConfig;+ };+ },.input_method => {if (!std.mem.eql(u8, key, "env")) return error.InvalidConfig;const text = theme_mod.unquote(value) catch return error.InvalidConfig;@@ -667,6 +713,7 @@ pub fn parse(allocator: Allocator, bytes: []const u8, path: []const u8) !Configconst Section = union(enum) {none,theme,+ taskbar_theme,input,input_method,compositor,@@ -747,7 +794,7 @@ fn parseSection(line: []const u8) !Section {const close = std.mem.indexOfScalar(u8, line, ']') orelse return error.InvalidConfig;const name = line[1..close];// Array tables and internal tags are deliberately not accepted here.- inline for (.{ .theme, .input, .input_method, .compositor, .region, .keybinds, .polkit, .idle, .night_light, .notifications, .desktop, .ipc, .animations }) |tag| {+ inline for (.{ .theme, .taskbar_theme, .input, .input_method, .compositor, .region, .keybinds, .polkit, .idle, .night_light, .notifications, .desktop, .ipc, .animations }) |tag| {if (std.mem.eql(u8, name, @tagName(tag))) return tag;}if (std.mem.startsWith(u8, name, "animations.")) {@@ -886,7 +933,12 @@ const input_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(InputConfig), Fi};const region_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(RegionConfig), FieldRule, null) = .{+ .timezone = .string,+ .language = .string,+ .formats = .string,.clock_24h = .boolean,+ .clock_show_seconds = .boolean,+ .clock_show_day = .boolean,.first_day_of_week = .enumeration,};@@ -1307,6 +1359,49 @@ fn fail(path: []const u8, line: usize, comptime fmt: []const u8, args: anytype)log.warn("{s}:{d}: {s}", .{ path, line, msg });}+test "[taskbar_theme] holds only taskbar tokens and is rewritten without touching its neighbours" {+ const a = std.testing.allocator;+ var cfg = try parse(a, "[theme]\nwindow_fg = \"#102030\"\n[taskbar_theme]\ntaskbar_bg = \"#112233\"\nwindow_fg = \"#445566\"\naccent = \"#ff0000\"\nchip_gap = 30\n[input]\ntap_drag = false\n", "mem");+ defer cfg.deinit();+ const chosen = cfg.taskbar_theme.?;+ try std.testing.expectEqual(theme_mod.parseColor("#112233") catch unreachable, chosen.taskbar_bg);+ try std.testing.expectEqual(theme_mod.parseColor("#445566") catch unreachable, theme_mod.taskbarTokens(chosen).window_fg);+ // Neither the main theme nor the taskbar's other tokens move.+ try std.testing.expectEqual(theme_mod.parseColor("#102030") catch unreachable, cfg.theme.window_fg);+ try std.testing.expectEqual(@as(Theme, .{}).accent, chosen.accent);+ try std.testing.expectEqual(@as(Theme, .{}).chip_gap, chosen.chip_gap);+ // The header alone chooses a taskbar theme; no header means the main one.+ var bare = try parse(a, "[taskbar_theme]\n", "mem");+ defer bare.deinit();+ try std.testing.expect(bare.taskbar_theme != null);+ var none = try parse(a, "[theme]\n", "mem");+ defer none.deinit();+ try std.testing.expect(none.taskbar_theme == null);++ // What the writer saves reads back equal, and `[theme]` is not mistaken for it.+ var body: std.ArrayList(u8) = .empty;+ defer body.deinit(a);+ try theme_mod.writeTaskbarInto(a, &body, chosen);+ var out: std.ArrayList(u8) = .empty;+ defer out.deinit(a);+ try spliceSection(a, &out, "[theme]\nfont = \"X\"\n\n[input]\ntap_drag = false\n", "[taskbar_theme]", body.items);+ try std.testing.expectEqualStrings("[theme]\nfont = \"X\"\n\n[input]\ntap_drag = false\n[taskbar_theme]\ntaskbar_bg = \"rgba(17,34,51,1.000)\"\nwindow_fg = \"rgba(68,85,102,1.000)\"\n", out.items);+ var reread = try parse(a, out.items, "mem");+ defer reread.deinit();+ try std.testing.expect(theme_mod.taskbarOverrideEql(chosen, reread.taskbar_theme));+ try std.testing.expectEqualStrings("X", reread.theme.font);++ // Replacing it again keeps one copy and no extra blank lines; null removes it.+ var again: std.ArrayList(u8) = .empty;+ defer again.deinit(a);+ try spliceSection(a, &again, out.items, "[taskbar_theme]", "[taskbar_theme]\n");+ try std.testing.expectEqualStrings("[theme]\nfont = \"X\"\n\n[input]\ntap_drag = false\n[taskbar_theme]\n", again.items);+ var removed: std.ArrayList(u8) = .empty;+ defer removed.deinit(a);+ try spliceSection(a, &removed, out.items, "[taskbar_theme]", null);+ try std.testing.expectEqualStrings("[theme]\nfont = \"X\"\n\n[input]\ntap_drag = false\n", removed.items);+}+test "empty config keeps built-in zoom steps and default keybinds" {var cfg = try parse(std.testing.allocator, "", "mem");defer cfg.deinit();@@ -1456,6 +1551,7 @@ test "input and theme reload detect every field and compare strings by content"inline for (std.meta.fields(Theme)) |field| {var changed = original_theme;@field(changed, field.name) = switch (field.type) {+ bool => !@field(original_theme, field.name),f32 => @field(original_theme, field.name) + 1,[]const u8 => "another theme",[4]f32 => .{ 0.1, 0.2, 0.3, 0.4 },diff --git a/src/config/setting_save.zig b/src/config/setting_save.zigindex 1d2f3f4..9b5fe98 100644--- a/src/config/setting_save.zig+++ b/src/config/setting_save.zig@@ -328,8 +328,33 @@ test "region preferences preserve unrelated settings and reject invalid weekdaysdefer a.free(day);const result = try patch(a, day, "region", "clock_24h", true);defer a.free(result);- var cfg = try loader.parse(a, result, "test");+ const zone = try patch(a, result, "region", "timezone", @as([]const u8, "Pacific/Auckland"));+ defer a.free(zone);+ const language = try patch(a, zone, "region", "language", @as([]const u8, "C.utf8"));+ defer a.free(language);+ const formats = try patch(a, language, "region", "formats", @as([]const u8, "en_NZ.utf8"));+ defer a.free(formats);+ var cfg = try loader.parse(a, formats, "test");defer cfg.deinit();+ try std.testing.expect(!cfg.region.clock_show_seconds);+ try std.testing.expect(cfg.region.clock_show_day);+ const seconds = try patch(a, formats, "region", "clock_show_seconds", true);+ defer a.free(seconds);+ const no_day = try patch(a, seconds, "region", "clock_show_day", false);+ defer a.free(no_day);+ var clock = try loader.parse(a, no_day, "test");+ defer clock.deinit();+ try std.testing.expect(clock.region.clock_show_seconds);+ try std.testing.expect(!clock.region.clock_show_day);+ try std.testing.expectEqualStrings("%H:%M:%S", clock.region.taskbarTimeFormat());+ clock.region.clock_24h = false;+ try std.testing.expectEqualStrings("%l:%M:%S %p", clock.region.taskbarTimeFormat());+ try std.testing.expectEqualStrings("%l:%M %p", clock.region.timeFormat());+ clock.region.clock_show_seconds = false;+ try std.testing.expectEqualStrings("%l:%M %p", clock.region.taskbarTimeFormat());+ try std.testing.expectEqualStrings("Pacific/Auckland", cfg.region.timezone);+ try std.testing.expectEqualStrings("C.utf8", cfg.region.language);+ try std.testing.expectEqualStrings("en_NZ.utf8", cfg.region.formats);try std.testing.expect(cfg.region.clock_24h);try std.testing.expectEqual(.monday, cfg.region.first_day_of_week);try std.testing.expect(!cfg.input.tap_drag);@@ -337,4 +362,6 @@ test "region preferences preserve unrelated settings and reject invalid weekdaystry std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, result, "first_day_of_week"));try std.testing.expectError(error.InvalidConfig, loader.parse(a, "[region]\nfirst_day_of_week = \"funday\"\n", "invalid"));try std.testing.expectError(error.InvalidConfig, loader.parse(a, "[region]\nclock_24h = \"yes\"\n", "invalid"));+ try std.testing.expectError(error.InvalidConfig, loader.parse(a, "[region]\nclock_show_seconds = 1\n", "invalid"));+ try std.testing.expectError(error.InvalidConfig, loader.parse(a, "[region]\nclock_show_day = \"yes\"\n", "invalid"));}diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zigindex 2d76725..6da8d27 100644--- a/src/config_runtime/apply.zig+++ b/src/config_runtime/apply.zig@@ -47,6 +47,7 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {server.night_light.reconfigure(new.night_light);}theme_mod.global = new.theme;+ theme_mod.taskbar_override = if (new.taskbar_theme) |chosen| theme_mod.taskbarTokens(chosen) else null;@import("ui").text.setPreferredFamilies(theme_mod.global.font, theme_mod.global.mono_font);camera_mod.zoom_levels = new.compositor.zoom_percents;@@ -156,6 +157,7 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {}const theme_changed = !themeEql(old.theme, new.theme) or old.compositor.border_radius != new.compositor.border_radius;+ const taskbar_theme_changed = !theme_mod.taskbarOverrideEql(old.taskbar_theme, new.taskbar_theme);if (theme_changed) {if (server.desktop) |desktop| desktop.app.themeChanged();if (server.locker) |lock| lock.themeChanged();@@ -173,6 +175,10 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {sm.buildTree();sm.relayout();}+ } else if (taskbar_theme_changed) {+ // Only the bar's colours moved; its picker in Appearance follows.+ server.refreshTaskbarsGeometry();+ if (server.input.open_control_center) |cc| cc.refresh();} else if (any_taskbar_changed) {server.refreshTaskbars();}@@ -264,11 +270,25 @@ fn logKeybindDiff(old: Config, new: Config) void {/// Called by both Settings and config reload; no new clock timers.pub fn applyRegion(server: *Server) void {+ if (server.greeter_mode) return;+ @import("region.zig").applyTimezone(@import("../main.zig").gpa, server.config.region.timezone, server.environ.getPosix("TZ")) catch |err| {+ log.warn("could not apply personal timezone: {}", .{err});+ };+ if (server.desktop) |desktop| {+ updateDesktopEnv(server, desktop) catch |err| log.warn("could not update desktop launch environment: {}", .{err});+ }var outputs = server.outputs.iterator(.forward);while (outputs.next()) |output| {- if (output.taskbar) |bar| bar.refreshClock();+ if (output.taskbar) |bar| bar.refreshClockSettings();if (output.calendar) |calendar| calendar.refresh();}if (server.locker) |lock| lock.themeChanged();if (server.input.open_control_center) |cc| cc.refresh();}++fn updateDesktopEnv(server: *Server, desktop: *@import("../desktop/embedded.zig").Desktop) !void {+ var env = try server.environ.createMap(std.heap.c_allocator);+ errdefer env.deinit();+ try server.applyChildEnv(&env);+ desktop.worker.updateChildEnv(env);+}diff --git a/src/config_runtime/region.zig b/src/config_runtime/region.zignew file mode 100644index 0000000..7b38fb5--- /dev/null+++ b/src/config_runtime/region.zig@@ -0,0 +1,31 @@+//! Apply a personal timezone to libc clocks without changing system files.+const std = @import("std");+const c = @cImport({+ @cUndef("_FORTIFY_SOURCE");+ @cInclude("stdlib.h");+ @cInclude("time.h");+ @cInclude("fcntl.h");+ @cInclude("unistd.h");+});++pub fn applyTimezone(allocator: std.mem.Allocator, zone: []const u8, inherited: ?[]const u8) !void {+ if (zone.len != 0) {+ // Only IANA zone files, never paths supplied by the caller or POSIX rules.+ if (zone.len > 255 or zone[0] == '/' or std.mem.indexOf(u8, zone, "..") != null) return error.InvalidTimezone;+ for (zone) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '/' and ch != '_' and ch != '-' and ch != '+') return error.InvalidTimezone;+ const path = try std.fmt.allocPrintSentinel(allocator, "/usr/share/zoneinfo/{s}", .{zone}, 0);+ defer allocator.free(path);+ const fd = c.open(path, c.O_RDONLY | c.O_CLOEXEC | c.O_NONBLOCK);+ if (fd < 0) return error.InvalidTimezone;+ defer _ = c.close(fd);+ var magic: [4]u8 = undefined;+ if (c.read(fd, &magic, magic.len) != magic.len or !std.mem.eql(u8, &magic, "TZif")) return error.InvalidTimezone;+ }+ const value = if (zone.len != 0) zone else inherited;+ if (value) |name| {+ const z = try allocator.dupeZ(u8, name);+ defer allocator.free(z);+ if (c.setenv("TZ", z, 1) != 0) return error.OutOfMemory;+ } else if (c.unsetenv("TZ") != 0) return error.OutOfMemory;+ c.tzset();+}diff --git a/src/control_center/folder_picker.zig b/src/control_center/folder_picker.zigindex 98404d5..be54c94 100644--- a/src/control_center/folder_picker.zig+++ b/src/control_center/folder_picker.zig@@ -1,6 +1,6 @@-//! Appearance's "Choose folder": runs Files in its folder-chooser mode (the+//! Settings' file and folder pickers: runs Files in chooser mode (the//! same process and JSON contract the FileChooser portal uses) and hands the-//! picked folder to a callback. The event loop only reads the child's pipe.+//! picked path to a callback. The event loop only reads the child's pipe.const std = @import("std");const wl = @import("wayland").server.wl;const Server = @import("../Server.zig");@@ -14,7 +14,7 @@ const c = @cImport({});const a = std.heap.c_allocator;-/// A folder path in JSON; anything larger is not a result.+/// A path in JSON; anything larger is not a result.const max_output = 64 * 1024;const Picker = struct {@@ -36,10 +36,11 @@ const Picker = struct {a.destroy(self);}- /// Ends the chooser and reports its outcome: the folder, or null when it+ /// Ends the chooser and reports its outcome: the path, or null when it/// was cancelled, failed or the session locked meanwhile.fn end(self: *Picker, path: ?[]const u8) void {defer self.destroy();+ if (active == self) active = null;self.on_done(self.owner, path);}@@ -93,11 +94,14 @@ pub fn cancel() void {/// Opens the chooser at `start_dir`; `on_done` gets the chosen folder's path/// (valid only during the call), or null. One chooser at a time.pub fn start(server: *Server, title: []const u8, start_dir: []const u8, owner: ?*anyopaque, on_done: *const fn (?*anyopaque, ?[]const u8) void) !void {+ return startWithOptions(server, .{ .mode = .folder, .title = title, .accept_label = "Use folder", .current_folder = start_dir }, owner, on_done);+}++pub fn startWithOptions(server: *Server, opts: chooser.Options, owner: ?*anyopaque, on_done: *const fn (?*anyopaque, ?[]const u8) void) !void {if (active != null or server.locker != null or server.greeter_mode) return error.Busy;var arena = std.heap.ArenaAllocator.init(a);defer arena.deinit();const alloc = arena.allocator();- const opts: chooser.Options = .{ .mode = .folder, .title = title, .accept_label = "Use folder", .current_folder = start_dir };const bytes = try std.json.Stringify.valueAlloc(alloc, opts, .{});const input = c.memfd_create("rediwm-folder-picker", c.MFD_CLOEXEC);if (input < 0) return error.CreateFailed;@@ -112,6 +116,7 @@ pub fn start(server: *Server, title: []const u8, start_dir: []const u8, owner: ?const executable = if (n > 0 and n < pathbuf.len) try std.fmt.allocPrint(alloc, "{s}/rediwm-files", .{std.fs.path.dirname(pathbuf[0..@intCast(n)]).?}) else "rediwm-files";var child = try std.process.spawn(server.io, .{ .argv = &.{ executable, "--chooser-stdin" }, .environ_map = &env, .stdin = .{ .file = .{ .handle = input, .flags = .{ .nonblocking = false } } }, .stdout = .pipe });errdefer child.kill(server.io);+ @import("../session/app_scope.zig").place(server, child.id.?, "file-chooser");const pidfd_result = std.os.linux.pidfd_open(child.id.?, 0);if (std.os.linux.errno(pidfd_result) != .SUCCESS) return error.PidfdFailed;const pidfd: c_int = @intCast(pidfd_result);diff --git a/src/control_center/panel.zig b/src/control_center/panel.zigindex fcfeed3..5594871 100644--- a/src/control_center/panel.zig+++ b/src/control_center/panel.zig@@ -291,7 +291,7 @@ pub const ControlCenter = struct {users_section.deinit(cc);cc.shortcuts.arena.deinit();cc.desktop.arena.deinit();- cc.region.arena.deinit();+ cc.region.deinit();cc.portals.arena.deinit();cc.default_apps.arena.deinit();cc.display.arena.deinit();diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zigindex 51f69bd..f0854b6 100644--- a/src/control_center/sections/appearance.zig+++ b/src/control_center/sections/appearance.zig@@ -92,7 +92,7 @@ pub const Section = struct {cursor_themes: ?[]cursor_theme.Theme = null,cursor_row_children: [2]Widget = undefined,family_row_children: [2]Widget = undefined,- row_storage: [21]Widget = undefined,+ row_storage: [22]Widget = undefined,focus_zoom_children: [3]Widget = undefined,/// Rescanned on every build, so images added meanwhile show up.wallpapers: []const wallpapers.Entry = &.{},@@ -107,6 +107,7 @@ pub const Section = struct {wallpaper_row_children: [2]Widget = undefined,wallpaper_footer_children: [2]Widget = undefined,theme_row_children: [2]Widget = undefined,+ taskbar_theme_row_children: [2]Widget = undefined,dark_row_children: [2]Widget = undefined,dark_label_children: [2]Widget = undefined,splash_row_children: [2]Widget = undefined,@@ -142,7 +143,10 @@ pub const Section = struct {item_controls: [taskbar_items.count][3]Widget = undefined,item_drag: ?struct { index: usize, press_y: f32, moved: bool = false, items: taskbar_items.Config } = null,item_focus: ?taskbar_items.Item = null,- start_menu_section_children: [5]Widget = undefined,+ start_menu_section_children: [6]Widget = undefined,+ start_logo_children: [3]Widget = undefined,+ start_logo_buttons: [2]Widget = undefined,+ start_logo_error: ?[]const u8 = null,};fn indexOfNearest(values: []const f32, v: f32) usize {@@ -248,6 +252,38 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {},};+ // The same presets for the taskbar alone, led by a choice that follows+ // the theme above. Its tokens are compared, not the whole theme.+ var taskbar_labels: [][]const u8 = &.{};+ var taskbar_selected: ?usize = null;+ if (arena.alloc([]const u8, out.presets.len + 1)) |labels| {+ taskbar_labels = labels;+ labels[0] = "Same as theme";+ if (theme.taskbar_override == null) taskbar_selected = 0;+ for (out.presets, 1..) |preset, i| {+ labels[i] = preset.name;+ const chosen = theme.taskbar_override orelse continue;+ if (taskbar_selected != null) continue;+ const parsed = theme.parse(arena, preset.bytes) catch continue;+ if (theme.taskbarTokensEql(parsed, chosen)) taskbar_selected = i;+ }+ } else |_| {}+ out.taskbar_theme_row_children = .{+ labelWidget("Taskbar theme"),+ .{+ .name = "taskbar_theme",+ .kind = .{ .select = .{+ .labels = taskbar_labels,+ .selected = taskbar_selected,+ .placeholder = "Custom",+ .disabled = taskbar_labels.len == 0,+ .owner = out,+ .on_change = &onTaskbarThemePicked,+ } },+ .width = .{ .fixed = segmented_width },+ },+ };+buildWallpaper(out, arena);const pal = panel.palette();@@ -496,11 +532,22 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {const menu_bottom_row = pxGroup(out, px_menu_bottom, "Menu bottom padding", std.math.clamp(t.start_menu_bottom_pad, 0.0, 40.0), 0, 40, 2, &PxHandler(px_menu_bottom, "start_menu_bottom_pad", false).changed);const icon_left_row = pxGroup(out, px_icon_left, "Icon left padding", std.math.clamp(t.start_menu_icon_left_pad, 0.0, 32.0), 0, 32, 2, &PxHandler(px_icon_left, "start_menu_icon_left_pad", false).changed);const icon_bottom_row = pxGroup(out, px_icon_bottom, "Icon bottom padding", std.math.clamp(t.start_menu_icon_bottom_pad, 0.0, 24.0), 0, 24, 2, &PxHandler(px_icon_bottom, "start_menu_icon_bottom_pad", false).changed);- out.start_menu_section_children = .{ sectionLabel("START MENU"), menu_left_row, menu_bottom_row, icon_left_row, icon_bottom_row };+ out.start_logo_buttons = .{+ .{ .name = "start_logo_choose", .kind = .{ .button = .{ .label = "Choose file…", .owner = out, .on_click = &onChooseStartLogo, .state = if (folder_picker.running()) .disabled else .idle } }, .width = .{ .fixed = 124 }, .height = .{ .fixed = 30 } },+ .{ .name = "start_logo_reset", .kind = .{ .button = .{ .label = "Reset to default", .owner = out, .on_click = &onResetStartLogo, .state = if (t.start_button_icon.len == 0 or folder_picker.running()) .disabled else .idle } }, .width = .{ .fixed = 140 }, .height = .{ .fixed = 30 } },+ };+ out.start_logo_children = .{+ labelWidget("Start button logo"),+ .{ .name = "start_logo_file", .kind = .{ .text = .{ .content = out.start_logo_error orelse (if (t.start_button_icon.len == 0) "Default R logo · PNG or SVG" else std.fs.path.basename(t.start_button_icon)), .font_size = 12, .color = pal.dim } } },+ .{ .kind = .container, .direction = .row, .gap = 8, .children = &out.start_logo_buttons },+ };+ const logo_row: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.start_logo_children };+ out.start_menu_section_children = .{ sectionLabel("START MENU"), logo_row, menu_left_row, menu_bottom_row, icon_left_row, icon_bottom_row };const start_menu_section: Widget = .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.start_menu_section_children };out.row_storage = .{.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.theme_row_children },+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.taskbar_theme_row_children },.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dark_row_children },.{ .kind = .container, .direction = .column, .gap = 12, .children = &out.wallpaper_children },.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.splash_row_children },@@ -830,7 +877,10 @@ fn applyThemeChange(s: *Section) void {/// a repaint pass on each slider tick; see `PxHandler`'s doc comment/// for which fields need the full path.fn applyThemeChangeImpl(s: *Section, taskbar_geometry: bool) void {- const server = s.cc.server;+ saveThemeChange(s.cc.server, taskbar_geometry);+}++fn saveThemeChange(server: *Server, taskbar_geometry: bool) void {if (server.theme_path) |path| {theme.save(main.gpa, server.io, path, theme.global);theme.loadGlobal(main.gpa, server.io, path);@@ -840,6 +890,46 @@ fn applyThemeChangeImpl(s: *Section, taskbar_geometry: bool) void {refreshTheme(server, taskbar_geometry);}+fn onChooseStartLogo(owner: ?*anyopaque, _: usize) void {+ const s = section(owner);+ const server = s.cc.server;+ s.start_logo_error = null;+ folder_picker.startWithOptions(server, .{+ .title = "Choose Start button logo",+ .accept_label = "Use logo",+ .current_folder = std.fs.path.dirname(theme.global.start_button_icon) orelse "",+ .filters = &.{.{ .name = "PNG and SVG images", .rules = &.{ .{ .kind = 0, .value = "*.png" }, .{ .kind = 0, .value = "*.svg" } } }},+ }, server, &onStartLogoChosen) catch |err| {+ std.log.warn("could not open the logo chooser: {}", .{err});+ s.start_logo_error = "Could not open the file chooser.";+ };+ s.cc.refresh();+}++fn onStartLogoChosen(owner: ?*anyopaque, path: ?[]const u8) void {+ // The server outlives the chooser, including when Settings is closed.+ const server: *Server = @ptrCast(@alignCast(owner orelse return));+ if (path) |picked| {+ // Theme strings use a literal, double-quoted TOML dialect.+ if (!std.fs.path.isAbsolute(picked) or std.mem.indexOfAny(u8, picked, "\"\\\n\r\t") != null) {+ if (server.input.open_control_center) |cc| {+ cc.appearance.start_logo_error = "Choose a path without quotes, backslashes or control characters.";+ cc.refresh();+ }+ return;+ }+ theme.global.start_button_icon = server.config.arena.allocator().dupe(u8, picked) catch return;+ saveThemeChange(server, false);+ } else if (server.input.open_control_center) |cc| cc.refresh();+}++fn onResetStartLogo(owner: ?*anyopaque, _: usize) void {+ const s = section(owner);+ s.start_logo_error = null;+ theme.global.start_button_icon = "";+ applyThemeChange(s);+}+pub fn refreshTheme(server: *@import("../../Server.zig"), taskbar_geometry: bool) void {if (server.desktop) |desktop| desktop.app.themeChanged();@import("ui").text.setPreferredFamilies(theme.global.font, theme.global.mono_font);@@ -880,6 +970,31 @@ fn onThemePicked(owner: ?*anyopaque, _: usize, index: usize) void {}}+/// Gives the taskbar the colours of the picked preset (index 0 hands it back+/// to the main theme). Only the bar changes: `theme.global` keeps whatever the+/// theme row above chose, and so does the saved `[theme]` section.+fn onTaskbarThemePicked(owner: ?*anyopaque, _: usize, index: usize) void {+ const s = section(owner);+ const server = s.cc.server;+ if (index == 0) {+ theme.taskbar_override = null;+ } else {+ if (index > s.presets.len) return;+ const preset = s.presets[index - 1];+ // Only the colour tokens are kept, so nothing outlives this arena.+ var scratch: std.heap.ArenaAllocator = .init(main.gpa);+ defer scratch.deinit();+ const parsed = theme.parse(scratch.allocator(), preset.bytes) catch |err| {+ std.log.warn("taskbar theme '{s}' failed to parse: {}", .{ preset.name, err });+ return;+ };+ theme.taskbar_override = theme.taskbarTokens(parsed);+ }+ if (server.config.path.len > 0) loader.replaceTaskbarThemeSection(main.gpa, server.io, server.config.path, theme.taskbar_override);+ server.refreshTaskbarsGeometry();+ if (server.input.open_control_center) |cc| cc.refresh();+}+fn onFontFamilyChanged(owner: ?*anyopaque, _: usize, index: usize) void {const s = section(owner);const families = s.font_families orelse return;diff --git a/src/control_center/sections/default_apps.zig b/src/control_center/sections/default_apps.zigindex e4889d9..d3d5ed2 100644--- a/src/control_center/sections/default_apps.zig+++ b/src/control_center/sections/default_apps.zig@@ -45,7 +45,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {s.values[index] = values.items;children[index + 1] = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .gap = 12, .children = try a.dupe(W, &.{text(if (kind == .file_manager) "File Manager" else "Terminal"),- .{ .name = "default_" ++ @tagName(kind), .kind = .{ .select = .{ .labels = labels.items, .selected = selected_index, .owner = cc, .on_change = if (kind == .file_manager) fileChanged else terminalChanged } }, .width = .{ .fixed = 240 } },+ .{ .name = "default_" ++ @tagName(kind), .kind = .{ .select = .{ .labels = labels.items, .selected = selected_index, .notify_on_reselect = kind == .file_manager, .owner = cc, .on_change = if (kind == .file_manager) fileChanged else terminalChanged } }, .width = .{ .fixed = 240 } },}) };}children[3] = text(s.message);diff --git a/src/control_center/sections/desktop.zig b/src/control_center/sections/desktop.zigindex cabecb3..731cb98 100644--- a/src/control_center/sections/desktop.zig+++ b/src/control_center/sections/desktop.zig@@ -46,15 +46,25 @@ fn card(a: std.mem.Allocator, items: []const W) !W {}fn button(cc: *panel.ControlCenter, id: usize, label: []const u8, disabled: bool) W {- return .{ .kind = .{ .button = .{ .label = label, .owner = cc, .id = id, .on_click = change, .state = if (disabled) .disabled else .idle } }, .height = .{ .fixed = 36 }, .width = .{ .fixed = if (id == 4) 180 else 42 } };+ var w: W = .{ .kind = .{ .button = .{ .label = label, .owner = cc, .id = id, .on_click = change, .state = if (disabled) .disabled else .idle } } };+ if (id == 4) {+ w.width = .{ .fixed = 180 };+ w.height = .{ .fixed = 36 };+ } else {+ w.kind.button.size = .lg;+ w.width = .{ .fixed = 56 };+ w.height = .{ .fixed = 52 };+ }+ return w;}fn dimension(a: std.mem.Allocator, cc: *panel.ControlCenter, vertical: bool, value: u32) !W {const id: usize = if (vertical) 2 else 0;var number = text(try std.fmt.allocPrint(a, "{d}", .{value}), 22, false);- number.width = .{ .flex = 1 };+ number.width = .{ .fixed = 28 };var row = try container(a, .row, &.{ button(cc, id, "←", value == 1), number, button(cc, id + 1, "→", value == 10) });row.@"align" = .center;+ row.justify = .center;return container(a, .column, &.{text(if (vertical) "Vertical Pan" else "Horizontal Pan", 13, false),row,diff --git a/src/control_center/sections/region.zig b/src/control_center/sections/region.zigindex 98a0863..098e8d9 100644--- a/src/control_center/sections/region.zig+++ b/src/control_center/sections/region.zig@@ -1,10 +1,12 @@-//! Read-only session locale information and personal shell clock preferences.+//! Personal session locale, timezone and shell clock preferences.const std = @import("std");const panel = @import("../panel.zig");const ui = @import("ui");const W = ui.layout.Widget;const gpa = @import("../../main.zig").gpa;const config = @import("config");+const wl = @import("wayland").server.wl;+const Child = @import("../../session/child.zig");const c = @cImport({@cDefine("_GNU_SOURCE", "1");@cUndef("_FORTIFY_SOURCE");@@ -13,6 +15,8 @@ const c = @cImport({@cInclude("time.h");@cInclude("stdio.h");@cInclude("monetary.h");+ @cInclude("fcntl.h");+ @cInclude("unistd.h");});const days = [_][]const u8{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };@@ -21,8 +25,137 @@ pub const Section = struct {arena: std.heap.ArenaAllocator = .init(gpa),root: W = undefined,message: []const u8 = "",+ options: std.heap.ArenaAllocator = .init(gpa),+ locales: std.ArrayList([]const u8) = .empty,+ zones: std.ArrayList([]const u8) = .empty,+ values: [3][]const []const u8 = .{ &.{}, &.{}, &.{} },+ loaded: bool = false,+ locale_child: ?*Child = null,+ locale_source: ?*wl.EventSource = null,+ locale_fd: i32 = -1,+ locale_output: std.ArrayList(u8) = .empty,++ pub fn deinit(s: *Section) void {+ if (s.locale_source) |source| source.remove();+ if (s.locale_fd >= 0) _ = c.close(s.locale_fd);+ if (s.locale_child) |child| {+ child.detach();+ child.signal(.KILL);+ }+ s.options.deinit();+ s.arena.deinit();+ }};+fn less(_: void, lhs: []const u8, rhs: []const u8) bool {+ return std.mem.lessThan(u8, lhs, rhs);+}++fn loadOptions(s: *Section, cc: *panel.ControlCenter) !void {+ s.loaded = true;+ const a = s.options.allocator();+ try s.zones.append(a, "UTC");+ const table = std.Io.Dir.readFileAlloc(.cwd(), cc.server.io, "/usr/share/zoneinfo/zone.tab", a, .limited(1 << 20)) catch "";+ var lines = std.mem.splitScalar(u8, table, '\n');+ while (lines.next()) |line| {+ if (line.len == 0 or line[0] == '#') continue;+ var columns = std.mem.splitScalar(u8, line, '\t');+ _ = columns.next();+ _ = columns.next();+ if (columns.next()) |zone| try s.zones.append(a, zone);+ }+ std.mem.sort([]const u8, s.zones.items, {}, less);+ var child = try std.process.spawn(cc.server.io, .{ .argv = &.{ "/usr/bin/locale", "-a" }, .stdout = .pipe, .stderr = .ignore });+ errdefer {+ child.kill(cc.server.io);+ }+ s.locale_fd = child.stdout.?.handle;+ errdefer {+ _ = c.close(s.locale_fd);+ s.locale_fd = -1;+ }+ _ = c.fcntl(s.locale_fd, c.F_SETFL, @as(c_int, c.O_NONBLOCK));+ const loop = cc.server.wl_server.getEventLoop();+ s.locale_source = try loop.addFd(*panel.ControlCenter, s.locale_fd, .{ .readable = true }, localeReady, cc);+ errdefer {+ s.locale_source.?.remove();+ s.locale_source = null;+ }+ s.locale_child = try Child.watch(gpa, loop, child.id.?, cc, localeExited);+}++fn localeExited(owner: ?*anyopaque, _: *Child, _: ?u32) void {+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));+ cc.region.locale_child = null;+}++fn localeReady(_: c_int, _: wl.EventMask, cc: *panel.ControlCenter) c_int {+ const s = &cc.region;+ var buffer: [4096]u8 = undefined;+ while (true) {+ const n = c.read(s.locale_fd, &buffer, buffer.len);+ if (n < 0) {+ if (std.posix.errno(n) == .INTR) continue;+ if (std.posix.errno(n) == .AGAIN) return 0;+ break;+ }+ if (n == 0) break;+ if (s.locale_output.items.len + @as(usize, @intCast(n)) > 64 * 1024) break;+ s.locale_output.appendSlice(s.options.allocator(), buffer[0..@intCast(n)]) catch break;+ }+ s.locale_source.?.remove();+ s.locale_source = null;+ _ = c.close(s.locale_fd);+ s.locale_fd = -1;+ const a = s.options.allocator();+ var lines = std.mem.splitScalar(u8, s.locale_output.items, '\n');+ while (lines.next()) |line| {+ const name = std.mem.trim(u8, line, " \t\r");+ if (name.len == 0 or std.mem.eql(u8, name, "POSIX")) continue;+ const z = a.dupeZ(u8, name) catch continue;+ const locale = c.newlocale(c.LC_ALL_MASK, z, null) orelse continue;+ c.freelocale(locale);+ s.locales.append(a, z) catch break;+ }+ std.mem.sort([]const u8, s.locales.items, {}, less);+ cc.refresh();+ return 0;+}++fn choice(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator, comptime key: []const u8, index: usize, choices: []const []const u8, inherited: []const u8, item: ?c.nl_item) !W {+ var labels: std.ArrayList([]const u8) = .empty;+ var values: std.ArrayList([]const u8) = .empty;+ try labels.append(a, try std.fmt.allocPrint(a, "Inherited from login ({s})", .{inherited}));+ try values.append(a, "");+ const selected = @field(cc.server.config.region, key);+ var selected_index: usize = 0;+ for (choices) |value| {+ try labels.append(a, if (item) |what| try localeLabel(a, value, what) else value);+ try values.append(a, value);+ if (std.mem.eql(u8, value, selected)) selected_index = values.items.len - 1;+ }+ if (selected.len != 0 and selected_index == 0) {+ try labels.append(a, try std.fmt.allocPrint(a, "Current: {s}", .{selected}));+ try values.append(a, selected);+ selected_index = values.items.len - 1;+ }+ s.values[index] = values.items;+ return .{ .name = key, .kind = .{ .select = .{ .labels = labels.items, .selected = selected_index, .disabled = index != 0 and s.locale_source != null, .owner = cc, .id = index, .on_change = preferenceChanged } }, .width = .{ .percent = 1 } };+}++fn preferenceChanged(owner: ?*anyopaque, id: usize, index: usize) void {+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(owner orelse return));+ if (id >= cc.region.values.len or index >= cc.region.values[id].len) return;+ const value = cc.region.values[id][index];+ const owned = cc.server.config.arena.allocator().dupe(u8, value) catch return;+ switch (id) {+ 0 => save(owner, "timezone", owned),+ 1 => save(owner, "language", owned),+ 2 => save(owner, "formats", owned),+ else => {},+ }+}+fn text(value: []const u8, size: f32, dim: bool) W {const t = panel.palette();return .{ .kind = .{ .text = .{ .content = value, .font_size = size, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } } };@@ -74,7 +207,8 @@ fn timezone(a: std.mem.Allocator, cc: *panel.ControlCenter) ![]const u8 {}fn previews(a: std.mem.Allocator, prefs: config.loader.RegionConfig) !W {- const locale = c.newlocale(c.LC_ALL_MASK, "", null) orelse return text("Regional formats are unavailable for this session.", 12, true);+ const name = try a.dupeZ(u8, prefs.formats);+ const locale = c.newlocale(c.LC_ALL_MASK, name, null) orelse return text("Regional formats are unavailable for this session.", 12, true);defer c.freelocale(locale);// Fixed examples make format changes easy to compare, with no preview timer.var tm: c.struct_tm = std.mem.zeroes(c.struct_tm);@@ -89,7 +223,7 @@ fn previews(a: std.mem.Allocator, prefs: config.loader.RegionConfig) !W {var currency: [128]u8 = @splat(0);_ = c.strftime_l(&date, date.len, "%x", &tm, locale);// Match the shell's clock, which currently uses English AM/PM labels.- _ = c.strftime(&time, time.len, prefs.timeFormat(), &tm);+ _ = c.strftime(&time, time.len, prefs.taskbarTimeFormat(), &tm);// Only this thread, and only for the numeric conversion. Never setlocale:// the compositor has workers and they must retain their own locale state.const previous = c.uselocale(locale);@@ -105,6 +239,7 @@ fn previews(a: std.mem.Allocator, prefs: config.loader.RegionConfig) !W {}pub fn build(s: *Section, cc: *panel.ControlCenter) void {+ if (!s.loaded and !cc.server.greeter_mode) loadOptions(s, cc) catch {};_ = s.arena.reset(.retain_capacity);s.root = tree(s, cc, s.arena.allocator()) catch panel.outOfMemory();}@@ -113,13 +248,15 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {const prefs = cc.server.config.region;const language = try card(a, &.{text("Language", 17, false),- try info(a, "Session language", try localeLabel(a, localeName(cc, "LC_MESSAGES"), c._NL_IDENTIFICATION_LANGUAGE)),- text("RediWM currently uses English.", 12, true),+ text("Application language", 13, false),+ try choice(s, cc, a, "language", 1, s.locales.items, localeName(cc, "LC_MESSAGES"), c._NL_IDENTIFICATION_LANGUAGE),+ text("RediWM currently uses English. Only installed locales are listed.", 12, true),});const region = try card(a, &.{text("Region", 17, false),- try info(a, "Regional formats", try localeLabel(a, localeName(cc, "LC_TIME"), c._NL_ADDRESS_COUNTRY_NAME)),- text("Inherited from your login session.", 12, true),+ text("Regional formats", 13, false),+ try choice(s, cc, a, "formats", 2, s.locales.items, localeName(cc, "LC_TIME"), c._NL_ADDRESS_COUNTRY_NAME),+ text("Date format for the taskbar; date, number and currency formats for new apps.", 12, true),});var toggle = try container(a, .row, &.{text("Use 24-hour time", 13, false),@@ -127,11 +264,27 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {});toggle.justify = .space_between;toggle.@"align" = .center;+ var seconds_toggle = try container(a, .row, &.{+ text("Show seconds", 13, false),+ .{ .name = "clock_show_seconds", .kind = .{ .toggle = .{ .on = prefs.clock_show_seconds, .style = .settings, .owner = cc, .on_change = secondsChanged } } },+ });+ seconds_toggle.justify = .space_between;+ seconds_toggle.@"align" = .center;+ var day_toggle = try container(a, .row, &.{+ text("Show day", 13, false),+ .{ .name = "clock_show_day", .kind = .{ .toggle = .{ .on = prefs.clock_show_day, .style = .settings, .owner = cc, .on_change = dayChanged } } },+ });+ day_toggle.justify = .space_between;+ day_toggle.@"align" = .center;const timing = try card(a, &.{text("Time & Date", 17, false),- try info(a, "Time zone", try timezone(a, cc)),+ text("Time zone", 13, false),+ try choice(s, cc, a, "timezone", 0, s.zones.items, try timezone(a, cc), null),toggle,- text("Taskbar, calendar, lock screen and Files.", 12, true),+ text("Taskbar, calendar, lock screen and new apps.", 12, true),+ seconds_toggle,+ day_toggle,+ text("Taskbar clock. The date uses your regional format.", 12, true),text("First day of the week", 13, false),.{ .name = "first_day_of_week", .kind = .{ .select = .{ .labels = &days, .selected = @intFromEnum(prefs.first_day_of_week), .owner = cc, .on_change = firstDayChanged } }, .width = .{ .percent = 1 } },text("Changes the taskbar calendar.", 12, true),@@ -142,8 +295,13 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {try container(a, .column, &.{ region, preview }),});body.width = .{ .percent = 1 };- var root = try container(a, .column, &.{ body, text(s.message, 12, true) });- if (s.message.len == 0) root.children = root.children[0..1];+ var root = try container(a, .column, &.{+ text("Saved for your user’s RediWM session only; system defaults are unchanged.", 12, true),+ text("Language and region apply to new apps launched by RediWM. Reopen apps to use them.", 12, true),+ body,+ text(s.message, 12, true),+ });+ if (s.message.len == 0) root.children = root.children[0..3];root.width = .{ .percent = 1 };return root;}@@ -163,6 +321,12 @@ fn save(owner: ?*anyopaque, comptime key: []const u8, value: @FieldType(config.lfn clockChanged(owner: ?*anyopaque, _: usize, on: bool) void {save(owner, "clock_24h", on);}+fn secondsChanged(owner: ?*anyopaque, _: usize, on: bool) void {+ save(owner, "clock_show_seconds", on);+}+fn dayChanged(owner: ?*anyopaque, _: usize, on: bool) void {+ save(owner, "clock_show_day", on);+}fn firstDayChanged(owner: ?*anyopaque, _: usize, index: usize) void {if (index < days.len) save(owner, "first_day_of_week", @enumFromInt(index));}diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zigindex 8c68c39..219f4c1 100644--- a/src/desktop/watcher.zig+++ b/src/desktop/watcher.zig@@ -72,6 +72,7 @@ pub const Worker = struct {io: std.Io,environ: std.process.Environ,child_env: std.process.Environ.Map,+ pending_child_env: ?std.process.Environ.Map = null,dir: []const u8,layout: []const u8,theme_cfg: theme.Config,@@ -135,6 +136,7 @@ pub const Worker = struct {}self.commands.deinit(a);self.catalog_arena.deinit();+ if (self.pending_child_env) |*env| env.deinit();self.child_env.deinit();for (self.theme_cfg.base_dirs) |d| a.free(d);a.free(self.theme_cfg.base_dirs);@@ -153,6 +155,15 @@ pub const Worker = struct {var count: u64 = 0;_ = c.read(fd, &count, @sizeOf(u64));}+ /// Transfers ownership; only the worker replaces the environment it reads.+ pub fn updateChildEnv(self: *Worker, env: std.process.Environ.Map) void {+ _ = c.pthread_mutex_lock(&self.mutex);+ defer _ = c.pthread_mutex_unlock(&self.mutex);+ if (self.pending_child_env) |*old| old.deinit();+ self.pending_child_env = env;+ signal(self.wake_worker);+ }+/// Asks the worker to rescan from the Wayland thread.pub fn requestRefresh(self: *Worker) void {self.refresh.store(true, .release);@@ -355,6 +366,11 @@ pub const Worker = struct {wd = c.inotify_add_watch(fd, zdir, c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO | c.IN_CLOSE_WRITE | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF);}_ = c.pthread_mutex_lock(&self.mutex);+ if (self.pending_child_env) |env| {+ self.child_env.deinit();+ self.child_env = env;+ self.pending_child_env = null;+ }const commands = self.commands;self.commands = .empty;_ = c.pthread_mutex_unlock(&self.mutex);diff --git a/src/files/app.zig b/src/files/app.zigindex e5d6d48..201b2a4 100644--- a/src/files/app.zig+++ b/src/files/app.zig@@ -6,6 +6,7 @@ const c = @import("c.zig").api;const git = @import("git.zig");const worker_mod = @import("worker.zig");const history_mod = @import("history.zig");+const recent = @import("recent.zig");const ops_mod = @import("ops.zig");const clipboard_mod = @import("clipboard.zig");const dirsize = @import("dirsize.zig");@@ -152,6 +153,7 @@ pub const ViewItem = struct {is_broken: bool,bytes: i64,mtime: i64,+ opened: i64 = 0,mode: c.mode_t = 0,permissions_text: []const u8 = "",icon_name: []const u8,@@ -265,6 +267,7 @@ pub const App = struct {git_column_weight: ?f64 = null,column_resize: ?struct { column: usize, x: f64, widths: [5]f64 } = null,sort_mode: Sort = .name,+ recent_sort_mode: Sort = .modified,folders_only: bool = false,// Only meaningful inside a Git repository; on by default there.changed_only: bool = true,@@ -512,7 +515,7 @@ pub const App = struct {return;}const cur = self.history.current;- const name = if (self.trash_dir != null and std.mem.eql(u8, cur, self.trash_dir.?)) "Trash" else if (std.mem.eql(u8, cur, "/")) "/" else std.fs.path.basename(cur);+ const name = if (self.isRecent()) "Recent" else if (self.trash_dir != null and std.mem.eql(u8, cur, self.trash_dir.?)) "Trash" else if (std.mem.eql(u8, cur, "/")) "/" else std.fs.path.basename(cur);_ = std.fmt.bufPrintZ(&self.title_z, "{s} — RediWM Files", .{name}) catch {@memcpy(self.title_z[0..12], "RediWM Files");self.title_z[12] = 0;@@ -679,6 +682,7 @@ pub const App = struct {}fn toolbarButtonEnabled(self: *App, action: header.Action) bool {+ if (self.isRecent() and (action == .new or action == .paste)) return false;if (self.history.archive_len > 0) switch (action) {.new, .cut, .copy, .paste, .trash => return false,else => {},@@ -853,6 +857,7 @@ pub const App = struct {}pub fn navigate(self: *App, new_path: []const u8) void {+ if (self.chooser != null and recent.isLocation(new_path)) return;self.rememberView();self.history.navigate(new_path) catch return;self.applyHistoryNav(self.history.current);@@ -1103,8 +1108,10 @@ pub const App = struct {return if (mode == .size) a.bytes > b.bytes else a.bytes < b.bytes;}}- if (mode == .modified and a.mtime != b.mtime) return a.mtime > b.mtime;- if (mode == .modified_asc and a.mtime != b.mtime) return a.mtime < b.mtime;+ const a_date = if (a.opened != 0) a.opened else a.mtime;+ const b_date = if (b.opened != 0) b.opened else b.mtime;+ if (mode == .modified and a_date != b_date) return a_date > b_date;+ if (mode == .modified_asc and a_date != b_date) return a_date < b_date;if (mode == .type or mode == .type_desc) {const order = std.mem.order(u8, itemType(a), itemType(b));if (order != .eq) return if (mode == .type) order == .lt else order == .gt;@@ -1166,6 +1173,7 @@ pub const App = struct {.missing = it.missing,.bytes = bytes,.mtime = it.mtime,+ .opened = it.opened,.mode = it.mode,.permissions_text = std.fmt.allocPrint(mem, "{s} ({s})", .{ formatPermissions(it.mode), it.owner }) catch continue,.icon_name = mem.dupe(u8, it.icon_name) catch continue,@@ -1175,7 +1183,7 @@ pub const App = struct {.selection_border = if (previous) |item| item.selection_border else .{},}) catch continue;}- std.mem.sort(ViewItem, self.items.items, self.sort_mode, lessThan);+ std.mem.sort(ViewItem, self.items.items, self.effectiveSort(), lessThan);for (self.items.items, 0..) |item, i| {if (old_focus) |path| {if (std.mem.eql(u8, path, item.path)) self.focused_index = i;@@ -1293,6 +1301,9 @@ pub const App = struct {.open => {if (self.dialog.?.applications.?.open()) {const message = self.dialog.?.applications.?.message;+ if (message.len == 0) {+ for (self.dialog.?.applications.?.apps.paths) |path| self.worker.recordOpened(path);+ }self.closeDialog();if (message.len > 0) self.setStatusNotice(message, true);self.refresh();@@ -1304,7 +1315,7 @@ pub const App = struct {}pub fn openNewFolderDialog(self: *App) void {- if (self.history.archive_len > 0) return;+ if (self.isRecent() or self.history.archive_len > 0) return;self.closeDialog();var dlg = Dialog{.kind = .new_folder,@@ -1336,7 +1347,7 @@ pub const App = struct {}pub fn openNewFileDialog(self: *App) void {- if (self.history.archive_len > 0) return;+ if (self.isRecent() or self.history.archive_len > 0) return;self.closeDialog();var dlg = Dialog{.kind = .new_file,@@ -1613,11 +1624,12 @@ pub const App = struct {}pub fn executePaste(self: *App, kind: ops_mod.OpKind, paths: []const []const u8) bool {+ if (self.isRecent()) return false;return self.executeTransfer(kind, paths, self.history.current, true);}pub fn executeTransfer(self: *App, kind: ops_mod.OpKind, paths: []const []const u8, directory: []const u8, clipboard: bool) bool {- if (self.history.archive_len > 0) return false;+ if (self.history.archive_len > 0 or recent.isLocation(directory)) return false;if (paths.len == 0) return false;const runner = self.job_runner orelse return false;runner.start(kind, paths, directory, .ask) catch {@@ -2011,8 +2023,8 @@ pub const App = struct {const at_home = std.mem.eql(u8, path, self.home_dir) or (std.mem.startsWith(u8, path, self.home_dir) and path.len > self.home_dir.len and path[self.home_dir.len] == '/');const at_trash = if (self.trash_dir) |trash| std.mem.eql(u8, path, trash) or(std.mem.startsWith(u8, path, trash) and path.len > trash.len and path[trash.len] == '/') else false;- ends[0] = if (at_trash) self.trash_dir.?.len else if (at_home) self.home_dir.len else 1;- labels[0] = if (at_trash) "Trash" else if (at_home) "Home" else "/";+ ends[0] = if (self.isRecent()) path.len else if (at_trash) self.trash_dir.?.len else if (at_home) self.home_dir.len else 1;+ labels[0] = if (self.isRecent()) "Recent" else if (at_trash) "Trash" else if (at_home) "Home" else "/";var start = ends[0];while (start < path.len and count < ends.len) {if (path[start] == '/') {@@ -2192,13 +2204,24 @@ pub const App = struct {}fn columnLabels(self: *App) []const []const u8 {- return if (self.repository() != null) &.{ "Name", "Git" } else &column_labels;+ return if (self.repository() != null) &.{ "Name", "Git" } else if (self.isRecent()) &.{ "Name", "Size", "Type", "Opened", "Permissions" } else &column_labels;}const column_labels = [_][]const u8{ "Name", "Size", "Type", "Modified", "Permissions" };fn columnMinimums(width: f64) [5]f64 {- const scale = @min(1, width / 224);- return .{ 64 * scale, 40 * scale, 40 * scale, 40 * scale, 40 * scale };+ if (width < 224) {+ const scale = width / 224;+ return .{ 64 * scale, 40 * scale, 40 * scale, 40 * scale, 40 * scale };+ }+ // Keep enough room for the full date and time when the view is wide+ // enough; below that, let the Modified column yield space to Name.+ return .{ 64, 40, 40, @min(136, width - 184), 40 };+ }++ fn columnMinimumTotal(minimum: [5]f64) f64 {+ var total: f64 = 0;+ for (minimum) |value| total += value;+ return total;}fn listWidths(self: *App) [5]f64 {@@ -2211,13 +2234,24 @@ pub const App = struct {}if (self.column_weights) |weights| {const minimum = columnMinimums(width);+ const extra = @max(0, width - columnMinimumTotal(minimum));var widths: [5]f64 = undefined;- for (weights, 0..) |weight, i| widths[i] = minimum[i] + weight * @max(0, width - 224);+ for (weights, 0..) |weight, i| widths[i] = minimum[i] + weight * extra;return widths;}- const detail = @min(110, width * 0.14);+ const minimum = columnMinimums(width);+ const detail = @max(minimum[1], @min(110, width * 0.14));+ const modified = @max(minimum[3], @min(160, width * 0.20));const permissions = @min(200, width * 0.26);- return .{ width - detail * 3 - permissions, detail, detail, detail, permissions };+ var widths: [5]f64 = .{ 0, detail, detail, modified, @max(minimum[4], permissions) };+ var overflow = widths[1] + widths[2] + widths[3] + widths[4] - (width - minimum[0]);+ for ([_]usize{ 4, 2, 1 }) |i| {+ const shrink = @min(@max(0, overflow), widths[i] - minimum[i]);+ widths[i] -= shrink;+ overflow -= shrink;+ }+ widths[0] = width - widths[1] - widths[2] - widths[3] - widths[4];+ return widths;}fn listColumn(self: *App, column: usize) header.Rect {@@ -2251,7 +2285,7 @@ pub const App = struct {return;}const minimum = columnMinimums(total);- const extra = total - 224;+ const extra = total - columnMinimumTotal(minimum);if (extra <= 0) return;const delta = std.math.clamp(x - drag.x, minimum[drag.column] - widths[drag.column], widths[drag.column + 1] - minimum[drag.column + 1]);widths[drag.column] += delta;@@ -2487,7 +2521,7 @@ pub const App = struct {}fn sortColumn(self: *App) usize {- return switch (self.sort_mode) {+ return switch (self.effectiveSort()) {.name, .name_desc => 0,.size, .size_asc => 1,.type, .type_desc => 2,@@ -2495,7 +2529,7 @@ pub const App = struct {};}fn sortDescending(self: *App) bool {- return switch (self.sort_mode) {+ return switch (self.effectiveSort()) {.name_desc, .size, .modified, .type_desc => true,else => false,};@@ -2517,12 +2551,13 @@ pub const App = struct {fn sortByColumn(self: *App, column: usize) void {if (column >= 4 or (self.repository() != null and column != 0)) return;const reverse = self.sortColumn() == column and !self.sortDescending();- self.sort_mode = switch (column) {+ const mode: Sort = switch (column) {0 => if (reverse) .name_desc else .name,1 => if (reverse) .size else .size_asc,2 => if (reverse) .type_desc else .type,else => if (reverse) .modified else .modified_asc,};+ self.setSort(mode);self.rebuildView();self.savePreferences();self.startSortFeedback(nowMs());@@ -2578,7 +2613,21 @@ pub const App = struct {return if (ext.len > 1) ext[1..] else "File";}- const places = [_][]const u8{ "Home", "Trash", "Desktop", "Documents", "Downloads", "Pictures", "Music", "Videos", "Projects" };+ const places = [_][]const u8{ "Home", "Trash", "Recent", "Desktop", "Documents", "Downloads", "Pictures", "Music", "Videos", "Projects" };++ const places_start = 3;++ fn isRecent(self: *const App) bool {+ return recent.isLocation(self.history.current);+ }++ fn effectiveSort(self: *const App) Sort {+ return if (self.isRecent()) self.recent_sort_mode else self.sort_mode;+ }++ fn setSort(self: *App, mode: Sort) void {+ if (self.isRecent()) self.recent_sort_mode = mode else self.sort_mode = mode;+ }/// Where the pins start: the built-in places come first.const pin_base = places.len;@@ -2632,18 +2681,23 @@ pub const App = struct {}fn placePinnable(index: usize) bool {- return index >= 2 and index < pin_base;+ return index >= places_start and index < pin_base;}fn placeVisible(self: *App, index: usize) bool {return switch (self.rowKind(index)) {- .builtin => !placePinnable(index) or self.unpinned_places & (@as(u8, 1) << @as(u3, @intCast(index - 2))) == 0,+ .builtin => if (index == 2 and self.chooser != null) false else !placePinnable(index) or self.unpinned_places & (@as(u8, 1) << @as(u3, @intCast(index - places_start))) == 0,.pin => true,.device => |k| k < self.device_list.items.len,};}fn openPlace(self: *App, index: usize) void {+ if (index == 2) {+ self.navigate(recent.location);+ self.focus = .file_view;+ return;+ }switch (self.rowKind(index)) {.device => |k| {self.activateDevice(k);@@ -2756,7 +2810,7 @@ pub const App = struct {}const step: f64 = @floatFromInt(self.placeStep());const count = self.pins.items.items.len;- const top: f64 = @floatFromInt(self.placeY(2) - 30);+ const top: f64 = @floatFromInt(self.placeY(places_start) - 30);if (y < top or y >= self.pinBoundary(count) + 16) return null;const nearest = @round((y - self.pinBoundary(0)) / step);return @intFromFloat(std.math.clamp(nearest, 0, @as(f64, @floatFromInt(count))));@@ -2791,7 +2845,7 @@ pub const App = struct {if (!item.is_dir or item.missing or item.is_broken) return null;return item.path;}- return self.history.current;+ return if (self.isRecent()) null else self.history.current;}pub fn highlightDrop(self: *App, x: f64, y: f64, accepted: bool) void {@@ -3066,7 +3120,7 @@ pub const App = struct {for (0..index) |i| {if (!self.placeVisible(i)) hidden += 1;}- return self.contentTop() - self.sidebar_scroll - hidden * step + (if (index < 2) 16 + @as(i32, @intCast(index)) * step else 80 + @as(i32, @intCast(index - 1)) * step);+ return self.contentTop() - self.sidebar_scroll - hidden * step + (if (index < places_start) 16 + @as(i32, @intCast(index)) * step else 80 + @as(i32, @intCast(index - 1)) * step);}/// Where pin `j` is drawn; `j` == the pin count is the slot under the last@@ -3074,7 +3128,7 @@ pub const App = struct {fn pinRowY(self: *App, j: usize) i32 {const step = self.placeStep();var hidden: i32 = 0;- for (2..pin_base) |i| {+ for (0..pin_base) |i| {if (!self.placeVisible(i)) hidden += 1;}return self.contentTop() - self.sidebar_scroll - hidden * step + 80 + @as(i32, @intCast(pin_base - 1 + j)) * step;@@ -3103,6 +3157,7 @@ pub const App = struct {.builtin => |i| switch (i) {0 => self.home_dir,1 => self.trash_dir orelse std.fmt.bufPrint(buf, "{s}/.local/share/Trash/files", .{self.home_dir}) catch null,+ 2 => recent.location,else => std.fmt.bufPrint(buf, "{s}/{s}", .{ self.home_dir, places[i] }) catch null,},.pin => |j| self.pins.items.items[j].path,@@ -3133,7 +3188,7 @@ pub const App = struct {c.cairo_fill(cr);}setSource(cr, ui_theme.global.window_fg);- drawText(cr, "PLACES", 24, @floatFromInt(self.placeY(2) - 12), shell_ui.headingSize(), true);+ drawText(cr, "PLACES", 24, @floatFromInt(self.placeY(places_start) - 12), shell_ui.headingSize(), true);for (0..self.deviceBase()) |i| {if (!self.placeVisible(i)) continue;const y: f64 = @floatFromInt(self.placeY(i));@@ -3158,10 +3213,14 @@ pub const App = struct {c.cairo_fill(cr);}setSource(cr, withAlpha(ui_theme.global.app_icon, alpha));- if (i < 2) {+ if (i < places_start) {if (shell_ui.Layer.begin(cr, .{ .x = 21, .y = @floatCast(y + 3), .w = 24, .h = 24 })) |icon_layer| {var layer = icon_layer;- layer.renderer.drawIcon(0, 0, 24, 24, .{ .id = if (i == 0) .home else .trash, .color = withAlpha(ui_theme.global.app_icon, alpha) });+ layer.renderer.drawIcon(0, 0, 24, 24, .{ .id = switch (i) {+ 0 => .home,+ 1 => .trash,+ else => .clock,+ }, .color = withAlpha(ui_theme.global.app_icon, alpha) });layer.finish();}} else if (pin != null and pin.?.kind == .file) {@@ -3416,6 +3475,7 @@ pub const App = struct {self.setStatusNotice("Could not open Text Editor", true);return;};+ self.worker.recordOpened(path);self.children.add(self.allocator, child.id.?) catch child.kill(self.io);}@@ -3439,6 +3499,7 @@ pub const App = struct {}if (c.lseek(fd, 0, c.SEEK_SET) < 0) return error.SeekFailed;try self.launchImageList(fd, index);+ self.worker.recordOpened(self.items.items[selected].path);}fn launchImageList(self: *App, fd: c_int, index: usize) !void {@@ -3486,33 +3547,42 @@ pub const App = struct {pub fn openFile(self: *App, path: []const u8) void {if (self.chooser != null) return;const pdf = isPdf(path) and !@import("associations.zig").hasAlternativeDefault(path, "rediwm-pdf.desktop");- var executable: []const u8 = if (pdf) "rediwm-pdf" else "gio";+ if (!pdf) {+ @import("associations.zig").launchDefault(path) catch |err| {+ std.log.warn("failed to open '{s}': {}", .{ path, err });+ self.setStatusNotice("Could not open file", true);+ return;+ };+ self.worker.recordOpened(path);+ return;+ }+ var executable: []const u8 = "rediwm-pdf";var exe_buf: [4096]u8 = undefined;var sibling_buf: [4096]u8 = undefined;- if (pdf) {- const n = c.readlink("/proc/self/exe", &exe_buf, exe_buf.len);- if (n > 0 and n < exe_buf.len) {- if (std.fs.path.dirname(exe_buf[0..@intCast(n)])) |dir| {- if (std.fmt.bufPrintZ(&sibling_buf, "{s}/rediwm-pdf", .{dir})) |sibling| {- if (c.access(sibling, c.X_OK) == 0) executable = sibling;- } else |_| {}- }+ const n = c.readlink("/proc/self/exe", &exe_buf, exe_buf.len);+ if (n > 0 and n < exe_buf.len) {+ if (std.fs.path.dirname(exe_buf[0..@intCast(n)])) |dir| {+ if (std.fmt.bufPrintZ(&sibling_buf, "{s}/rediwm-pdf", .{dir})) |sibling| {+ if (c.access(sibling, c.X_OK) == 0) executable = sibling;+ } else |_| {}}}var child = std.process.spawn(self.io, .{- .argv = &.{ executable, if (pdf) "--" else "open", path },+ .argv = &.{ executable, "--", path },}) catch |err| {std.log.warn("failed to open '{s}': {}", .{ path, err });self.setStatusNotice("Could not open file", true);return;};+ self.worker.recordOpened(path);self.children.add(self.allocator, child.id.?) catch child.kill(self.io);}fn browseArchive(self: *App, path: []const u8) void {self.rememberView();self.history.navigateLocation(path, path.len) catch return;+ self.worker.recordOpened(path);self.applyHistoryNav(self.history.current);}@@ -4398,7 +4468,7 @@ pub const App = struct {self.cutSelected();return;} else if (sym == c.XKB_KEY_v or sym == c.XKB_KEY_V) {- self.paste_requested = true;+ if (!self.isRecent()) self.paste_requested = true;return;} else if (sym == c.XKB_KEY_l or sym == c.XKB_KEY_L) {self.focus = .location_bar;@@ -4527,7 +4597,7 @@ pub const App = struct {}// Clean path- const resolved = std.fs.path.resolve(self.allocator, &.{target}) catch target;+ const resolved = if (recent.isLocation(target)) target else std.fs.path.resolve(self.allocator, &.{target}) catch target;defer if (resolved.ptr != target.ptr) self.allocator.free(resolved);self.navigate(resolved);@@ -4713,7 +4783,7 @@ pub const App = struct {// Reuse the shell glyphs until dedicated file-action artwork is available.return switch (self.menu orelse return null) {.file => self.fileActions()[row].icon(),- .background => if (self.history.archive_len > 0) .refresh else ([_]IconId{ .plus, .edit, .paste, .refresh })[row],+ .background => if (self.history.archive_len > 0 or self.isRecent()) .refresh else ([_]IconId{ .plus, .edit, .paste, .refresh })[row],else => null,};}@@ -4758,6 +4828,11 @@ pub const App = struct {fn fileActions(self: *App) []const FileAction {if (self.history.archive_len > 0) return &.{.open};+ if (self.isRecent()) {+ if (self.selectedArchive() != null) return &.{ .open, .open_with, .extract, .extract_to, .cut, .copy, .rename, .trash, .properties };+ if (self.canOpenWith()) return &.{ .open, .open_with, .cut, .copy, .rename, .trash, .properties };+ return &.{ .open, .cut, .copy, .rename, .trash, .properties };+ }if (self.selectedArchive() != null) return &.{ .open, .open_with, .extract, .extract_to, .cut, .copy, .paste, .rename, .trash, .properties };if (self.canOpenWith()) return &.{ .open, .open_with, .cut, .copy, .paste, .rename, .trash, .properties };if (self.hasSizeSelection()) return &.{ .open, .cut, .copy, .paste, .rename, .trash, .size, .properties };@@ -4777,7 +4852,7 @@ pub const App = struct {for (actions, 0..) |action, i| self.file_menu_labels[i] = action.label();break :blk self.file_menu_labels[0..actions.len];},- .sidebar => if (placePinnable(self.menu_place))+ .sidebar => if (self.menu_place == 2) &.{"Open"} else if (placePinnable(self.menu_place))&.{ "Open", "Unpin", "Properties" }else switch (self.rowKind(self.menu_place)) {.pin => &.{ "Open", "Remove from Places", "Properties" },@@ -4787,7 +4862,7 @@ pub const App = struct {(if (volume.mount != null) &.{ "Open", "Eject" } else &.{"Mount"})else&.{},- .background => if (self.history.archive_len > 0) &.{"Refresh"} else &.{ "New Folder", "New File", "Paste", "Refresh" },+ .background => if (self.history.archive_len > 0 or self.isRecent()) &.{"Refresh"} else &.{ "New Folder", "New File", "Paste", "Refresh" },.chooser_filter => self.chooser_filter_labels.items,};}@@ -4819,7 +4894,7 @@ pub const App = struct {if (row == 0) {self.openPlace(self.menu_place);} else if (row == 1 and placePinnable(self.menu_place)) {- self.unpinned_places |= @as(u8, 1) << @as(u3, @intCast(self.menu_place - 2));+ self.unpinned_places |= @as(u8, 1) << @as(u3, @intCast(self.menu_place - places_start));self.sidebar_scroll = std.math.clamp(self.sidebar_scroll, 0, @max(0, self.sidebarExtent() - (self.h - self.footerHeight())));self.nav_hover = .{};self.savePreferences();@@ -4844,7 +4919,7 @@ pub const App = struct {else => {},},.sort => {- if (row < 8) self.sort_mode = @enumFromInt(row);+ if (row < 8) self.setSort(@enumFromInt(row));self.rebuildView();self.savePreferences();self.scroll_y = 0;@@ -4880,7 +4955,7 @@ pub const App = struct {.size => self.calculateSizeSelected(),.properties => self.openSelectedProperties(),},- .background => if (self.history.archive_len > 0) self.refresh() else switch (row) {+ .background => if (self.history.archive_len > 0 or self.isRecent()) self.refresh() else switch (row) {0 => self.openNewFolderDialog(),1 => self.openNewFileDialog(),2 => self.paste_requested = true,@@ -4899,7 +4974,7 @@ pub const App = struct {context_menu.frame(cr, .{ .x = self.menu_x, .y = self.menu_y, .w = width, .h = height }, context);for (labels, 0..) |label, i| {const row = self.menuRowRect(i);- const checked = (self.menu == .sort and i == @intFromEnum(self.sort_mode)) or+ const checked = (self.menu == .sort and i == @intFromEnum(self.effectiveSort())) or(self.menu == .filter and ((i == 0 and self.folders_only) or (i == 1 and self.show_hidden) or (i == 2 and self.changed_only) or (i == 3 and self.full_paths)));context_menu.row(cr, .{ .x = row.x, .y = row.y, .w = row.w, .h = row.h }, .{.label = label,@@ -4958,7 +5033,7 @@ pub const App = struct {(action == .filter and (self.folders_only or self.show_hidden or self.changedOnly())) or (action == .search and self.search_visible);const opts: ui_button.Options = switch (action) {.new => .{ .leading_icon = .plus, .label = "New" },- .sort => .{ .leading_icon = .sort, .label = switch (self.sort_mode) {+ .sort => .{ .leading_icon = .sort, .label = switch (self.effectiveSort()) {.name, .name_desc => "Name",.size, .size_asc => "Size",.modified, .modified_asc => "Date",@@ -5048,7 +5123,7 @@ pub const App = struct {}} else if (self.items.items.len == 0) {setSource(cr, ui_theme.global.window_fg);- drawText(cr, if (self.search.text.items.len > 0 or self.folders_only) "No matching items" else if (self.changedOnly()) "No changed files" else "This folder is empty", @floatFromInt(self.sidebarWidth() + 24), @floatFromInt(self.viewTop() + 36), shell_ui.textSize(), false);+ drawText(cr, if (self.search.text.items.len > 0 or self.folders_only) "No matching items" else if (self.changedOnly()) "No changed files" else if (self.isRecent()) "No recent files" else "This folder is empty", @floatFromInt(self.sidebarWidth() + 24), @floatFromInt(self.viewTop() + 36), shell_ui.textSize(), false);} else {self.renderFileItems(cr, viewport_h);}@@ -5352,7 +5427,7 @@ pub const App = struct {const ty = self.listColumn(2);drawEllipsis(cr, itemType(item), ty.x + 4, y + baseline, ty.w - 8, shell_ui.textSize(), false);const mt = self.listColumn(3);- const timestamp = @import("settings.zig").dateTime(item.mtime, &buf);+ const timestamp = @import("settings.zig").dateTime(if (self.isRecent()) item.opened else item.mtime, &buf);drawEllipsis(cr, timestamp, mt.x + 4, y + baseline, mt.w - 8, shell_ui.textSize(), false);const permissions = self.listColumn(4);const mode = formatPermissions(item.mode);@@ -6468,8 +6543,8 @@ test "sidebar hover glides between places and leaves the current one to its ownconst original_height = app.h;for ([_]i32{ 500, 700 }) |height| {app.h = height;- const first = app.placeRect(2);- const next = app.placeRect(3);+ const first = app.placeRect(App.places_start);+ const next = app.placeRect(App.places_start + 1);try std.testing.expectEqual(first.y + first.h, next.y);var y = first.y;while (y < next.y + next.h) : (y += 1) {@@ -6858,7 +6933,7 @@ test "sidebar menus unpin only Places and close gaps without changing selection"defer app.deinit();try testItems(&app, 2);app.items.items[0].selected = true;- const y = app.placeY(2);+ const y = app.placeY(App.places_start);const last_place_y = app.placeY(App.pin_base - 1);app.handleMotion(70, @floatFromInt(y + 10));app.handleButton(0x111, true);@@ -6867,12 +6942,12 @@ test "sidebar menus unpin only Places and close gaps without changing selection"try std.testing.expectEqualStrings("Properties", app.menuLabels()[2]);app.runMenu(2); // Properties must not alter pinned places.app.closeDialog();- try std.testing.expect(app.placeVisible(2));+ try std.testing.expect(app.placeVisible(App.places_start));app.openMenu(.sidebar, 70, @floatFromInt(y));app.runMenu(1);- try std.testing.expect(!app.placeVisible(2));- try std.testing.expectEqual(y, app.placeY(3));- try std.testing.expectEqual(@as(?usize, 3), app.placeAt(70, @floatFromInt(y + 10)));+ try std.testing.expect(!app.placeVisible(App.places_start));+ try std.testing.expectEqual(y, app.placeY(App.places_start + 1));+ try std.testing.expectEqual(@as(?usize, App.places_start + 1), app.placeAt(70, @floatFromInt(y + 10)));try std.testing.expectEqual(last_place_y - app.placeStep(), app.placeY(App.pin_base - 1));try std.testing.expect(app.items.items[0].selected);for ([_]usize{ 0, 1 }) |index| {@@ -6883,13 +6958,29 @@ test "sidebar menus unpin only Places and close gaps without changing selection"app.runMenu(1);try std.testing.expect(app.placeVisible(index));}- for (2..App.pin_base) |index| {+ app.menu_place = 2;+ app.openMenu(.sidebar, 70, 210);+ try std.testing.expectEqualSlices([]const u8, &.{"Open"}, app.menuLabels());+ app.menu = null;+ try std.testing.expect(app.placeVisible(2));+ try std.testing.expectEqual(app.placeY(1) + app.placeStep(), app.placeY(2));+ for (App.places_start..App.pin_base) |index| {app.menu_place = index;app.openMenu(.sidebar, 70, 140);app.runMenu(1);}try std.testing.expectEqual(@as(u8, 0x7f), app.unpinned_places);try std.testing.expectEqual(@as(?usize, null), app.placeAt(70, @floatFromInt(y + 10)));+ app.closeDialog();+ try app.history.navigate(recent.location);+ try std.testing.expect(!app.history.canUp());+ try std.testing.expect(!app.toolbarButtonEnabled(.new));+ try std.testing.expect(!app.toolbarButtonEnabled(.paste));+ try std.testing.expectEqual(Sort.modified, app.effectiveSort());+ try std.testing.expectEqual(@as(?[]const u8, null), app.dropDirectoryAt(500, 300));+ app.openNewFolderDialog();+ try std.testing.expect(app.dialog == null);+ try std.testing.expect(app.placeActive(2));}test "pins sit after Projects, take drops by gap and keep the rows in drawn order" {@@ -6917,7 +7008,7 @@ test "pins sit after Projects, take drops by gap and keep the rows in drawn ordeapp.device_list.items = &.{};// A drag snaps to the nearest gap from anywhere on PLACES, and only there.- const desktop: f64 = @floatFromInt(app.placeY(2) + 10);+ const desktop: f64 = @floatFromInt(app.placeY(App.places_start) + 10);const first_gap = app.pinBoundary(0);try std.testing.expectEqual(@as(?usize, 0), app.pinSlotAt(70, desktop));try std.testing.expectEqual(@as(?usize, 0), app.pinSlotAt(70, first_gap + 4));diff --git a/src/files/associations.zig b/src/files/associations.zigindex b06b07f..65e2a63 100644--- a/src/files/associations.zig+++ b/src/files/associations.zig@@ -188,6 +188,21 @@ pub const Applications = struct {extern fn g_app_info_get_id(app: *anyopaque) ?[*:0]const u8;+/// Launch through the same MIME default that Open With displays. A URI-based+/// launch can pick the handler for file:// instead of the file's content type.+pub fn launchDefault(path: []const u8) !void {+ const filename = try std.heap.c_allocator.dupeZ(u8, path);+ defer std.heap.c_allocator.free(filename);+ const kind = g_content_type_guess(filename, null, 0, null) orelse return error.UnknownContentType;+ defer g_free(kind);+ const app = g_app_info_get_default_for_type(kind, 0) orelse return error.NoDefaultApplication;+ defer g_object_unref(app);+ const file = g_file_new_for_path(filename);+ defer g_object_unref(file);+ var files: List = .{ .data = file };+ if (g_app_info_launch(app, &files, null, null) == 0) return error.LaunchFailed;+}+/// Keep the bundled PDF viewer fallback, but honor an explicit alternative.pub fn hasAlternativeDefault(path: []const u8, bundled_id: []const u8) bool {const filename = std.heap.c_allocator.dupeZ(u8, path) catch return false;diff --git a/src/files/history.zig b/src/files/history.zigindex 9711ca7..5269c26 100644--- a/src/files/history.zig+++ b/src/files/history.zig@@ -51,7 +51,7 @@ pub const History = struct {return self.forward_stack.items.len > 0;}pub fn canUp(self: *const History) bool {- return !std.mem.eql(u8, self.current, "/");+ return !@import("recent.zig").isLocation(self.current) and !std.mem.eql(u8, self.current, "/");}pub fn navigate(self: *History, new_path: []const u8) !void {const archive_len = if (self.archive_len > 0 and new_path.len >= self.archive_len anddiff --git a/src/files/recent.zig b/src/files/recent.zignew file mode 100644index 0000000..b73fa19--- /dev/null+++ b/src/files/recent.zig@@ -0,0 +1,112 @@+//! The shared freedesktop recent-file history. All disk work runs on Files' worker.+const std = @import("std");+const clipboard = @import("clipboard.zig");+const Allocator = std.mem.Allocator;++pub const location = "recent:///";+pub fn isLocation(value: []const u8) bool {+ return std.mem.eql(u8, value, location);+}++// Keep GLib's headers out of translate-c, like associations.zig.+extern fn g_bookmark_file_new() *anyopaque;+extern fn g_bookmark_file_free(bookmark: *anyopaque) void;+extern fn g_bookmark_file_load_from_data(bookmark: *anyopaque, data: [*]const u8, length: usize, err: ?*?*anyopaque) c_int;+extern fn g_bookmark_file_get_uris(bookmark: *anyopaque, length: *usize) [*:null]?[*:0]u8;+extern fn g_bookmark_file_get_visited_date_time(bookmark: *anyopaque, uri: [*:0]const u8, err: ?*?*anyopaque) ?*anyopaque;+extern fn g_bookmark_file_get_modified_date_time(bookmark: *anyopaque, uri: [*:0]const u8, err: ?*?*anyopaque) ?*anyopaque;+extern fn g_date_time_to_unix(date: *anyopaque) i64;+extern fn g_bookmark_file_set_visited_date_time(bookmark: *anyopaque, uri: [*:0]const u8, date: *anyopaque) void;+extern fn g_bookmark_file_set_modified_date_time(bookmark: *anyopaque, uri: [*:0]const u8, date: *anyopaque) void;+extern fn g_date_time_new_now_utc() *anyopaque;+extern fn g_date_time_unref(date: *anyopaque) void;+extern fn g_bookmark_file_set_mime_type(bookmark: *anyopaque, uri: [*:0]const u8, mime: [*:0]const u8) void;+extern fn g_bookmark_file_add_application(bookmark: *anyopaque, uri: [*:0]const u8, name: [*:0]const u8, exec: [*:0]const u8) void;+extern fn g_bookmark_file_to_data(bookmark: *anyopaque, length: *usize, err: ?*?*anyopaque) ?[*:0]u8;+extern fn g_file_set_contents_full(filename: [*:0]const u8, data: [*]const u8, length: isize, flags: c_int, mode: c_int, err: ?*?*anyopaque) c_int;+extern fn g_content_type_guess(filename: [*:0]const u8, data: ?[*]const u8, size: usize, uncertain: ?*c_int) ?[*:0]u8;+extern fn g_content_type_get_mime_type(content_type: [*:0]const u8) ?[*:0]u8;+extern fn g_strfreev(strings: [*:null]?[*:0]u8) void;+extern fn g_free(memory: ?*anyopaque) void;++pub const Entry = struct { path: [:0]const u8, opened: i64 };++pub fn path(a: Allocator, env: std.process.Environ) ![:0]u8 {+ const base = env.getPosix("XDG_DATA_HOME");+ if (base) |dir| {+ if (std.fs.path.isAbsolute(dir)) return std.fmt.allocPrintSentinel(a, "{s}/recently-used.xbel", .{dir}, 0);+ }+ const home = env.getPosix("HOME") orelse return error.NoHome;+ return std.fmt.allocPrintSentinel(a, "{s}/.local/share/recently-used.xbel", .{home}, 0);+}++fn load(a: Allocator, io: std.Io, filename: []const u8) !*anyopaque {+ const bookmark = g_bookmark_file_new();+ errdefer g_bookmark_file_free(bookmark);+ const data = std.Io.Dir.cwd().readFileAlloc(io, filename, a, .limited(8 * 1024 * 1024)) catch |err| switch (err) {+ error.FileNotFound => return bookmark,+ else => return err,+ };+ defer a.free(data);+ if (g_bookmark_file_load_from_data(bookmark, data.ptr, data.len, null) == 0) return error.InvalidHistory;+ return bookmark;+}++/// Local files only; URI decoding rejects remote hosts, malformed escapes and NULs.+pub fn read(a: Allocator, io: std.Io, env: std.process.Environ) ![]Entry {+ const filename = try path(a, env);+ defer a.free(filename);+ const bookmark = try load(a, io, filename);+ defer g_bookmark_file_free(bookmark);+ var count: usize = 0;+ const uris = g_bookmark_file_get_uris(bookmark, &count);+ defer g_strfreev(uris);+ var entries: std.ArrayList(Entry) = .empty;+ errdefer {+ for (entries.items) |entry| a.free(entry.path);+ entries.deinit(a);+ }+ for (uris[0..count]) |maybe_uri| {+ const uri = maybe_uri orelse continue;+ const decoded = clipboard.decodeLocalPath(a, std.mem.span(uri)) catch continue;+ defer a.free(decoded);+ const date = g_bookmark_file_get_visited_date_time(bookmark, uri, null) orelse+ g_bookmark_file_get_modified_date_time(bookmark, uri, null);+ const owned = try a.dupeZ(u8, decoded);+ errdefer a.free(owned);+ // Bookmark date getters return borrowed values.+ try entries.append(a, .{ .path = owned, .opened = if (date) |d| g_date_time_to_unix(d) else 0 });+ }+ return entries.toOwnedSlice(a);+}++/// Re-read before writing so another window's latest entries are preserved.+pub fn record(a: Allocator, io: std.Io, env: std.process.Environ, opened: []const u8) !void {+ if (!std.fs.path.isAbsolute(opened)) return;+ const filename = try path(a, env);+ defer a.free(filename);+ const bookmark = try load(a, io, filename);+ defer g_bookmark_file_free(bookmark);+ const raw_uri = try clipboard.encodeLocalUri(a, opened);+ defer a.free(raw_uri);+ const uri = try a.dupeZ(u8, raw_uri);+ defer a.free(uri);+ const zpath = try a.dupeZ(u8, opened);+ defer a.free(zpath);+ const content_type = g_content_type_guess(zpath, null, 0, null);+ defer g_free(content_type);+ const mime = if (content_type) |t| g_content_type_get_mime_type(t) else null;+ defer g_free(mime);+ g_bookmark_file_set_mime_type(bookmark, uri, mime orelse "application/octet-stream");+ g_bookmark_file_add_application(bookmark, uri, "RediWM Files", "rediwm-files %f");+ const now = g_date_time_new_now_utc();+ defer g_date_time_unref(now);+ g_bookmark_file_set_visited_date_time(bookmark, uri, now);+ g_bookmark_file_set_modified_date_time(bookmark, uri, now);+ try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(filename).?);+ var length: usize = 0;+ const data = g_bookmark_file_to_data(bookmark, &length, null) orelse return error.WriteHistoryFailed;+ defer g_free(data);+ // G_FILE_SET_CONTENTS_CONSISTENT: atomic replacement, private on first creation.+ if (g_file_set_contents_full(filename, data, @intCast(length), 1, 0o600, null) == 0) return error.WriteHistoryFailed;+}diff --git a/src/files/settings.zig b/src/files/settings.zigindex 6516bc7..ef89b6f 100644--- a/src/files/settings.zig+++ b/src/files/settings.zig@@ -15,20 +15,30 @@ pub const ThemeUpdate = struct {allocator: std.mem.Allocator,region: config.RegionConfig = .{},- fn init(a: std.mem.Allocator, t: theme.Theme) !ThemeUpdate {+ fn init(a: std.mem.Allocator, t: theme.Theme, prefs: config.RegionConfig) !ThemeUpdate {var value = t;value.font = try a.dupe(u8, t.font);errdefer a.free(value.font);value.mono_font = try a.dupe(u8, t.mono_font);errdefer a.free(value.mono_font);value.start_button_icon = try a.dupe(u8, t.start_button_icon);- return .{ .value = value, .allocator = a };+ errdefer a.free(value.start_button_icon);+ var owned = prefs;+ owned.timezone = try a.dupe(u8, prefs.timezone);+ errdefer a.free(owned.timezone);+ owned.language = try a.dupe(u8, prefs.language);+ errdefer a.free(owned.language);+ owned.formats = try a.dupe(u8, prefs.formats);+ return .{ .value = value, .allocator = a, .region = owned };}pub fn deinit(self: ThemeUpdate) void {self.allocator.free(self.value.font);self.allocator.free(self.value.mono_font);self.allocator.free(self.value.start_button_icon);+ self.allocator.free(self.region.timezone);+ self.allocator.free(self.region.language);+ self.allocator.free(self.region.formats);}/// Transfers ownership to the UI thread. Never call from a worker.@@ -100,6 +110,7 @@ pub const Settings = struct {var arena = std.heap.ArenaAllocator.init(a);defer arena.deinit();var t: theme.Theme = .{};+ var prefs: config.RegionConfig = .{};self.animations = .{};self.region = .{};for (paths, 0..) |path, i| {@@ -109,17 +120,21 @@ pub const Settings = struct {self.animations = parseAnimations(bytes);var cfg = config.parse(arena.allocator(), bytes, p) catch null;if (cfg) |*value| {- self.region = value.region;- value.deinit();+ defer value.deinit();+ prefs = value.region;+ prefs.timezone = arena.allocator().dupe(u8, prefs.timezone) catch return null;+ prefs.language = arena.allocator().dupe(u8, prefs.language) catch return null;+ prefs.formats = arena.allocator().dupe(u8, prefs.formats) catch return null;}}var next = t;theme.overlay(arena.allocator(), &next, bytes) catch continue;t = next;}- var update = ThemeUpdate.init(a, t) catch return null;- update.region = self.region;- return update;+ // Settings only retains scalar preferences; returned updates own strings.+ self.region.clock_24h = prefs.clock_24h;+ self.region.first_day_of_week = prefs.first_day_of_week;+ return ThemeUpdate.init(a, t, prefs) catch null;}};@@ -186,7 +201,7 @@ test "Files follows config edits, theme overrides and file removal" {defer update2.deinit();try std.testing.expectEqual(@as(f32, 12), update2.value.scrollbar_width);try std.testing.expectEqualStrings("Noto Sans", update2.value.font);- try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = &config_path, .data = "[theme]\nscrollbar_width = 4\n[region]\nclock_24h = true\n" });+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = &config_path, .data = "[theme]\nscrollbar_width = 4\n[region]\nclock_24h = true\ntimezone = \"Pacific/Auckland\"\nlanguage = \"C.utf8\"\nformats = \"en_NZ.utf8\"\n" });settings.last_second = -1;const update3 = settings.poll(a, io).?;defer update3.deinit();@@ -209,6 +224,9 @@ test "Files follows config edits, theme overrides and file removal" {try std.testing.expectEqualStrings(time24, formatDateTime(timestamp, &buf, update3.region)[11..]);}try std.testing.expectEqualStrings("Unavailable", formatDateTime(0, buf[0..4], update3.region));+ try std.testing.expectEqualStrings("Pacific/Auckland", update3.region.timezone);+ try std.testing.expectEqualStrings("C.utf8", update3.region.language);+ try std.testing.expectEqualStrings("en_NZ.utf8", update3.region.formats);// Outstanding worker updates retain their strings across later polls.try std.testing.expectEqualStrings("Liberation Sans", update1.value.font);}diff --git a/src/files/worker.zig b/src/files/worker.zigindex 593ca7c..c0928a8 100644--- a/src/files/worker.zig+++ b/src/files/worker.zig@@ -4,6 +4,7 @@ const c = @import("c.zig").api;const theme = @import("../icon_theme.zig");const icons = @import("../icon_cache.zig");const git = @import("git.zig");+const recent = @import("recent.zig");const Allocator = std.mem.Allocator;pub const Item = struct {@@ -19,6 +20,7 @@ pub const Item = struct {is_broken: bool,bytes: i64,mtime: i64,+ opened: i64 = 0,mode: c.mode_t = 0,owner: []const u8 = "",icon_name: []const u8,@@ -66,6 +68,7 @@ pub const Worker = struct {show_hidden: bool = false,request_id: u64 = 1,pending_snapshot: ?*Snapshot = null,+ opened_paths: std.ArrayList([]u8) = .empty,/// Signalled after each request so the worker sleeps between them/// instead of polling on an 80 ms clock.wake: c_int = -1,@@ -112,6 +115,8 @@ pub const Worker = struct {_ = c.close(self.wake_main);if (self.pending_snapshot) |s| s.destroy();if (self.theme) |t| t.deinit();+ for (self.opened_paths.items) |p| self.allocator.free(p);+ self.opened_paths.deinit(self.allocator);for (self.theme_cfg.base_dirs) |d| self.allocator.free(d);self.allocator.free(self.theme_cfg.base_dirs);@@ -124,6 +129,17 @@ pub const Worker = struct {return self.navigateLocation(new_dir, show_hidden, 0);}+ pub fn recordOpened(self: *Worker, path: []const u8) void {+ _ = c.pthread_mutex_lock(&self.mutex);+ defer _ = c.pthread_mutex_unlock(&self.mutex);+ const owned = self.allocator.dupe(u8, path) catch return;+ self.opened_paths.append(self.allocator, owned) catch {+ self.allocator.free(owned);+ return;+ };+ self.signal();+ }+pub fn navigateLocation(self: *Worker, new_dir: []const u8, show_hidden: bool, archive_len: usize) u64 {_ = c.pthread_mutex_lock(&self.mutex);defer _ = c.pthread_mutex_unlock(&self.mutex);@@ -199,7 +215,18 @@ pub const Worker = struct {var inotify_wd: c_int = -1;var git_watches: [4]c_int = @splat(-1);- while (!self.stop.load(.acquire)) {+ while (true) {+ _ = c.pthread_mutex_lock(&self.mutex);+ const opened = self.opened_paths;+ self.opened_paths = .empty;+ _ = c.pthread_mutex_unlock(&self.mutex);+ for (opened.items) |p| {+ recent.record(self.allocator, self.io, self.environ, p) catch {};+ self.allocator.free(p);+ }+ var opened_storage = opened;+ opened_storage.deinit(self.allocator);+ if (self.stop.load(.acquire)) break;if (settings.poll(self.allocator, self.io)) |t| {_ = c.pthread_mutex_lock(&self.mutex);self.animation_settings = settings.animations;@@ -240,15 +267,21 @@ pub const Worker = struct {if (inotify_fd >= 0 and watched_dir != null) {var zpath_buf: [4096]u8 = undefined;- const watch_path = if (cur_archive_len > 0) std.fs.path.dirname(cur_dir[0..cur_archive_len]) orelse "/" else watched_dir.?;- const zpath = std.fmt.bufPrintZ(&zpath_buf, "{s}", .{watch_path}) catch null;- if (zpath) |zp| {+ const recent_path = if (recent.isLocation(cur_dir)) recent.path(self.allocator, self.environ) catch null else null;+ defer if (recent_path) |p| self.allocator.free(p);+ var watch_path = if (recent_path) |p| std.fs.path.dirname(p).? else if (cur_archive_len > 0) std.fs.path.dirname(cur_dir[0..cur_archive_len]) orelse "/" else watched_dir.?;+ while (true) {+ const zp = std.fmt.bufPrintZ(&zpath_buf, "{s}", .{watch_path}) catch break;inotify_wd = c.inotify_add_watch(inotify_fd,zp,c.IN_CREATE | c.IN_DELETE | c.IN_MOVED_FROM | c.IN_MOVED_TO |c.IN_CLOSE_WRITE | c.IN_ATTRIB | c.IN_DELETE_SELF | c.IN_MOVE_SELF,);+ // A first-run data directory may not exist yet. Watch+ // its nearest existing parent until it is created.+ if (inotify_wd >= 0 or recent_path == null) break;+ watch_path = std.fs.path.dirname(watch_path) orelse break;}}}@@ -306,7 +339,15 @@ pub const Worker = struct {off += @sizeOf(c.struct_inotify_event) + ev.len;}}- if (changed) self.rescan_requested.store(true, .release);+ if (changed) {+ self.rescan_requested.store(true, .release);+ if (recent.isLocation(cur_dir)) {+ // Re-establish the watch after creation or replacement+ // of the data directory, without a periodic rescan.+ if (watched_dir) |d| self.allocator.free(d);+ watched_dir = null;+ }+ }}} else {_ = c.usleep(80 * 1000);@@ -391,6 +432,29 @@ pub const Worker = struct {return snap;};+ if (recent.isLocation(dir_path)) {+ const entries = recent.read(mem, self.io, self.environ) catch {+ snap.err_msg = "Could not read recent files";+ return snap;+ };+ var list: std.ArrayList(Item) = .empty;+ var owners: std.AutoHashMapUnmanaged(c.uid_t, []const u8) = .empty;+ var associations: @import("associations.zig").Resolver = .{ .allocator = mem };+ var seen: std.StringHashMapUnmanaged(void) = .empty;+ for (entries) |entry| {+ const name = std.fs.path.basename(entry.path);+ if (!show_hidden and std.mem.startsWith(u8, name, ".")) continue;+ if (seen.contains(entry.path)) continue;+ var item = statItem(mem, &owners, &associations, name, entry.path) orelse continue;+ if (item.is_dir or item.is_broken or (item.mode & c.S_IFMT != c.S_IFREG and !item.is_symlink)) continue;+ item.opened = entry.opened;+ seen.put(mem, entry.path, {}) catch continue;+ list.append(mem, item) catch continue;+ }+ snap.items = list.toOwnedSlice(mem) catch &.{};+ return snap;+ }+var dir = std.Io.Dir.cwd().openDir(self.io, dir_path, .{ .iterate = true }) catch |err| {snap.err_msg = switch (err) {error.FileNotFound => "Folder not found",diff --git a/src/icon_cache.zig b/src/icon_cache.zigindex e940298..5c89447 100644--- a/src/icon_cache.zig+++ b/src/icon_cache.zig@@ -8,7 +8,7 @@// codebase's own buffer convention (see chrome.zig/Taskbar.BarBuffer), so// the rasterized pixels are copied out verbatim, no conversion. PNG reuses// the existing (deliberately minimal) png.zig decoder, then gets-// bilinearly resampled to the requested size, since hicolor's fixed sizes+// area-filtered when reduced to the requested size, since hicolor's fixed sizes// essentially never match our device-pixel target exactly.const std = @import("std");const Io = std.Io;@@ -282,9 +282,9 @@ fn lerpArgb(a: u32, b: u32, t: f32) u32 {return (out[0] << 24) | (out[1] << 16) | (out[2] << 8) | out[3];}-// Bilinear resample of a premultiplied-ARGB buffer into a square icon slot,-// centering rectangular artwork without stretching it. Valid on premultiplied-// data (unlike some other filters) since resize is a linear operation.+// Resample a premultiplied-ARGB buffer into a square icon slot, centering+// rectangular artwork without stretching it. Each reduced pixel averages its+// entire source footprint; bilinear sampling alone aliases small app icons.fn resample(src: []const u32, src_w: i32, src_h: i32, dst_size: i32) ![]u32 {const dst = try gpa.alloc(u32, @intCast(dst_size * dst_size));const dw: usize = @intCast(dst_size);@@ -297,6 +297,43 @@ fn resample(src: []const u32, src_w: i32, src_h: i32, dst_size: i32) ![]u32 {const left = (dwf - image_w) / 2;const top = (dwf - image_h) / 2;+ if (longest > dwf) {+ const source_per_pixel = longest / dwf;+ for (0..dw) |dy| {+ const y_start = (@as(f32, @floatFromInt(dy)) - top) * source_per_pixel;+ const y_end = y_start + source_per_pixel;+ for (0..dw) |dx| {+ const x_start = (@as(f32, @floatFromInt(dx)) - left) * source_per_pixel;+ const x_end = x_start + source_per_pixel;+ var channels = [4]f32{ 0, 0, 0, 0 };+ const first_y: i32 = @intFromFloat(@floor(@max(0, y_start)));+ const last_y: i32 = @intFromFloat(@ceil(@min(sh, y_end)));+ const first_x: i32 = @intFromFloat(@floor(@max(0, x_start)));+ const last_x: i32 = @intFromFloat(@ceil(@min(sw, x_end)));+ var sy = first_y;+ while (sy < last_y) : (sy += 1) {+ const yf: f32 = @floatFromInt(sy);+ const wy = @min(y_end, yf + 1) - @max(y_start, yf);+ var sx = first_x;+ while (sx < last_x) : (sx += 1) {+ const xf: f32 = @floatFromInt(sx);+ const weight = wy * (@min(x_end, xf + 1) - @max(x_start, xf));+ const pixel = src[@intCast(sy * src_w + sx)];+ const sample = unpack(pixel);+ for (0..4) |channel| channels[channel] += sample[channel] * weight;+ }+ }+ const area = source_per_pixel * source_per_pixel;+ var result: u32 = 0;+ for (channels) |channel| {+ result = (result << 8) | @as(u32, @intFromFloat(@round(channel / area)));+ }+ dst[dy * dw + dx] = result;+ }+ }+ return dst;+ }+var dy: usize = 0;while (dy < dw) : (dy += 1) {const py = @as(f32, @floatFromInt(dy)) + 0.5;@@ -343,6 +380,14 @@ test "rectangular PNG icons keep their proportions" {for (pixels[4..12]) |pixel| try std.testing.expectEqual(@as(u32, 0xff), pixel >> 24);}+test "shrinking an icon preserves fine detail across each pixel footprint" {+ var src = [_]u32{0} ** 64;+ src[0] = 0x80800000;+ const pixels = try resample(&src, 8, 8, 2);+ defer gpa.free(pixels);+ try std.testing.expectEqualSlices(u32, &.{ 0x08080000, 0, 0, 0 }, pixels);+}+test "decode palette PNG via cairo fallback" {const paths = [_][*:0]const u8{"/usr/share/icons/hicolor/32x32/apps/cups.png",diff --git a/src/ipc/protocol.zig b/src/ipc/protocol.zigindex d66a705..7a9ed1b 100644--- a/src/ipc/protocol.zig+++ b/src/ipc/protocol.zig@@ -900,14 +900,14 @@ pub const ConfigLoadedEvent = struct {error_name: ?[]const u8 = null,};-pub const ThemeToken = struct { name: []const u8, color: ?[4]f32 = null, number: ?f32 = null, text: ?[]const u8 = null };+pub const ThemeToken = struct { name: []const u8, color: ?[4]f32 = null, number: ?f32 = null, text: ?[]const u8 = null, boolean: ?bool = null };pub const ThemeTokens = struct {entries: []const ThemeToken,pub fn jsonStringify(self: ThemeTokens, jws: anytype) !void {try jws.beginObject();for (self.entries) |token| {try jws.objectField(token.name);- if (token.color) |color| try jws.write(color) else if (token.number) |number| try jws.write(number) else try jws.write(token.text);+ if (token.color) |color| try jws.write(color) else if (token.number) |number| try jws.write(number) else if (token.boolean) |boolean| try jws.write(boolean) else try jws.write(token.text);}try jws.endObject();}diff --git a/src/ipc/settings.zig b/src/ipc/settings.zigindex 0469a43..c22768f 100644--- a/src/ipc/settings.zig+++ b/src/ipc/settings.zig@@ -83,7 +83,7 @@ pub fn getTheme(server: *Server, a: std.mem.Allocator) !protocol.Response {inline for (fields, 0..) |field, i| {entries[i] = .{ .name = field.name };const value = @field(theme.global, field.name);- if (field.type == [4]f32 or field.type == ?[4]f32) entries[i].color = value else if (field.type == []const u8) entries[i].text = value else if (@typeInfo(field.type) == .float) entries[i].number = value else @compileError("unhandled theme token " ++ field.name);+ if (field.type == [4]f32 or field.type == ?[4]f32) entries[i].color = value else if (field.type == []const u8) entries[i].text = value else if (field.type == bool) entries[i].boolean = value else if (@typeInfo(field.type) == .float) entries[i].number = value else @compileError("unhandled theme token " ++ field.name);}return .{ .ok = .{ .theme = .{ .tokens = .{ .entries = entries }, .path = server.theme_path, .dark_mode = server.config.compositor.dark_mode } } };}diff --git a/src/network/popup.zig b/src/network/popup.zigindex 1638305..ff0f2a2 100644--- a/src/network/popup.zig+++ b/src/network/popup.zig@@ -14,6 +14,7 @@ const toggle = @import("ui").widgets.toggle;const checkbox = @import("ui").widgets.checkbox;const Secret = @import("ui").widgets.secret_input.Input;const Caret = @import("../caret_overlay.zig").CaretOverlay;+const hover_glide = @import("ui").hover_glide;const network = @import("manager.zig");const sonar = @import("sonar.zig");const secure = @import("secure_allocator.zig").allocator;@@ -67,6 +68,7 @@ pub const Popup = struct {focus: Focus = .toggle,focus_index: usize = 0,hover: ?usize = null,+ item_hover: hover_glide.Glide = .{},hits: [280]Hit = undefined,hit_count: usize = 0,scroll: f32 = 0,@@ -131,6 +133,8 @@ pub const Popup = struct {if (self.caret.placed) |*p| p.origin_y = @floatFromInt(self.buffer_node.node.y);const active = self.caret.frame(now);self.paintSonar(now);+ const row_quantum = anim.rasterPixelQuantum(self.output.wlr_output.scale) / (row_height * self.factor);+ if (self.item_hover.step(now, 1, row_quantum)) self.refresh();const expanding = !self.opening.height.settled(now) or !self.closing.height.settled(now);// Sample both every frame: sampleChanged must run once per frame each.const quantum = 1 / (self.output.wlr_output.scale * self.factor);@@ -140,7 +144,7 @@ pub const Popup = struct {self.refresh();if (!self.opening.height.settled(now)) self.ensureFormVisible();}- return active or expanding or !self.slide.settled(now) or self.sonarFading() or (self.sonarVisible() and self.searching() and anim.enabled() and !anim.reducedMotion());+ return active or expanding or self.item_hover.animating(now) or !self.slide.settled(now) or self.sonarFading() or (self.sonarVisible() and self.searching() and anim.enabled() and !anim.reducedMotion());}fn searching(self: *Popup) bool {return if (self.manager()) |m| m.searching() else false;@@ -228,6 +232,11 @@ pub const Popup = struct {const next = self.hit(@floatCast(sx / self.factor), @floatCast(sy / self.factor));if (next == self.hover) return;self.hover = next;+ const target: ?hover_glide.Cell = if (next) |i| if (self.hits[i].focus == .row)+ .{ .col = 0, .row = @intCast(self.hits[i].index) }+ else+ null else null;+ self.item_hover.setTarget(anim.nowMs(), target);self.refresh();}fn hit(self: *Popup, x: f32, y: f32) ?usize {@@ -264,6 +273,7 @@ pub const Popup = struct {pub fn scrollWheel(self: *Popup, delta: f32) void {self.scroll = std.math.clamp(self.scroll + delta, 0, @max(0, self.content_height - (self.height - header - footer - self.status_height)));self.hover = null;+ self.item_hover.setTarget(anim.nowMs(), null);self.refresh();}fn ensureFormVisible(self: *Popup) void {@@ -457,6 +467,23 @@ pub const Popup = struct {fn focused(self: *Popup, f: Focus, index: usize) bool {return self.focus == f and ((f != .row and f != .security_option) or self.focus_index == index);}+ fn networkRowY(self: *Popup, index: usize) ?f32 {+ const m = self.manager() orelse return null;+ if (!m.available or !m.enabled or !m.hardware or m.device.len == 0 or index >= m.count) return null;+ var y = header - self.scroll;+ for (m.networks[0..index]) |net| y += row_height + self.shownHeight(net);+ return y;+ }+ fn itemHoverBox(self: *Popup, row: f32) ?Rect {+ const m = self.manager() orelse return null;+ if (m.count == 0) return null;+ const bounded = std.math.clamp(row, 0, @as(f32, @floatFromInt(m.count - 1)));+ const low: usize = @intFromFloat(@floor(bounded));+ const high = @min(low + 1, m.count - 1);+ const low_y = self.networkRowY(low) orelse return null;+ const high_y = self.networkRowY(high) orelse return null;+ return .{ .x = 12, .y = low_y + (high_y - low_y) * (bounded - @floor(bounded)), .w = width - 24, .h = row_height };+ }fn formHeight(self: *Popup) f32 {if (self.hidden) return @as(f32, if (self.security == .open) 220 else 292) + @as(f32, if (self.security_open) 102 else 0);if (self.selected) |s| {@@ -550,6 +577,13 @@ pub const Popup = struct {r.fillRect(20, 65, width - 40, 1, .{ .color = t.border });r.clip = .{ .x = 12, .y = header, .w = width - 24, .h = self.height - header - footer - self.status_height };self.caret_reported = false;+ if (self.item_hover.frame.alpha > 0) if (self.itemHoverBox(self.item_hover.frame.row)) |box| {+ var fill = t.surface_hover;+ var border = t.border_soft;+ fill[3] *= self.item_hover.frame.alpha;+ border[3] *= self.item_hover.frame.alpha;+ r.fillRect(box.x, box.y, box.w, box.h, .{ .color = fill, .radius = 5, .border_width = 1, .border_color = border });+ };var y = header - self.scroll;if (enabled) {if (count == 0) {@@ -560,8 +594,8 @@ pub const Popup = struct {const selected = if (self.selected) |s| network.sameNetwork(s, net) else false;const extra = self.shownHeight(net);const box: Rect = .{ .x = 12, .y = y, .w = width - 24, .h = row_height };- const hovered = self.addHit(box, .row, i);- if (selected or extra > 0 or net.connected or hovered or self.focused(.row, i)) r.fillRect(12, y, width - 24, row_height + extra, .{ .color = t.surface_hover, .radius = 5 });+ _ = self.addHit(box, .row, i);+ if (selected or extra > 0 or net.connected or self.focused(.row, i)) r.fillRect(12, y, width - 24, row_height + extra, .{ .color = t.surface_hover, .radius = 5 });if (net.connected or selected or extra > 0) r.fillRect(12, y + 5, 3, row_height - 10 + extra, .{ .color = t.accent, .radius = 1 });var signal_color = t.window_fg;signal_color[3] *= 0.45 + @as(f32, @floatFromInt(net.strength)) / 100 * 0.55;diff --git a/src/session/lock.zig b/src/session/lock.zigindex a8a7116..4d072c9 100644--- a/src/session/lock.zig+++ b/src/session/lock.zig@@ -45,7 +45,7 @@ pub fn clearKeyScratch(bytes: []u8) void {pub const Lock = struct {server: *Server,- /// Redraws the clock at the next minute; the lock has no other deadline.+ /// Handles the clock and transient controls deadlines.timer: *wl.EventSource,user: [256]u8 = @splat(0),name: [256]u8 = @splat(0),@@ -71,6 +71,8 @@ pub const Lock = struct {retry_at: i64 = 0,revision: u64 = 1,minute: i64 = -1,+ controls_visible: bool = false,+ controls_hide_at: i64 = 0,confirm: ?bool = null, // false = power off, true = rebootpower_child: ?*Child = null,avatar: ?png.Image = null,@@ -169,10 +171,13 @@ pub const Lock = struct {self.scheduleClock();}- /// Wakes at the next minute boundary, as the taskbar clock does.+ /// Wakes for the next clock minute or transient controls timeout.fn scheduleClock(self: *Lock) void {- const delay: c_int = @intCast((60 - @mod(c.time(null), 60)) * 1000 + 25);- self.timer.timerUpdate(delay) catch {};+ var delay: i64 = (60 - @mod(c.time(null), 60)) * 1000 + 25;+ if (self.controls_visible and self.controls_hide_at > 0) {+ delay = @min(delay, @max(1, self.controls_hide_at - anim.nowMs()));+ }+ self.timer.timerUpdate(@intCast(delay)) catch {};}/// Everyone outside the compositor who tracks the lock: rediwm-session,@@ -358,7 +363,24 @@ pub const Lock = struct {/// Volume, mute or brightness changed; redraw only the controls block.pub fn controlsChanged(self: *Lock) void {if (self.greeter != null) return;- if (self.controls.refresh(self.server)) self.server.scheduleFrames();+ const previous_volume = self.controls.volume;+ const previous_muted = self.controls.muted;+ const previous_brightness = self.controls.brightness;+ if (self.controls.refresh(self.server)) {+ self.server.scheduleFrames();+ if (self.controls.volume != previous_volume or self.controls.muted != previous_muted or self.controls.brightness != previous_brightness) {+ self.showControls();+ }+ }+ }++ fn showControls(self: *Lock) void {+ if (self.greeter != null or self.controls.height() == 0) return;+ const newly_visible = !self.controls_visible;+ self.controls_visible = true;+ self.controls_hide_at = anim.nowMs() + 2500;+ self.scheduleClock();+ if (newly_visible) self.server.scheduleFrames();}/// The control under a layout point, with its track's left edge and@@ -378,16 +400,24 @@ pub const Lock = struct {if (self.controls.drag != null) {const before = self.controls.revision;self.controls.dragTo(self.server, @floatCast(x));+ self.controls_hide_at = anim.nowMs() + 2500;+ self.scheduleClock();if (self.controls.revision != before) self.server.scheduleFrames();return;}- const hit: ?lock_controls.Hit = if (self.controlsAt(x, y)) |at| at.hit else null;+ const at = self.controlsAt(x, y);+ if (at != null) self.showControls();+ const hit: ?lock_controls.Hit = if (at) |found| found.hit else null;if (self.controls.setHover(hit)) self.server.scheduleFrames();}/// The primary button went up, wherever the pointer is.pub fn pointerReleased(self: *Lock) void {- if (self.controls.endDrag()) self.server.scheduleFrames();+ if (self.controls.endDrag()) {+ self.controls_hide_at = anim.nowMs() + 2500;+ self.scheduleClock();+ self.server.scheduleFrames();+ }}fn powerExited(owner: ?*anyopaque, _: *Child, status: ?u32) void {@@ -403,6 +433,12 @@ pub const Lock = struct {self.minute = minute;self.changed();}+ if (self.controls_visible and self.controls.drag == null and anim.nowMs() >= self.controls_hide_at) {+ self.controls_visible = false;+ self.controls_hide_at = 0;+ _ = self.controls.setHover(null);+ self.server.scheduleFrames();+ }self.scheduleClock();return 0;}@@ -613,6 +649,7 @@ pub const Lock = struct {pub fn click(self: *Lock, x: f64, y: f64) void {if (self.controlsAt(x, y)) |at| {+ self.showControls();switch (at.hit.part) {.icon => if (at.hit.kind == .volume) lock_controls.toggleMute(self.server),.track => self.controls.beginDrag(self.server, at.hit.kind, at.left, at.span, @floatCast(x)),@@ -737,7 +774,7 @@ const Geometry = struct {}};-const field_options: text_field.Options = .{ .size = .lg, .trailing = .reveal };+const field_options: text_field.Options = .{ .size = .lg, .secret_dots = .{ .diameter = 0.46, .pitch = 1.05 }, .trailing = .reveal };pub const View = struct {tree: *wlr.SceneTree,@@ -804,7 +841,7 @@ pub const View = struct {/// on, changed. The greeter and an output without either backend show none.fn syncControls(self: *View, lock: *Lock, b: wlr.Box, scale: f32) void {const block_h = lock.controls.height();- if (lock.greeter != null or block_h == 0 or b.width <= 0 or b.height <= 0) return self.hideControls();+ if (lock.greeter != null or !lock.controls_visible or block_h == 0 or b.width <= 0 or b.height <= 0) return self.hideControls();const key = ControlsKey{ .revision = lock.controls.revision, .width = b.width, .height = b.height, .scale = scale };if (self.controls_key) |have| if (std.meta.eql(have, key)) return;const geo = Geometry.init(@floatFromInt(b.width), @floatFromInt(b.height));@@ -1050,7 +1087,7 @@ test "lock output guard is opaque independent of wallpaper and UI buffers" {}test "lock raster scales to small outputs and renders a solid accent unlock button" {- var lock = Lock{ .server = undefined, .timer = undefined };+ var lock = Lock{ .server = undefined, .timer = undefined, .controls_visible = true };@memcpy(lock.name[0..11], "Alex Morgan");@memcpy(lock.user[0..10], "alexmorgan");lock.controls = .{ .has_volume = true, .volume = 0.5, .has_brightness = true, .brightness = 0.25 };diff --git a/src/session/lock_controls.zig b/src/session/lock_controls.zigindex fa78f93..1e46bca 100644--- a/src/session/lock_controls.zig+++ b/src/session/lock_controls.zig@@ -1,4 +1,4 @@-//! Volume and brightness sliders at the bottom of the built-in lock screen.+//! Transient volume and brightness sliders on the built-in lock screen.//!//! The hardware keys already work behind the lock; these are the pointer and//! touch way to the same two controls. They are not part of the lock's@@ -9,6 +9,8 @@//! row exists only while its backend reports one: no default sink, no//! backlight, no row. A drag shows its own value until release, then the//! backend's report takes over again.+//! The block is hidden at rest and appears on pointer use or a hardware value+//! change, then hides again after a short idle timeout.//!//! Everything here is in the block's design units (the lock's 600x900//! canvas) except the drag's track, which is kept in layout pixels so a dragdiff --git a/src/taskbar/chip_style.zig b/src/taskbar/chip_style.zigindex aeb89b1..29144fb 100644--- a/src/taskbar/chip_style.zig+++ b/src/taskbar/chip_style.zig@@ -5,12 +5,27 @@ const chrome = @import("../chrome.zig");pub fn Look(comptime C: type) type {return struct { fill: C, border: C };}+/// Whose colours a pill wears: the main theme's (window tabs) or the taskbar+/// theme's, which a chosen taskbar theme can make different.+pub const Source = enum { window, taskbar };++fn token(comptime source: Source, comptime name: theme.TaskbarToken) [4]f32 {+ return switch (source) {+ .window => @field(theme.global, @tagName(name)),+ .taskbar => theme.taskbar(name),+ };+}+pub fn look(comptime C: type, active: bool, attention: bool, hover: f32, press: f32) Look(C) {- const idle = if (active) C.fromRgba(theme.global.taskbar_hover).scaled(2.8) else C.fromRgba(theme.global.taskbar_surface);- const hovered = C.fromRgba(theme.global.taskbar_hover).scaled(if (active) 3.6 else 2.0);+ return lookFrom(C, .window, active, attention, hover, press);+}++pub fn lookFrom(comptime C: type, comptime source: Source, active: bool, attention: bool, hover: f32, press: f32) Look(C) {+ const idle = if (active) C.fromRgba(token(source, .taskbar_hover)).scaled(2.8) else C.fromRgba(token(source, .taskbar_surface));+ const hovered = C.fromRgba(token(source, .taskbar_hover)).scaled(if (active) 3.6 else 2.0);return .{- .fill = C.fromRgba(theme.global.surface_hover).scaled(press).over(C.lerp(idle, hovered, hover)),- .border = if (attention) C.fromRgba(theme.global.danger).scaled(2.5 + 0.8 * hover + press) else C.fromRgba(theme.global.taskbar_border).scaled(if (active) 2.2 + 0.6 * hover + 0.8 * press else 1 + hover + 0.8 * press),+ .fill = C.fromRgba(token(source, .surface_hover)).scaled(press).over(C.lerp(idle, hovered, hover)),+ .border = if (attention) C.fromRgba(token(source, .danger)).scaled(2.5 + 0.8 * hover + press) else C.fromRgba(token(source, .taskbar_border)).scaled(if (active) 2.2 + 0.6 * hover + 0.8 * press else 1 + hover + 0.8 * press),};}diff --git a/src/taskbar/start_button.zig b/src/taskbar/start_button.zigindex bb7ed18..49539a6 100644--- a/src/taskbar/start_button.zig+++ b/src/taskbar/start_button.zig@@ -104,7 +104,7 @@ pub fn paintPixel(state: Paint, px: f32, py: f32, bar_height: i32, scale: f32, econst dot_cx = base_left + fsize / 2;const dot_cy = base_top + fsize + indicator_gap + indicator_diameter / 2;const cov = edgeCoverage(sdCircle(px, py, dot_cx, dot_cy, indicator_diameter / 2), scale);- if (cov > 0) return Color.fromRgba(theme.global.start_button_indicator).scaled(cov * open_amt);+ if (cov > 0) return Color.fromRgba(theme.taskbar(.start_button_indicator)).scaled(cov * open_amt);}const mapped = mapPoint(state, px, py, bar_height, edge_pad, btn_size);@@ -117,5 +117,5 @@ pub fn paintPixel(state: Paint, px: f32, py: f32, bar_height: i32, scale: f32, eif (cov <= 0) return null;const highlight = @max(state.hover, open_amt);- return Color.fromRgba(theme.global.start_button_hover).scaled(cov * highlight);+ return Color.fromRgba(theme.taskbar(.start_button_hover)).scaled(cov * highlight);}diff --git a/src/ui/layout.zig b/src/ui/layout.zigindex 7769bef..d99a210 100644--- a/src/ui/layout.zig+++ b/src/ui/layout.zig@@ -392,6 +392,8 @@ pub const StepperData = struct {/// Borrowed labels; keep them alive until the tree is destroyed. Callbacks may/// rebuild the tree. Popup state is transient and resets with the widget.pub const SelectData = struct {+ /// Explicitly selecting the current choice reapplies its external state.+ notify_on_reselect: bool = false,owner: ?*anyopaque = null,id: usize = 0,/// Visible placeholders that cannot be committed.diff --git a/src/ui/paint.zig b/src/ui/paint.zigindex f42d0e9..0f79b05 100644--- a/src/ui/paint.zig+++ b/src/ui/paint.zig@@ -1546,6 +1546,13 @@ test "secret input widget never retains hidden or echo-on responses in run cache// And through the shared field, frame and all._ = field_widget.paintSecret(&renderer, .{ .x = 0, .y = 0, .w = 400, .h = 50 }, .{ .size = .lg, .trailing = .reveal }, .{ .focused = true }, &field, "");_ = field_widget.paintSecret(&renderer, .{ .x = 0, .y = 0, .w = 400, .h = 50 }, .{ .size = .lg, .trailing = .reveal }, .{ .focused = true, .revealed = true }, &field, "");+ // Dotted masking: the caret keeps the field font's height, hidden or not.+ const box: field_widget.Rect = .{ .x = 0, .y = 0, .w = 400, .h = 50 };+ const dotted: field_widget.Options = .{ .size = .lg, .secret_dots = .{ .diameter = 0.46, .pitch = 1.05 } };+ const hidden = field_widget.paintSecret(&renderer, box, dotted, .{ .focused = true }, &field, "").caret.?;+ const clear = field_widget.paintSecret(&renderer, box, dotted, .{ .focused = true, .revealed = true }, &field, "").caret.?;+ try std.testing.expectEqual(clear.h, hidden.h);+ try std.testing.expectEqual(clear.y, hidden.y);try std.testing.expectEqual(before, text_mod.testingRunCacheCount());}diff --git a/src/ui/theme.zig b/src/ui/theme.zigindex fe59ba3..1d4118e 100644--- a/src/ui/theme.zig+++ b/src/ui/theme.zig@@ -1,5 +1,5 @@// A deliberately tiny TOML reader for the shell-chrome theme file: only a-// `[theme]` section header, bare numeric values, and quoted string values+// `[theme]` section header, bare numeric/boolean values, and quoted string values// (colors as "#rrggbb"/"#rrggbbaa" or "rgba(r,g,b,a)", font names as plain// strings). No arrays, tables-of-tables, dates, or multi-line strings — the// token set below is everything this engine actually reads.@@ -33,6 +33,8 @@ pub const Theme = struct {chrome_height: f32 = 46.0,/// Space between window controls, independent of their size.chrome_control_gap: f32 = 4.0,+ /// Circular window controls and pill-shaped tabs, including tab controls.+ chrome_round_buttons: bool = false,// Window decorations use neutral charcoal independently of shell glass.window_bg: [4]f32 = .{ @as(f32, 7.6) / 255.0, 9.0 / 255.0, 11.0 / 255.0, 0.80 }, // 80% darkness and opacity// Neutral foregrounds keep text and monochrome icons free of a blue tint.@@ -311,6 +313,84 @@ pub fn shellPalette() Theme {return t;}+/// The colour tokens the taskbar draws with. A taskbar theme (Appearance's+/// "Task Bar theme", `[taskbar_theme]` in the config) replaces just these, and+/// only on the taskbar: every other surface keeps the main theme. Geometry+/// (`taskbar_size`, chip and start-button sizes and gaps, radii) stays with the+/// main theme, which has sliders for it.+pub const TaskbarToken = enum {+ taskbar_bg,+ taskbar_surface,+ taskbar_hover,+ taskbar_border,+ border_soft,+ surface_hover,+ window_fg,+ window_dim,+ danger,+ window_close_hover,+ start_button_hover,+ start_button_indicator,+ start_button_logo_color,+ battery_bg,+ battery_full,+ battery_low,+ battery_critical,+ battery_shimmer,+};++/// The chosen taskbar theme; null follows `global`. Only its `TaskbarToken`+/// fields mean anything (see `taskbarTokens`).+pub var taskbar_override: ?Theme = null;++/// A taskbar colour: the taskbar theme's when one is chosen, else the main+/// theme's. The taskbar reads these instead of `global` so the two can differ.+pub fn taskbar(comptime token: TaskbarToken) @FieldType(Theme, @tagName(token)) {+ if (taskbar_override) |chosen| return @field(chosen, @tagName(token));+ return @field(global, @tagName(token));+}++/// Just `t`'s taskbar tokens over a default theme: the form `taskbar_override`+/// holds, so nothing else of `t` (its strings in particular) is kept.+pub fn taskbarTokens(t: Theme) Theme {+ var out: Theme = .{};+ inline for (std.meta.fields(TaskbarToken)) |field| @field(out, field.name) = @field(t, field.name);+ return out;+}++/// Whether two themes' taskbar tokens look the same once written: colours+/// compare as `writeTaskbarInto` stores them, so a saved and reloaded theme+/// still equals the preset it came from.+pub fn taskbarTokensEql(a: Theme, b: Theme) bool {+ inline for (std.meta.fields(TaskbarToken)) |field| {+ if (!sameWritten(@field(a, field.name), @field(b, field.name))) return false;+ }+ return true;+}++fn sameWritten(a: anytype, b: @TypeOf(a)) bool {+ if (comptime @TypeOf(a) == ?[4]f32) {+ const left = a orelse return b == null;+ const right = b orelse return false;+ return sameWritten(left, right);+ }+ return std.meta.eql(quantize(a), quantize(b));+}++pub fn taskbarOverrideEql(a: ?Theme, b: ?Theme) bool {+ const left = a orelse return b == null;+ const right = b orelse return false;+ return taskbarTokensEql(left, right);+}++/// Applies `key` only when it is a taskbar token, so a section holding a whole+/// theme file's keys still yields just the taskbar's. False for any other key.+pub fn applyTaskbarKey(allocator: Allocator, t: *Theme, key: []const u8, value: []const u8) !bool {+ if (std.meta.stringToEnum(TaskbarToken, key) == null) return false;+ try applyKey(allocator, t, key, value);+ return true;+}+/// Appearance presets write ordinary numeric theme tokens, so hand-edited/// radii remain the source of truth and repeated picks never compound.pub const RadiusPreset = enum { sharp, default, round };@@ -424,6 +504,7 @@ fn keysOf(comptime T: type) []const []const u8 {}const color_keys = keysOf([4]f32);const number_keys = keysOf(f32);+const boolean_keys = keysOf(bool);const optional_color_keys = keysOf(?[4]f32);const string_keys = keysOf([]const u8);@@ -473,6 +554,12 @@ pub fn stripComment(line: []const u8) []const u8 {pub fn applyKey(allocator: Allocator, t: *Theme, key: []const u8, value: []const u8) !void {@setEvalBranchQuota(10000);+ inline for (boolean_keys) |name| {+ if (std.mem.eql(u8, key, name)) {+ @field(t, name) = if (std.mem.eql(u8, value, "true")) true else if (std.mem.eql(u8, value, "false")) false else return error.InvalidBoolean;+ return;+ }+ }inline for (string_keys) |name| {if (std.mem.eql(u8, key, name)) {const text = try unquote(value);@@ -578,8 +665,15 @@ fn appendColor(allocator: Allocator, buf: *std.ArrayList(u8), key: []const u8, cpub fn writeInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {const defaults: Theme = .{};try buf.appendSlice(allocator, "[theme]\n");+ inline for (boolean_keys) |name| {+ if (@field(t, name) != @field(defaults, name)) try appendLine(allocator, buf, "{s} = {}\n", .{ name, @field(t, name) });+ }inline for (string_keys) |name| {- if (!std.mem.eql(u8, @field(t, name), @field(defaults, name))) try appendLine(allocator, buf, "{s} = \"{s}\"\n", .{ name, @field(t, name) });+ if (!std.mem.eql(u8, @field(t, name), @field(defaults, name))) {+ try buf.appendSlice(allocator, name ++ " = \"");+ try buf.appendSlice(allocator, @field(t, name));+ try buf.appendSlice(allocator, "\"\n");+ }}inline for (number_keys) |name| {// Keep the frame radius explicit even at Default, so a legacy@@ -601,6 +695,22 @@ pub fn writeInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void}}+/// The `[taskbar_theme]` section for `t`'s taskbar tokens. Values equal to the+/// defaults are left out, as `writeInto` does: the section's presence, not its+/// keys, says a taskbar theme is chosen, and it reads back over the defaults.+pub fn writeTaskbarInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme) !void {+ const defaults: Theme = .{};+ try buf.appendSlice(allocator, "[taskbar_theme]\n");+ inline for (std.meta.fields(TaskbarToken)) |field| {+ const value = @field(t, field.name);+ if (comptime @TypeOf(value) == ?[4]f32) {+ if (value) |color| try appendColor(allocator, buf, field.name, color);+ } else if (!std.meta.eql(quantize(value), quantize(@field(defaults, field.name)))) {+ try appendColor(allocator, buf, field.name, value);+ }+ }+}+pub fn unquote(v: []const u8) ![]const u8 {if (v.len >= 2 and v[0] == '"' and v[v.len - 1] == '"') return v[1 .. v.len - 1];return error.ExpectedQuotedString;@@ -857,10 +967,16 @@ test "chrome geometry validates and survives theme serialization" {var t: Theme = .{};try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "chrome_control_gap", value));}- const t = try parse(a, "[theme]\nchrome_height = 28\nchrome_control_gap = 0\n");+ for ([_][]const u8{ "1", "\"true\"", "True" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidBoolean, applyKey(a, &t, "chrome_round_buttons", value));+ }+ try std.testing.expect(!(try parse(a, "[theme]\nchrome_round_buttons = false\n")).chrome_round_buttons);+ const t = try parse(a, "[theme]\nchrome_height = 28\nchrome_control_gap = 0\nchrome_round_buttons = true\n");var buf: std.ArrayList(u8) = .empty;try writeInto(a, &buf, t);const restored = try parse(a, buf.items);try std.testing.expectEqual(@as(f32, 28), restored.chrome_height);try std.testing.expectEqual(@as(f32, 0), restored.chrome_control_gap);+ try std.testing.expect(restored.chrome_round_buttons);}diff --git a/src/ui/widgets/battery.zig b/src/ui/widgets/battery.zigindex 8069855..3f14f9a 100644--- a/src/ui/widgets/battery.zig+++ b/src/ui/widgets/battery.zig@@ -54,6 +54,20 @@ pub const Colors = struct {pub fn of(t: theme.Theme) Colors {return .{ .border = t.taskbar_border, .fg = t.window_fg, .bg = t.battery_bg, .full = t.battery_full, .low = t.battery_low, .critical = t.battery_critical, .shimmer = t.battery_shimmer };}++ /// The badge as the taskbar shows it: its theme's colours, which may+ /// differ from the rest of the shell's.+ pub fn taskbar() Colors {+ return .{+ .border = theme.taskbar(.taskbar_border),+ .fg = theme.taskbar(.window_fg),+ .bg = theme.taskbar(.battery_bg),+ .full = theme.taskbar(.battery_full),+ .low = theme.taskbar(.battery_low),+ .critical = theme.taskbar(.battery_critical),+ .shimmer = theme.taskbar(.battery_shimmer),+ };+ }};/// Straight (not premultiplied) colour.diff --git a/src/ui/widgets/button.zig b/src/ui/widgets/button.zigindex 0d7e1c1..f6cb9b4 100644--- a/src/ui/widgets/button.zig+++ b/src/ui/widgets/button.zig@@ -39,6 +39,8 @@ pub const Options = struct {/// lock's Power and Restart.stacked: bool = false,alignment: enum { center, left } = .center,+ /// Override for chrome's tab navigation buttons, which use the ghost look.+ radius: ?f32 = null,};pub const State = struct {@@ -132,7 +134,7 @@ pub fn paintBackground(r: *Renderer, box: Rect, opts: Options, state: State) voiconst border_w: f32 = if (ring) 2 else if (opts.variant == .secondary) 1 else 0;if (bg[3] > 0 or border_w > 0) r.fillRect(box.x, box.y, box.w, box.h, .{.color = bg,- .radius = if (opts.variant == .chrome) chrome.control_radius else m.radius,+ .radius = opts.radius orelse if (opts.variant == .chrome) chrome.cornerRadius(t.chrome_round_buttons, box.w, box.h, chrome.control_radius) else m.radius,.border_width = border_w,.border_color = if (ring) t.controlFocusColor() else if (hovered) t.border else t.border_soft,});@@ -334,4 +336,12 @@ test "ghost and chrome buttons draw nothing until hovered" {try std.testing.expectEqual(@as(u32, 0), pixels[5 * 40 + 20]);paint(&r, box, .{ .variant = .chrome, .icon = .close, .icon_scale = 0.01 }, .{ .pointer = .hover });try std.testing.expectEqual(@as(u32, 217), pixels[5 * 40 + 20] >> 24);+ try std.testing.expect(pixels[2 * 40 + 2] >> 24 > 0);+ @memset(&pixels, 0);+ var t = theme.global;+ t.chrome_round_buttons = true;+ r.palette = t;+ paint(&r, box, .{ .variant = .chrome, .icon = .close, .icon_scale = 0.01 }, .{ .pointer = .hover });+ try std.testing.expectEqual(@as(u32, 0), pixels[2 * 40 + 2]);+ try std.testing.expectEqual(@as(u32, 217), pixels[5 * 40 + 20] >> 24);}diff --git a/src/ui/widgets/field.zig b/src/ui/widgets/field.zigindex 2fbc376..ea9a904 100644--- a/src/ui/widgets/field.zig+++ b/src/ui/widgets/field.zig@@ -21,6 +21,9 @@ pub const Trailing = enum { none, reveal };pub const Options = struct {size: Size = .md,+ /// Draws a hidden secret as circles of this size and pitch instead of+ /// bullet glyphs. The caret and hint stay at the field's font size.+ secret_dots: ?secret_input.Dots = null,/// None by default; `.search` for search boxes.leading_icon: ?layout.IconId = null,leading_icon_size: ?f32 = null,@@ -145,6 +148,7 @@ pub fn paintSecret(r: *Renderer, box: Rect, opts: Options, state: State, input:.caret = state.focused and !state.disabled,.placeholder = placeholder,.draw_caret = !state.external_caret,+ .dots = opts.secret_dots,});return out;}diff --git a/src/ui/widgets/secret_input.zig b/src/ui/widgets/secret_input.zigindex e758bf2..9d687d2 100644--- a/src/ui/widgets/secret_input.zig+++ b/src/ui/widgets/secret_input.zig@@ -2,10 +2,45 @@const std = @import("std");const text = @import("../text.zig");const theme = @import("../theme.zig");-const Renderer = @import("../paint.zig").Renderer;+const ui_paint = @import("../paint.zig");+const Renderer = ui_paint.Renderer;/// Bullets beyond this many are not drawn; no caller stores more characters.const max_bullets = 512;++/// Masked characters drawn as circles instead of bullet glyphs, so their size+/// and spacing are the caller's choice rather than the face's. Both are in+/// ems of the field's font size.+pub const Dots = struct {+ diameter: f32,+ /// Centre to centre; the caret sits halfway between two dots.+ pitch: f32,+};++/// `Dots` in whole device pixels (as logical units): every dot then+/// rasterizes identically and the gaps cannot wander by a pixel.+const DotGrid = struct {+ pitch: f32,+ /// A cell's left edge to its dot's.+ lead: f32,+ diameter: f32,++ fn init(dots: Dots, font_size: f32, scale: f32) DotGrid {+ const pitch = @max(1, @round(dots.pitch * font_size * scale));+ const diameter = std.math.clamp(@round(dots.diameter * font_size * scale), 1, pitch);+ return .{ .pitch = pitch / scale, .lead = @floor((pitch - diameter) / 2) / scale, .diameter = diameter / scale };+ }+};++/// Characters, not bytes, capped at what the mask draws.+fn masked(bytes: []const u8) usize {+ var count: usize = 0;+ for (bytes) |b| {+ if (b & 0xc0 != 0x80) count += 1;+ }+ return @min(count, max_bullets);+}+pub const Input = struct {storage: []u8,len: usize = 0,@@ -62,6 +97,9 @@ pub const Input = struct {/// Off when the caller animates the caret itself from the returned/// `CaretPlace` (a blinking, gliding overlay).draw_caret: bool = true,+ /// Mask with circles rather than bullet glyphs. The caret and the+ /// placeholder stay on `font_size` either way.+ dots: ?Dots = null,};/// Where the caret belongs, in the renderer's logical units.@@ -83,23 +121,12 @@ pub const Input = struct {/// place when `look.caret` is set.pub fn paint(self: *const Input, r: *Renderer, x: f32, y: f32, w: f32, h: f32, font_size: f32, look: Look) ?CaretPlace {const t = r.palette orelse theme.global;- var mask: [max_bullets * 3]u8 = undefined;- const shown = if (look.hidden) self.bullets(&mask) else self.value();- const prefix = if (look.hidden) blk: {- var count: usize = 0;- for (self.value()[0..self.cursor]) |b| {- if (b & 0xc0 != 0x80) count += 1;- }- break :blk shown[0..@min(shown.len, count * 3)];- } else self.value()[0..self.cursor];- const advance = text.measureSensitiveWidth(prefix, .manrope, font_size, r.scale) catch 0;- const scroll = @max(0, advance - w + 2);- r.drawTextScrolled(.{ .x = x, .y = y, .w = w, .h = h, .scroll_x = scroll, .style = .{- .content = if (shown.len == 0) look.placeholder else shown,- .font_size = font_size,- .color = if (shown.len == 0) t.faint else t.fg,- .sensitive = true,- } });+ const dots: ?Dots = if (look.hidden and self.len > 0) look.dots else null;+ const advance = if (dots) |spec|+ self.paintDots(r, x, y, w, h, font_size, spec)+ else+ self.paintText(r, x, y, w, h, font_size, look);+ const scroll = scrollFor(advance, w);if (!look.caret) return null;// The face's ink box, which is what the text is centred on.const ink = text.verticalMetrics(.manrope, font_size, r.scale) catch@@ -109,6 +136,50 @@ pub const Input = struct {if (look.draw_caret) r.fillRect(place.origin_x + place.offset, place.y, place.w, place.h, .{ .color = t.caretColor() });return place;}+ /// How far the row scrolls to keep a caret `advance` in is in a box `w` wide.+ fn scrollFor(advance: f32, w: f32) f32 {+ return @max(0, advance - w + 2);+ }++ /// Bullet glyphs (or the clear text, or the placeholder) through the+ /// sensitive text path. Returns the caret's advance.+ fn paintText(self: *const Input, r: *Renderer, x: f32, y: f32, w: f32, h: f32, font_size: f32, look: Look) f32 {+ const t = r.palette orelse theme.global;+ var mask: [max_bullets * 3]u8 = undefined;+ const shown = if (look.hidden) self.bullets(&mask) else self.value();+ const prefix = if (look.hidden)+ shown[0..@min(shown.len, masked(self.value()[0..self.cursor]) * 3)]+ else+ self.value()[0..self.cursor];+ const advance = text.measureSensitiveWidth(prefix, .manrope, font_size, r.scale) catch 0;+ r.drawTextScrolled(.{ .x = x, .y = y, .w = w, .h = h, .scroll_x = scrollFor(advance, w), .style = .{+ .content = if (shown.len == 0) look.placeholder else shown,+ .font_size = font_size,+ .color = if (shown.len == 0) t.faint else t.fg,+ .sensitive = true,+ } });+ return advance;+ }++ /// One circle per character on a fixed pitch, centred in the box and+ /// clipped to it. Returns the caret's advance.+ fn paintDots(self: *const Input, r: *Renderer, x: f32, y: f32, w: f32, h: f32, font_size: f32, spec: Dots) f32 {+ const t = r.palette orelse theme.global;+ const grid = DotGrid.init(spec, font_size, r.scale);+ const advance = grid.pitch * @as(f32, @floatFromInt(masked(self.value()[0..self.cursor])));+ const origin = @round((x - scrollFor(advance, w)) * r.scale) / r.scale;+ const top = @round(((y + h / 2) - grid.diameter / 2) * r.scale) / r.scale;+ r.clean = false;+ var clipped = r.*;+ clipped.clip = ui_paint.intersectClip(r.clip, .{ .x = x, .y = y, .w = w, .h = h });+ for (0..masked(self.value())) |i| {+ const dot_x = origin + grid.pitch * @as(f32, @floatFromInt(i)) + grid.lead;+ if (dot_x + grid.diameter <= x or dot_x >= x + w) continue;+ clipped.fillRect(dot_x, top, grid.diameter, grid.diameter, .{ .color = t.fg, .radius = grid.diameter / 2 });+ }+ return advance;+ }+pub fn bullets(self: *const Input, out: []u8) []const u8 {var n: usize = 0;for (self.value()) |b| if (b & 0xc0 != 0x80 and n + 3 <= out.len) {diff --git a/src/ui/widgets/select.zig b/src/ui/widgets/select.zigindex 4480c24..537e816 100644--- a/src/ui/widgets/select.zig+++ b/src/ui/widgets/select.zig@@ -64,7 +64,7 @@ fn reveal(w: *Widget) void {pub fn commit(w: *Widget, index: usize) void {const d = &w.kind.select;if (d.disabled or index >= d.labels.len or std.mem.indexOfScalar(usize, d.disabled_options, index) != null) return;- const changed = d.selected == null or d.selected.? != index;+ const changed = d.notify_on_reselect or d.selected == null or d.selected.? != index;const callback = d.on_change;const owner = d.owner;const id = d.id;diff --git a/src/ui/window_chrome.zig b/src/ui/window_chrome.zigindex 5ba3376..eb69cd7 100644--- a/src/ui/window_chrome.zig+++ b/src/ui/window_chrome.zig@@ -10,6 +10,11 @@ pub const title_icon_gap: i32 = 10;const icon_scale: f32 = 1.11;pub const button_glyph_scale: f32 = icon_scale * 1.1;pub const control_radius: f32 = 4;+/// Round chrome uses half the shorter side: circles for controls, pills for tabs.+pub fn cornerRadius(round: bool, width: f32, height: f32, default_radius: f32) f32 {+ return if (round) @min(width, height) / 2 else default_radius;+}+pub const ControlKind = enum { minimize, maximize, close };// Charcoal header with evenly spaced, unboxed window controls.diff --git a/tests/appearance_chrome.py b/tests/appearance_chrome.pyindex 6781b8e..c31bd51 100644--- a/tests/appearance_chrome.py+++ b/tests/appearance_chrome.py@@ -31,10 +31,10 @@ def run(scale, external_theme=False):config = ('[compositor]\nxwayland = false\nfocus_zoom = "keep"\n''[desktop]\nenabled = false\n''[animations]\nenabled = false\n'- '[theme]\nwindow_bg = "#101215"\nshadow = "#00000000"\n')+ '[theme]\nwindow_bg = "#101215"\nshadow = "#00000000"\nchrome_round_buttons = false\n')theme_path = tmp / ("theme.toml" if external_theme else "rediwm-config.toml")if external_theme:- theme_path.write_text('[theme]\n')+ theme_path.write_text('[theme]\nchrome_round_buttons = false\n')env_extra = {"DBUS_SESSION_BUS_ADDRESS": "", "XDG_DATA_HOME": str(data),"REDIWM_NO_GLASS": "1"}if external_theme:@@ -101,6 +101,44 @@ def run(scale, external_theme=False):def controls():return {w["name"]: w for w in ipc.get_widget_tree(f"window/{win_id}")["widgets"]}+ # Reload while a control is hovered: retained chrome must+ # change its corner pixels without moving the hit target.+ ipc.action("move_window_to", {"id": win_id, "x": 80, "y": 80})+ ipc.set_zoom(win_id, 100)+ ipc.focus_window(win_id)++ def control_pixels(name):+ box = controls()[name]["global_box"]+ ipc.move_cursor(rounded(box["x"] + box["width"] / 2), rounded(box["y"] + box["height"] / 2))+ ipc.wait_for_frame()+ path = tmp / "control-shape.png"+ path.unlink(missing_ok=True)+ ipc.screenshot(str(path))+ with Image.open(path) as image:+ image = image.convert("RGB")+ corner = image.getpixel((rounded((box["x"] + 2) * scale), rounded((box["y"] + 2) * scale)))+ edge = image.getpixel((rounded((box["x"] + box["width"] / 2) * scale), rounded((box["y"] + 2) * scale)))+ return box, corner, edge++ names = ("minimize", "maximize", "close")+ square = {name: control_pixels(name) for name in names}+ theme_path.write_text(theme_path.read_text().replace("chrome_round_buttons = false", "chrome_round_buttons = true"))+ ipc.reload_config()+ assert ipc.action("get_theme")["tokens"]["chrome_round_buttons"] is True+ for name in names:+ box, corner, edge = control_pixels(name)+ assert box == square[name][0], (name, box, square[name])+ assert sum(abs(a - b) for a, b in zip(corner, square[name][1])) > 6, (name, corner, square[name])+ assert edge == square[name][2], (name, edge, square[name])+ theme_path.write_text(theme_path.read_text().replace("chrome_round_buttons = true", "chrome_round_buttons = false"))+ ipc.reload_config()+ assert ipc.action("get_theme")["tokens"]["chrome_round_buttons"] is False+ for name in names:+ assert control_pixels(name) == square[name], name+ ipc.move_cursor(10, 10)+ theme_path.write_text(theme_path.read_text().replace("chrome_round_buttons = false", "chrome_round_buttons = true"))+ ipc.reload_config()+open_appearance()assert ui.scroll_into_view("chrome_height")["value"] == 46assert ui.scroll_into_view("chrome_control_gap")["value"] == 4@@ -135,6 +173,7 @@ def run(scale, external_theme=False):saved = tomllib.loads(theme_path.read_text())["theme"]assert saved["chrome_height"] == height, savedassert saved["chrome_control_gap"] == gap, saved+ assert saved["chrome_round_buttons"] is True, savedassert tomllib.loads((tmp / "rediwm-config.toml").read_text())["compositor"]["focus_zoom"] == "keep"close_settings()debug = ipc.get_window_debug(win_id)@@ -241,7 +280,7 @@ def run(scale, external_theme=False):open_appearance()assert ui.scroll_into_view("chrome_height")["value"] == 84assert ui.scroll_into_view("chrome_control_gap")["value"] == 24- print(f"PASS: chrome height/gap, pixels and controls (scale={scale}, external={external_theme})")+ print(f"PASS: chrome round buttons, height/gap, pixels and controls (scale={scale}, external={external_theme})")finally:if focus_client is not None:stop_process(focus_client)diff --git a/tests/appearance_settings.py b/tests/appearance_settings.pyindex e3b9a0c..6e8e03a 100644--- a/tests/appearance_settings.py+++ b/tests/appearance_settings.py@@ -11,6 +11,7 @@ import refrom ipc_client import IPCClient, spawn_compositor, stop_processfrom ui_driver import UIDriver+from desktop_zoom import wait_forfrom PIL import Image@@ -30,7 +31,9 @@ def test_appearance_settings():"[animations]\nenabled = true\nspeed = 1.0\nreduced_motion = \"auto\"\n""[theme]\nfont = \"Manrope\"\nmono_font = \"JetBrains Mono\"\nwindow_bg = \"rgba(16,18,21,0.980)\"\n")- env = {"DBUS_SESSION_BUS_ADDRESS": ""}+ env = {"DBUS_SESSION_BUS_ADDRESS": "", "DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/nonexistent",+ "REDIWM_FILES_DEVICES": "0", "XDG_DATA_HOME": str(tmp / "data"),+ "XDG_CACHE_HOME": str(tmp / "cache")}process, log = spawn_compositor(tmp, config_content=initial_config, env_extra=env)try:@@ -79,6 +82,63 @@ def test_appearance_settings():assert sum(n for n, color in image.convert("RGB").getcolors(image.width * image.height) if color == (18, 52, 86)) > 20, "app_bg reload did not repaint Settings"appearance_page()+ # Pick a real image through Files, persist a long path, and+ # check the taskbar's pixels before and after restoring R.+ logo_dir = tmp / ("custom logo " + "a" * 140)+ logo_dir.mkdir()+ logo = logo_dir / "logo.png"+ Image.new("RGBA", (32, 32), (18, 231, 73, 255)).save(logo)++ def chooser():+ return next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-file-chooser"), None)++ logo_shots = iter(range(10000))++ def logo_visible():+ shot = tmp / f"logo-shot-{next(logo_shots)}.png"+ ipc.screenshot(str(shot))+ with Image.open(shot) as image:+ colors = image.convert("RGB").crop((0, image.height - 80, 100, image.height)).getdata()+ return sum(1 for c in colors if c == (18, 231, 73)) > 100++ assert ui.scroll_into_view("start_logo_reset")["is_disabled"]+ click_widget(ui.scroll_into_view("start_logo_choose"))+ window = wait_for(chooser, "logo file chooser")+ assert next(w for w in widgets() if w["name"] == "start_logo_choose")["is_disabled"]+ ipc.focus_window(window["id"])+ time.sleep(.3)+ ipc.key(29, True)+ ipc.key_down_up(38) # Ctrl+L+ ipc.key(29, False)+ ipc.type_text(str(logo_dir))+ ipc.key_press("Return")+ time.sleep(.5)+ ipc.key_press("Home")+ ipc.key_press("Return")+ wait_for(lambda: chooser() is None, "logo chooser accepted")+ wait_for(lambda: read_config()["theme"].get("start_button_icon") == str(logo), "saved logo path")+ wait_for(logo_visible, "custom taskbar logo")+ ipc.reload_config()+ ipc.wait_for_panel_settled("control_center")+ assert not ui.scroll_into_view("start_logo_reset")["is_disabled"]++ click_widget(ui.scroll_into_view("start_logo_choose"))+ window = wait_for(chooser, "logo chooser reopened")+ ipc.focus_window(window["id"])+ time.sleep(.3)+ ipc.key_press("Escape")+ wait_for(lambda: chooser() is None, "logo chooser cancelled")+ assert read_config()["theme"]["start_button_icon"] == str(logo)+ assert logo_visible()++ click_widget(ui.scroll_into_view("start_logo_reset"))+ wait_for(lambda: not read_config()["theme"].get("start_button_icon"), "default logo saved")+ wait_for(lambda: not logo_visible(), "default logo restored")+ assert ui.scroll_into_view("start_logo_reset")["is_disabled"]+ ipc.reload_config()+ ipc.wait_for_panel_settled("control_center")+ assert not logo_visible()+focus_zoom = ui.scroll_into_view("focus_zoom")assert focus_zoom.get("selected_index") == 1, "boost should be the default"for index, mode in ((0, "keep"), (2, "camera"), (1, "boost")):@@ -273,6 +333,46 @@ def test_appearance_settings():for name in ("caret", "selection", "selection_fg", "field_border_focus"):assert name not in light_theme+ # A taskbar theme recolours only the bar: Dark on a Light desktop.+ def taskbar_pixel(name):+ ipc.move_cursor(2, 2)+ ipc.wait_for_frame()+ box = ipc.get_shell_state()["taskbars"][0]["box"]+ shot = tmp / name+ ipc.screenshot(str(shot))+ with Image.open(shot) as image:+ return image.convert("RGB").getpixel((box["x"] + box["width"] // 2,+ box["y"] + box["height"] // 2))++ assert ui.scroll_into_view("taskbar_theme")["selected_index"] == 0+ click_widget(ui.scroll_into_view("taskbar_theme"))+ ipc.key_press("Home")+ ipc.key_press("Down")+ ipc.key_press("Return")+ ipc.wait_for_panel_settled("control_center")+ assert ui.scroll_into_view("taskbar_theme")["selected_index"] == 1+ assert max(taskbar_pixel("dark-taskbar.png")) < 90, "taskbar did not take the Dark taskbar theme"+ tokens = ipc.action("get_theme")["tokens"]+ assert all(abs(a - b) < 0.001 for a, b in zip(tokens["taskbar_bg"], [241 / 255, 244 / 255, 247 / 255, 0.94]))+ assert all(abs(a - b) < 0.001 for a, b in zip(tokens["window_fg"], [31 / 255, 36 / 255, 48 / 255, 1]))+ assert ui.scroll_into_view("theme")["selected_index"] == 1+ assert read_config()["taskbar_theme"] == {}+ assert read_config()["theme"]["shell_accent"].startswith("rgba(14,165,160,")+ ipc.reload_config()+ ipc.close_panel("control_center")+ ipc.wait_for("control_center_closed", timeout_ms=5000)+ ipc.action("open_appearance")+ ipc.wait_for_panel_settled("control_center")+ assert ui.scroll_into_view("taskbar_theme")["selected_index"] == 1+ assert max(taskbar_pixel("dark-taskbar-reloaded.png")) < 90+ click_widget(ui.scroll_into_view("taskbar_theme"))+ ipc.key_press("Home")+ ipc.key_press("Return")+ ipc.wait_for_panel_settled("control_center")+ assert ui.scroll_into_view("taskbar_theme")["selected_index"] == 0+ assert "taskbar_theme" not in read_config()+ assert min(taskbar_pixel("light-taskbar-again.png")) > 200, "taskbar did not return to the main theme"+ipc.reload_config()ipc.close_panel("control_center")ipc.wait_for("control_center_closed", timeout_ms=5000)diff --git a/tests/calendar_popup.py b/tests/calendar_popup.pyindex 0a2fef3..ef5dae2 100644--- a/tests/calendar_popup.py+++ b/tests/calendar_popup.py@@ -1,6 +1,11 @@#!/usr/bin/env python3"""Clock popup navigation and dismissal, isolated from the host desktop."""import argparse+import json+import locale+import os+import sys+from hardware_keys import waitfrom pathlib import Pathimport tempfileimport time@@ -14,8 +19,8 @@ def run(scale):with tempfile.TemporaryDirectory(prefix="rediwm-calendar-") as directory:tmp = Path(directory)# Pixel equality checks need a settled popup, not its opening slide.- process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n[animations]\nenabled = false\n',- env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": directory})+ process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "pixman"), config_content='[compositor]\nxwayland = false\n[animations]\nenabled = false\n',+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": directory, "TZ": "Pacific/Auckland", "LC_ALL": "C", "LANGUAGE": "en"})try:with IPCClient(tmp, timeout=15) as ipc:ipc.wait_for("wallpaper_presented", timeout_ms=10000)@@ -65,6 +70,8 @@ def run(scale):ui.click("region", panel="control_center")ui.wait_settled("control_center")assert not any(w["label"] == "Preferred Languages" for w in ui.widgets())+ assert ui.find("clock_show_seconds")["on"] is False+ assert ui.find("clock_show_day")["on"] is Trueassert ui.find("first_day_of_week", panel="control_center")["selected_index"] == 0ui.click(ui.scroll_into_view("first_day_of_week"), panel="control_center")ipc.key_down_up(108) # Sunday -> Monday@@ -124,7 +131,128 @@ def run(scale):ui.wait_settled("control_center")assert ui.find("first_day_of_week", panel="control_center")["selected_index"] == 0assert any(w["label"] == "3:24 PM" for w in ui.widgets())- print(f"PASS: calendar navigation, preferences, live reload and dismissal at scale {scale}")+ assert any("session only; system defaults are unchanged" in (w["label"] or "") for w in ui.widgets())+ wait(lambda: not ui.find("language")["is_disabled"], "installed locales")+ for name in ("language", "formats"):+ ui.click(ui.scroll_into_view(name), panel="control_center")+ ipc.key_press("Home")+ ipc.key_press("Down")+ ipc.key_press("Return")+ ui.wait_settled("control_center")+ assert tomllib.loads(cfg_path.read_text())["region"][name] == "C"+ # UTC is the last sorted zone. Changing it must refresh the+ # existing clock without modifying the host's timezone files.+ before_zone = capture()+ ui.click(ui.scroll_into_view("timezone"), panel="control_center")+ ipc.key_press("End")+ ipc.key_press("Return")+ ui.wait_settled("control_center")+ assert tomllib.loads(cfg_path.read_text())["region"]["timezone"] == "UTC"+ after_zone = capture()+ clock_crop = tuple(round(v * float(scale)) for v in+ (bar["x"] + bar["width"] - 100, bar["y"],+ bar["x"] + bar["width"], bar["y"] + bar["height"]))+ assert ImageChops.difference(before_zone.crop(clock_crop), after_zone.crop(clock_crop)).getbbox(), "clock did not follow timezone"+ marker = tmp / "child-env.json"+ script = "import json,os; from pathlib import Path; Path(" + repr(str(marker)) + ").write_text(json.dumps(dict(os.environ)))"+ ipc.action("spawn", {"argv": [sys.executable, "-c", script]})+ wait(marker.exists, "new app environment")+ child_env = json.loads(marker.read_text())+ assert child_env["TZ"] == "UTC", child_env+ assert child_env["LANG"] == child_env["LC_MESSAGES"] == "C"+ assert child_env["LC_TIME"] == child_env["LC_NUMERIC"] == child_env["LC_MONETARY"] == "C"+ assert "LC_ALL" not in child_env and "LANGUAGE" not in child_env+ # Reopen Settings to prove that choices survive its arenas.+ window = next(w for w in ipc.get_windows() if w["app_id"] == "rediwm-settings")+ ipc.close_window(window["id"])+ ui.wait_absent("control_center")+ ipc.open_control_center()+ ui.wait_settled("control_center")+ ui.click("region", panel="control_center")+ wait(lambda: not ui.find("language")["is_disabled"], "locales after reopen")+ for name in ("timezone", "language", "formats"):+ assert ui.find(name)["selected_index"] > 0+ ui.click(ui.scroll_into_view(name), panel="control_center")+ ipc.key_press("Home")+ ipc.key_press("Return")+ ui.wait_settled("control_center")+ assert tomllib.loads(cfg_path.read_text())["region"][name] == ""++ def clock_image():+ box = next(i["box"] for i in ipc.get_shell_state()["taskbars"][0]["right_items"]+ if i["name"] == "clock")+ return capture().crop(tuple(round(v * float(scale)) for v in+ (box["x"], box["y"], box["x"] + box["width"], box["y"] + box["height"])))++ def ink(image):+ return image.convert("L").point(lambda value: 255 if value > 150 else 0).getbbox()++ # A two-line clock centers both runs in its fitted column.+ shown = clock_image()+ split = shown.height // 2+ for line in (shown.crop((0, 0, shown.width, split)), shown.crop((0, split, shown.width, shown.height))):+ bounds = ink(line)+ assert bounds and abs((bounds[0] + bounds[2]) / 2 - shown.width / 2) <= 2 * float(scale), bounds++ ui.click(ui.scroll_into_view("clock_show_seconds"))+ ui.wait_settled("control_center")+ assert any(w["label"] == "3:24:00 PM" for w in ui.widgets())+ before = ipc.get_perf()["taskbar_clock_frame_requests"]+ first_second = clock_image()+ time.sleep(2.2)+ assert ipc.get_perf()["taskbar_clock_frame_requests"] - before >= 2, "seconds did not rearm the clock timer"+ assert ImageChops.difference(first_second, clock_image()).getbbox(), "seconds did not repaint"++ ui.click(ui.scroll_into_view("clock_show_day"))+ ui.wait_settled("control_center")+ prefs = tomllib.loads(cfg_path.read_text())["region"]+ assert prefs["clock_show_seconds"] is True and prefs["clock_show_day"] is False+ single_line = clock_image()+ bounds = ink(single_line)+ assert bounds and abs((bounds[1] + bounds[3]) / 2 - single_line.height / 2) <= 2 * float(scale), bounds+ assert bounds[3] - bounds[1] < 22 * float(scale), "date line remained visible"++ window = next(w for w in ipc.get_windows() if w["app_id"] == "rediwm-settings")+ ipc.close_window(window["id"])+ ui.wait_absent("control_center")+ ipc.reload_config()+ ipc.open_control_center()+ ui.wait_settled("control_center")+ ui.click("region", panel="control_center")+ ui.wait_settled("control_center")+ assert ui.find("clock_show_seconds")["on"] is True+ assert ui.find("clock_show_day")["on"] is False+ ui.click(ui.scroll_into_view("clock_show_seconds"))+ ui.wait_settled("control_center")+ before = ipc.get_perf()["taskbar_clock_frame_requests"]+ time.sleep(2.2)+ assert ipc.get_perf()["taskbar_clock_frame_requests"] - before <= 1, "disabled seconds still wake every second"+ ui.click(ui.scroll_into_view("clock_show_day"))+ ui.wait_settled("control_center")++ # Check that the taskbar itself follows the regional date,+ # when a second installed locale is available on the test host.+ try:+ locale.setlocale(locale.LC_TIME, "en_NZ.utf8")+ except locale.Error:+ pass+ else:+ baseline_config = cfg_path.read_text()+ cfg_path.write_text(baseline_config.replace('formats = ""', 'formats = "C"'))+ ipc.reload_config()+ us_date = clock_image()+ cfg_path.write_text(baseline_config.replace('formats = ""', 'formats = "en_NZ.utf8"'))+ ipc.reload_config()+ nz_date = clock_image()+ # The C format has a two-digit year; en_NZ uses four.+ assert us_date.size != nz_date.size or ImageChops.difference(us_date, nz_date).getbbox(), "taskbar date ignored regional format"+ cfg_path.write_text(baseline_config)+ ipc.reload_config()+ print(f"PASS: calendar, region/language/timezone, centered clock, seconds/day toggles, persistence and child environment at scale {scale}")+ except Exception:+ log.flush()+ print((tmp / "compositor.log").read_text()[-5000:])+ raisefinally:stop_process(process)log.close()diff --git a/tests/control_center.py b/tests/control_center.pyindex d53e392..e3fd660 100644--- a/tests/control_center.py+++ b/tests/control_center.py@@ -193,6 +193,26 @@ print(f'fixture,backlight,{value},{value}%,100')assert not any(w["role"] == "swatch" or w.get("label") == "Accent colour" for w in widgets())assert any(w.get("name") == "theme" for w in widgets())capture("appearance")+ # A held scrollbar keeps working beyond the window edge.+ def content_scroll():+ return next(w for w in widgets() if w["role"] == "scroll_container")++ viewport = content_scroll()["global_box"]+ assert content_scroll()["content_size"] > viewport["height"]+ bar_x = viewport["x"] + viewport["width"] - 7+ bar_y = viewport["y"] + 8+ outside_x = box["x"] - 40+ ipc.move_cursor(bar_x, bar_y)+ ipc.pointer_button(272, True)+ ipc.move_cursor(outside_x, bar_y + 30)+ first_offset = content_scroll()["scroll_offset"]+ assert first_offset > 0, "scrollbar stopped outside Settings"+ ipc.move_cursor(outside_x, bar_y + 60)+ assert content_scroll()["scroll_offset"] > first_offset+ ipc.pointer_button(272, False)+ released_offset = content_scroll()["scroll_offset"]+ ipc.move_cursor(bar_x, bar_y + 90)+ assert content_scroll()["scroll_offset"] == released_offset, "scrollbar kept dragging after release"page("Audio")ipc.move_cursor(box["x"] + box["width"] - 80, box["y"] + box["height"] - 80)ipc.scroll(0, 600)@@ -330,6 +350,14 @@ def default_applications(scale):ipc.wait_for_frame()association = (tmp / "config/mimeapps.list").read_text()assert "inode/directory=test-files.desktop" in association, association+ # Reapply the current choice after another app changes the association.+ association_path = tmp / "config/mimeapps.list"+ association_path.write_text(association.replace(+ "inode/directory=test-files.desktop", "inode/directory=test-terminal.desktop"))+ ui.click(ui.scroll_into_view("default_file_manager"), panel="control_center")+ ipc.key_press("Return")+ wait(lambda: "inode/directory=test-files.desktop" in association_path.read_text(),+ "reselecting the file manager restores the folder association")window = next(w for w in ipc.get_windows() if w.get("app_id") == "rediwm-settings")ipc.close_window(window["id"])ui.wait_absent("control_center")diff --git a/tests/files_associations.py b/tests/files_associations.pyindex a9800b0..b7e4aa9 100644--- a/tests/files_associations.py+++ b/tests/files_associations.py@@ -33,7 +33,8 @@ def run():("application/x-rediwm-specific", "specific", "specific-file"),("application/x-rediwm-override", "override", None),("application/x-rediwm-noicon", "noicon", None),- ("application/pdf", "pdf", None)]+ ("application/pdf", "pdf", None),+ ("video/mp4", "mp4", None)]xml = '<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">'for mime_type, extension, icon in types:xml += f'<mime-type type="{mime_type}"><comment>Test model</comment><glob pattern="*.{extension}" weight="80"/>'@@ -45,18 +46,22 @@ def run():launcher = tmp / "record-open"launcher.write_text('#!/usr/bin/python3\nimport pathlib,sys\npathlib.Path(' + repr(str(marker)) + ').write_text(sys.argv[1]+"\\n"+sys.argv[2])\n')launcher.chmod(0o755)- for app, icon in (("openscad", "openscad"), ("override", "override-app"), ("missing", "no-such-app-icon-rediwm")):+ for app, icon in (("openscad", "openscad"), ("override", "override-app"),+ ("missing", "no-such-app-icon-rediwm"), ("celluloid", "override-app"),+ ("thunar", "no-such-app-icon-rediwm")):(apps / f"{app}.desktop").write_text('[Desktop Entry]\nType=Application\n'f'Name={app}\nIcon={icon}\nExec={launcher} {app} %f\nTerminal=false\n'- 'MimeType=' + ';'.join(t[0] for t in types) + ';\n')+ 'MimeType=' + ';'.join(t[0] for t in types) ++ (';x-scheme-handler/file;\n' if app == 'thunar' else ';\n'))(apps / "alternate.desktop").write_text('[Desktop Entry]\nType=Application\n'f'Name=Alternate Editor\nIcon=override-app\nExec={launcher} alternate %f\nTerminal=false\n')for i in range(12):(apps / f"extra-{i}.desktop").write_text('[Desktop Entry]\nType=Application\n'f'Name=Z Extra {i:02d}\nExec={launcher} extra-{i} %f\nTerminal=false\n')- defaults = ["openscad", "openscad", "override", "missing"]+ defaults = ["openscad", "openscad", "override", "missing", "", "celluloid"](config / "mimeapps.list").write_text('[Default Applications]\n' + ''.join(- f'{t[0]}={app}.desktop;\n' for t, app in zip(types, defaults)))+ f'{t[0]}={app}.desktop;\n' for t, app in zip(types, defaults) if app) ++ 'x-scheme-handler/file=thunar.desktop;\n')for name in ("a model #.scad", "b.specific", "c.override", "d.noicon"):(home / name).write_text('cube([1, 2, 3]);\n')env = dict(os.environ, HOME=str(home), XDG_DATA_HOME=str(data), XDG_DATA_DIRS=str(data),@@ -297,6 +302,18 @@ def run():wait_for(marker.exists, "ordinary PDF Open ignored the saved default")assert marker.read_text() == 'alternate\n' + str(pdf)+ # A file:// handler must not override the video's MIME default+ # when the user double-clicks it.+ video = home / 'z-video.mp4'+ video.write_bytes(b'\x00\x00\x00\x18ftypmp42')+ key(63) # Refresh the directory listing.+ time.sleep(.4)+ marker.unlink(missing_ok=True)+ click(738, 316)+ click(738, 316)+ wait_for(marker.exists, "double-click ignored the video MIME default")+ assert marker.read_text() == 'celluloid\n' + str(video)+# A directory's second action remains Cut, not Open With.folder = home / '0-folder'folder.mkdir()@@ -309,8 +326,10 @@ def run():wait_for(lambda: any(w['title'] == '0-folder — RediWM Files' for w in ipc.get_windows()),"folder context menu unexpectedly opened an app picker")assert client.poll() is None- print("PASS: MIME icons, Properties permissions and compact layout, Open With, default persistence, cancellation and folder exclusion")+ print("PASS: MIME icons, Properties permissions and compact layout, Open With, video default on double-click, default persistence, cancellation and folder exclusion")except Exception:+ if (tmp / "compositor.log").exists():+ print((tmp / "compositor.log").read_text()[-5000:])if (tmp / "files.log").exists():print((tmp / "files.log").read_text()[-5000:])raisediff --git a/tests/files_browser.py b/tests/files_browser.pyindex 06d4a1f..74b2aa7 100755--- a/tests/files_browser.py+++ b/tests/files_browser.py@@ -30,16 +30,26 @@ def run():(browse_dir / 'sample.txt').write_text('hello world')(browse_dir / '.hidden_file').write_text('secret')- # Mock GIO opening and trashing in helper bin+ # Use a private default application for opening, and mock GIO trash.helpers = tmp / 'bin'helpers.mkdir()opened_marker = tmp / 'opened-file'trash_marker = tmp / 'trashed-files'+ opener = helpers / 'record-open'+ opener.write_text(f'#!/bin/sh\nprintf "%s" "$1" > "{opened_marker}"\n')+ opener.chmod(0o755)+ apps = tmp / 'data/applications'+ apps.mkdir(parents=True)+ (apps / 'rediwm-test-opener.desktop').write_text(+ '[Desktop Entry]\nType=Application\nName=Test Opener\n'+ f'Exec={opener} %f\nMimeType=text/plain;\n')+ config = tmp / 'config'+ config.mkdir()+ (config / 'mimeapps.list').write_text(+ '[Default Applications]\ntext/plain=rediwm-test-opener.desktop;\n')gio_helper = helpers / 'gio'gio_helper.write_text(f'''#!/bin/sh-if [ "$1" = "open" ]; then- printf "%s" "$2" > "{opened_marker}"-elif [ "$1" = "trash" ]; then+if [ "$1" = "trash" ]; thenshiftwhile [ "$1" != "" ]; doif [ "$1" != "--" ]; then@@ -56,6 +66,8 @@ fios.environ,XDG_RUNTIME_DIR=str(tmp),XDG_STATE_HOME=str(tmp / "state"),+ XDG_DATA_HOME=str(tmp / "data"),+ XDG_CONFIG_HOME=str(config),WLR_BACKENDS='headless', REDIWM_FILES_DEVICES='0',REDIWM_IPC_AUTOMATION='1',WLR_HEADLESS_OUTPUTS='1',@@ -164,7 +176,7 @@ fi# Back restores the subfolder selection; explicitly start at the first item.send_key(102)- # Navigate Right twice to reach sample.txt, then Enter to open with gio open+ # Navigate Right twice to reach sample.txt, then Enter to open it.for _ in range(2):for pressed in (True, False):action('key', {'keycode': 106, 'pressed': pressed})@@ -174,10 +186,10 @@ fiaction('key', {'keycode': 28, 'pressed': pressed})time.sleep(0.3)- wait_for(opened_marker.exists, 'File was not opened via gio open')+ wait_for(opened_marker.exists, 'File was not opened with its MIME default')opened_path = opened_marker.read_text().strip()assert opened_path == str(browse_dir / 'sample.txt'), f"Unexpected opened file: {opened_path}"- print(f"Verified opening file via gio open: '{opened_path}'")+ print(f"Verified opening file with its MIME default: '{opened_path}'")# Test inotify auto-refresh: create dynamic.txt in browse_dirdynamic_file = browse_dir / 'dynamic.txt'diff --git a/tests/files_controls.py b/tests/files_controls.pyindex 8c2c786..c6d7631 100644--- a/tests/files_controls.py+++ b/tests/files_controls.py@@ -5,6 +5,7 @@ import osfrom pathlib import Pathimport socketimport subprocess+import sysimport tempfileimport timeimport zipfile@@ -25,6 +26,33 @@ def run():(home / "alpha-file.txt").write_text("small")(home / "zeta-file.txt").write_text("large" * 100)(home / ".hidden-file").write_text("hidden")+ data = tmp / "data"+ data.mkdir()+ recent_file = data / "recently-used.xbel"+ recent_old = home / "Research" / "a older file.bin"+ recent_new = home / "Work" / "z résumé.bin"+ recent_old.write_text("older")+ recent_new.write_text("newer")++ def write_recent(newest=recent_new):+ entries = [(recent_old.as_uri(), "2026-01-01T00:00:00Z"),+ (recent_new.as_uri(), "2026-02-01T00:00:00Z"),+ ((home / "gone.bin").as_uri(), "2026-03-01T00:00:00Z"),+ ("file://remote-host/tmp/remote.bin", "2026-04-01T00:00:00Z")]+ body = "".join(+ '<bookmark href="' + uri + '" visited="' ++ ("2026-05-01T00:00:00Z" if uri == newest.as_uri() else date) ++ '" modified="' + date + '"><info><metadata owner="http://freedesktop.org">'+ '<mime:mime-type type="application/octet-stream"/>'+ '<bookmark:applications><bookmark:application name="Fixture" exec="gio open %u" '+ 'modified="' + date + '" count="1"/></bookmark:applications>'+ '</metadata></info></bookmark>' for uri, date in entries)+ replacement = recent_file.with_suffix(".tmp")+ replacement.write_text('<xbel version="1.0" xmlns:bookmark="http://www.freedesktop.org/standards/desktop-bookmarks" '+ 'xmlns:mime="http://www.freedesktop.org/standards/shared-mime-info">' + body + '</xbel>')+ replacement.replace(recent_file)++ write_recent()helpers = tmp / "bin"helpers.mkdir()marker = tmp / "opened"@@ -144,6 +172,42 @@ def run():click(70, 140)title("Home")+ # Recent below Trash uses shared history, newest opened first,+ # and opens real paths (including spaces and Unicode).+ click(70, 210)+ title("Recent")+ if "--places-only" in sys.argv and (preview := os.environ.get("REDIWM_FILES_PREVIEW")):+ time.sleep(.3)+ preview = Path(preview).resolve()+ preview.unlink(missing_ok=True)+ action('screenshot', {"path": str(preview)})+ key(102) # Home: first item+ key(28)+ wait_for(lambda: marker.exists() and marker.read_text() == str(recent_new),+ "Recent did not open the newest local file")+ marker.unlink()+ wait_for(lambda: "RediWM Files" in recent_file.read_text(),+ "Files did not record the open in shared history")+ key(106, alt=True) # Recent has no parent directory.+ title("Recent")+ key(38, ctrl=True) # Ctrl+L, Enter keeps the virtual location.+ key(28)+ title("Recent")+ key(49, ctrl=True) # Ctrl+N cannot create inside a virtual location.+ title("Recent")+ click(70, 210, 273)+ key(28) # The Recent menu offers Open only.+ title("Recent")+ write_recent(recent_old)+ time.sleep(.3)+ key(102)+ key(28)+ wait_for(lambda: marker.exists() and marker.read_text() == str(recent_old),+ "Recent did not refresh after an external history replacement")+ marker.unlink()+ click(70, 140)+ title("Home")+# Toolbar New popup is actionable with the keyboard.click(50, 80)key(28)@@ -226,18 +290,18 @@ def run():key(102)time.sleep(.2)# Sidebar context menus target the clicked place without navigating first.- click(70, 270, 273) # Documents+ click(70, 305, 273) # Documentstitle("Home")key(28) # Opentitle("Documents")- click(70, 270, 273)+ click(70, 305, 273)key(108)key(28) # Unpintitle("Documents") # Unpin does not navigate or delete the folder.assert (home / "Documents").is_dir()saved = (tmp / "state/rediwm/files-view").read_bytes()assert saved[0] == ord("3") and saved[3] & 2 and saved[4] == 1, saved- click(70, 270) # Downloads now occupies Documents' old row.+ click(70, 305) # Downloads now occupies Documents' old row.title("Downloads")click(70, 140, 273) # Home has Open and Properties, without Unpin.key(108)@@ -248,6 +312,10 @@ def run():key(28)title("Home")+ print("PASS: Files navigation, Recent, toolbar and Places controls", flush=True)+ if "--places-only" in sys.argv:+ return+# Repository discovery switches a grid preference to Name/Git.# Changes remain live across index updates and branch switches.repo = home / "git-project"diff --git a/tests/files_drag.py b/tests/files_drag.pyindex b7664b5..45d2545 100644--- a/tests/files_drag.py+++ b/tests/files_drag.py@@ -32,7 +32,7 @@ def run(browser=False, select=False, list_view=False):with IPCClient(tmp).connect() as ipc:display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),- XDG_STATE_HOME=str(tmp / "state"), XDG_CONFIG_HOME=str(tmp / "config"),+ XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,GDK_BACKEND="wayland", DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent",REDIWM_FILES_DEVICES="0")@@ -184,7 +184,7 @@ def run_pin():with IPCClient(tmp).connect() as ipc:display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),- XDG_STATE_HOME=str(tmp / "state"), XDG_CONFIG_HOME=str(tmp / "config"),+ XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0")for key in ("DISPLAY", "REDIWM_SOCKET", "WAYLAND_DEBUG"):@@ -192,7 +192,7 @@ def run_pin():with (tmp / "files.log").open("w") as out:files = subprocess.Popen([str(ROOT / "zig-out/bin/rediwm-files"), str(home)], env=env, stdout=out, stderr=out)win = wait_for(lambda: next((w for w in ipc.get_windows() if w["app_id"] == "rediwm-files"), None), "Files did not map")- ipc.action('set_window_size', {"id": win["id"], "width": 1000, "height": 560})+ ipc.action('set_window_size', {"id": win["id"], "width": 1000, "height": 588})ipc.action('move_window_to', {"id": win["id"], "x": 10, "y": 30})ipc.action('focus_window', {"id": win["id"]})time.sleep(.6)@@ -200,7 +200,7 @@ def run_pin():# Window coordinates: three grid cards 252 px apart, the sidebar 208 px# wide with rows 32 px apart. Row n of the pins is centred at- # 462 + 32n, and the gap above it is at 446 + 32n.+ # 494 + 32n, and the gap above it is at 478 + 32n.def move(x, y):ipc.action('move_cursor', {"x": round(box["x"] + x), "y": round(box["y"] + y)})def button(pressed, code=272):@@ -239,23 +239,23 @@ def run_pin():names = [home / "pinned folder", home / "second folder", home / "note.txt"]# A file onto the section pins it, even aimed far from the gap.- drag(2, 80, 240, line_at=446)+ drag(2, 80, 270, line_at=478)wait_for(lambda: pins() == [str(names[2])], "the dropped file was not pinned")# Above the first pin, then between the two.- drag(0, 80, 240, line_at=446)+ drag(0, 80, 270, line_at=478)wait_for(lambda: pins() == [str(names[0]), str(names[2])], "folder did not land above the first pin")- drag(1, 80, 480, line_at=478)+ drag(1, 80, 512, line_at=510)wait_for(lambda: pins() == [str(n) for n in names], "folder did not land between the pins")# Off PLACES nothing is accepted, and a listed folder is not added twice.drag(0, 600, 400)- drag(0, 80, 240)+ drag(0, 80, 270)time.sleep(.3)assert pins() == [str(n) for n in names], pins()# A click opens a folder pin.- click(80, 494)+ click(80, 526)wait_for(lambda: any(w["title"].startswith("second folder") for w in ipc.get_windows()), "pin did not open its folder")# Removing one keeps the others in order.- click(80, 526, 273)+ click(80, 558, 273)time.sleep(.2)for key in (108, 28):ipc.action('key', {"keycode": key, "pressed": True})@@ -300,7 +300,7 @@ def run_transfer(same_window=False, copy=False, list_view=False, folder=True):with IPCClient(tmp).connect() as ipc:display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))env = dict(os.environ, HOME=str(home), XDG_RUNTIME_DIR=str(tmp),- XDG_STATE_HOME=str(tmp / "state"), XDG_CONFIG_HOME=str(tmp / "config"),+ XDG_STATE_HOME=str(tmp / "state"), XDG_DATA_HOME=str(tmp / "data"), XDG_CONFIG_HOME=str(tmp / "config"),REDIWM_CONFIG=str(tmp / "rediwm-config.toml"), WAYLAND_DISPLAY=display,DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent", REDIWM_FILES_DEVICES="0")env.pop("DISPLAY", None)diff --git a/tests/files_fixes.py b/tests/files_fixes.pyindex 44b285a..9308f75 100644--- a/tests/files_fixes.py+++ b/tests/files_fixes.py@@ -36,7 +36,7 @@ def run(scale="1"):try:sock = wait_for(lambda: next(tmp.glob("rediwm-*.sock"), None), "IPC unavailable")display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))- env = dict(os.environ, **env_extra, XDG_RUNTIME_DIR=directory, WAYLAND_DISPLAY=display)+ env = dict(os.environ, **env_extra, XDG_RUNTIME_DIR=directory, XDG_DATA_HOME=str(tmp / "data"), WAYLAND_DISPLAY=display)with IPCClient(sock) as ipc:def key(code, ctrl=False, shift=False, alt=False):mods = ([29] if ctrl else []) + ([42] if shift else []) + ([56] if alt else [])diff --git a/tests/start_menu.py b/tests/start_menu.pyindex 718618c..9283dde 100644--- a/tests/start_menu.py+++ b/tests/start_menu.py@@ -69,6 +69,26 @@ def run():assert widget_tree.get("panel") == "start_menu", widget_treeassert len(widget_tree.get("widgets", [])) > 0, "no widgets in start_menu"+ def viewport():+ return next(w for w in client.get_widget_tree("start_menu")["widgets"] if w["role"] == "scroll_container")++ area = viewport()["global_box"]+ assert viewport()["content_size"] > area["height"]+ bar_x = area["x"] + area["width"] - 7+ bar_y = area["y"] + 8+ outside_x = area["x"] + area["width"] + 100+ client.move_cursor(bar_x, bar_y)+ client.pointer_button(272, True)+ client.move_cursor(outside_x, bar_y + 30)+ first_offset = viewport()["scroll_offset"]+ assert first_offset > 0, "scrollbar stopped outside the Start menu"+ client.move_cursor(outside_x, bar_y + 60)+ assert viewport()["scroll_offset"] > first_offset+ client.pointer_button(272, False)+ released_offset = viewport()["scroll_offset"]+ client.move_cursor(bar_x, bar_y + 90)+ assert viewport()["scroll_offset"] == released_offset, "scrollbar kept dragging after release"+# Timer repeats must retain the original keyboard text after# the key event's temporary UTF-8 buffer has been reused.client.key(33, True) # Hold 'f' across several repeat ticks.diff --git a/tests/window_tabs.py b/tests/window_tabs.pyindex 8b69454..97699ea 100644--- a/tests/window_tabs.py+++ b/tests/window_tabs.py@@ -11,6 +11,8 @@ import subprocessimport tempfileimport tomllib+from PIL import Image+from desktop_zoom import build_client, wait_forfrom ipc_client import IPCClient, spawn_compositor, stop_processfrom ui_driver import UIDriver@@ -33,11 +35,14 @@ def run():"rediwm-files", "rediwm-editor",]))config = ('[compositor]\nxwayland = false\nfocus_zoom = "keep"\n'- '[desktop]\nenabled = false\n[animations]\nenabled = false\n')+ '[desktop]\nenabled = false\n[animations]\nenabled = false\n'+ '[theme]\nchrome_round_buttons = false\n'+ 'window_bg = "#101215"\nshadow = "#00000000"\n')process, log = spawn_compositor(tmp, config_content=config,scale=os.environ.get("REDIWM_TEST_SCALE", "1"),renderer=os.environ.get("REDIWM_TEST_RENDERER", "pixman"),- env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_DATA_HOME": str(tmp / "data")})+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_DATA_HOME": str(tmp / "data"),+ "REDIWM_NO_GLASS": "1"})clients = []try:with IPCClient(tmp, timeout=15) as ipc:@@ -112,6 +117,46 @@ def run():assert not widgets(first)[0]["visible"]assert window(first)["is_minimized"] is Falseassert (window(second)["x"], window(second)["y"]) == (60, 60)+ # Tabs, their close buttons and + reload to the same round+ # style while preserving geometry, then restore the old pixels.+ scale = float(os.environ.get("REDIWM_TEST_SCALE", "1"))+ ipc.focus_window(second)++ def shape_pixels(name):+ widget = next(w for w in widgets(second) if w["name"] == name)+ box = widget["global_box"]+ dx = min(30, box["width"] / 2) if name == f"tab/{second}" else box["width"] / 2+ ipc.move_cursor(round(box["x"] + dx), round(box["y"] + box["height"] / 2))+ ipc.wait_for_frame()+ path = tmp / "tab-shape.png"+ path.unlink(missing_ok=True)+ ipc.screenshot(str(path))+ with Image.open(path) as image:+ image = image.convert("RGB")+ corner = image.getpixel((round((box["x"] + 2) * scale), round((box["y"] + 2) * scale)))+ edge = image.getpixel((round((box["x"] + box["width"] / 2) * scale), round((box["y"] + 2) * scale)))+ return widget["box"], corner, edge++ names = (f"tab/{second}", f"tab/{second}/close", "tab_new")+ square = {name: shape_pixels(name) for name in names}+ path = tmp / "rediwm-config.toml"+ path.write_text(path.read_text().replace("chrome_round_buttons = false", "chrome_round_buttons = true"))+ ipc.reload_config()+ assert ipc.action("get_theme")["tokens"]["chrome_round_buttons"] is True+ for name in names:+ box, corner, edge = shape_pixels(name)+ assert box == square[name][0], (name, box, square[name])+ assert sum(abs(a - b) for a, b in zip(corner, square[name][1])) > 6, (name, corner, square[name])+ assert max(abs(a - b) for a, b in zip(edge, square[name][2])) <= 2, (name, edge, square[name])+ path.write_text(path.read_text().replace("chrome_round_buttons = true", "chrome_round_buttons = false"))+ ipc.reload_config()+ for name in names:+ box, corner, edge = shape_pixels(name)+ assert box == square[name][0], (name, box, square[name][0])+ for actual, expected in ((corner, square[name][1]), (edge, square[name][2])):+ assert max(abs(a - b) for a, b in zip(actual, expected)) <= 1, (name, actual, expected)+ path.write_text(path.read_text().replace("chrome_round_buttons = false", "chrome_round_buttons = true"))+ ipc.reload_config()# A close request to an inactive tab must reveal its native# confirmation dialog, and refusing close keeps the tab alive.ipc.action('close_window', {"id": first})