Skip to content

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

taskbar updates

oxydizerdeb3bc686fd6
diff --git a/TESTING.md b/TESTING.md
index b4d15cc..456c744 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -13,10 +13,10 @@ debugging on the host, see AGENTS.md, "Rendering".
| Command | What it checks |
| --- | --- |
-| `zig build test` | In-process unit tests: rasterizers vs. full rasters, UI, config, IPC parser/serializer fixtures, glass damage, projection damage, restack and visibility cuts, hit tests and surface feedback from its typed graph (paint order, unrounded edges, list lifetime), lifecycle/allocation failures, Files/desktop logic. No compositor or bus. |
+| `zig build test` | In-process unit tests: rasterizers vs. full rasters, UI, config, IPC parser/serializer fixtures, glass damage, projection damage, restack and visibility cuts, hit tests and surface feedback from its typed graph (paint order, unrounded edges, list lifetime), a tree's dim (inheritance, the popup barrier, damage), lifecycle/allocation failures, Files/desktop logic. No compositor or bus. |
| `zig build test-glass` | The glass registry and an effect's geometry in the graph at every zoom (no GPU). Glass pixels are gated in `test-scene-pass` (stage 5b) and by `tests/glass_reblur.py`. |
| `zig build test-pass-spike` | The owned-pass spike of `docs/plans/scene-graph-stage1.md`: rounded clip, border, shadow, external-OES texture, backdrop blur, buffer-age damage and cost on headless GLES2 (needs a render node; `-Doptimize=ReleaseSafe` for cost). |
-| `zig build test-scene-pass` | Stage 3's owned GLES2 drawing backend against wlroots: transforms, crops, filters, premultiplied alpha, damage, external-OES (an RGB EGLImage and a linear NV12 dmabuf; needs gbm), GL/EGL state and acquire/release timelines. Needs a compatible render node (`WLR_RENDER_DRM_DEVICE` on multi-GPU machines); also run with `-Doptimize=ReleaseSafe`. The unavailable-acquire test intentionally logs `drmSyncobjTransfer failed`. Stage 4b's rounded-shape gates are in the same fixture: clip against a supersampled reference, piece joins, border/body, premultiplied edges, the opaque cover, shadow, and partial repaint across a clip edge; the 128 parity cases also run through the shaped programs. Stage 4d's shadow gate compares every pixel with the CPU chrome's shadow formula. |
+| `zig build test-scene-pass` | Stage 3's owned GLES2 drawing backend against wlroots: transforms, crops, filters, premultiplied alpha, damage, external-OES (an RGB EGLImage and a linear NV12 dmabuf; needs gbm), GL/EGL state and acquire/release timelines. Needs a compatible render node (`WLR_RENDER_DRM_DEVICE` on multi-GPU machines); also run with `-Doptimize=ReleaseSafe`. The unavailable-acquire test intentionally logs `drmSyncobjTransfer failed`. Stage 4b's rounded-shape gates are in the same fixture: clip against a supersampled reference, piece joins, border/body, premultiplied edges, the opaque cover, shadow, and partial repaint across a clip edge; the 128 parity cases also run through the shaped programs. Stage 4d's shadow gate compares every pixel with the CPU chrome's shadow formula. The dim gates (`rediwm_scene_pass_set_dim`, inactive window dimming) compare a dimmed pass's rects, shapes, rings, translucent texels and glass composite with a C reference of the grade, and check that shadows are not graded, that a pass starts undimmed and that a bad fraction fails the pass. |
| `zig build test-lock` | Lock/greeter painter, password editing, PAM transitions (PAM is replaced at link time in test binaries only), greeter↔rediwm-dm conversation. |
| `zig build test-dm` | rediwm-dm relay state machine and framing. |
| `zig build test-dbus`, `test-polkit`, `test-polkit-ui`, `test-notifications`, `test-settings-portal`, `test-power`, `test-power-profiles`, `test-tray`, `test-app-activation`, `test-rediwm-session`, `test-layout-autosave`, `test-files`, `test-images` | Subsystem suites; the D-Bus ones re-exec under `dbus-run-session`. |
@@ -134,7 +134,7 @@ Network settings, password/hidden forms, saved and open joins, radio, wired
details, connect/disconnect and permission errors, service restart and scrolling;
`--settings-only` runs just the settings checks), `battery_popup.py` (fake sysfs and private power-profile
service; charge states, missing details, selection and dismissal),
-`keyboard_shortcuts.py`, `dock.py` (opt-in Appearance toggle, bounded height slider, live resizing and size persistence, launcher/input, shared shortcut icons and running pills, smooth pill animation/reversals and idle scheduling, preferred apps and terminal fallback, running windows, fullscreen, scale, live radius, context menu and remembered removal),
+`keyboard_shortcuts.py`, `dock.py` (opt-in Appearance toggle, four-edge position selector, bounded size and hover-zoom sliders, live placement/resizing and persistence, vertical icon/indicator layout, inward tooltips and menus, launcher/input, shared shortcut icons and running pills, hover zoom and pill animation/reversals, reduced motion and idle scheduling, preferred apps and terminal fallback, running windows, fullscreen, scale, live radius, context menu and remembered removal; `--positions-only` isolates placement),
`panel_damage.py`, `glass_hold.py` (holds and
mixed-scale idle), `glass_reblur.py` (glass re-blurs for changes below it,
never for its own client), `animations.py`, `hotspots.py`, `launch_feedback.py`,
@@ -145,6 +145,17 @@ never for its own client), `animations.py`, `hotspots.py`, `launch_feedback.py`,
`mini_map_canvas.py` (live canvas growth/shrink with open windows, minimap fit
and off-canvas reachability).
+`taskbar_sections.py` checks left/center/right defaults, live section controls,
+ordering and visibility, centered window groups, nonoverlapping input bounds,
+the moved Start menu, legacy item lists and restart persistence. It supports
+`REDIWM_TEST_SCALE=1.5` and `REDIWM_TEST_OUTPUTS=2`.
+
+`wifi_popup.py --popup-only --gold --top 1.5` and
+`battery_popup.py --gold --top --scale 1.5` also check Gold's cream cards,
+control contrast and popup interactions with a top taskbar at fractional scale.
+Omit `--top` to exercise bottom placement, or `--gold` for the default palette.
+`--popup-only` skips the separate tray-blink and Settings-page checks.
+
`window_tabs.py` covers the Appearance checkbox list, opt-in persistence, explicit
+ launches, independent groups, tab focus, shared geometry, overflow, closing and
disabling without closing clients, close-confirmation dialogs, fullscreen and
diff --git a/assets/themes/gold.toml b/assets/themes/gold.toml
index 5c162cb..c118a10 100644
--- a/assets/themes/gold.toml
+++ b/assets/themes/gold.toml
@@ -42,14 +42,17 @@ window_close_hover = "#AD5A4A"
text_secondary = "#6D6257"
app_bg = "#EEE6DB"
app_toolbar = "#E8DFD2"
-app_sidebar = "#443D3A"
+app_sidebar = "rgba(68,61,58,1.0)"
app_bar = "#E8DED1"
app_item = "#F3ECE2"
-app_item_hover = "#E5D6C3"
+app_item_hover = "rgba(229,214,195,0.96)"
app_item_border = "#CBBDA9"
app_item_selected = "#E6C7A8"
app_nav_selected = "#E6C7A8"
app_sidebar_selected = "#745C48"
+app_sidebar_hover = "rgba(116,92,72,0.96)"
+app_sidebar_hover_marker = "#FFF1D5"
+app_surface_hover = "rgba(229,214,195,0.96)"
app_divider = "#CFC2B2"
app_icon = "#E4D8C8"
scrollbar_thumb = "#AC9377"
@@ -66,7 +69,7 @@ on_accent = "#30251C"
shell_accent = "#D5A16A"
shell_on_accent = "#30251C"
surface = "rgba(239,218,190,0.08)"
-surface_hover = "rgba(239,218,190,0.14)"
+surface_hover = "rgba(116,92,72,0.96)"
border = "rgba(231,202,166,0.32)"
border_soft = "rgba(231,202,166,0.16)"
border_hover = "rgba(246,213,171,0.56)"
@@ -74,7 +77,7 @@ border_focus = "rgba(224,181,131,0.70)"
glass = "rgba(58,49,43,0.68)"
glass_strong = "rgba(58,49,43,0.85)"
shadow = "rgba(12,8,7,0.38)"
-border_glow = "rgba(255,204,141,0.68)"
+border_glow = "rgba(255,204,141,1.0)"
taskbar_bg = "rgba(43,39,39,0.93)"
taskbar_surface = "rgba(247,229,204,0.035)"
taskbar_hover = "rgba(247,229,204,0.09)"
@@ -82,16 +85,32 @@ taskbar_border = "rgba(230,204,170,0.32)"
start_menu_bg = "rgba(48,42,38,0.94)"
start_menu_border = "rgba(237,207,165,0.46)"
start_menu_search_bg = "#39312B"
-start_menu_selected_bg = "rgba(219,170,113,0.16)"
+start_menu_selected_bg = "rgba(116,92,72,0.96)"
start_menu_selected_border = "rgba(237,197,146,0.44)"
start_menu_selected_marker = "#DFAC74"
field_bg = "#39312B"
field_border = "#74604D"
selection_alpha = 0.25
-toggle_track = "rgba(227,209,185,0.22)"
-slider_track = "rgba(0,0,0,0.32)"
+toggle_track = "#96908A"
+toggle_on = "#D9945C"
+toggle_thumb = "#FAF6F0"
+toggle_shaded = true
+slider_track = "#352F2B"
+slider_shaded = true
+slider_highlight = "#FFF3D7"
pill_bg = "rgba(234,207,174,0.08)"
settings_card_bg = "rgba(241,218,188,0.055)"
+# Taskbar panels: warm frosted glass and ivory inset cards.
+popup_bg = "rgba(80,70,63,0.40)"
+popup_border = "rgba(249,226,198,0.72)"
+popup_radius = 22
+popup_blur = true
+popup_card_bg = "rgba(239,230,216,0.94)"
+popup_card_fg = "#39332E"
+popup_card_dim = "#71665B"
+popup_card_border = "rgba(255,246,231,0.80)"
+popup_card_radius = 16
+popup_battery_ring = "#E8B47E"
calendar_border = "rgba(237,207,165,0.48)"
osd_border = "rgba(237,207,165,0.48)"
start_button_hover = "rgba(241,218,188,0.10)"
@@ -114,9 +133,9 @@ app_menu_bg = "#EEE6DB"
app_field_bg = "#E0D5C5"
app_field_border = "#C8B59F"
shell_border_focus = "#E0B583"
-border_glow_depth = 3
+border_glow_depth = 7
border_glow_length = 80
-border_glow_reach = 56
+border_glow_reach = 504
workspace_active_border = "#DDB282"
dock_bg = "rgba(56,49,46,0.80)"
dock_border = "rgba(237,210,176,0.58)"
@@ -130,7 +149,8 @@ notification_radius = 18
notification_blur = true
control_thumb = "#FFF0DA"
slider_thumb_radius = 10
-slider_thumb_size = 14
+slider_thumb_size = 20
+slider_settings_track_height = 5.5
toggle_radius = 12
toggle_thumb_radius = 10
settings_card_radius = 12
diff --git a/docs/plans/printers.md b/docs/plans/printers.md
new file mode 100644
index 0000000..3f8e692
--- /dev/null
+++ b/docs/plans/printers.md
@@ -0,0 +1,432 @@
+# Plan: Printers page in Settings (setup, status, and "why didn't it print")
+
+Status: draft, 2026-10-13. Nothing is built. Decisions D1–D6 are proposed,
+not taken. Phase 0 settles the facts marked **(verify)** before any UI work.
+
+Scope: a Printers page in Settings that lists printers and their jobs, adds
+and configures them, and, the part that justifies more than a simple list,
+tells the user *which layer* failed when a printer does not work. It talks to
+CUPS (the only print system on every distro we ship for). It is not tied to
+one distro and it ships no print driver.
+
+## Where this comes from
+
+A field report (`~/Documents/arch-xprinter-tspl-troubleshooting.md`, summarised
+here so the plan stands alone): a cheap USB 4×6 thermal label printer
+(Xprinter/Zijiang family, VID:PID `0416:5011`, advertised 300 dpi, speaks TSPL)
+took hours to get printing. Almost none of that time went to fixing; it went to
+finding out *where* the failure was. In the order it was met:
+
+| # | What went wrong | Layer |
+| - | --- | --- |
+| 1 | Printer appeared and vanished in `lsusb`; its USB string said "Virtual Com Port" although its interface class is 7 (Printer) | USB |
+| 2 | `usblp` node vanished, a `tee` then created a *regular file* at `/dev/usb/lp0` | device node |
+| 3 | Guessed Zebra ZPL / EPL; the self-test (hold FEED while powering on) said TSPL | printer language |
+| 4 | CUPS libusb backend: "USB transaction timeout during read", because the printer claims bidirectional USB and cannot do it | CUPS backend |
+| 5 | A raw TSPL write to the node printed; that one fact split hardware+USB from CUPS+filters | method |
+| 6 | Node name changed after a power cycle (fixed with a udev symlink) | device node |
+| 7 | Advertised 300 dpi; 203 dpi gave the right physical size | queue settings |
+| 8 | Queue deleted by accident, recreated by hand | queue |
+| 9 | Job "ran", label fed, blank. Log: media `4x5.Borderless` not 4×6, `cupsCompression=4294967295`, `rangecheck in .putdeviceprops`, `Sent 0 bytes`, "No pages were found." | filters / PPD |
+
+The report's last state is unresolved (item 9), and several changes were made
+at once (quirk, `usblp` blacklist, udev rule, driver, backend), so which of
+them mattered was never isolated. Phase 0 does that.
+
+What we take from it, and it holds for any printer, not only labels:
+
+1. Printing is a chain, and a good page shows the chain and marks the first
+ broken link (the "ladder").
+2. The most useful single test is *send a job that skips the filters*. If that
+ prints, the fault is in rendering or the driver, not USB or the printer.
+3. Most "it printed nothing" cases leave evidence the user cannot read (the
+ CUPS error log is root-only) but CUPS also reports it over IPP.
+4. Two settings are wrong far more often than anything else: paper size and
+ resolution. Show them next to the queue.
+5. A copy-able diagnostic report turns "it doesn't work" into something
+ fixable by someone else.
+
+## Goals and non-goals
+
+Goals
+
+* List printers (USB, network, shared) with state, reasons in words
+ ("Out of paper", "Cover open", "Toner low") and ink/toner levels where CUPS
+ has them.
+* Show and cancel jobs; resume a queue CUPS stopped after an error.
+* Add a printer without a terminal: detected USB devices, network printers
+ CUPS discovers, or a typed address. Pick a driver automatically when there is
+ a trustworthy match, otherwise say so plainly.
+* Per-printer settings the user can understand: paper size, resolution,
+ colour/mono, duplex, quality, and for label printers darkness/speed when the
+ driver exposes them. Set as the queue default.
+* The ladder, two test prints (through the driver, and skipping it), a ruler
+ test for resolution, and "Copy diagnostic report".
+* Works with no CUPS, a stopped CUPS, a socket-activated CUPS, and with no
+ privileges: what cannot be done says why and what to do.
+* Same behaviour on Arch, Debian/Ubuntu, Fedora and openSUSE (our release
+ families); nothing in the page assumes a package manager.
+
+Non-goals
+
+* No driver of our own (no PPD, no raster filter, no TSPL/ZPL generator);
+ see "Not in this plan".
+* No print dialog: applications print through the Print portal or GTK/Qt
+ dialogs and CUPS. This page configures what they see.
+* No print server features: sharing, CUPS web admin, policies, quotas,
+ authentication to remote servers, IPP Fax.
+* No scanner/MFP support (that is SANE; separate).
+* No Bluetooth pairing for printers (the Bluetooth page owns pairing; a paired
+ Bluetooth printer shows up only if CUPS lists it).
+* No guessing from the network: no port scanning. Discovery is what CUPS
+ already reports (DNS-SD/IPP).
+
+## Design
+
+### Talk to CUPS over IPP, unprivileged (D1)
+
+Read and the user-level actions go straight to cupsd over IPP on its unix
+socket (`/run/cups/cups.sock` by default; honour `CUPS_SERVER` and
+`~/.cups/client.conf` like every CUPS client, so tests and unusual setups need
+no hook). A small IPP client in Zig (`src/printing/ipp.zig`: encoder, bounded
+decoder, HTTP/1.1 over the socket), in the spirit of `src/dbus`: no new
+library, no libcups ABI to match across four distro families, and no
+glib. Operations needed: Get-Printers / Get-Printer-Attributes, Get-Jobs /
+Get-Job-Attributes, Cancel-Job, Cancel-Jobs (own jobs), Print-Job (tests),
+CUPS-Get-Devices, CUPS-Get-PPDs, Pause/Resume-Printer where allowed.
+
+Alternative (not chosen): link libcups. Smaller code, but a new link-time
+dependency in every release tarball and the build containers, for a protocol
+whose subset we need is under 1,000 lines.
+
+The decoder treats the response as untrusted (cupsd can be remote through
+`CUPS_SERVER`): bounded lengths and counts, no recursion beyond collections,
+text fields length-capped and stripped of control characters before they reach
+a widget.
+
+### Live only while visible, no polling
+
+Same rule as the Services page. The page is live while it is on screen
+(`show` from `printers.build`, `hide` from `selectPage`/`detachSettings`); dark
+means no subscription, no sockets, nothing held. While live:
+
+* **cupsd changes:** a CUPS event subscription if one can be had without
+ polling. cupsd can notify over D-Bus (`org.cups.cupsd.Notifier`) once a
+ subscription exists, and `Create-Printer-Subscription` with `dbus://` is the
+ standard route. **(verify)** that it is present and readable by an
+ unprivileged user on each family. Fallback, if not: reload on page
+ show, on the user's action, and when a job we started changes; never on a
+ timer.
+* **USB hotplug:** a kernel uevent listener (netlink `NETLINK_KOBJECT_UEVENT`,
+ subsystems `usb` and `usbmisc`) that triggers one sysfs rescan. The scan is
+ a pure function from a sysfs root to a list of printer-class devices
+ (class 7, VID:PID, manufacturer/product/serial strings, bound driver, the
+ matching `/dev/usb/lp*` node and its file type). Debounce: a plug event
+ arrives as a burst.
+* Work happens on a worker thread that signals an eventfd; nothing blocks the
+ compositor loop. The IPP client has deadlines, because a half-dead cupsd
+ must not hang the page.
+
+### The ladder
+
+For the selected printer, one row per layer. Each row is pass / fail / unknown
+(not applicable or cannot tell), with a one-line reason; the first failing row
+is expanded with its fix. Layers by connection kind:
+
+USB printer
+
+1. **Found on USB.** Interface class 7 from sysfs. Fail text names what was
+ seen ("a device 0416:5011 is attached but is not a printer class device").
+ Never read the product string as truth (finding 1 above).
+2. **Kernel device node.** For the matched device: `/dev/usb/lp*` exists and is
+ a character device, and the user/CUPS can reach it. Fail: node missing
+ (`usblp` not loaded or deliberately blocked), or *a regular file sits where
+ the node should be* (finding 2). The page never writes to a node itself; the
+ check is `stat`.
+3. **CUPS running.** IPP answers. If not, say whether the socket exists and
+ whether the unit is enabled; offer "Start CUPS" only through the same
+ privileged path as the rest (D3).
+4. **Queue exists and accepts jobs.** Exists, `printer-state`, `printer-is-
+ accepting-jobs`, stopped reasons (`printer-state-reasons`).
+5. **Backend reaches it.** The queue's device URI points at the device that
+ rung 1 found (a stale `usb://` serial or a vanished `file`/vendor URI is
+ the usual cause of "was working yesterday"); last job's backend message if
+ any.
+6. **Settings fit the media.** Queue default page size and resolution against
+ what the user says they load (asked once for label printers); mismatch is
+ the finding-7/9 case.
+7. **Last job printed something.** From the last job: state, sheets
+ completed, `job-state-reasons`, `job-printer-state-message`. A job
+ `completed` with 0 sheets and a message like "No pages were found." is
+ reported as *finished but printed nothing*, pointing at the filter stage
+ (item 9), not at USB.
+
+Network printer: reachable (IPP Get-Printer-Attributes on its URI, with a short
+deadline) replaces rungs 1–2; the rest apply. A printer reported by DNS-SD but
+not reachable says so (different subnet, VPN, firewall) without scanning.
+
+The ladder only *reports*. Each fix is an explicit button, and none runs
+unasked.
+
+### Two tests, and why there are two (D4)
+
+* **Test page through the driver:** CUPS's own test page, or a small PDF
+ sized to the queue's media with a border and a 1-inch square. Exercises
+ the whole chain.
+* **Test skipping the filters:** Print-Job with `document-format`
+ `application/vnd.cups-raw` (what `lp -o raw` does) carrying a tiny
+ command-language test chosen from the known-devices table or the printer's
+ `printer-device-id` (`CMD:` field: `TSPL`, `ZPL`, `EPL`, `CPCL`, `PCL`,
+ `POSTSCRIPT`, ...). It exercises backend, USB and the printer, and not
+ filters or PPD. **(verify)** that cupsd passes it through unchanged on a
+ queue that has a PPD on all four families.
+
+Read together: raw prints and filtered does not → filters/PPD/media; neither
+prints → backend/USB/printer/paper. This is finding 5 as a button pair.
+
+If the printer's language is unknown (no `CMD:` and no table hit), a
+**"Which language does it speak?"** step sends one probe label per language,
+one at a time, asking "did anything print?" after each. The page also says,
+in words, to hold FEED while powering on for the self-test sheet, since that
+page names the language and the real resolution.
+
+### Resolution and size: a ruler, not trust
+
+Product listings lie about dpi (finding 7). For queues the user marks as a
+label printer (or whose driver reports a label media class), "Check scale"
+prints a rectangle of known size (for example 2 × 3 in) and asks what was
+measured, in the user's unit. If it is off, the page suggests the supported
+resolution that corrects it and sets it as the queue default. The ratio is
+computed, not looked up. For other printers, margins and page size are shown
+and editable from the driver's options; no ruler.
+
+### Adding a printer (D2)
+
+Sources, in order shown:
+
+1. Printers CUPS already lists (`CUPS-Get-Devices`: USB, DNS-SD, socket).
+ Devices CUPS lists whose URI is already used by a queue are hidden.
+2. Detected USB printers that CUPS did not list (the ladder's rungs 1–2 data):
+ shown with *why* it is missing ("the kernel driver did not create a
+ device", "CUPS cannot open it") instead of silently absent.
+3. A typed address: `ipp://`, `ipps://`, `socket://`, `lpd://`, and hostnames
+ resolving to those. Allow-list of schemes. No `file:`, no `smb:` (the
+ latter carries credentials), no scripts or vendor backends the user types.
+
+Driver choice, no driver of ours:
+
+1. **Driverless first:** an IPP Everywhere / AirPrint printer, or a USB printer
+ exposed over IPP by `ipp-usb` when that is present, is added with the
+ `everywhere` model; no PPD. **(verify)** the model name per CUPS version.
+2. **Match by device ID:** `CUPS-Get-PPDs` with the device's IEEE 1284 ID;
+ take the best match CUPS ranks (`ppd-match`), show make/model and the
+ driver's package name so the user can see what they get.
+3. **No match:** say so. Offer a *raw queue* (jobs pass through untouched,
+ fine for applications that already emit the printer's language), and show
+ the known-devices note ("this model speaks TSPL; ordinary PDF printing needs
+ a third-party TSPL driver, not shipped in your distribution's repositories"),
+ with the project name and URL, not an install command we cannot vouch for.
+ We do not download or install third-party code.
+
+New queues are created enabled and accepting, named from the model with
+characters CUPS allows, and *never* silently replace an existing queue of the
+same name (finding 8: the report lost queues to accidents; deleting needs a
+confirmation that names the printer, and "Remove" is separate from "Disable").
+
+### Known devices: a small data table
+
+`src/printing/known_devices.zig` (or an embedded TOML like theme presets), keyed
+by `vid:pid` and optionally IEEE 1284 make/model:
+
+```
+0416:5011 command_set=TSPL resolution=203 media=4x6 bidirectional=false
+ note="Advertises 300 dpi; measured 203. USB class 7, product string 'POS Label Printer'."
+```
+
+Fields are facts about the *hardware*, never instructions we run. It feeds the
+language probe, the default resolution, the ladder's rung-6 hint, and the
+report. It starts with the one device we have tested and grows by pull request.
+An entry means "verified on that hardware, source in the commit message".
+
+### Privileged actions (D3)
+
+Creating, modifying and removing queues, and starting CUPS, need rights an
+unprivileged user and a compositor must not have. In order of preference:
+
+1. **`cups-pk-helper`** (`org.opensuse.CupsPkHelper.Mechanism` on the system
+ bus; it is what GNOME Settings and `system-config-printer` use). Polkit
+ handles the authorization and our polkit agent already shows the prompt. We
+ write no root code. Present on the families we ship for **(verify)** and
+ packaged as a recommended, not required, dependency.
+2. If it is absent: the page is read-only for those actions and says exactly
+ which package is missing, by name for the detected distro (`/etc/os-release`
+ `ID`/`ID_LIKE`), without running it.
+3. Only if Phase 0 shows something the user needs that neither covers (for
+ example a CUPS USB quirk, if it proves necessary and survives package
+ updates), a narrow `rediwm-printers-helper` under `pkexec`, built to the
+ rules in `src/accounts_helper/AGENTS.md`: argv arrays only, absolute paths,
+ every field validated, a polkit action in `data/`, kept out of greeter mode.
+ The root-code list in `AGENTS.md` must be amended in the same change.
+
+Writing a USB quirk is the one thing that needs a decision (D5): the quirk may
+be unnecessary (the working queue in the report used a backend that writes the
+node and so avoids libusb), and a file in `/usr/share/cups/usb/` is owned by
+the package. **(verify)** whether cupsd reads every file in that directory, so
+a separate drop-in would survive upgrades. If a quirk is needed we *tell the
+user*, with the exact line and where to put it; we do not edit package files.
+
+### Diagnostic report
+
+"Copy diagnostic report" puts plain text on the clipboard; it is never sent
+anywhere. Contents: distro and CUPS version, the ladder with reasons, the
+printer's VID:PID, interface class and node type, queue URI with credentials
+and hostnames of *other* machines masked, queue options, the last N jobs'
+state/sheets/reasons/messages, `printer-state-reasons`, and
+which tests were run with their outcome. No document names, no user names,
+no job content, no log lines we cannot read without root.
+
+### Page layout
+
+Left: printers (icon, name, state dot, "Default" tag). Right, for the selected
+printer, top to bottom:
+
+* header: name, model, status sentence, ink/toner bars if reported;
+* ladder (collapsed to one line when everything passes);
+* jobs: list with cancel; "Resume printer" when stopped;
+* settings: paper size, resolution, colour, duplex, quality, driver options
+ as the driver's own groups, "Set as default";
+* tools: Test page, Test without driver, Check scale, Copy report;
+* danger zone: Remove printer (confirmation naming it).
+
+Empty states: CUPS not installed (say what and how, by distro), CUPS stopped,
+no printers ("Add a printer" with detected USB first), printer unplugged
+(ladder shows rung 1 failing, settings dimmed).
+
+All controls come from `ui/widgets/` (no hand-drawn controls); text through the
+i18n mechanism; the ladder uses the existing shell icons plus text, never
+colour alone.
+
+## Decisions to take
+
+* **D1** hand-rolled IPP client vs libcups: proposed hand-rolled.
+* **D2** discovery: only what CUPS reports + USB sysfs + typed address:
+ proposed yes, no scanning.
+* **D3** privilege path: cups-pk-helper first, no helper of ours unless Phase 0
+ proves a need: proposed.
+* **D4** test pair (through driver / skipping filters) and the language
+ probe: proposed.
+* **D5** USB quirks: advise only, never edit package files: proposed.
+* **D6** per-user vs system default printer: per-user default lives in
+ `~/.cups/lpoptions` and is what applications' dialogs honour; the CUPS-wide
+ default needs rights. Proposed: set the per-user default, offer the
+ system default only if the privileged path is present.
+
+## Phases
+
+### Phase 0: facts, no UI (small)
+
+On the author's printer and on at least one printer that needs no special
+handling; record results in this plan.
+
+* Rebuild a throwaway queue from scratch for the label printer and find the
+ *minimal* set of changes (quirk vs `usblp` vs udev symlink vs backend choice)
+ and the cause of `cupsCompression=4294967295` (queue PPD vs the installed
+ Ghostscript/cups-filters). Decides whether a quirk note exists at all.
+* Verify every **(verify)** item above on Arch plus one of each other family in
+ the existing podman setup (never the live session; see the release notes).
+* Confirm what an unprivileged user can read over IPP (jobs of others, device
+ list, PPD list, subscriptions) on a default install.
+* Output: facts here, and fixtures for Phase 1 (recorded IPP exchanges).
+
+### Phase 1: read-only page (medium)
+
+`src/printing/{ipp,cups,usb_sysfs,ladder,known_devices}.zig`,
+`control_center/sections/printers.zig`.
+
+* Printer list, state in words, jobs, ink/toner.
+* The ladder, rungs 1–7, from IPP plus sysfs.
+* Cancel own jobs; resume a stopped queue where allowed.
+* Hotplug via uevents; CUPS events or action-driven reload.
+* Empty states; Copy diagnostic report.
+* Test page through the driver; raw test (Phase 1b if the passthrough check
+ needs work).
+* Gate: ladder verdicts match reality on the label printer for each induced
+ fault (unplugged, queue stopped, wrong URI, filter fail).
+
+### Phase 2: set up and configure (medium)
+
+* Add flow (sources, driverless/PPD match/raw), remove, rename, set default.
+* Driver options as groups from the PPD or IPP `-supported` attributes; media
+ and resolution in plain words.
+* Privileged actions through cups-pk-helper; absence handled.
+* Label printers: media class, "Check scale", language probe, known-devices
+ hints.
+* Gate: a printer is added, configured, test-printed and removed with no
+ terminal on Arch and one other family.
+
+### Phase 3: polish and distro coverage (small)
+
+* Per-distro guidance strings (missing package names), `os-release` aware.
+* Reload on cupsd restart, graceful loss of CUPS mid-use.
+* `AGENTS.md`, `TESTING.md`, release notes, Settings search keywords, i18n
+ extraction for the new strings.
+
+### Optional: our own helper (only if Phase 0 requires it)
+
+See D3 item 3. Not scheduled.
+
+## Tests
+
+* **Unit (Zig):** IPP encode/decode round-trips and hostile inputs (truncated,
+ oversized counts, nested collections, bad UTF-8); ladder verdicts as a pure
+ function of (sysfs snapshot, IPP snapshot); sysfs scan over fixture trees,
+ including the regular-file-at-the-node case and the `0416:5011` "Virtual Com
+ Port" string; URI allow-list; report masking.
+* **Integration (`tests/printers.py`):** a fake cupsd on a private unix socket,
+ selected through `CUPS_SERVER` (a real CUPS variable, so no test hook), speaking
+ the IPP subset above, with scripted failure modes: not running, stopped
+ queue, job completed with zero sheets and the "No pages were found." message,
+ slow server, garbage reply. The page is driven over IPC like the other
+ Settings pages; clicks use the settle/wait rules in `TESTING.md`.
+* **Never** the real cupsd or a real printer in a test: the author has a
+ working queue attached. Hardware checks (USB layer, real test prints) are
+ manual and written into the Phase 1/2 gate notes.
+* The sysfs layer cannot be faked end to end without a production hook, so it
+ is covered by the fixture-tree unit tests plus the manual hardware gate.
+* Cost gate: opening the page makes no wakeups while idle (per-thread context
+ switch count), and closing it releases the socket and the listener.
+
+## Risks and open questions
+
+* One physical test printer. The generic parts (ladder, test pair, media
+ check, report) are testable against a fake and any printer; the quirks and
+ device facts are only as good as the hardware we have. The known-devices
+ table says so in each entry.
+* CUPS behaviour differs between versions (2.3/2.4, cups-filters 1.x/2.x, the
+ new libcups3/`cups-browsed` split, `ipp-usb` presence). Phase 0 checks the
+ families we ship; anything newer is reported honestly as "unknown".
+* cups-pk-helper is not installed everywhere. If it is missing on a family,
+ D3 item 2 is the user experience there, and it should be acceptable, not an
+ error.
+* Remote cupsd (`CUPS_SERVER=host`): supported for reading; setup actions are
+ disabled with a reason. Encrypted/authenticated remote servers are out.
+* Sandboxed callers (`[[sandbox_allow]]`) and the security-context filter are
+ untouched; the page runs inside the compositor's own process, like the other
+ Settings pages.
+* The Print portal path (rediwm-pdf) is separate and unchanged. A queue this
+ page creates must be visible to it; check in Phase 2.
+* Hotplug without a udev library: kernel uevents are enough for "something
+ changed, rescan", but their format is a kernel ABI; keep the parser tiny and
+ tolerant.
+
+## Not in this plan
+
+* **A print driver of our own** (PPD generation, PDF→raster→TSPL/ZPL, a CUPS
+ filter or backend). Decided against: unsupported printers get a clear
+ explanation, a raw queue, and a pointer to the third-party driver, not a
+ driver from us.
+* Scanning, MFPs, SANE.
+* CUPS server administration, sharing, quotas, authenticated remote servers.
+* Print preview, a print dialog, a print-to-PDF queue.
+* Bluetooth printer pairing and Bluetooth backends.
+* Network scanning or probing of any kind.
diff --git a/docs/themes.md b/docs/themes.md
index 3f486b7..c471156 100644
--- a/docs/themes.md
+++ b/docs/themes.md
@@ -83,9 +83,20 @@ with mauve accents and the bundled `wallpaper-mocha.png` Auckland skyline.
Gold uses warm charcoal decorations, ivory app content, champagne accents,
the bundled gold wallpaper and colour icons. It puts the taskbar at the top
and enables the bottom dock. Notifications use tinted backdrop glass.
+Choosing Gold also applies its folder, Home and Trash artwork to the desktop,
+Files and its sidebar; no separate icon-theme selection is needed. Pack icons
+take priority, with the usual icons filling any gaps.
RediWM Dark, RediWM Light, Redi Blue and Redi-Mocha explicitly restore the
standard 44-pixel taskbar at the bottom with the dock disabled.
+Gold's switches use shaded amber/grey tracks and ivory knobs. Set
+`toggle_shaded = true` for that recessed treatment; `toggle_on` and
+`toggle_thumb` optionally override the usual `accent` and `control_thumb`,
+while `toggle_track` controls the off colour.
+Its sliders use `slider_shaded = true` for a recessed rail, luminous fill and
+round metallic thumb. `slider_highlight` sets the bright reflections over the
+accent colour; `slider_track` sets the unfilled rail.
+
## Layout defaults
Packs may include this optional section:
@@ -94,24 +105,33 @@ Packs may include this optional section:
[layout]
taskbar_position = "top" # top or bottom
dock_enabled = true
-dock_height = 76 # 48–96 logical pixels
+dock_position = "bottom" # top, bottom, left or right
+dock_height = 76 # thickness; 48–96 logical pixels
+dock_hover_zoom = 1.05 # 1.0–1.5; 1.0 disables hover enlargement
```
Only these appearance settings are accepted here. Resolution is compositor
defaults → pack layout → explicit `[compositor]` settings. Choosing a theme
-or **Reset to theme** clears these three personal overrides; a pack without
+or **Reset to theme** clears these personal overrides; a pack without
layout values returns to the ordinary bottom taskbar and disabled dock.
Hidden dock entries and application preferences are preserved. **Save look…**
includes the current layout.
## Separate surface palettes
-Optional `[theme]` colours `app_fg`, `app_sidebar_fg`, `app_sidebar_selected`, `app_menu_bg`,
+Optional `[theme]` colours `app_fg`, `app_sidebar_fg`, `app_sidebar_selected`,
+`app_sidebar_hover`, `app_surface_hover`, `app_menu_bg`,
`app_field_bg` and `app_field_border` let client content differ from window
decorations. The shared app loader resolves them for Files, Images, Editor
and PDF, including their controls. Unset values keep existing theme behaviour.
GTK colour export also uses the app and sidebar foregrounds.
+`app_sidebar_hover_marker` adds a bright leading bar and an accent-coloured
+glow to Files sidebar hovers. Gold enables it; unset leaves the plain fill.
+Gold uses 96% opaque hover fills and a fully opaque Files sidebar. Its sidebar
+and shell menu hovers stay brown so their ivory text remains readable; app
+content and toolbar hovers use champagne.
+
`dock_bg` and `dock_border` override the taskbar-derived dock colours;
`dock_radius` is in logical pixels (zero follows the window frame radius).
An explicit dock background uses its own alpha without the inherited dock's
@@ -120,6 +140,14 @@ An explicit dock background uses its own alpha without the inherited dock's
control notification cards. `notification_blur = true` enables the existing
backdrop renderer behind them. Defaults retain the previous appearance.
+Wi-Fi and battery popups accept `popup_bg`, `popup_border`, `popup_radius`
+and `popup_blur`. With blur enabled they use a rounded glass panel without a
+pointer. `popup_card_bg`, `popup_card_fg`, `popup_card_dim`,
+`popup_card_border` and `popup_card_radius` style the network rows and battery
+detail/profile cards. `popup_battery_ring` overrides the normal battery arc;
+critical charge still uses the danger colour. Gold uses 40%-opaque warm glass, ivory
+cards and an amber arc. Unset colours retain the stock appearance.
+
## Terminal palette
For Foot launched from RediWM's default-terminal action, dock, Start menu or
diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md
index 7f29626..448f60e 100644
--- a/docs/wiki/Configuration.md
+++ b/docs/wiki/Configuration.md
@@ -62,13 +62,35 @@ keep 12-hour time and Sunday first until changed.
## Handy `[compositor]` keys
+Settings → Appearance includes **Dock position**, **Dock size** and **Dock hover zoom**.
+Choose top, bottom, left or right; side docks stack upright icons vertically.
+`dock_position = "bottom"` is the default. `dock_height` controls thickness
+(height for top/bottom, width for left/right) from 48 to 96 logical pixels.
+`dock_hover_zoom = 1.05` is the default; choose 1.0 to disable enlargement,
+or up to 1.5. The setting applies immediately and follows the animation and
+reduced-motion preferences.
+
+The taskbar has **Left**, **Center**, and **Right** sections in Appearance.
+Start defaults to the left, the window list to the center, and application tray
+icons plus Battery, Network, Volume, and Clock to the right. Each item's section
+control moves it immediately; drag its handle (or use Up/Down while the handle
+is focused) to reorder it within that section. Visibility toggles keep its place.
+The center group stays centered on the display when it fits, and shifts or
+narrows the window list to avoid the side groups.
+
+For example, `taskbar_items = ["left:start", "center:windows", "right:tray",
+"right:battery", "right:network", "right:volume", "right:clock"]` is the default.
+Use `"-right:clock"` to hide the clock. Existing four-item status lists still
+load, preserving their order and visibility alongside Start and the window list.
+
| Key | Default | Notes |
| --- | --- | --- |
| `allow_tearing` | `false` | lets focused fullscreen clients request async presentation |
| `window_tab_apps` | `[]` | app IDs that get tabs |
| `default_file_manager`, `default_terminal` | `""` | desktop IDs, empty means Files / auto terminal |
| `taskbar_position` | `"bottom"` | `top` or `bottom` |
-| `taskbar_items` | battery, network, volume, clock | prefix a name with `-` to hide it |
+| `dock_position` | `"bottom"` | `top`, `bottom`, `left` or `right`; inside the usable area beside the taskbar |
+| `taskbar_items` | Start left, window list center, tray/status items right | ordered `section:item` entries; prefix with `-` to hide an item |
| `focus_follows_mouse` | `false` | |
| `canvas_columns`, `canvas_rows` | `3`, `3` | 1 to 10 |
| `mini_map_enabled` | `true` | |
@@ -82,8 +104,12 @@ keep 12-hour time and Sunday first until changed.
| `window_gap` | `0` | px between snapped windows |
| `snap_to_edges` | `true` | |
| `dodge_file_drags` | `true` | file manager slides aside while you drag a file out |
+| `drag_feedback` | `true` | softly lift a window during a move drag; suppressed by reduced motion |
+| `drag_scale` | `1.03` | drag lift multiplier, `1.00`–`1.10`; adjustable in Appearance |
| `files_single_click_open` | `true` | Files opens files and folders with one click on their icon in list or icons view |
| `switcher_opacity`, `inactive_opacity` | `1.0` | |
+| `inactive_dim` | `true` | windows that are not the focus lose a little brightness and colour; fullscreen windows never dim. Settings, Appearance has the switch |
+| `inactive_dim_amount` | `0.08` | 0.0 to 0.5, the fraction of brightness and of colour an unfocused window loses |
| `border_radius` | `10` | Legacy frame radius; `[theme].radius_lg` takes precedence. |
| `xwayland` | `true` | `false` means native only |
| `xwayland_native_scaling` | `false` | sharp X11 on fractional scales, restart needed |
@@ -95,6 +121,9 @@ keep 12-hour time and Sunday first until changed.
| `lock_on_suspend` | `true` | |
| `sound_theme`, `sound_enabled`, `sound_disabled_events` | `"freedesktop"`, `true`, `[]` | event sounds, used by `play_sound` |
+Drag lift uses a gentle spring around the grab point and returns smoothly on
+release. Its timing can be adjusted with `[animations.window_drag]`.
+
## Outputs
```toml
diff --git a/scripts/install-session-root.sh b/scripts/install-session-root.sh
index a03a3cb..5a9185a 100755
--- a/scripts/install-session-root.sh
+++ b/scripts/install-session-root.sh
@@ -58,6 +58,18 @@ cp -R "$release_dir/share/rediwm/wallpapers" /usr/local/share/rediwm/.wallpapers
chmod -R u=rwX,go=rX /usr/local/share/rediwm/.wallpapers-new
rm -rf /usr/local/share/rediwm/wallpapers
mv -T /usr/local/share/rediwm/.wallpapers-new /usr/local/share/rediwm/wallpapers
+# Packs carry artwork as well as the palettes embedded in the executables.
+# Replace bundled packs individually, preserving any other installed packs.
+for pack in "$release_dir"/share/rediwm/themes/*/; do
+ [ -d "$pack" ] || continue
+ name=$(basename "$pack")
+ install -d /usr/local/share/rediwm/themes
+ rm -rf "/usr/local/share/rediwm/themes/.$name-new"
+ cp -R "$pack" "/usr/local/share/rediwm/themes/.$name-new"
+ chmod -R u=rwX,go=rX "/usr/local/share/rediwm/themes/.$name-new"
+ rm -rf "/usr/local/share/rediwm/themes/$name"
+ mv -T "/usr/local/share/rediwm/themes/.$name-new" "/usr/local/share/rediwm/themes/$name"
+done
for binary in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-editor rediwm-pdf rediwm-share-picker rediwm-session rediwm-dm rediwm-accounts-helper; do
mv -fT "$stage/$binary" "/usr/local/bin/$binary"
done
diff --git a/scripts/release-verify.sh b/scripts/release-verify.sh
index 6ae56fe..6f5afa7 100644
--- a/scripts/release-verify.sh
+++ b/scripts/release-verify.sh
@@ -58,6 +58,9 @@ for bin in rediwm rediwm-msg rediwm-theme rediwm-files rediwm-images rediwm-edit
done
[ -f /usr/share/wayland-sessions/rediwm-release-safe.desktop ] || die "the session entry is missing"
[ -d /usr/local/lib/rediwm ] || die "the bundled libraries are missing"
+for asset in theme.toml icons/folder.png icons/user-home.png icons/user-trash.png wallpapers/wallpaper-gold.png; do
+ runuser -u tester -- test -r "/usr/local/share/rediwm/themes/gold/$asset" || die "Gold theme asset is missing or unreadable: $asset"
+done
log "Starting the installed compositor headless"
xdg=$(mktemp -d)
diff --git a/src/Dock.zig b/src/Dock.zig
index 5693ff7..d8bae64 100644
--- a/src/Dock.zig
+++ b/src/Dock.zig
@@ -38,11 +38,12 @@ const Metrics = struct {
}
};
-const Pill = struct {
+const ItemAnimation = struct {
shortcut: ?Shortcut = null,
id: u64 = 0,
width: anim.Anim = .{},
opacity: anim.Anim = .{ .property = .opacity },
+ zoom: anim.Anim = .{ .from = 1, .to = 1 },
};
output: ?*Output = null,
@@ -52,6 +53,7 @@ tooltip: ?*wlr.SceneBuffer = null,
glass_effect: ?*glass.Effect = null,
data: SceneData = undefined,
box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = config.dock_height_default },
+position: @import("config").types.DockPosition = .bottom,
scale: f32 = 0,
dirty: bool = true,
visible: bool = false,
@@ -59,8 +61,8 @@ root: ui.layout.Widget = .{ .kind = .container },
buttons: [max_items]ui.layout.Widget = undefined,
ids: [max_items]u64 = @splat(0),
shortcuts: [max_items]?Shortcut = @splat(null),
-pills: [max_items]Pill = @splat(.{}),
-pills_animating: bool = false,
+animations: [max_items]ItemAnimation = @splat(.{}),
+animating: bool = false,
count: usize = 0,
offset: usize = 0,
windows: usize = 0,
@@ -113,8 +115,11 @@ pub fn tick(self: *Self, output: *Output, now_ms: i64) bool {
const usable = output.usableBox();
const m: Metrics = .{ .height = @intCast(server.config.compositor.dock_height) };
const shortcut_count = self.shortcutCount();
- const min_width = @max(260, @as(i32, @intCast(shortcut_count)) * m.itemStep() + m.padding() * 2 + 12);
- const visible = server.locker == null and usable.width >= min_width and usable.height >= @max(140, m.height + 72) and
+ const position = server.config.compositor.dock_position;
+ const available_length = if (position.vertical()) usable.height else usable.width;
+ const available_thickness = if (position.vertical()) usable.width else usable.height;
+ const min_length = @max(260, @as(i32, @intCast(shortcut_count)) * m.itemStep() + m.padding() * 2 + 12);
+ const visible = server.locker == null and available_length >= min_length and available_thickness >= @max(140, m.height + 72) and
!(if (focused) |top| top.fullscreen and top.currentOutput() == output else false);
self.tree.?.node.setEnabled(visible);
if (self.visible != visible) {
@@ -127,22 +132,24 @@ pub fn tick(self: *Self, output: *Output, now_ms: i64) bool {
return false;
}
if (self.scale != output.wlr_output.scale) self.dirty = true;
- if (self.box.height != m.height) self.dirty = true;
+ if (self.position != position or self.metrics().height != m.height) self.dirty = true;
// Output geometry can change without a window or theme notification.
- const capacity: usize = @intCast(@min(max_items - shortcut_count, @max(0, @divTrunc(usable.width - m.padding() * 2 - 16, m.itemStep()) - @as(i32, @intCast(shortcut_count)))));
+ const capacity: usize = @intCast(@min(max_items - shortcut_count, @max(0, @divTrunc(available_length - m.padding() * 2 - 16, m.itemStep()) - @as(i32, @intCast(shortcut_count)))));
const wanted = @min(capacity, self.windows) + shortcut_count;
- if (self.box.width != @as(i32, @intCast(wanted)) * m.itemStep() + m.padding() * 2) self.dirty = true;
+ if ((if (position.vertical()) self.box.height else self.box.width) != @as(i32, @intCast(wanted)) * m.itemStep() + m.padding() * 2) self.dirty = true;
const rebuilt = self.dirty;
if (rebuilt) self.rebuild(capacity, usable) catch return false;
self.tree.?.node.setEnabled(self.count > 0);
if (self.count == 0) {
- self.pills_animating = false;
+ self.animating = false;
return false;
}
- if (rebuilt or self.pills_animating) self.paint(now_ms) catch return false;
self.place(usable);
+ if (rebuilt or self.animating) {
+ self.paint(now_ms) catch return false;
+ } else self.paintTooltip() catch {};
self.tree.?.node.setPosition(self.box.x, self.box.y);
- return self.pills_animating;
+ return self.animating;
}
fn hidden(items: []const []const u8, name: []const u8) bool {
@@ -164,11 +171,23 @@ fn shortcutCount(self: *Self) usize {
fn place(self: *Self, usable: wlr.Box) void {
self.box.x = usable.x + @divTrunc(usable.width - self.box.width, 2);
- self.box.y = usable.y + usable.height - self.box.height - 10;
+ self.box.y = usable.y + @divTrunc(usable.height - self.box.height, 2);
+ switch (self.position) {
+ .top => self.box.y = usable.y + 10,
+ .bottom => self.box.y = usable.y + usable.height - self.box.height - 10,
+ .left => self.box.x = usable.x + 10,
+ .right => self.box.x = usable.x + usable.width - self.box.width - 10,
+ }
}
fn metrics(self: *const Self) Metrics {
- return .{ .height = self.box.height };
+ return .{ .height = if (self.position.vertical()) self.box.width else self.box.height };
+}
+
+/// Put the running indicator on the output-edge side of each upright icon.
+fn buttonCross(self: *const Self) i32 {
+ const m = self.metrics();
+ return if (self.position == .top or self.position == .left) m.height - m.length(8) - m.length(48) else m.length(8);
}
const AppMatch = struct {
@@ -212,7 +231,7 @@ fn shortcutApps(self: *Self, entries: []const apps.AppEntry, scratch: std.mem.Al
fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
const output = self.output.?;
- const previous_pills = self.pills;
+ const previous_animations = self.animations;
const previous_count = self.count;
const snapshot = output.server.start_menu_catalog.retainSnapshot();
defer snapshot.release();
@@ -249,9 +268,11 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
self.offset = @min(self.offset, self.windows -| capacity);
const window_count = @min(capacity, self.windows);
self.count = window_count + self.shortcutCount();
- self.box.height = @intCast(output.server.config.compositor.dock_height);
- const m = self.metrics();
- self.box.width = @as(i32, @intCast(self.count)) * m.itemStep() + m.padding() * 2;
+ self.position = output.server.config.compositor.dock_position;
+ const m: Metrics = .{ .height = @intCast(output.server.config.compositor.dock_height) };
+ const length = @as(i32, @intCast(self.count)) * m.itemStep() + m.padding() * 2;
+ self.box.width = if (self.position.vertical()) m.height else length;
+ self.box.height = if (self.position.vertical()) length else m.height;
self.scale = output.wlr_output.scale;
const hovered = self.dispatcher.hovered != null;
self.dispatcher.reset();
@@ -268,18 +289,19 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
index += 1;
}
if (self.shortcutShown(.settings)) self.setButton(index, .settings, if (targets[@intFromEnum(Shortcut.settings)]) |top| top.id else 0);
- for (self.pills[0..self.count], 0..) |*pill, i| {
+ for (self.animations[0..self.count], 0..) |*pill, i| {
const shortcut = self.shortcuts[i];
const id = self.ids[i];
pill.* = .{ .shortcut = shortcut, .id = id };
// Widget indexes move as windows open or items are removed. A
// shortcut keeps its animation when its representative window changes.
- for (previous_pills[0..previous_count]) |previous| {
+ for (previous_animations[0..previous_count]) |previous| {
if (previous.shortcut == shortcut and (shortcut != null or previous.id == id)) {
pill.* = previous;
break;
}
}
+ self.setButtonZoom(i, std.math.clamp(pill.zoom.value(anim.nowMs()), 1, output.server.config.compositor.dock_hover_zoom));
}
// The pointer rests on a replaced button: hover it before painting, so
// the rebuild paints once.
@@ -298,8 +320,8 @@ fn setButton(self: *Self, index: usize, shortcut: ?Shortcut, id: u64) void {
self.buttons[index] = .{
.name = if (shortcut) |s| @tagName(s) else std.fmt.allocPrint(self.arena.allocator(), "window_{d}", .{id}) catch "window",
.kind = .{ .button = .{ .label = self.arena.allocator().dupe(u8, self.label(index)) catch "Application", .variant = .ghost, .owner = self, .id = index, .on_click = clicked } },
- .computed_x = @floatFromInt(@as(i32, @intCast(index)) * m.itemStep() + m.padding()),
- .computed_y = @floatFromInt(m.length(8)),
+ .computed_x = @floatFromInt(if (self.position.vertical()) self.buttonCross() else @as(i32, @intCast(index)) * m.itemStep() + m.padding()),
+ .computed_y = @floatFromInt(if (self.position.vertical()) @as(i32, @intCast(index)) * m.itemStep() + m.padding() else self.buttonCross()),
.computed_width = @floatFromInt(m.length(48)),
.computed_height = @floatFromInt(m.length(48)),
};
@@ -313,6 +335,19 @@ fn topAt(self: *Self, index: usize) ?*Toplevel {
return null;
}
+fn setButtonZoom(self: *Self, index: usize, zoom: f32) void {
+ const m = self.metrics();
+ const base: f32 = @floatFromInt(m.length(48));
+ const side = @max(base, @as(f32, @floatFromInt(m.length(36))) * zoom);
+ const button = &self.buttons[index];
+ const along = @as(f32, @floatFromInt(@as(i32, @intCast(index)) * m.itemStep() + m.padding())) + (base - side) / 2;
+ const cross = @as(f32, @floatFromInt(self.buttonCross())) + (base - side) / 2;
+ button.computed_x = if (self.position.vertical()) cross else along;
+ button.computed_y = if (self.position.vertical()) along else cross;
+ button.computed_width = side;
+ button.computed_height = side;
+}
+
fn label(self: *Self, index: usize) []const u8 {
if (self.shortcuts[index]) |shortcut| return switch (shortcut) {
.applications => "Applications",
@@ -345,6 +380,7 @@ const Look = struct {
icon: ?IconEntry,
pill_width: f32,
pill_opacity: f32,
+ zoom: f32,
};
fn paint(self: *Self, now_ms: i64) !void {
@@ -355,9 +391,9 @@ fn paint(self: *Self, now_ms: i64) !void {
if (pal.dock_bg == null) bg[3] = @max(bg[3], 0.86);
const focused = @import("ipc/handlers.zig").findFocusedToplevel(output.server);
var looks: [max_items]Look = undefined;
- self.pills_animating = false;
+ self.animating = false;
var hasher = std.hash.Wyhash.init(0);
- hashValue(&hasher, .{ pal, bg, self.scale, self.box.width, self.box.height, self.count, self.offset, self.windows });
+ hashValue(&hasher, .{ pal, bg, self.scale, self.position, self.box.width, self.box.height, self.count, self.offset, self.windows });
for (self.buttons[0..self.count], looks[0..self.count], 0..) |button, *look, index| {
const top = self.topAt(index);
const icon_name = if (self.shortcuts[index]) |shortcut| switch (shortcut) {
@@ -366,24 +402,35 @@ fn paint(self: *Self, now_ms: i64) !void {
.terminal => "utilities-terminal",
.settings => "preferences-system",
} else if (top) |t| t.appId() else "";
- const lookup = output.server.iconLookup(icon_name, @import("geometry.zig").devicePixels(m.length(36), self.scale));
+ // Retain one raster at the configured maximum, not a new size each frame.
+ const hover_zoom = output.server.config.compositor.dock_hover_zoom;
+ const lookup = output.server.iconLookup(icon_name, @import("geometry.zig").devicePixels(@intFromFloat(@ceil(@as(f32, @floatFromInt(m.length(36))) * hover_zoom)), self.scale));
const active = top != null and top == focused;
const width: f32 = if (top == null) 0 else if (active) 22 else 10;
const opacity: f32 = if (top) |t| if (t.minimized) 0.4 else 1 else 0;
- const pill = &self.pills[index];
+ const pill = &self.animations[index];
+ const zoom: f32 = if (self.dispatcher.hovered == &self.buttons[index]) hover_zoom else 1;
+ if (hover_zoom == 1) {
+ pill.zoom.cancel(1);
+ } else if (pill.zoom.to != zoom) pill.zoom.retargetTo(now_ms, zoom, anim.curveFor(.taskbar_hover));
if (pill.width.to != width) pill.width.retargetTo(now_ms, width, anim.curveFor(.taskbar_hover));
if (pill.opacity.to != opacity) pill.opacity.retargetTo(now_ms, opacity, anim.curveFor(.taskbar_hover));
_ = pill.width.sampleChanged(now_ms, anim.rasterPixelQuantum(self.scale) / (4 * m.size(1)));
_ = pill.opacity.sampleChanged(now_ms, anim.rasterAlphaQuantum());
- self.pills_animating = self.pills_animating or !pill.width.settled(now_ms) or !pill.opacity.settled(now_ms);
+ _ = pill.zoom.sampleChanged(now_ms, anim.rasterPixelQuantum(self.scale) / (4 * m.size(36)));
+ self.animating = self.animating or !pill.width.settled(now_ms) or !pill.opacity.settled(now_ms) or !pill.zoom.settled(now_ms);
look.* = .{
.focused = active,
.icon = if (lookup == .ready) lookup.ready else null,
.pill_width = @max(0, pill.width.last_quantised),
.pill_opacity = std.math.clamp(pill.opacity.last_quantised, 0, 1),
+ .zoom = std.math.clamp(pill.zoom.last_quantised, 1, hover_zoom),
};
+ // Input covers the painted icon even at 1.5×. Keep centres fixed so
+ // moving between neighbours cannot make the row chase the pointer.
+ self.setButtonZoom(index, look.zoom);
const icon_id: ?u64 = if (look.icon) |icon| icon.id else null;
- hashValue(&hasher, .{ self.shortcuts[index], button.kind.button.state, look.focused, icon_id, look.pill_width, look.pill_opacity });
+ hashValue(&hasher, .{ self.shortcuts[index], button.kind.button.state, look.focused, icon_id, look.pill_width, look.pill_opacity, look.zoom });
}
const key = hasher.final();
if (key != self.drawn) try self.paintDock(pal, bg, looks[0..self.count]);
@@ -400,7 +447,7 @@ fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look)
var border = pal.accent;
border[3] = 0.55;
border = pal.dock_border orelse border;
- const radius = @min(if (pal.dock_radius > 0) pal.dock_radius else ui.window_chrome.frameRadius(), @as(f32, @floatFromInt(self.box.height)) / 2);
+ const radius = @min(if (pal.dock_radius > 0) pal.dock_radius else ui.window_chrome.frameRadius(), @as(f32, @floatFromInt(m.height)) / 2);
glass.Effect.configure(self.glass_effect, radius, 1);
r.fillRect(0, 0, @floatFromInt(self.box.width), @floatFromInt(self.box.height), .{ .color = bg, .radius = radius, .border_width = 1, .border_color = border });
for (self.buttons[0..self.count], looks, 0..) |button, look, index| {
@@ -409,10 +456,10 @@ fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look)
const cy = button.computed_y + button.computed_height / 2;
ui.widgets.button.paintBackground(&r, .{ .x = x, .y = button.computed_y, .w = button.computed_width, .h = button.computed_height }, .{ .variant = .ghost, .radius = m.size(12) }, .{ .pointer = button.kind.button.state, .selected = look.focused });
if (look.icon) |icon| {
- const size: f32 = @floatFromInt(m.length(36));
+ const size = @as(f32, @floatFromInt(m.length(36))) * look.zoom;
r.drawImageCover(cx - size / 2, cy - size / 2, size, size, 0, .{ .pixels = icon.pixels, .width = icon.size, .height = icon.size });
} else {
- const size: f32 = @floatFromInt(m.length(34));
+ const size = @as(f32, @floatFromInt(m.length(34))) * look.zoom;
r.drawIcon(cx - size / 2, cy - size / 2, size, size, .{ .id = if (self.shortcuts[index]) |shortcut| switch (shortcut) {
.applications => .grid,
.files => .folder,
@@ -425,14 +472,24 @@ fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look)
accent[3] *= look.pill_opacity;
const width = m.size(look.pill_width);
const thickness = @max(2, m.size(4));
- r.fillRect(cx - width / 2, @floatFromInt(m.length(58)), width, thickness, .{ .color = accent, .radius = @min(width, thickness) / 2 });
+ const cross: f32 = if (self.position == .top or self.position == .left) @as(f32, @floatFromInt(m.height - m.length(58))) - thickness else @floatFromInt(m.length(58));
+ if (self.position.vertical()) {
+ r.fillRect(cross, cy - width / 2, thickness, width, .{ .color = accent, .radius = @min(width, thickness) / 2 });
+ } else r.fillRect(cx - width / 2, cross, width, thickness, .{ .color = accent, .radius = @min(width, thickness) / 2 });
}
}
var divider = pal.window_fg;
divider[3] = 0.16;
- if (self.count > 1 and self.shortcuts[0] == .applications) r.fillRect(@floatFromInt(m.itemStep() + m.padding() - m.length(4)), m.size(18), 1, m.size(30), .{ .color = divider });
- if (self.offset > 0) r.drawIcon(1, m.size(28), m.size(10), m.size(12), .{ .id = .chevron_left, .color = pal.accent });
- if (self.offset + self.count - self.shortcutCount() < self.windows) r.drawIcon(@as(f32, @floatFromInt(self.box.width)) - m.size(11), m.size(28), m.size(10), m.size(12), .{ .id = .chevron_right, .color = pal.accent });
+ if (self.count > 1 and self.shortcuts[0] == .applications) {
+ const along: f32 = @floatFromInt(m.itemStep() + m.padding() - m.length(4));
+ if (self.position.vertical()) r.fillRect(m.size(18), along, m.size(30), 1, .{ .color = divider }) else r.fillRect(along, m.size(18), 1, m.size(30), .{ .color = divider });
+ }
+ if (self.offset > 0) {
+ if (self.position.vertical()) r.drawIcon(m.size(28), 1, m.size(12), m.size(10), .{ .id = .chevron_up, .color = pal.accent }) else r.drawIcon(1, m.size(28), m.size(10), m.size(12), .{ .id = .chevron_left, .color = pal.accent });
+ }
+ if (self.offset + self.count - self.shortcutCount() < self.windows) {
+ if (self.position.vertical()) r.drawIcon(m.size(28), @as(f32, @floatFromInt(self.box.height)) - m.size(11), m.size(12), m.size(10), .{ .id = .chevron_down, .color = pal.accent }) else r.drawIcon(@as(f32, @floatFromInt(self.box.width)) - m.size(11), m.size(28), m.size(10), m.size(12), .{ .id = .chevron_right, .color = pal.accent });
+ }
self.node.?.setBuffer(&image.base);
self.node.?.setDestSize(self.box.width, self.box.height);
}
@@ -450,16 +507,17 @@ fn paintTooltip(self: *Self) !void {
const pal = ui.theme.shellPalette();
const value = self.label(index);
var hasher = std.hash.Wyhash.init(0);
- hashValue(&hasher, .{ pal, self.scale, self.box.width, value });
+ const usable = self.output.?.usableBox();
+ hashValue(&hasher, .{ pal, self.scale, self.position, self.box.width, usable.width, value });
const key = hasher.final();
if (key == self.tip_drawn) {
// Same text: only the button under it may differ.
- const width = self.tooltip.?.dst_width;
- self.tooltip.?.node.setPosition(std.math.clamp(@as(i32, @intFromFloat(hovered.computed_x + hovered.computed_width / 2)) - @divTrunc(width, 2), 0, self.box.width - width), -38);
+ self.placeTooltip(hovered, self.tooltip.?.dst_width, usable);
self.tooltip.?.node.setEnabled(true);
return;
}
- const width: i32 = @intFromFloat(@min(@as(f32, @floatFromInt(self.box.width)), @max(80, (ui.text.measureWidthF(value, .manrope, pal.font_size, 1) catch 100) + 24)));
+ const max_width = if (self.position.vertical()) usable.width - self.box.width - 18 else self.box.width;
+ const width: i32 = @intFromFloat(@min(@as(f32, @floatFromInt(max_width)), @max(80, (ui.text.measureWidthF(value, .manrope, pal.font_size, 1) catch 100) + 24)));
const image = try PanelBuffer.create(width, 30, self.scale);
defer image.base.drop();
var r = ui.paint.Renderer.init(image.pixels, image.width, image.height, self.scale);
@@ -470,11 +528,25 @@ fn paintTooltip(self: *Self) !void {
r.drawText(10, 0, @floatFromInt(width - 20), 30, .{ .content = value, .font_size = pal.font_size, .color = pal.window_fg });
self.tooltip.?.setBuffer(&image.base);
self.tooltip.?.setDestSize(width, 30);
- self.tooltip.?.node.setPosition(std.math.clamp(@as(i32, @intFromFloat(hovered.computed_x + hovered.computed_width / 2)) - @divTrunc(width, 2), 0, self.box.width - width), -38);
+ self.placeTooltip(hovered, width, usable);
self.tooltip.?.node.setEnabled(true);
self.tip_drawn = key;
}
+fn placeTooltip(self: *Self, hovered: *ui.layout.Widget, width: i32, usable: wlr.Box) void {
+ var x = self.box.x + @as(i32, @intFromFloat(hovered.computed_x + hovered.computed_width / 2)) - @divTrunc(width, 2);
+ var y = self.box.y + @as(i32, @intFromFloat(hovered.computed_y + hovered.computed_height / 2)) - 15;
+ switch (self.position) {
+ .top => y = self.box.y + self.box.height + 8,
+ .bottom => y = self.box.y - 38,
+ .left => x = self.box.x + self.box.width + 8,
+ .right => x = self.box.x - width - 8,
+ }
+ x = std.math.clamp(x, usable.x, @max(usable.x, usable.x + usable.width - width));
+ y = std.math.clamp(y, usable.y, @max(usable.y, usable.y + usable.height - 30));
+ self.tooltip.?.node.setPosition(x - self.box.x, y - self.box.y);
+}
+
pub fn motion(self: *Self, x: f64, y: f64) void {
const old = self.dispatcher.hovered;
self.dispatcher.pointerMotion(&self.root, @floatCast(x), @floatCast(y));
@@ -509,7 +581,7 @@ pub fn contextMenu(self: *Self, x: f64, y: f64, screen_x: i32) bool {
const shortcut = self.shortcuts[index];
if (target == null and shortcut == null) return false;
const input = &self.output.?.server.input;
- input.window_menu.openDock(self, target, shortcut, screen_x);
+ input.window_menu.openDock(self, target, shortcut, screen_x, self.box.y + @as(i32, @intFromFloat(y)));
return input.window_menu.node != null;
}
@@ -560,20 +632,22 @@ pub fn scroll(self: *Self, delta: f64) void {
}
pub fn captureAnimations(self: *Self, allocator: std.mem.Allocator, list: *std.ArrayList(anim.LiveCapture), now_ms: i64) !void {
- for (self.pills[0..self.count]) |*pill| {
+ for (self.animations[0..self.count]) |*pill| {
try anim.captureIfLive(allocator, list, &pill.width, .taskbar_hover, now_ms);
try anim.captureIfLive(allocator, list, &pill.opacity, .taskbar_hover, now_ms);
+ try anim.captureIfLive(allocator, list, &pill.zoom, .taskbar_hover, now_ms);
}
}
pub fn appendAnimations(self: *const Self, allocator: std.mem.Allocator, list: *std.ArrayList(@import("ipc/protocol.zig").AnimationData), now_ms: i64) !void {
const output = self.output orelse return;
const inspector = @import("ipc/animations.zig");
- for (self.pills[0..self.count], self.buttons[0..self.count]) |pill, button| {
+ for (self.animations[0..self.count], self.buttons[0..self.count]) |pill, button| {
const prefix = try std.fmt.allocPrint(allocator, "dock.{s}.{s}", .{ std.mem.span(output.wlr_output.name), button.name orelse "item" });
defer allocator.free(prefix);
try inspector.appendLive(allocator, list, try std.fmt.allocPrint(allocator, "{s}.pill_width", .{prefix}), pill.width, now_ms);
try inspector.appendLive(allocator, list, try std.fmt.allocPrint(allocator, "{s}.pill_opacity", .{prefix}), pill.opacity, now_ms);
+ try inspector.appendLive(allocator, list, try std.fmt.allocPrint(allocator, "{s}.hover_zoom", .{prefix}), pill.zoom, now_ms);
}
}
diff --git a/src/Input.zig b/src/Input.zig
index 0a5f8a7..c1b97b5 100644
--- a/src/Input.zig
+++ b/src/Input.zig
@@ -661,7 +661,10 @@ pub fn startMove(input: *Input, toplevel: *Toplevel) void {
toplevel.finishZoomAnimation();
toplevel.finishMoveAnimation();
toplevel.finishSizeAnimation();
- if (@import("tiling_grab.zig").begin(input, toplevel, null, 0x110)) return;
+ if (@import("tiling_grab.zig").begin(input, toplevel, null, 0x110)) {
+ input.server.scheduleFrames();
+ return;
+ }
toplevel.pending_restore = null;
const snapped = toplevel.layout() != .floating and !toplevel.isFullscreen();
input.move_snap.preview.hide();
@@ -684,6 +687,7 @@ pub fn startMove(input: *Input, toplevel: *Toplevel) void {
input.setNamedCursor("grabbing");
input.grab_x = origin.x;
input.grab_y = origin.y;
+ input.server.scheduleFrames();
// Snapshot current geometry for undo. Press folding: if a focus change
// already fired on this press, begin() will inherit its focus id.
const geom = toplevel.clientGeometry();
@@ -1417,6 +1421,7 @@ pub fn warpCursor(input: *Input, x: f64, y: f64, time_msec: u32) void {
pub fn processCursorMotion(input: *Input, time_msec: u32) void {
if (input.server.locker != null or input.server.polkit_dialog != null or input.server.switcher.active()) return;
+ defer input.updateGrabBorderGlow();
input.positionDragIcon();
input.drag_dodge.motion();
if (input.server.screenshot_selector.output != null) {
@@ -2233,6 +2238,17 @@ fn updateBorderGlow(input: *Input, hit: scene_data.Hit) void {
};
if (clear) target = top;
}
+ input.setBorderGlowTarget(target);
+}
+
+/// A compositor grab owns the pointer even outside the window's current box.
+/// Refresh again when chrome applies a size: client replies can follow motion.
+pub fn updateGrabBorderGlow(input: *Input) void {
+ if (input.cursor_mode != .move and input.cursor_mode != .resize) return;
+ input.setBorderGlowTarget(input.grabbed_toplevel);
+}
+
+fn setBorderGlowTarget(input: *Input, target: ?*Toplevel) void {
if (input.glow_toplevel) |previous| {
if (previous != target) previous.setGlow(null);
}
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index d1824e7..b9c97ea 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -118,7 +118,7 @@ pub fn startButtonLeft() i32 {
pub fn startButtonBox(bar: *Taskbar) wlr.Box {
const size = buttonSize();
return .{
- .x = bar.box.x + startButtonLeft(),
+ .x = bar.box.x + bar.startX(),
.y = bar.box.y + @divTrunc(bar.box.height - size, 2),
.width = size,
.height = size,
@@ -167,6 +167,7 @@ battery_shimmer: battery_highlight.Highlight = .{},
node_data: scene_data.SceneData = undefined,
timer: *wl.EventSource,
box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = default_bar_height },
+item_layout: taskbar_items.Layout = .{},
dirty: bool = true,
paint_causes: u8 = 0,
background_dirty: bool = true,
@@ -749,24 +750,31 @@ fn clockColumnWidth(bar: *Taskbar) f32 {
}
fn rightLayout(bar: *Taskbar) taskbar_items.Layout {
- return taskbar_items.arrange(bar.server.config.compositor.taskbar_items, @floatFromInt(bar.box.width - edge_pad), .{ battery_width, @floatFromInt(trayHit()), @floatFromInt(trayHit()), bar.clockColumnWidth() }, bar.battery_state.percent != null, tray_gap, clock_gap);
+ return bar.item_layout;
+}
+
+fn startX(bar: *Taskbar) i32 {
+ return @intFromFloat(@round(bar.item_layout.x[@intFromEnum(taskbar_items.Item.start)] orelse @as(f32, @floatFromInt(startButtonLeft()))));
+}
+
+fn calculateLayout(bar: *Taskbar, window_count: usize) taskbar_items.Layout {
+ var items = bar.server.config.compositor.taskbar_items;
+ const tray_count = bar.appTrayCount();
+ const app_width: f32 = @floatFromInt(tray_count * @as(usize, @intCast(trayHit() + tray_gap)));
+ const capture_width: f32 = if (bar.capturing()) @floatFromInt(bar.captureWidth()) else 0;
+ // Screen sharing remains accessible even when application icons are hidden.
+ if (bar.capturing()) items.visible[@intFromEnum(taskbar_items.Item.tray)] = true;
+ const windows_width = if (window_count == 0) 0 else @as(f32, @floatFromInt(window_count)) * @max(@as(f32, @floatFromInt(chipSize())), ui_theme.global.chip_width) +
+ @as(f32, @floatFromInt(window_count - 1)) * @as(f32, @floatFromInt(chipGap()));
+ return taskbar_items.arrange(items, @floatFromInt(startButtonLeft()), @floatFromInt(bar.box.width - edge_pad), @as(f32, @floatFromInt(bar.box.width)) / 2, .{ if (bar.battery_state.percent != null) battery_width else 0, @floatFromInt(trayHit()), @floatFromInt(trayHit()), bar.clockColumnWidth(), @floatFromInt(buttonSize()), windows_width, app_width + capture_width }, tray_gap, clock_gap);
}
pub fn itemBox(bar: *Taskbar, item: taskbar_items.Item) ?wlr.Box {
const x = bar.rightLayout().x[@intFromEnum(item)] orelse return null;
- const width: i32 = switch (item) {
- .battery => battery_width,
- .clock => @intFromFloat(@ceil(bar.clockColumnWidth())),
- else => trayHit(),
- };
+ const width: i32 = @intFromFloat(@ceil(bar.item_layout.widths[@intFromEnum(item)]));
return .{ .x = bar.box.x + @as(i32, @intFromFloat(@round(x))), .y = bar.box.y, .width = width, .height = bar.box.height };
}
-fn chipsRightEdge(bar: *Taskbar) f32 {
- const left = bar.appTrayLeft();
- return left - @as(f32, @floatFromInt(chip_clock_gap));
-}
-
const battery_width = battery_badge.width;
fn batteryX(bar: *Taskbar) f32 {
@@ -802,7 +810,7 @@ fn captureLabelWidth(bar: *Taskbar) i32 {
}
fn captureX(bar: *Taskbar) f32 {
- return bar.rightLayout().left - @as(f32, @floatFromInt(tray_gap + bar.captureWidth()));
+ return bar.appTrayLeft() + @as(f32, @floatFromInt(bar.appTrayCount() * @as(usize, @intCast(trayHit() + tray_gap))));
}
pub fn captureIndicatorBox(bar: *Taskbar) ?wlr.Box {
@@ -820,11 +828,11 @@ fn sharedChipWidth(bar: *Taskbar, count: usize) f32 {
const min_w: f32 = @floatFromInt(chipSize());
const max_w = @max(min_w, ui_theme.global.chip_width);
if (count == 0) return max_w;
- const available = chipsRightEdge(bar) - @as(f32, @floatFromInt(firstChipX()));
+ const available = bar.item_layout.widths[@intFromEnum(taskbar_items.Item.windows)];
const extra_gaps: usize = if (count > 1) count - 1 else 0;
const gap_total = @as(f32, @floatFromInt(chipGap())) * @as(f32, @floatFromInt(extra_gaps));
const each = (available - gap_total) / @as(f32, @floatFromInt(count));
- return @max(min_w, @min(max_w, each));
+ return @max(1, @min(max_w, each));
}
fn refreshStartLogo(bar: *Taskbar) void {
@@ -876,14 +884,26 @@ fn reconcile(bar: *Taskbar, now_ms: i64) bool {
defer visible.deinit(gpa);
var it = bar.server.world.toplevels.iterator(.forward);
while (it.next()) |toplevel| {
- if (!@import("workspaces.zig").visible(toplevel) or (bar.server.world.workspaces.active and toplevel.currentOutput() != Output.fromWlr(bar.wlr_output)) or toplevel.tab_hidden or (toplevel.live_rules.skip_taskbar orelse false)) continue;
+ if (!bar.itemShown(.windows) or !@import("workspaces.zig").visible(toplevel) or (bar.server.world.workspaces.active and toplevel.currentOutput() != Output.fromWlr(bar.wlr_output)) or toplevel.tab_hidden or (toplevel.live_rules.skip_taskbar orelse false)) continue;
visible.append(gpa, toplevel) catch break;
}
std.mem.sort(*Toplevel, visible.items, {}, taskbarOrderLessThan);
+ const layout = bar.calculateLayout(visible.items.len);
+ if (!std.meta.eql(layout, bar.item_layout)) {
+ bar.item_layout = layout;
+ bar.start_dirty = true;
+ bar.clock_dirty = true;
+ bar.tray_dirty = .{ true, true };
+ bar.battery_dirty = true;
+ bar.capture_dirty = true;
+ bar.app_tray_generation = 0;
+ bar.markDirty(paint_start | paint_clock | paint_tray | paint_capture);
+ changed = true;
+ }
const chip_w = sharedChipWidth(bar, visible.items.len);
var next: std.ArrayList(ChipState) = .empty;
- var x: f32 = @floatFromInt(firstChipX());
+ var x: f32 = bar.item_layout.x[@intFromEnum(taskbar_items.Item.windows)] orelse 0;
for (visible.items) |toplevel| {
const new_target = x;
var state: ChipState = found: {
@@ -1128,7 +1148,7 @@ pub fn hitTest(bar: *Taskbar, sx: f64, sy: f64) Target {
if (sy < 0 or sy >= @as(f64, @floatFromInt(bh))) return .none;
if (bar.itemShown(.clock) and sx >= bar.clockX() and sx < bar.clockX() + bar.clockColumnWidth()) return .clock;
if (bar.itemShown(.battery) and sx >= bar.batteryX() and sx < bar.batteryX() + battery_width) return .battery;
- if (start_button.hitTest(sx, sy, bh, startButtonLeft(), buttonSize())) return .start_button;
+ if (bar.itemShown(.start) and start_button.hitTest(sx, sy, bh, bar.startX(), buttonSize())) return .start_button;
const now_ms = nowMs();
for (bar.chips.items) |chip| {
const x = chip.renderX(now_ms);
@@ -1560,8 +1580,9 @@ fn render(bar: *Taskbar, now_ms: i64, causes: u8) void {
renderPart(bar, now_ms, .background, 0, 0, bar.box.width, bh, bar.buffer_node, null);
bar.background_dirty = false;
}
- if (bar.start_dirty) {
- renderPart(bar, now_ms, .start, startButtonLeft() - 2, 0, buttonSize() + 4, bh, bar.start_node, null);
+ bar.start_node.node.setEnabled(bar.itemShown(.start));
+ if (bar.itemShown(.start) and bar.start_dirty) {
+ renderPart(bar, now_ms, .start, bar.startX() - 2, 0, buttonSize() + 4, bh, bar.start_node, null);
bar.start_dirty = false;
}
const positions = bar.trayPositions();
@@ -1680,8 +1701,7 @@ fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_y: i
var danger = Color.fromRgba(ui_theme.taskbar(.danger));
if (@as(TrayKind, @enumFromInt(i)) == .wifi and bar.blink_dim) danger.a *= 0.25;
break :blk danger;
- } else
- Color.lerp(Color.tray_icon(), Color.tray_icon_hover(), hover);
+ } else Color.lerp(Color.tray_icon(), Color.tray_icon_hover(), hover);
const size = 20 * press;
var renderer = @import("ui").paint.Renderer.init(buf.pixels, buf.width, buf.height, scale);
renderer.drawIcon(bar.trayPositions()[i] + @as(f32, @floatFromInt(trayHit())) / 2 - size / 2 - @as(f32, @floatFromInt(origin_x)), @as(f32, @floatFromInt(bar.box.height)) / 2 - size / 2 - @as(f32, @floatFromInt(origin_y)), size, size, .{ .id = if (i == @intFromEnum(TrayKind.wifi)) .wifi else if (bar.audio_muted) .volume_muted else .volume, .color = .{ color.r, color.g, color.b, color.a } });
@@ -1715,9 +1735,9 @@ fn paintPartPixel(bar: *Taskbar, sampled_start: start_button.Paint, hover: f32,
.start => {
const btn_size = buttonSize();
var color = Color{ .r = 0, .g = 0, .b = 0, .a = 0 };
- if (start_button.paintPixel(sampled_start, px, py, bar.box.height, scale, startButtonLeft(), btn_size)) |sb| color = (Color{ .r = sb.r, .g = sb.g, .b = sb.b, .a = sb.a }).over(color);
+ if (start_button.paintPixel(sampled_start, px, py, bar.box.height, scale, bar.startX(), btn_size)) |sb| color = (Color{ .r = sb.r, .g = sb.g, .b = sb.b, .a = sb.a }).over(color);
if (bar.start_logo) |icon| {
- const mapped = start_button.mapPoint(sampled_start, px, py, bar.box.height, startButtonLeft(), btn_size);
+ const mapped = start_button.mapPoint(sampled_start, px, py, bar.box.height, bar.startX(), btn_size);
const pad: f32 = @floatFromInt(@divTrunc(btn_size - startIconSize(), 2));
const ix: i32 = @intFromFloat(@floor((mapped.x - (mapped.box_x + pad)) * scale));
const iy: i32 = @intFromFloat(@floor((mapped.y - (mapped.box_y + pad)) * scale));
@@ -1993,7 +2013,7 @@ 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.taskbar(.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(bar.startX() + @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), " ");
@@ -2263,15 +2283,21 @@ test "battery artwork remains centered as taskbar height and item gap change" {
}
pub fn appTrayCount(bar: *Taskbar) usize {
+ if (!bar.itemShown(.tray)) return 0;
const mgr = bar.server.tray orelse return 0;
- const right = if (bar.capturing()) bar.captureX() else bar.rightLayout().left;
- const room = @max(0, right - @as(f32, @floatFromInt(firstChipX() + 80)));
+ var fixed: f32 = @floatFromInt(edge_pad + startButtonLeft() + 80 + 5 * clock_gap);
+ if (bar.itemShown(.start)) fixed += @floatFromInt(buttonSize());
+ if (bar.itemShown(.battery)) fixed += battery_width;
+ if (bar.itemShown(.network)) fixed += @floatFromInt(trayHit());
+ if (bar.itemShown(.volume)) fixed += @floatFromInt(trayHit());
+ if (bar.itemShown(.clock)) fixed += bar.clockColumnWidth();
+ if (bar.capturing()) fixed += @floatFromInt(bar.captureWidth());
+ const room = @max(0, @as(f32, @floatFromInt(bar.box.width)) - fixed);
return @min(mgr.visibleCount(), @as(usize, @intFromFloat(room / @as(f32, @floatFromInt(trayHit() + tray_gap)))));
}
fn appTrayLeft(bar: *Taskbar) f32 {
- const right = if (bar.capturing()) bar.captureX() else bar.rightLayout().left;
- return right - @as(f32, @floatFromInt(bar.appTrayCount() * @as(usize, @intCast(trayHit() + tray_gap))));
+ return bar.item_layout.x[@intFromEnum(taskbar_items.Item.tray)] orelse 0;
}
pub fn appTrayBox(bar: *Taskbar, index: usize) wlr.Box {
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index 513e294..aa28da7 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -205,6 +205,10 @@ zoom_scale: f64 = 1.0,
/// Presentation-only focus boost. Neither saved geometry nor zoom_index changes.
zoom_boost: anim.Anim = .{},
zoom_boost_value: f64 = 0,
+/// Drag lift is presentation only; the grab point stays fixed under the pointer.
+drag_lift: anim.Anim = .{ .from = 1, .to = 1 },
+drag_lift_value: f64 = 1,
+drag_lift_anchor: geometry.Vec2 = .{ .x = 0, .y = 0 },
zoom_anim: @import("ui").anim.Anim = .{ .from = 1, .to = 1 },
zoom_anchor: geometry.Vec2 = .{ .x = 0, .y = 0 },
zoom_local: geometry.Vec2 = .{ .x = 0, .y = 0 },
@@ -260,6 +264,11 @@ glow_y: f32 = 0,
/// The window opacity the border colour of the shape was last given, so a
/// hover or focus repaint keeps the ring as faded as the body.
shape_opacity: f32 = 1,
+/// How dimmed the window is while it is not the focus (`applyDim`): 1 is all of
+/// `inactive_dim_amount`, eased with focus. `dim_shown` is the fraction of
+/// brightness and colour the output pass was last told to take away.
+dim_anim: anim.Anim = .{ .property = .opacity },
+dim_shown: f32 = 0,
// Inputs that produced the buffers currently attached to the scene nodes.
// syncChrome / syncShadow skip a re-raster when these still match.
last_titlebar: ?chrome.TitlebarMemo = null,
@@ -1559,13 +1568,58 @@ pub fn applyVisualTransform(toplevel: *Toplevel, now_ms: i64) void {
anim.windowMapScale(toplevel.map_motion.value(now_ms))
else
1.0;
- _ = @import("projection.zig").setTreeZoom(&toplevel.frame_tree.node, zoom_scale * factor);
+ _ = @import("projection.zig").setTreeZoom(&toplevel.frame_tree.node, zoom_scale * factor * toplevel.drag_lift_value);
+ const lift = toplevel.dragLiftOffset();
toplevel.frame_tree.node.setPosition(
- visualX(toplevel, now_ms) + animOffset(toplevel.dodge_x, now_ms) + animOffset(toplevel.switch_x, now_ms),
- visualY(toplevel, now_ms) + animOffset(toplevel.dodge_y, now_ms) + animOffset(toplevel.switch_y, now_ms),
+ visualX(toplevel, now_ms) + animOffset(toplevel.dodge_x, now_ms) + animOffset(toplevel.switch_x, now_ms) - lift.x,
+ visualY(toplevel, now_ms) + animOffset(toplevel.dodge_y, now_ms) + animOffset(toplevel.switch_y, now_ms) - lift.y,
);
}
+fn dragLiftOffset(toplevel: *const Toplevel) struct { x: i32, y: i32 } {
+ const extra = toplevel.worldScale() * (toplevel.drag_lift_value - 1);
+ return .{
+ .x = @intFromFloat(@round(toplevel.drag_lift_anchor.x * extra)),
+ .y = @intFromFloat(@round(toplevel.drag_lift_anchor.y * extra)),
+ };
+}
+
+pub fn tickDragLift(toplevel: *Toplevel, now_ms: i64) bool {
+ const input = &toplevel.server.input;
+ const moving = input.cursor_mode == .move and input.grabbed_toplevel == toplevel;
+ const config = toplevel.server.config.compositor;
+ const lift = moving and config.drag_feedback and !toplevel.isFullscreen() and
+ input.move_snap.unsnap_from == null and anim.enabled() and !anim.reducedMotion();
+ if (moving) {
+ const scale = toplevel.worldScale();
+ toplevel.drag_lift_anchor = if (input.tiling_grab != null)
+ .{ .x = @as(f64, @floatFromInt(toplevel.chrome_width)) / 2, .y = @as(f64, @floatFromInt(toplevel.chrome_height)) / 2 }
+ else
+ .{ .x = input.grab_x / scale, .y = input.grab_y / scale };
+ }
+ const target: f32 = if (lift) config.drag_scale else 1;
+ if (!toplevel.drag_lift.active() and toplevel.drag_lift.to == target) return false;
+ if (toplevel.drag_lift.to != target) toplevel.drag_lift.retargetTo(now_ms, target, anim.curveFor(.window_drag));
+ const live = toplevel.drag_lift.active();
+ _ = toplevel.drag_lift.sampleChanged(now_ms, 0.0001);
+ const settled = toplevel.drag_lift.settled(now_ms);
+ toplevel.drag_lift_value = std.math.clamp(if (settled) toplevel.drag_lift.to else toplevel.drag_lift.value(now_ms), 1, @import("config").loader.drag_scale_max);
+ if (settled) {
+ toplevel.drag_lift.cancel(@floatCast(toplevel.drag_lift_value));
+ if (live) {
+ toplevel.applyVisualTransform(now_ms);
+ input.processCursorMotion(0);
+ }
+ }
+ return !settled;
+}
+
+fn clearDragLift(toplevel: *Toplevel) void {
+ toplevel.drag_lift.cancel(1);
+ toplevel.drag_lift_value = 1;
+ if (toplevel.in_world) toplevel.applyVisualTransform(nowMs());
+}
+
fn animOffset(a: anim.Anim, now_ms: i64) i32 {
if (!a.active()) return 0;
return @intFromFloat(@round(a.value(now_ms)));
@@ -1931,14 +1985,18 @@ pub fn footerHeight(toplevel: *const Toplevel) i32 {
pub fn frameLocal(toplevel: *const Toplevel, lx: f64, ly: f64) geometry.Vec2 {
const point = toplevel.server.world.toWorld(lx, ly);
- const local = geometry.toLocal(point.x, point.y, toplevel.x, toplevel.y);
- return .{ .x = local.x / toplevel.worldScale(), .y = local.y / toplevel.worldScale() };
+ const lift = toplevel.dragLiftOffset();
+ const local = geometry.toLocal(point.x, point.y, toplevel.x - lift.x, toplevel.y - lift.y);
+ const scale = toplevel.worldScale() * toplevel.drag_lift_value;
+ return .{ .x = local.x / scale, .y = local.y / scale };
}
pub fn frameWorld(toplevel: *const Toplevel, x: f64, y: f64) geometry.Vec2 {
+ const lift = toplevel.dragLiftOffset();
+ const scale = toplevel.worldScale() * toplevel.drag_lift_value;
return .{
- .x = @as(f64, @floatFromInt(toplevel.x)) + x * toplevel.worldScale(),
- .y = @as(f64, @floatFromInt(toplevel.y)) + y * toplevel.worldScale(),
+ .x = @as(f64, @floatFromInt(toplevel.x - lift.x)) + x * scale,
+ .y = @as(f64, @floatFromInt(toplevel.y - lift.y)) + y * scale,
};
}
@@ -2559,6 +2617,7 @@ pub fn isGeometrySettled(toplevel: *Toplevel, now_ms: i64) bool {
if (toplevel.isResizing()) return false;
return toplevel.move_x.settled(now_ms) and toplevel.move_y.settled(now_ms) and
toplevel.size_w.settled(now_ms) and toplevel.size_h.settled(now_ms) and
+ toplevel.drag_lift.settled(now_ms) and
toplevel.switch_x.settled(now_ms) and toplevel.switch_y.settled(now_ms);
}
@@ -2667,6 +2726,7 @@ fn clearChromeCache(toplevel: *Toplevel) void {
/// shadow; geometry and theme changes pass true.
pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !void {
defer toplevel.server.scheduleFrames();
+ defer if (toplevel.server.input.grabbed_toplevel == toplevel) toplevel.server.input.updateGrabBorderGlow();
const geometry_box = toplevel.clientGeometry();
if (geometry_box.width <= 0 or geometry_box.height <= 0) return;
@@ -2913,6 +2973,7 @@ fn syncBorders(toplevel: *Toplevel, width: i32, height: i32) void {
pub fn detachInput(toplevel: *Toplevel) void {
toplevel.server.input.detachToplevel(toplevel);
+ toplevel.clearDragLift();
toplevel.clearDodge();
toplevel.clearZoomBoost();
toplevel.peek_mix = .{};
@@ -2933,6 +2994,37 @@ pub fn effectiveOpacity(toplevel: *Toplevel, now_ms: i64) f32 {
return (normal * (1 - mix) + toplevel.peek_level.value(now_ms) * mix) * toplevel.cameraFocusOpacity();
}
+/// 1 for a window that should show dimmed: not the focus, unless the dim is off,
+/// the window is fullscreen (a video on another output stays as it is) or leaving.
+fn dimTarget(toplevel: *Toplevel) f32 {
+ const config = &toplevel.server.config.compositor;
+ if (!config.inactive_dim or config.inactive_dim_amount <= 0 or toplevel.closing or toplevel.isFullscreen()) return 0;
+ return if (toplevel == @import("config_runtime/actions.zig").focusedToplevel(toplevel.server)) 0 else 1;
+}
+
+/// Takes some brightness and colour from a window that is not the focus
+/// (`inactive_dim`): the output pass draws its whole frame, titlebar and ring
+/// included, graded by what is set on the tree. The level eases in and out with
+/// focus; a taskbar preview shows every window as it is. Popups are no part of it.
+fn applyDim(toplevel: *Toplevel, now_ms: i64) void {
+ const target = toplevel.dimTarget();
+ if (toplevel.dim_anim.to != target) toplevel.dim_anim.retargetTo(now_ms, target, anim.curveFor(.window_dim));
+ const level = toplevel.dim_anim.value(now_ms) * (1 - toplevel.peek_mix.value(now_ms));
+ // Whole levels of an 8-bit channel: a finer step shows nothing and would only repaint.
+ const amount = std.math.clamp(@round(level * toplevel.server.config.compositor.inactive_dim_amount * 255) / 255, 0, 1);
+ if (amount == toplevel.dim_shown) return;
+ if (!projection.setTreeDim(&toplevel.frame_tree.node, amount, amount)) {
+ log.warn("could not dim window {d} by {d}", .{ toplevel.id, amount });
+ return;
+ }
+ toplevel.dim_shown = amount;
+}
+
+/// Whether the dim is still easing, so frames keep coming until it settles.
+pub fn dimAnimating(toplevel: *const Toplevel, now_ms: i64) bool {
+ return !toplevel.dim_anim.settled(now_ms);
+}
+
pub fn applyOpacity(toplevel: *Toplevel, now_ms: i64) void {
var opacity = std.math.clamp(toplevel.effectiveOpacity(now_ms) * toplevel.map_opacity.value(now_ms) * toplevel.switch_fade.value(now_ms), 0, 1);
toplevel.frame_tree.node.forEachBuffer(*f32, struct {
@@ -2944,6 +3036,7 @@ pub fn applyOpacity(toplevel: *Toplevel, now_ms: i64) void {
for (toplevel.border_rects) |rect| col.setRect(rect, color);
for (toplevel.frame_fills) |rect| col.setRect(rect, chrome.fillColor().scale(opacity));
toplevel.shape_opacity = opacity;
+ toplevel.applyDim(now_ms);
toplevel.applyShape();
glass.Effect.configure(toplevel.glass_effect, toplevel.cornerRadius(), opacity);
switch (toplevel.backend) {
diff --git a/src/World.zig b/src/World.zig
index eb267a0..eb47fb0 100644
--- a/src/World.zig
+++ b/src/World.zig
@@ -276,6 +276,7 @@ pub fn tickHover(world: *World, now_ms: i64) bool {
if (toplevel.tickGlow(now_ms)) animating = true;
if (toplevel.tickZoom(now_ms)) animating = true;
if (toplevel.tickZoomBoost(now_ms)) animating = true;
+ if (toplevel.tickDragLift(now_ms)) animating = true;
if (toplevel.tickMap(now_ms)) animating = true;
if (toplevel.tickMove(now_ms)) animating = true;
if (toplevel.tickDodge(now_ms)) animating = true;
@@ -301,6 +302,7 @@ pub fn tickHover(world: *World, now_ms: i64) bool {
if (toplevel.peek_level.to != level) toplevel.peek_level.retargetTo(now_ms, level, anim.curveFor(.window_peek));
}
toplevel.applyOpacity(now_ms);
+ if (toplevel.dimAnimating(now_ms)) animating = true;
_ = toplevel.peek_mix.sampleChanged(now_ms, anim.quantum_alpha);
_ = toplevel.peek_level.sampleChanged(now_ms, anim.quantum_alpha);
if (!toplevel.peek_mix.settled(now_ms) or !toplevel.peek_level.settled(now_ms)) animating = true;
diff --git a/src/battery_popup.zig b/src/battery_popup.zig
index a50a026..0fd6406 100644
--- a/src/battery_popup.zig
+++ b/src/battery_popup.zig
@@ -1,5 +1,7 @@
//! Battery details from the taskbar snapshot; no hardware reads or timers here.
const std = @import("std");
+const popup_style = @import("popup_style.zig");
+const glass = @import("glass.zig");
const wlr = @import("wlroots");
const Output = @import("Output.zig");
const gpa = @import("main.zig").gpa;
@@ -18,6 +20,7 @@ pub const Popup = struct {
output: *Output,
buffer_node: *wlr.SceneBuffer,
node_data: scene.SceneData = undefined,
+ glass_effect: ?*glass.Effect = null,
factor: f32 = 1,
slide: Anim = .{},
panel_box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = 0 },
@@ -40,6 +43,7 @@ pub const Popup = struct {
_ = self.slide.sampleChanged(now_ms, anim.quantum_alpha);
const t = self.slide.value(now_ms);
panel_present.applySlide(self.buffer_node, self.panel_box, t, if (self.output.server.config.compositor.taskbar_position == .top) -slide_distance else slide_distance);
+ popup_style.configureGlass(&self.glass_effect, self.output.server.glass_engine, self.buffer_node, self.factor);
return !self.slide.settled(now_ms);
}
@@ -85,28 +89,8 @@ pub const Popup = struct {
var r: paint.Renderer = .{ .pixels = buf.pixels, .width = buf.width, .height = buf.height, .scale = scale * self.factor };
const t = theme.shellPalette();
r.palette = t;
- var opaque_bg = t.window_bg;
- opaque_bg[3] = 1;
- r.fillRect(0, 0, 368, 480, .{ .color = opaque_bg, .radius = 9, .border_width = 1, .border_color = t.border_hover });
- // The pointer follows the battery even when taskbar items are reordered.
- for (0..@intCast(buf.height)) |iy| {
- const y = (@as(f32, @floatFromInt(iy)) + 0.5) / r.scale;
- if (y < 479) continue;
- for (0..@intCast(buf.width)) |ix| {
- const x = (@as(f32, @floatFromInt(ix)) + 0.5) / r.scale;
- const d = (@abs(x - tip) + y - 496) / @sqrt(@as(f32, 2));
- const coverage = std.math.clamp(0.5 - d * r.scale, 0, 1);
- if (coverage == 0) continue;
- const mix = (1 - std.math.clamp((-d - 1) * r.scale + 0.5, 0, 1)) * t.border_hover[3];
- buf.pixels[iy * @as(usize, @intCast(buf.width)) + ix] = (@import("color.zig").Straight{
- .r = t.window_bg[0] * (1 - mix) + t.border_hover[0] * mix,
- .g = t.window_bg[1] * (1 - mix) + t.border_hover[1] * mix,
- .b = t.window_bg[2] * (1 - mix) + t.border_hover[2] * mix,
- .a = coverage,
- }).argb();
- }
- }
- if (self.output.server.config.compositor.taskbar_position == .top) buf.flipVertical();
+ popup_style.background(&r, buf, 368, 496, 16, tip, self.output.server.config.compositor.taskbar_position == .top);
+ const card_t = popup_style.cardPalette(t);
const state = bar.battery_state;
var pct: [16]u8 = undefined;
const percent = if (state.percent) |p| std.fmt.bufPrint(&pct, "{d}%", .{p}) catch "" else "—";
@@ -126,28 +110,34 @@ pub const Popup = struct {
};
for ([_][]const u8{ "Health", "Full capacity", "Cycles" }, values, 0..) |name, value, i| {
const x: f32 = 20 + @as(f32, @floatFromInt(i)) * 112;
- r.fillRect(x, 274, 104, 70, .{ .color = t.surface_hover, .radius = 9 });
- label(&r, x + 10, 284, 90, 22, name, 12, t.window_dim, false);
- label(&r, x + 10, 307, 90, 28, value, if (std.mem.eql(u8, value, "Unavailable")) 11 else 19, t.window_fg, true);
+ if (t.popup_card_bg != null) popup_style.card(&r, x, 274, 104, 70) else r.fillRect(x, 274, 104, 70, .{ .color = t.surface_hover, .radius = 9 });
+ label(&r, x + 10, 284, 90, 22, name, 12, card_t.window_dim, false);
+ label(&r, x + 10, 307, 90, 28, value, if (std.mem.eql(u8, value, "Unavailable")) 11 else 19, card_t.window_fg, true);
}
r.fillRect(20, 356, 328, 1, .{ .color = t.border });
+ if (t.popup_card_bg != null) popup_style.card(&r, 20, 366, 328, 96);
+ r.palette = card_t;
const manager = self.output.server.power_profiles;
for (0..3) |i| {
const profile: Profile = @enumFromInt(i);
const enabled = if (manager) |m| m.supports(profile) else false;
const selected = if (manager) |m| m.active == profile else false;
const y: f32 = 366 + @as(f32, @floatFromInt(i)) * 32;
- if (self.focused == i) r.fillRect(20, y, 328, 32, .{ .color = t.surface_hover, .radius = 5 });
+ if (self.focused == i) {
+ const inset: f32 = if (t.popup_card_bg != null) 4 else 0;
+ r.fillRect(20 + inset, y + inset, 328 - 2 * inset, 32 - 2 * inset, .{ .color = card_t.surface_hover, .radius = if (t.popup_card_bg != null) t.popup_card_radius else 5 });
+ }
if (selected) {
checkbox.paint(&r, .{ .x = 28, .y = y, .w = 310, .h = 32 }, profile.label(), .{ .checked = true, .disabled = !enabled });
} else {
- label(&r, 28 + checkbox.box_size + checkbox.gap, y, 282, 32, profile.label(), t.font_size, if (enabled) t.fg else t.faint, false);
+ label(&r, 28 + checkbox.box_size + checkbox.gap, y, 282, 32, profile.label(), t.font_size, if (enabled) card_t.fg else card_t.faint, false);
}
}
self.buffer_node.setBuffer(&buf.base);
self.buffer_node.setDestSize(width, height);
self.panel_box = .{ .x = left, .y = self.output.taskbarPopupY(height, 12), .width = width, .height = height };
self.buffer_node.node.setPosition(left, self.panel_box.y + panel_present.slideOffset(self.slide.value(anim.nowMs()), if (self.output.server.config.compositor.taskbar_position == .top) -slide_distance else slide_distance));
+ popup_style.configureGlass(&self.glass_effect, self.output.server.glass_engine, self.buffer_node, self.factor);
self.output.wlr_output.scheduleFrame();
}
};
@@ -162,7 +152,7 @@ fn centered(r: *paint.Renderer, y: f32, h: f32, value: []const u8, size: f32, co
}
fn ring(r: *paint.Renderer, percent: u8) void {
- const color = if (percent <= 10) theme.global.danger else if (percent <= 25) [4]f32{ 0.98, 0.8, 0.25, 1 } else [4]f32{ 32.0 / 255.0, 226.0 / 255.0, 157.0 / 255.0, 1 };
+ const color = if (percent <= 10) theme.global.danger else if (theme.global.popup_battery_ring) |color| color else if (percent <= 25) [4]f32{ 0.98, 0.8, 0.25, 1 } else [4]f32{ 32.0 / 255.0, 226.0 / 255.0, 157.0 / 255.0, 1 };
for (0..@intCast(r.height)) |iy| {
const y = (@as(f32, @floatFromInt(iy)) + 0.5) / r.scale - 168;
if (@abs(y) > 96) continue;
diff --git a/src/config/default.zig b/src/config/default.zig
index 4117312..5b3dba2 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -118,12 +118,14 @@ pub const source =
\\default_file_manager = ""
\\default_terminal = ""
\\dock_enabled = false # compact launcher alongside the taskbar
- \\dock_height = 68 # logical px; 48-96, icons and spacing resize together
+ \\dock_position = "bottom" # top, bottom, left or right
+ \\dock_height = 68 # thickness in logical px; 48-96, icons and spacing resize together
+ \\dock_hover_zoom = 1.05 # 1.0-1.5; 1.0 disables icon enlargement on hover
\\dock_hidden_apps = [] # app IDs removed from the dock's context menu
\\dock_hidden_shortcuts = [] # applications, files, terminal, settings
- \\# Right-side taskbar items, left to right; prefix a name with - to hide it.
+ \\# Taskbar sections, ordered within each section; prefix with - to hide an item.
\\taskbar_position = "bottom" # top or bottom
- \\taskbar_items = ["battery", "network", "volume", "clock"]
+ \\taskbar_items = ["left:start", "center:windows", "right:tray", "right:battery", "right:network", "right:volume", "right:clock"]
\\focus_follows_mouse = false
\\canvas_columns = 3 # screens wide (1-10)
\\canvas_rows = 3 # screens tall (1-10)
@@ -139,10 +141,14 @@ pub const source =
\\# Default tile gap: 0 px in canvas, 8 px in workspaces. Uncomment to override.
\\# window_gap = 8 # px around and between tiled windows
\\snap_to_edges = true # drag a window to a screen edge to tile or maximize it
+ \\drag_feedback = true # softly lift a window while dragging it
+ \\drag_scale = 1.03 # drag lift multiplier, 1.00-1.10
\\dodge_file_drags = true # a file manager slides aside while you drag a file out of it
\\files_single_click_open = true # Files: one click on an icon opens the file or folder
\\switcher_opacity = 1.0 # 0.0-1.0, background only; previews stay opaque
\\inactive_opacity = 1.0 # 0.0-1.0, 1.0 = no change
+ \\inactive_dim = true # windows that are not the focus lose a little brightness and colour
+ \\inactive_dim_amount = 0.08 # 0.0-0.5, how much they lose (fullscreen windows never dim)
\\border_radius = 10 # window corner radius
\\xwayland = true # X11 apps via Xwayland; false keeps native-only
\\xwayland_native_scaling = false # sharp X11 apps on fractional scales (requires restart)
diff --git a/src/config/loader.zig b/src/config/loader.zig
index e0ba32a..a4c4057 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -30,6 +30,8 @@ pub const AccelCurve = types.AccelCurve;
const log = std.log.scoped(.config);
pub const max_zoom_steps: u8 = 8;
+pub const drag_scale_min: f32 = 1.0;
+pub const drag_scale_max: f32 = 1.10;
const default_zoom_percents = [_]u8{ 100, 85, 70, 55 };
/// Browsers smooth wheel scrolling themselves (prefixes also cover their
@@ -121,6 +123,7 @@ pub const DesktopMode = enum { canvas, workspaces };
pub const dock_height_min: u32 = 48;
pub const dock_height_max: u32 = 96;
pub const dock_height_default: u32 = 68;
+pub const dock_hover_zoom_max: f32 = 1.5;
pub const CompositorConfig = struct {
desktop_mode: DesktopMode = .canvas,
@@ -128,7 +131,9 @@ pub const CompositorConfig = struct {
default_file_manager: []const u8 = "",
default_terminal: []const u8 = "",
dock_enabled: bool = false,
+ dock_position: types.DockPosition = .bottom,
dock_height: u32 = dock_height_default,
+ dock_hover_zoom: f32 = 1.05,
dock_hidden_apps: []const []const u8 = &.{},
dock_hidden_shortcuts: []const []const u8 = &.{},
taskbar_items: TaskbarItems = .{},
@@ -158,12 +163,19 @@ pub const CompositorConfig = struct {
window_gap: ?u32 = null,
/// Dragging a window to an open screen edge tiles or maximizes it.
snap_to_edges: bool = true,
+ /// Soft presentation-only lift while moving a window.
+ drag_feedback: bool = true,
+ drag_scale: f32 = 1.03,
/// A file manager slides aside while a file is dragged out of it; see
/// `input/drag_dodge.zig`.
dodge_file_drags: bool = true,
/// Files opens an item with one click on its icon; names still select.
files_single_click_open: bool = true,
inactive_opacity: f32 = 1.0,
+ /// A window that is not the focus loses `inactive_dim_amount` of its
+ /// brightness and of its colour (`Toplevel.applyDim`).
+ inactive_dim: bool = true,
+ inactive_dim_amount: f32 = 0.08,
switcher_opacity: f32 = 1.0,
border_radius: u32 = 10,
allow_tearing: bool = false,
@@ -1051,7 +1063,9 @@ const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(CompositorC
.desktop_mode = .enumeration,
.floating_apps = .json_string_list,
.dock_enabled = .boolean,
+ .dock_position = .enumeration,
.dock_height = .{ .uint = .{ .min = dock_height_min, .max = dock_height_max } },
+ .dock_hover_zoom = .{ .float = .{ .min = 1, .max = dock_hover_zoom_max } },
.dock_hidden_apps = .json_string_list,
.dock_hidden_shortcuts = .json_string_list,
.taskbar_items = .taskbar_items,
@@ -1078,9 +1092,13 @@ const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(CompositorC
.focus_zoom = .enumeration,
.window_gap = .{ .uint = .{ .min = 0, .max = 512 } },
.snap_to_edges = .boolean,
+ .drag_feedback = .boolean,
+ .drag_scale = .{ .float = .{ .min = drag_scale_min, .max = drag_scale_max } },
.dodge_file_drags = .boolean,
.files_single_click_open = .boolean,
.inactive_opacity = .{ .float = .{ .min = 0, .max = 1 } },
+ .inactive_dim = .boolean,
+ .inactive_dim_amount = .{ .float = .{ .min = 0, .max = 0.5 } },
.switcher_opacity = .{ .float = .{ .min = 0, .max = 1 } },
.border_radius = .{ .uint = .{ .min = 0, .max = 128 } },
.allow_tearing = .boolean,
@@ -1774,6 +1792,12 @@ test "config field parsing preserves ranges and derived zoom state" {
}
var c = CompositorConfig{};
+ try std.testing.expectEqual(types.DockPosition.bottom, c.dock_position);
+ inline for (.{ "top", "bottom", "left", "right" }) |value| {
+ try applyCompositorKey(&c, a, "dock_position", value);
+ try std.testing.expectEqual(std.meta.stringToEnum(types.DockPosition, value).?, c.dock_position);
+ }
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "dock_position", "center"));
try std.testing.expectEqual(@as(u32, 0), c.windowGap());
c.desktop_mode = .workspaces;
try std.testing.expectEqual(@as(u32, 8), c.windowGap());
@@ -1794,6 +1818,13 @@ test "config field parsing preserves ranges and derived zoom state" {
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, fixture[0], fixture[3]));
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, fixture[0], fixture[4]));
}
+ inline for (.{ "1", "1.05", "1.5" }) |value| {
+ try applyCompositorKey(&c, a, "dock_hover_zoom", value);
+ try std.testing.expectEqual(try std.fmt.parseFloat(f32, value), c.dock_hover_zoom);
+ }
+ inline for (.{ "nan", "inf", "0.99", "1.51" }) |value| {
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "dock_hover_zoom", value));
+ }
inline for (.{ "camera_zoom_min", "camera_zoom_max", "inactive_opacity" }) |key| {
try applyCompositorKey(&c, a, key, "0.5");
try std.testing.expectEqual(@as(f32, 0.5), @field(c, key));
@@ -1811,6 +1842,15 @@ test "config field parsing preserves ranges and derived zoom state" {
try applyCompositorKey(&c, a, "inactive_opacity", "1");
try std.testing.expectEqual(@as(f32, 1), c.inactive_opacity);
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "inactive_opacity", "1.01"));
+ try std.testing.expect(c.inactive_dim);
+ try std.testing.expectEqual(@as(f32, 0.08), c.inactive_dim_amount);
+ try applyCompositorKey(&c, a, "inactive_dim", "false");
+ try std.testing.expect(!c.inactive_dim);
+ try applyCompositorKey(&c, a, "inactive_dim_amount", "0.5");
+ try std.testing.expectEqual(@as(f32, 0.5), c.inactive_dim_amount);
+ inline for (.{ "nan", "inf", "-0.1", "0.51" }) |v| {
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "inactive_dim_amount", v));
+ }
try applyCompositorKey(&c, a, "focus_follows_mouse", "true");
try std.testing.expect(c.focus_follows_mouse);
try applyCompositorKey(&c, a, "xwayland", "false");
diff --git a/src/config/taskbar_items.zig b/src/config/taskbar_items.zig
index 8e2f96a..266c9b3 100644
--- a/src/config/taskbar_items.zig
+++ b/src/config/taskbar_items.zig
@@ -1,11 +1,15 @@
-//! Ordered right-hand taskbar items. Hidden items retain their place in the list.
+//! Ordered taskbar sections. Hidden items keep their section and order.
const std = @import("std");
+pub const Section = enum { left, center, right };
pub const Item = enum {
battery,
network,
volume,
clock,
+ start,
+ windows,
+ tray,
pub fn label(item: Item) []const u8 {
return switch (item) {
@@ -13,31 +17,58 @@ pub const Item = enum {
.network => "Network",
.volume => "Volume",
.clock => "Clock",
+ .start => "Start button",
+ .windows => "Window list",
+ .tray => "Application tray",
};
}
};
pub const count = std.meta.fields(Item).len;
pub const Config = struct {
- order: [count]Item = .{ .battery, .network, .volume, .clock },
- visible: [count]bool = .{ true, true, true, true },
+ order: [count]Item = .{ .start, .windows, .tray, .battery, .network, .volume, .clock },
+ visible: [count]bool = @splat(true),
+ sections: [count]Section = .{ .right, .right, .right, .right, .left, .center, .right },
pub fn move(config: *Config, index: usize, right: bool) void {
if (index >= count or (!right and index == 0) or (right and index == count - 1)) return;
const other = if (right) index + 1 else index - 1;
+ if (config.section(config.order[index]) != config.section(config.order[other])) return;
std.mem.swap(Item, &config.order[index], &config.order[other]);
}
+ pub fn section(config: Config, item: Item) Section {
+ return config.sections[@intFromEnum(item)];
+ }
+
+ pub fn normalize(config: *Config) void {
+ const previous = config.order;
+ var index: usize = 0;
+ for (std.enums.values(Section)) |zone| for (previous) |item| {
+ if (config.section(item) != zone) continue;
+ config.order[index] = item;
+ index += 1;
+ };
+ }
+
+ pub fn setSection(config: *Config, item: Item, zone: Section) void {
+ config.sections[@intFromEnum(item)] = zone;
+ config.normalize();
+ }
+
pub fn shown(config: Config, item: Item) bool {
return config.visible[@intFromEnum(item)];
}
- /// A minus prefix hides an item while keeping its configured position.
+ /// New lists use section:item. The original four-item lists remain valid.
+ /// A minus prefix hides an item without forgetting its placement.
pub fn parse(value: []const u8) !Config {
const raw = std.mem.trim(u8, value, " \t\r");
if (raw.len < 2 or raw[0] != '[' or raw[raw.len - 1] != ']') return error.InvalidValue;
var result: Config = .{};
+ var order: [count]Item = undefined;
var seen = [_]bool{false} ** count;
+ var legacy = true;
var tokens = std.mem.splitScalar(u8, raw[1 .. raw.len - 1], ',');
var index: usize = 0;
while (tokens.next()) |token| {
@@ -46,15 +77,28 @@ pub const Config = struct {
var name = entry[1 .. entry.len - 1];
const visible = name[0] != '-';
if (!visible) name = name[1..];
+ var zone: ?Section = null;
+ if (std.mem.indexOfScalar(u8, name, ':')) |colon| {
+ zone = std.meta.stringToEnum(Section, name[0..colon]) orelse return error.InvalidValue;
+ name = name[colon + 1 ..];
+ legacy = false;
+ }
const item = std.meta.stringToEnum(Item, name) orelse return error.InvalidValue;
const id = @intFromEnum(item);
if (seen[id]) return error.InvalidValue;
+ if (id >= 4) legacy = false;
seen[id] = true;
- result.order[index] = item;
+ order[index] = item;
result.visible[id] = visible;
+ if (zone) |s| result.sections[id] = s;
index += 1;
}
- if (index != count) return error.InvalidValue;
+ if (legacy and index == 4) {
+ @memcpy(result.order[3..], order[0..4]);
+ } else if (index == count) {
+ result.order = order;
+ } else return error.InvalidValue;
+ result.normalize();
return result;
}
@@ -64,7 +108,7 @@ pub const Config = struct {
try buffer.writer.writeByte('[');
for (config.order, 0..) |item, i| {
if (i > 0) try buffer.writer.writeAll(", ");
- try buffer.writer.print("\"{s}{s}\"", .{ if (config.shown(item)) "" else "-", @tagName(item) });
+ try buffer.writer.print("\"{s}{s}:{s}\"", .{ if (config.shown(item)) "" else "-", @tagName(config.section(item)), @tagName(item) });
}
try buffer.writer.writeByte(']');
return buffer.toOwnedSlice();
@@ -72,51 +116,86 @@ pub const Config = struct {
};
pub const Layout = struct {
- x: [count]?f32 = .{ null, null, null, null },
- left: f32,
+ x: [count]?f32 = @splat(null),
+ widths: [count]f32 = @splat(0),
};
-pub fn arrange(config: Config, right: f32, widths: [count]f32, battery_present: bool, gap: f32, clock_gap: f32) Layout {
- var result: Layout = .{ .left = right };
- var next: ?Item = null;
- var index: usize = count;
- while (index > 0) {
- index -= 1;
- const item = config.order[index];
- if (!config.shown(item) or (item == .battery and !battery_present)) continue;
- if (next) |neighbor| result.left -= if (item == .clock or neighbor == .clock) clock_gap else gap;
- result.left -= widths[@intFromEnum(item)];
- result.x[@intFromEnum(item)] = result.left;
- next = item;
+fn spacing(a: Item, b: Item, gap: f32, clock_gap: f32) f32 {
+ return if (a == .clock or b == .clock) clock_gap else gap;
+}
+
+/// Center the middle group on the output, moving it only to avoid the edges.
+/// The window list gives up width before any fixed control does.
+pub fn arrange(config: Config, left: f32, right: f32, center: f32, widths: [count]f32, gap: f32, clock_gap: f32) Layout {
+ var result: Layout = .{};
+ var totals: [3]f32 = @splat(0);
+ var previous: [3]?Item = @splat(null);
+ for (config.order) |item| {
+ const id = @intFromEnum(item);
+ if (!config.shown(item) or widths[id] <= 0) continue;
+ const zone = @intFromEnum(config.section(item));
+ if (previous[zone]) |p| totals[zone] += spacing(p, item, gap, clock_gap);
+ totals[zone] += widths[id];
+ result.widths[id] = widths[id];
+ previous[zone] = item;
+ }
+ var groups: usize = 0;
+ for (totals) |total| if (total > 0) {
+ groups += 1;
+ };
+ const zones_gap = @as(f32, @floatFromInt(groups -| 1)) * clock_gap;
+ const overflow = @max(0, totals[0] + totals[1] + totals[2] + zones_gap - (right - left));
+ const wid = @intFromEnum(Item.windows);
+ const shrink = @min(result.widths[wid], overflow);
+ result.widths[wid] -= shrink;
+ totals[@intFromEnum(config.section(.windows))] -= shrink;
+ const middle_min = left + totals[0] + (if (totals[0] > 0) clock_gap else @as(f32, 0));
+ const middle_max = right - totals[2] - (if (totals[2] > 0) clock_gap else @as(f32, 0)) - totals[1];
+ var cursor = [3]f32{ left, std.math.clamp(center - totals[1] / 2, middle_min, @max(middle_min, middle_max)), right - totals[2] };
+ previous = @splat(null);
+ for (config.order) |item| {
+ const id = @intFromEnum(item);
+ if (!config.shown(item) or widths[id] <= 0) continue;
+ const zone = @intFromEnum(config.section(item));
+ if (previous[zone]) |p| cursor[zone] += spacing(p, item, gap, clock_gap);
+ result.x[id] = cursor[zone];
+ cursor[zone] += result.widths[id];
+ previous[zone] = item;
}
return result;
}
-test "taskbar order and hidden state round trip and reject malformed lists" {
+test "taskbar sections and hidden state round trip, migrate old lists and reject malformed lists" {
var config: Config = .{};
- config.move(0, true);
+ config.setSection(.volume, .left);
+ config.move(1, false);
config.visible[@intFromEnum(Item.volume)] = false;
const encoded = try config.serialize(std.testing.allocator);
defer std.testing.allocator.free(encoded);
try std.testing.expectEqualDeep(config, try Config.parse(encoded));
- for ([_][]const u8{ "[]", "[\"battery\", \"network\", \"volume\", \"volume\"]", "[\"battery\", \"network\", \"volume\", \"chevron\"]" }) |bad| {
+ const legacy = try Config.parse("[\"clock\", \"-network\", \"battery\", \"volume\"]");
+ try std.testing.expectEqual(Section.left, legacy.section(.start));
+ try std.testing.expectEqual(Section.center, legacy.section(.windows));
+ try std.testing.expectEqual(Item.clock, legacy.order[3]);
+ try std.testing.expect(!legacy.shown(.network));
+ for ([_][]const u8{ "[]", "[\"battery\", \"network\", \"volume\", \"volume\"]", "[\"battery\", \"network\", \"volume\", \"chevron\"]", "[\"left:battery\", \"network\", \"volume\", \"clock\"]" }) |bad| {
try std.testing.expectError(error.InvalidValue, Config.parse(bad));
}
}
-test "taskbar layout packs visible items and keeps move boundaries stable" {
+test "taskbar centers windows, separates sections and shrinks windows before fixed items" {
var config: Config = .{};
- config.move(0, false);
- config.move(count - 1, true);
- try std.testing.expectEqualDeep(Config{}, config);
- const widths = [count]f32{ 112, 34, 34, 96 };
- const full = arrange(config, 1000, widths, true, 6, 16);
- try std.testing.expectEqual(@as(?f32, 904), full.x[@intFromEnum(Item.clock)]);
- config.visible[@intFromEnum(Item.network)] = false;
- const hidden = arrange(config, 1000, widths, false, 6, 16);
- try std.testing.expect(hidden.x[@intFromEnum(Item.battery)] == null);
- try std.testing.expect(hidden.x[@intFromEnum(Item.network)] == null);
- try std.testing.expectEqual(@as(f32, 854), hidden.left);
- config.visible = .{ false, false, false, false };
- try std.testing.expectEqual(@as(f32, 1000), arrange(config, 1000, widths, true, 6, 16).left);
+ const widths = [count]f32{ 0, 34, 34, 96, 42, 200, 0 };
+ const full = arrange(config, 4, 980, 500, widths, 6, 16);
+ try std.testing.expectEqual(@as(?f32, 400), full.x[@intFromEnum(Item.windows)]);
+ try std.testing.expectEqual(@as(?f32, 884), full.x[@intFromEnum(Item.clock)]);
+ config.setSection(.clock, .center);
+ config.setSection(.network, .left);
+ const moved = arrange(config, 4, 980, 500, widths, 6, 16);
+ try std.testing.expectEqual(@as(?f32, 52), moved.x[@intFromEnum(Item.network)]);
+ const crowded = arrange(config, 4, 400, 200, .{ 0, 34, 34, 96, 42, 1000, 0 }, 6, 16);
+ try std.testing.expect(crowded.widths[@intFromEnum(Item.windows)] < 1000);
+ try std.testing.expect(crowded.x[@intFromEnum(Item.clock)].? + 96 <= crowded.x[@intFromEnum(Item.volume)].? - 16);
+ config.visible = @splat(false);
+ try std.testing.expectEqualDeep(Layout{}, arrange(config, 4, 980, 500, widths, 6, 16));
}
diff --git a/src/config/theme_pack.zig b/src/config/theme_pack.zig
index 422d963..f004ec9 100644
--- a/src/config/theme_pack.zig
+++ b/src/config/theme_pack.zig
@@ -11,9 +11,11 @@ const Io = std.Io;
pub const Layout = struct {
taskbar_position: ?@import("types.zig").TaskbarPosition = null,
dock_enabled: ?bool = null,
+ dock_position: ?@import("types.zig").DockPosition = null,
dock_height: ?u32 = null,
+ dock_hover_zoom: ?f32 = null,
- pub const keys = .{ "taskbar_position", "dock_enabled", "dock_height" };
+ pub const keys = .{ "taskbar_position", "dock_enabled", "dock_position", "dock_height", "dock_hover_zoom" };
pub fn apply(self: Layout, compositor: anytype) void {
inline for (keys) |key| if (@field(self, key)) |value| {
@@ -26,16 +28,22 @@ pub const Layout = struct {
self.taskbar_position = std.meta.stringToEnum(@import("types.zig").TaskbarPosition, try theme.unquote(value)) orelse return error.InvalidLayout;
} else if (std.mem.eql(u8, key, "dock_enabled")) {
self.dock_enabled = if (std.mem.eql(u8, value, "true")) true else if (std.mem.eql(u8, value, "false")) false else return error.InvalidLayout;
+ } else if (std.mem.eql(u8, key, "dock_position")) {
+ self.dock_position = std.meta.stringToEnum(@import("types.zig").DockPosition, try theme.unquote(value)) orelse return error.InvalidLayout;
} else if (std.mem.eql(u8, key, "dock_height")) {
const height = std.fmt.parseInt(u32, value, 10) catch return error.InvalidLayout;
if (height < 48 or height > 96) return error.InvalidLayout;
self.dock_height = height;
+ } else if (std.mem.eql(u8, key, "dock_hover_zoom")) {
+ const zoom = std.fmt.parseFloat(f32, value) catch return error.InvalidLayout;
+ if (!std.math.isFinite(zoom) or zoom < 1 or zoom > 1.5) return error.InvalidLayout;
+ self.dock_hover_zoom = zoom;
} else return error.InvalidLayout;
}
pub fn write(a: A, bytes: *std.ArrayList(u8), compositor: anytype) !void {
- const text = try std.fmt.allocPrint(a, "[layout]\ntaskbar_position = \"{s}\"\ndock_enabled = {}\ndock_height = {d}\n", .{
- @tagName(compositor.taskbar_position), compositor.dock_enabled, compositor.dock_height,
+ const text = try std.fmt.allocPrint(a, "[layout]\ntaskbar_position = \"{s}\"\ndock_enabled = {}\ndock_position = \"{s}\"\ndock_height = {d}\ndock_hover_zoom = {d}\n", .{
+ @tagName(compositor.taskbar_position), compositor.dock_enabled, @tagName(compositor.dock_position), compositor.dock_height, compositor.dock_hover_zoom,
});
defer a.free(text);
try bytes.appendSlice(a, text);
@@ -237,7 +245,17 @@ test "pack metadata, future tokens and unsafe paths" {
try std.testing.expectError(error.UnsafeAssetPath, parse(a, "[theme]\nstart_button_icon = \"../logo.svg\"", "nord", "/tmp/nord"));
for ([_][]const u8{ "../x", "/x", "x//y", "x/./y", "x\\y" }) |path| try std.testing.expect(!relative(path));
try std.testing.expect(!validId("../nord"));
- for ([_][]const u8{ "dock_height = 47", "dock_height = 97", "dock_enabled = 1", "taskbar_position = \"left\"", "xwayland = true" }) |line| {
+ inline for (.{ "top", "bottom", "left", "right" }) |position| {
+ const pack = try parse(a, "[layout]\ndock_position = \"" ++ position ++ "\"\n", "test", "");
+ var compositor = @import("loader.zig").CompositorConfig{};
+ pack.layout.apply(&compositor);
+ try std.testing.expectEqualStrings(position, @tagName(compositor.dock_position));
+ var bytes: std.ArrayList(u8) = .empty;
+ try Layout.write(a, &bytes, compositor);
+ const exported = try parse(a, bytes.items, "test", "");
+ try std.testing.expectEqual(pack.layout.dock_position, exported.layout.dock_position);
+ }
+ for ([_][]const u8{ "dock_height = 47", "dock_height = 97", "dock_hover_zoom = 0.99", "dock_hover_zoom = 1.51", "dock_hover_zoom = nan", "dock_enabled = 1", "dock_position = \"center\"", "taskbar_position = \"left\"", "xwayland = true" }) |line| {
const bytes = try std.fmt.allocPrint(a, "[layout]\n{s}\n", .{line});
try std.testing.expectError(error.InvalidLayout, parse(a, bytes, "test", ""));
}
diff --git a/src/config/types.zig b/src/config/types.zig
index 4a9e9ce..a328a3e 100644
--- a/src/config/types.zig
+++ b/src/config/types.zig
@@ -1,6 +1,16 @@
const std = @import("std");
pub const PanModifier = enum { super, super_alt };
pub const TaskbarPosition = enum { top, bottom };
+pub const DockPosition = enum {
+ top,
+ bottom,
+ left,
+ right,
+
+ pub fn vertical(self: DockPosition) bool {
+ return self == .left or self == .right;
+ }
+};
pub const AccelProfile = enum {
flat,
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 64cca7d..51d376e 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -135,9 +135,23 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
if (server.input.open_control_center) |cc| cc.refresh();
}
applyWindowOpacity(server);
+ if (old.compositor.drag_feedback != new.compositor.drag_feedback or
+ old.compositor.drag_scale != new.compositor.drag_scale)
+ {
+ server.scheduleFrames();
+ if (server.input.open_control_center) |cc| cc.refresh();
+ }
if (old.compositor.inactive_opacity != new.compositor.inactive_opacity) {
if (server.input.open_control_center) |cc| cc.refresh();
}
+ if (old.compositor.inactive_dim != new.compositor.inactive_dim or
+ old.compositor.inactive_dim_amount != new.compositor.inactive_dim_amount)
+ {
+ // The windows ease to the new dim; a hand edit while settings is open
+ // must show in its toggle.
+ server.scheduleFrames();
+ if (server.input.open_control_center) |cc| cc.refresh();
+ }
if (server.idle) |im| {
im.applyConfig(new.idle);
@@ -207,14 +221,17 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
if (server.input.open_control_center) |cc| cc.refresh();
}
- if (old.compositor.dock_height != new.compositor.dock_height or
+ if (old.compositor.dock_position != new.compositor.dock_position or
+ old.compositor.dock_height != new.compositor.dock_height or
+ old.compositor.dock_hover_zoom != new.compositor.dock_hover_zoom or
!stringListsEql(old.compositor.dock_hidden_apps, new.compositor.dock_hidden_apps) or
!stringListsEql(old.compositor.dock_hidden_shortcuts, new.compositor.dock_hidden_shortcuts))
{
if (server.input.window_menu.dock != null) server.input.window_menu.close();
var output_it = server.outputs.iterator(.forward);
while (output_it.next()) |output| output.dock.invalidate();
- if (old.compositor.dock_height != new.compositor.dock_height) {
+ if (old.compositor.dock_position != new.compositor.dock_position) server.scheduleFrames();
+ if (old.compositor.dock_position != new.compositor.dock_position or old.compositor.dock_height != new.compositor.dock_height or old.compositor.dock_hover_zoom != new.compositor.dock_hover_zoom) {
if (server.input.open_control_center) |cc| cc.refresh();
}
}
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index 96d6bd4..640bcb2 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -61,7 +61,8 @@ const page_icons = [_]layout.IconId{ .settings, .mouse, .display, .music, .wifi,
const max_devices = 16;
pub fn palette() theme.Theme {
- var t = theme.global;
+ // Settings paints app surfaces even though its host is compositor-owned.
+ var t = theme.global.forApp();
t.bg = t.window_bg;
t.fg = t.window_fg;
t.dim = t.window_dim;
@@ -459,12 +460,14 @@ pub const ControlCenter = struct {
const nav_count = page_names.len - @as(usize, @intFromBool(!has_services));
const nav_gap: f32 = if (cc.panel_box.height < 550) 2 else 5;
const nav_height = @min(52, @max(24, (@as(f32, @floatFromInt(cc.panel_box.height)) - 48 - nav_gap * @as(f32, @floatFromInt(nav_count - 1))) / @as(f32, @floatFromInt(nav_count))));
+ const nav_fg = theme.global.sidebarForeground();
for (cc.nav_rows[0..nav_count], 0..) |*row, i| {
const selected = i == @intFromEnum(cc.page);
cc.nav_children[i] = .{
- .{ .kind = .{ .icon = .{ .id = page_icons[i], .color = if (selected) t.accent else t.fg } }, .width = .{ .fixed = 22 }, .height = .{ .fixed = 22 } },
+ .{ .kind = .{ .icon = .{ .id = page_icons[i], .color = if (selected) t.accent else nav_fg } }, .width = .{ .fixed = 22 }, .height = .{ .fixed = 22 } },
label(page_labels[i], 14, false),
};
+ cc.nav_children[i][1].kind.text.color = nav_fg;
cc.nav_children[i][1].width = .{ .flex = 1 };
row.* = .{
.name = page_names[i],
@@ -1109,7 +1112,7 @@ pub const ControlCenter = struct {
}
const box = navRowBox(list, cc.nav_selected_row);
renderer.fillRect(box.x, box.y, box.w, box.h, .{
- .color = t.start_menu_selected_bg,
+ .color = t.sidebarSelected(),
.radius = t.radius,
.border_width = 1,
.border_color = t.start_menu_selected_border,
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index 2c5fe9a..afced54 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -89,6 +89,7 @@ const px_chrome_control_gap = 12;
const px_menu_width = 13;
const px_menu_height = 14;
const px_dock_height = 15;
+const px_dock_hover_zoom = 16;
pub const Section = struct {
cc: *panel.ControlCenter = undefined,
@@ -102,10 +103,15 @@ pub const Section = struct {
cursor_themes: ?[]cursor_theme.Theme = null,
cursor_row_children: [2]Widget = undefined,
family_row_children: [2]Widget = undefined,
- row_storage: [27]Widget = undefined,
+ row_storage: [30]Widget = undefined,
dock_children: [2]Widget = undefined,
- dock_group_children: [2]Widget = undefined,
+ dock_position_children: [2]Widget = undefined,
+ dock_group_children: [4]Widget = undefined,
focus_zoom_children: [3]Widget = undefined,
+ drag_feedback_children: [2]Widget = undefined,
+ drag_scale_header_children: [2]Widget = undefined,
+ drag_scale_children: [2]Widget = undefined,
+ drag_scale_value_buf: [16]u8 = undefined,
/// Rescanned on every build, so images added meanwhile show up.
wallpapers: []const wallpapers.Entry = &.{},
wallpaper_children: [3]Widget = undefined,
@@ -140,6 +146,8 @@ pub const Section = struct {
splash_label_children: [2]Widget = undefined,
dodge_row_children: [2]Widget = undefined,
dodge_label_children: [2]Widget = undefined,
+ dim_row_children: [2]Widget = undefined,
+ dim_label_children: [2]Widget = undefined,
anim_enabled_row_children: [2]Widget = undefined,
anim_enabled_label_children: [2]Widget = undefined,
anim_speed_row_children: [2]Widget = undefined,
@@ -163,12 +171,13 @@ pub const Section = struct {
inactive_opacity_header_children: [2]Widget = undefined,
inactive_opacity_group_children: [2]Widget = undefined,
inactive_opacity_value_buf: [16]u8 = undefined,
- px: [16]PxControl = undefined,
+ px: [17]PxControl = undefined,
taskbar_section_children: [8]Widget = undefined,
taskbar_position_children: [2]Widget = undefined,
- items_children: [3]Widget = undefined,
+ items_children: [5]Widget = undefined,
+ items_section_children: [3][2]Widget = undefined,
item_rows: [taskbar_items.count]Widget = undefined,
- item_controls: [taskbar_items.count][3]Widget = undefined,
+ item_controls: [taskbar_items.count][4]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: [9]Widget = undefined,
@@ -423,6 +432,15 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .name = "dodge_file_drags", .kind = .{ .toggle = .{ .on = dodge_on, .owner = out, .on_change = &onDodgeFileDragsChanged } } },
};
+ out.dim_label_children = .{
+ .{ .kind = .{ .text = .{ .content = "Dim inactive windows", .font_size = 13, .weight = 600, .color = pal.fg } } },
+ .{ .kind = .{ .text = .{ .content = "Slightly darken and mute windows that are not focused", .font_size = 12, .color = pal.dim } } },
+ };
+ out.dim_row_children = .{
+ .{ .kind = .container, .direction = .column, .gap = 2, .width = .{ .flex = 1 }, .children = &out.dim_label_children },
+ .{ .name = "inactive_dim", .kind = .{ .toggle = .{ .on = out.cc.server.config.compositor.inactive_dim, .owner = out, .on_change = &onInactiveDimChanged } } },
+ };
+
const anim_enabled = out.cc.server.config.animations.enabled;
out.anim_enabled_label_children = .{
.{ .kind = .{ .text = .{ .content = "Animations", .font_size = 13, .weight = 600, .color = pal.fg } } },
@@ -460,6 +478,25 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .kind = .{ .text = .{ .content = focus_zoom_descriptions[@intFromEnum(focus_zoom)], .font_size = 12, .color = pal.dim } } },
};
+ out.drag_feedback_children = .{
+ labelWidget("Drag feedback"),
+ .{ .name = "drag_feedback", .kind = .{ .toggle = .{ .on = out.cc.server.config.compositor.drag_feedback, .owner = out, .on_change = &onDragFeedbackChanged } } },
+ };
+ const drag_scale = out.cc.server.config.compositor.drag_scale;
+ const drag_formatted = std.fmt.bufPrint(&out.drag_scale_value_buf, "{d:.2}×", .{drag_scale}) catch "?";
+ out.drag_scale_header_children = .{ labelWidget("Drag lift scale"), pillWidget(drag_formatted) };
+ out.drag_scale_children = .{
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .children = &out.drag_scale_header_children },
+ .{ .name = "drag_scale", .kind = .{ .slider = .{
+ .value = drag_scale,
+ .min = loader.drag_scale_min,
+ .max = loader.drag_scale_max,
+ .step = 0.01,
+ .owner = out,
+ .on_change = &onDragScaleChanged,
+ } } },
+ };
+
if (out.font_families == null) {
out.font_families = @import("ui").font_fallback.listFamilies(out.font_arena.allocator()) catch null;
}
@@ -627,15 +664,28 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
const item = items.order[i];
out.item_controls[i] = .{
.{ .kind = .{ .text = .{ .content = item.label(), .font_size = 13, .weight = 600, .color = pal.fg } }, .width = .{ .flex = 1 } },
- .{ .kind = .{ .button = .{ .label = "Drag to reorder", .icon = .drag_handle, .owner = out, .id = i } }, .width = .{ .fixed = 32 }, .height = .{ .fixed = 30 } },
- .{ .kind = .{ .toggle = .{ .on = items.shown(item), .owner = out, .on_change = &ItemToggle(i).changed } } },
+ .{ .name = std.fmt.allocPrint(arena, "taskbar_{s}_order", .{@tagName(item)}) catch null, .kind = .{ .button = .{ .label = "Drag to reorder", .icon = .drag_handle, .owner = out, .id = i } }, .width = .{ .fixed = 32 }, .height = .{ .fixed = 30 } },
+ .{ .name = std.fmt.allocPrint(arena, "taskbar_{s}_visible", .{@tagName(item)}) catch null, .kind = .{ .toggle = .{ .on = items.shown(item), .owner = out, .on_change = &ItemToggle(i).changed } } },
+ .{ .name = std.fmt.allocPrint(arena, "taskbar_{s}_section", .{@tagName(item)}) catch null, .kind = .{ .segmented = .{ .labels = &.{ "Left", "Center", "Right" }, .selected = @intFromEnum(items.section(item)), .owner = out, .id = i, .on_change = &onItemSectionChanged } }, .width = .{ .fixed = 180 } },
};
out.item_rows[i] = .{ .kind = .container, .direction = .row, .gap = 8, .@"align" = .center, .children = &out.item_controls[i] };
}
+ var item_start: usize = 0;
+ inline for (.{ "LEFT", "CENTER", "RIGHT" }, 0..) |label, zone| {
+ var item_end = item_start;
+ while (item_end < taskbar_items.count and @intFromEnum(items.section(items.order[item_end])) == zone) item_end += 1;
+ out.items_section_children[zone] = .{
+ sectionLabel(label),
+ .{ .kind = .container, .direction = .column, .gap = 8, .children = out.item_rows[item_start..item_end] },
+ };
+ item_start = item_end;
+ }
out.items_children = .{
- labelWidget("Right-side items (left to right)"),
- .{ .kind = .{ .text = .{ .content = "Drag to reorder; toggle visibility. Battery appears when available.", .font_size = 12, .color = pal.dim } } },
- .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.item_rows },
+ labelWidget("Taskbar sections"),
+ .{ .kind = .{ .text = .{ .content = "Choose a section; drag to reorder within it. Toggle visibility. Battery appears when available.", .font_size = 12, .color = pal.dim } } },
+ .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.items_section_children[0] },
+ .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.items_section_children[1] },
+ .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.items_section_children[2] },
};
const items_group: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.items_children };
out.taskbar_section_children = .{ sectionLabel("TASKBAR"), position_row, taskbar_row, chip_width_row, chip_gap_row, start_gap_row, start_icon_row, items_group };
@@ -746,11 +796,20 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
labelWidget("RediWM dock"),
.{ .name = "dock_enabled", .kind = .{ .toggle = .{ .on = out.cc.server.config.compositor.dock_enabled, .owner = out, .on_change = &onDockChanged } } },
};
- const dock_height_row = pxGroup(out, px_dock_height, "Dock height", @floatFromInt(server.config.compositor.dock_height), @floatFromInt(loader.dock_height_min), @floatFromInt(loader.dock_height_max), 2, &onDockHeightChanged);
+ out.dock_position_children = .{
+ labelWidget("Dock position"),
+ .{ .name = "dock_position", .kind = .{ .segmented = .{ .labels = &.{ "Top", "Bottom", "Left", "Right" }, .selected = @intFromEnum(server.config.compositor.dock_position), .owner = out, .on_change = &onDockPositionChanged } }, .width = .{ .fixed = segmented_width } },
+ };
+ const dock_height_row = pxGroup(out, px_dock_height, "Dock size", @floatFromInt(server.config.compositor.dock_height), @floatFromInt(loader.dock_height_min), @floatFromInt(loader.dock_height_max), 2, &onDockHeightChanged);
out.px[px_dock_height].group_children[1].name = "dock_height";
+ const dock_zoom_row = pxGroup(out, px_dock_hover_zoom, "Dock hover zoom (1.00× disables)", server.config.compositor.dock_hover_zoom, 1, loader.dock_hover_zoom_max, 0.05, &onDockHoverZoomChanged);
+ out.px[px_dock_hover_zoom].group_children[1].name = "dock_hover_zoom";
+ updateDockZoomLabel(out);
out.dock_group_children = .{
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_children },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_position_children },
dock_height_row,
+ dock_zoom_row,
};
out.row_storage = .{
.{ .kind = .container, .direction = .column, .gap = 8, .children = pack_controls },
@@ -766,6 +825,8 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.anim_speed_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.reduced_motion_row_children },
.{ .kind = .container, .direction = .column, .gap = 8, .children = &out.focus_zoom_children },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.drag_feedback_children },
+ .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.drag_scale_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.cursor_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.family_row_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.font_row_children },
@@ -774,6 +835,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.glow_row_children },
chrome_row,
buildWindowTabs(out),
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dim_row_children },
inactive_opacity_row,
window_gap_row,
pxGroup(out, px_scrollbar_width, "Scrollbar width", t.scrollbar_width, 4, 24, 1, &PxHandler(px_scrollbar_width, "scrollbar_width", false).changed),
@@ -1431,6 +1493,18 @@ fn onChromeDarknessChanged(owner: ?*anyopaque, _: usize, value: f32) void {
applyThemeChange(section(owner));
}
+/// Live first, then saved: the windows ease to the new dim.
+fn onInactiveDimChanged(owner: ?*anyopaque, _: usize, on: bool) void {
+ const server = section(owner).cc.server;
+ if (server.config.compositor.inactive_dim == on) return;
+ server.config.compositor.inactive_dim = on;
+ @import("../../config_runtime/apply.zig").applyWindowOpacity(server);
+ server.scheduleFrames();
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "inactive_dim", on) catch |err| {
+ std.log.warn("could not save inactive_dim: {}", .{err});
+ };
+}
+
fn onInactiveOpacityChanged(owner: ?*anyopaque, _: usize, value: f32) void {
const s = section(owner);
const server = section(owner).cc.server;
@@ -1504,6 +1578,29 @@ fn onFocusZoomChanged(owner: ?*anyopaque, _: usize, index: usize) void {
s.focus_zoom_children[2].markDirty();
}
+fn onDragFeedbackChanged(owner: ?*anyopaque, _: usize, on: bool) void {
+ const server = section(owner).cc.server;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "drag_feedback", on) catch |err| {
+ std.log.warn("could not save drag_feedback: {}", .{err});
+ return;
+ };
+ server.config.compositor.drag_feedback = on;
+ server.scheduleFrames();
+}
+
+fn onDragScaleChanged(owner: ?*anyopaque, _: usize, value: f32) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ const scale = std.math.clamp(value, loader.drag_scale_min, loader.drag_scale_max);
+ server.config.compositor.drag_scale = scale;
+ server.scheduleFrames();
+ s.drag_scale_header_children[1].kind.text.content = std.fmt.bufPrint(&s.drag_scale_value_buf, "{d:.2}×", .{scale}) catch "?";
+ s.drag_scale_header_children[1].markDirty();
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "drag_scale", scale) catch |err| {
+ std.log.warn("could not save drag_scale: {}", .{err});
+ };
+}
+
fn onAnimationsEnabledChanged(owner: ?*anyopaque, _: usize, on: bool) void {
const server = section(owner).cc.server;
if (server.config.animations.enabled == on) return;
@@ -1635,6 +1732,7 @@ fn previewItems(s: *Section) void {
controls[1].kind.button.state = if (drag != null and drag.?.index == i) .press else .idle;
controls[1].kind.button.variant = if (drag != null and drag.?.index == i) .primary else .secondary;
controls[2].kind.toggle.on = items.shown(item);
+ controls[3].kind.segmented.selected = @intFromEnum(items.section(item));
for (controls) |*control| control.markDirty();
}
s.cc.requestRepaint();
@@ -1646,8 +1744,8 @@ pub fn moveItemDrag(s: *Section, y: f32) void {
drag.moved = true;
var target = drag.index;
// Cross the neighbouring row's centre before shifting it out of the way.
- while (target + 1 < taskbar_items.count and y > s.item_rows[target + 1].computed_y + s.item_rows[target + 1].computed_height / 2) target += 1;
- while (target > 0 and y < s.item_rows[target - 1].computed_y + s.item_rows[target - 1].computed_height / 2) target -= 1;
+ while (target + 1 < taskbar_items.count and drag.items.section(drag.items.order[target + 1]) == drag.items.section(drag.items.order[drag.index]) and y > s.item_rows[target + 1].computed_y + s.item_rows[target + 1].computed_height / 2) target += 1;
+ while (target > 0 and drag.items.section(drag.items.order[target - 1]) == drag.items.section(drag.items.order[drag.index]) and y < s.item_rows[target - 1].computed_y + s.item_rows[target - 1].computed_height / 2) target -= 1;
if (target == drag.index) return;
while (drag.index != target) {
const down = target > drag.index;
@@ -1665,6 +1763,7 @@ pub fn endItemDrag(s: *Section, commit: bool) void {
// A config reload during the grab can change visibility independently.
var items = s.cc.server.config.compositor.taskbar_items;
items.order = drag.items.order;
+ items.normalize();
saveItems(s, items);
}
previewItems(s);
@@ -1709,6 +1808,14 @@ pub fn itemKey(s: *Section, key: @import("ui").input.Key) bool {
return false;
}
+fn onItemSectionChanged(owner: ?*anyopaque, index: usize, zone: usize) void {
+ if (index >= taskbar_items.count or zone >= 3) return;
+ const s = section(owner);
+ var items = s.cc.server.config.compositor.taskbar_items;
+ items.setSection(items.order[index], @enumFromInt(zone));
+ saveItems(s, items);
+}
+
fn ItemToggle(comptime index: usize) type {
return struct {
fn changed(owner: ?*anyopaque, _: usize, on: bool) void {
@@ -1801,6 +1908,25 @@ fn onDockChanged(owner: ?*anyopaque, _: usize, on: bool) void {
server.scheduleFrames();
}
+fn onDockPositionChanged(owner: ?*anyopaque, _: usize, index: usize) void {
+ if (index >= 4) return;
+ const s = section(owner);
+ const server = s.cc.server;
+ const position: @TypeOf(server.config.compositor.dock_position) = @enumFromInt(index);
+ if (position == server.config.compositor.dock_position) return;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "dock_position", position) catch |err| {
+ std.log.warn("could not save dock position: {}", .{err});
+ s.dock_position_children[1].kind.segmented.selected = @intFromEnum(server.config.compositor.dock_position);
+ s.dock_position_children[1].markDirty();
+ return;
+ };
+ server.config.compositor.dock_position = position;
+ if (server.input.window_menu.dock != null) server.input.window_menu.close();
+ var it = server.outputs.iterator(.forward);
+ while (it.next()) |output| output.dock.invalidate();
+ server.scheduleFrames();
+}
+
fn onDockHeightChanged(owner: ?*anyopaque, _: usize, value: f32) void {
const s = section(owner);
const server = s.cc.server;
@@ -1821,3 +1947,26 @@ fn onDockHeightChanged(owner: ?*anyopaque, _: usize, value: f32) void {
while (it.next()) |output| output.dock.invalidate();
server.scheduleFrames();
}
+
+fn updateDockZoomLabel(s: *Section) void {
+ s.px[px_dock_hover_zoom].header_children[1].kind.text.content = std.fmt.bufPrint(&s.px[px_dock_hover_zoom].value_buf, "{d:.2}×", .{s.cc.server.config.compositor.dock_hover_zoom}) catch "?";
+ s.px[px_dock_hover_zoom].header_children[1].markDirty();
+}
+
+fn onDockHoverZoomChanged(owner: ?*anyopaque, _: usize, value: f32) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ const zoom = std.math.clamp(@round(value * 20) / 20, 1, loader.dock_hover_zoom_max);
+ if (zoom == server.config.compositor.dock_hover_zoom) return;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "dock_hover_zoom", zoom) catch |err| {
+ std.log.warn("could not save dock hover zoom: {}", .{err});
+ s.px[px_dock_hover_zoom].group_children[1].kind.slider.value = server.config.compositor.dock_hover_zoom;
+ s.px[px_dock_hover_zoom].group_children[1].markDirty();
+ return;
+ };
+ server.config.compositor.dock_hover_zoom = zoom;
+ updateDockZoomLabel(s);
+ var it = server.outputs.iterator(.forward);
+ while (it.next()) |output| output.dock.invalidate();
+ server.scheduleFrames();
+}
diff --git a/src/control_center/sections/services.zig b/src/control_center/sections/services.zig
index ce8407c..d762b91 100644
--- a/src/control_center/sections/services.zig
+++ b/src/control_center/sections/services.zig
@@ -53,7 +53,7 @@ fn tableText(value: []const u8, secondary: bool) W {
return .{ .kind = .{ .text = .{
.content = value,
.font_size = @floatCast(if (secondary) cairo.statusSize() else cairo.textSize()),
- .color = ui.theme.global.window_fg,
+ .color = panel.palette().fg,
} } };
}
/// Empty-table message, painted like a row so the table keeps its shape.
@@ -83,9 +83,9 @@ fn columnHeader(a: std.mem.Allocator, cc: *panel.ControlCenter, s: *Section, lab
caption.width = .{ .flex = 1 };
var children: std.ArrayList(W) = .empty;
try tryAppend(&children, a, caption);
- if (sorted) try tryAppend(&children, a, .{ .kind = .{ .icon = .{ .id = if (s.descending) .chevron_down else .chevron_up, .color = ui.theme.global.window_fg } }, .width = .{ .fixed = 8 }, .height = .{ .fixed = 8 } });
+ if (sorted) try tryAppend(&children, a, .{ .kind = .{ .icon = .{ .id = if (s.descending) .chevron_down else .chevron_up, .color = panel.palette().fg } }, .width = .{ .fixed = 8 }, .height = .{ .fixed = 8 } });
if (index < column_widths.len - 1) {
- var divider = ui.theme.global.window_fg;
+ var divider = panel.palette().fg;
divider[3] *= 0.2;
try tryAppend(&children, a, .{ .kind = .{ .rect = .{ .color = divider } }, .width = .{ .fixed = 1 }, .height = .{ .fixed = 18 } });
}
diff --git a/src/control_center/sections/shortcuts.zig b/src/control_center/sections/shortcuts.zig
index 581e27f..1799464 100644
--- a/src/control_center/sections/shortcuts.zig
+++ b/src/control_center/sections/shortcuts.zig
@@ -106,7 +106,8 @@ fn group(action: keys.Action) usize {
};
}
fn text(value: []const u8, dim: bool) W {
- return .{ .kind = .{ .text = .{ .content = value, .font_size = if (dim) 12 else 13, .weight = if (dim) 400 else 600, .color = if (dim) ui.theme.global.window_dim else ui.theme.global.window_fg } } };
+ const t = panel.palette();
+ return .{ .kind = .{ .text = .{ .content = value, .font_size = if (dim) 12 else 13, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } } };
}
fn button(cc: *panel.ControlCenter, id: usize, value: []const u8, icon: ?ui.layout.IconId, callback: *const fn (?*anyopaque, usize) void) W {
return .{ .kind = .{ .button = .{ .label = value, .icon = icon, .owner = cc, .id = id, .on_click = callback } }, .height = .{ .fixed = 32 }, .width = if (icon != null) .{ .fixed = 32 } else .auto };
@@ -126,7 +127,7 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
}
fn buildGroups(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !void {
- const t = ui.theme.global;
+ const t = panel.palette();
// Config reloads can replace string payloads and reorder bindings. Retain
// only the key identity; cancel if that row no longer denotes the same key.
if (s.editing) |i| {
diff --git a/src/files/AGENTS.md b/src/files/AGENTS.md
index 87fc130..1d85194 100644
--- a/src/files/AGENTS.md
+++ b/src/files/AGENTS.md
@@ -34,7 +34,7 @@ configuration is not checked).
* **App side:** `stepThumbs` re-requests only when the visible rows or
`view_revision` change; `drainThumbs` damages just the arrived icons through
`addDamage`. `itemIconRect` is the single source of icon geometry for
- painting and damage. Thumbnails are drawn in `drawItemIcon` (grid 48, list
+ painting and damage. Thumbnails are drawn in `drawItemIcon` (grid 54, list
24, drag icon 32) from a bilinear-filtered 128 px raster.
* **Shared freedesktop cache** (`$XDG_CACHE_HOME/thumbnails/normal|large`):
the name is the MD5 of the GLib-escaped `file://` URI, validated by
diff --git a/src/files/app.zig b/src/files/app.zig
index debd2f3..878747b 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -2167,11 +2167,19 @@ pub const App = struct {
fn itemInset(self: *App) i32 {
return if (self.compactList()) 0 else 20;
}
+ const GridCard = struct {
+ const padding_x: f64 = 10;
+ const padding_top: f64 = 8;
+ const icon_size: f64 = 54;
+ const name_baseline: f64 = 78;
+ const detail_baseline: f64 = 101;
+ const height: i32 = 112;
+ };
fn rowHeight(self: *App) i32 {
- return if (self.compactList()) 32 else if (self.list_view) 38 else 144;
+ return if (self.compactList()) 32 else if (self.list_view) 38 else GridCard.height + 8;
}
fn cardHeight(self: *App) i32 {
- return if (self.compactList()) 30 else if (self.list_view) 36 else 136;
+ return if (self.compactList()) 30 else if (self.list_view) 36 else GridCard.height;
}
/// Text baseline of a list row, from the row's top.
fn listBaseline(self: *App) f64 {
@@ -2392,9 +2400,9 @@ pub const App = struct {
} else {
const width: f64 = @floatFromInt(cell - 20);
return .{
- .x = x + 22,
- .y = y + 102,
- .w = @max(32, width - 44),
+ .x = x + GridCard.padding_x - 4,
+ .y = y + GridCard.detail_baseline - 15,
+ .w = @max(32, width - 2 * (GridCard.padding_x - 4)),
.h = 22,
};
}
@@ -3294,6 +3302,27 @@ pub const App = struct {
};
}
+ fn drawPackPlaceIcon(self: *App, cr: *c.cairo_t, index: usize, y: f64, alpha: f32) bool {
+ const name: []const u8 = switch (self.rowKind(index)) {
+ .builtin => |i| ([_][]const u8{ "user-home", "user-trash", "document-open-recent", "user-desktop", "folder-documents", "folder-download", "folder-pictures", "folder-music", "folder-videos", "folder" })[i],
+ .pin => |i| if (self.pins.items.items[i].kind == .file) "text-x-generic" else "folder",
+ .device => return false,
+ };
+ const size = 24 * self.scale;
+ const entry = icons.getPack(self.theme_cfg, self.io, name, size) orelse
+ (if (index >= places_start and std.mem.startsWith(u8, name, "folder-")) icons.getPack(self.theme_cfg, self.io, "folder", size) else null) orelse return false;
+ const surface = c.cairo_image_surface_create_for_data(@ptrCast(@constCast(entry.pixels.ptr)), c.CAIRO_FORMAT_ARGB32, entry.size, entry.size, entry.size * 4) orelse return false;
+ defer c.cairo_surface_destroy(surface);
+ c.cairo_save(cr);
+ defer c.cairo_restore(cr);
+ c.cairo_translate(cr, 21, y + 3);
+ const scale = 24 / @as(f64, @floatFromInt(entry.size));
+ c.cairo_scale(cr, scale, scale);
+ c.cairo_set_source_surface(cr, surface, 0, 0);
+ c.cairo_paint_with_alpha(cr, alpha);
+ return true;
+ }
+
fn renderSidebar(self: *App, cr: *c.cairo_t) void {
const width: f64 = @floatFromInt(self.sidebarWidth());
if (width == 0) return;
@@ -3312,9 +3341,7 @@ pub const App = struct {
const glide = self.nav_hover.frame;
if (glide.alpha > 0) {
const box = self.navHighlight(glide);
- roundedRect(cr, box.x, box.y, box.w, box.h, 5);
- setSource(cr, withAlpha(ui_theme.global.app_item_hover, glide.alpha));
- c.cairo_fill(cr);
+ shell_ui.drawSidebarHover(cr, .{ .x = @floatCast(box.x), .y = @floatCast(box.y), .w = @floatCast(box.w), .h = @floatCast(box.h) }, glide.alpha);
}
setSource(cr, ui_theme.global.sidebarForeground());
drawText(cr, "PLACES", 24, @floatFromInt(self.placeY(places_start) - 12), shell_ui.headingSize(), true);
@@ -3342,7 +3369,9 @@ pub const App = struct {
c.cairo_fill(cr);
}
setSource(cr, withAlpha(ui_theme.global.app_icon, alpha));
- if (i < places_start) {
+ if (self.drawPackPlaceIcon(cr, i, y, alpha)) {
+ // The pack's colour artwork replaces this place's plain glyph.
+ } else 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 = switch (i) {
@@ -5637,11 +5666,11 @@ pub const App = struct {
if (cut) c.cairo_push_group(cr);
const icon = self.itemIconRect(index);
self.drawItemIcon(cr, item, icon.x, icon.y, icon.w);
- const label_x = x - self.horizontalOffset() + (if (self.list_view) @as(f64, 42) else 26);
+ const label_x = x - self.horizontalOffset() + (if (self.list_view) @as(f64, 42) else GridCard.padding_x);
setSource(cr, ui_theme.global.window_fg);
- const name_width = if (self.list_view) self.listColumn(0).w - 46 else width - 42;
+ const name_width = if (self.list_view) self.listColumn(0).w - 46 else width - 2 * GridCard.padding_x;
// A path that does not fit loses its head, so the file's own name stays readable.
- const name_y = y + (if (self.list_view) baseline else 94);
+ const name_y = y + (if (self.list_view) baseline else GridCard.name_baseline);
if (item.label.len > 0) drawHeadEllipsis(cr, item.label, label_x, name_y, name_width, shell_ui.textSize(), false) else drawEllipsis(cr, item.name, label_x, name_y, name_width, shell_ui.textSize(), false);
var buf: [64]u8 = undefined;
var size_buf: [64]u8 = undefined;
@@ -5678,26 +5707,26 @@ pub const App = struct {
} else {
if (item.is_symlink) {
setSource(cr, ui_theme.global.window_fg);
- drawText(cr, itemType(item), x + 26, y + 117, shell_ui.textSize(), false);
+ drawText(cr, itemType(item), label_x, y + GridCard.detail_baseline, shell_ui.textSize(), false);
} else if (item.is_dir) {
if (disp.is_running) {
setSource(cr, ui_theme.global.window_fg);
- drawText(cr, disp.text, x + 26, y + 117, shell_ui.textSize(), false);
+ drawText(cr, disp.text, label_x, y + GridCard.detail_baseline, shell_ui.textSize(), false);
const tw = measureText(cr, disp.text, shell_ui.textSize(), false);
- drawSpinner(cr, x + 26 + tw + 10, y + 117 - 4, 4.5);
+ drawSpinner(cr, label_x + tw + 10, y + GridCard.detail_baseline - 4, 4.5);
} else if (is_size_hovered and std.mem.eql(u8, disp.text, "—")) {
- roundedRect(cr, x + 22, y + 117 - 14, 24, 18, 4);
+ roundedRect(cr, label_x - 4, y + GridCard.detail_baseline - 14, 24, 18, 4);
setSource(cr, ui_theme.global.surface_hover);
c.cairo_fill(cr);
setSource(cr, ui_theme.global.window_fg);
- drawText(cr, "—", x + 28, y + 117, shell_ui.textSize(), false);
+ drawText(cr, "—", label_x + 2, y + GridCard.detail_baseline, shell_ui.textSize(), false);
} else {
setSource(cr, ui_theme.global.window_fg);
- drawText(cr, disp.text, x + 26, y + 117, shell_ui.textSize(), false);
+ drawText(cr, disp.text, label_x, y + GridCard.detail_baseline, shell_ui.textSize(), false);
}
} else {
setSource(cr, ui_theme.global.window_fg);
- drawText(cr, formatSize(item.bytes, &buf), x + 26, y + 117, shell_ui.textSize(), false);
+ drawText(cr, formatSize(item.bytes, &buf), label_x, y + GridCard.detail_baseline, shell_ui.textSize(), false);
}
}
if (cut) {
@@ -5742,10 +5771,10 @@ pub const App = struct {
/// Where an item's icon (or thumbnail) is drawn, in window coordinates.
fn itemIconRect(self: *App, index: i32) header.Rect {
const cols = self.columns();
- const size: f64 = if (self.list_view) 24 else 48;
+ const size: f64 = if (self.list_view) 24 else GridCard.icon_size;
return .{
- .x = @as(f64, @floatFromInt(self.sidebarWidth() + 20 + @mod(index, cols) * self.cellWidth())) + (if (self.list_view) @as(f64, 12) else 26) - self.horizontalOffset(),
- .y = @as(f64, @floatFromInt(self.viewTop() + self.itemInset() + @divTrunc(index, cols) * self.rowHeight() - self.scroll_y)) + (if (self.compactList()) @as(f64, 3) else if (self.list_view) @as(f64, 6) else 20),
+ .x = @as(f64, @floatFromInt(self.sidebarWidth() + 20 + @mod(index, cols) * self.cellWidth())) + (if (self.list_view) @as(f64, 12) else GridCard.padding_x) - self.horizontalOffset(),
+ .y = @as(f64, @floatFromInt(self.viewTop() + self.itemInset() + @divTrunc(index, cols) * self.rowHeight() - self.scroll_y)) + (if (self.compactList()) @as(f64, 3) else if (self.list_view) @as(f64, 6) else GridCard.padding_top),
.w = size,
.h = size,
};
@@ -6330,7 +6359,7 @@ test "grid hit testing respects gutters, scrolling and responsive columns" {
try std.testing.expectEqual(@as(?usize, 3), app.itemAt(250, 308));
try std.testing.expectEqual(@as(?usize, null), app.itemAt(220, 158));
try std.testing.expectEqual(@as(?usize, null), app.itemAt(450, 158));
- try std.testing.expectEqual(@as(?usize, null), app.itemAt(250, 273));
+ try std.testing.expectEqual(@as(?usize, null), app.itemAt(250, 248));
app.scroll_y = 156;
try std.testing.expectEqual(@as(?usize, 3), app.itemAt(250, 158));
app.revealIndex(19);
@@ -6566,6 +6595,10 @@ test "history restores names and scroll while tolerating removed items" {
}
test "retained hover repairs match complete Cairo rasters at scale 1 and 1.5" {
+ const saved_theme = ui_theme.global;
+ defer ui_theme.global = saved_theme;
+ // Exercise the illuminated sidebar edge as it moves and fades, too.
+ ui_theme.global.app_sidebar_hover_marker = .{ 1, 0.95, 0.84, 1 };
const before = anim.currentSettings();
defer anim.applySettings(before);
anim.applySettings(.{ .reduced_motion = .off });
@@ -6870,16 +6903,16 @@ test "file drag threshold preserves multi-selection and ordinary release collaps
try testItems(&app, 10);
app.items.items[0].selected = true;
app.items.items[1].selected = true;
- app.handleMotion(250, 158);
+ app.handleMotion(310, 158);
app.handleButton(0x110, true);
try std.testing.expect(app.items.items[1].selected);
- app.handleMotion(253, 158);
+ app.handleMotion(313, 158);
try std.testing.expect(!app.drag_ready);
- app.handleMotion(270, 158);
+ app.handleMotion(330, 158);
try std.testing.expect(app.drag_ready);
app.handleButton(0x110, false);
try std.testing.expect(app.items.items[1].selected);
- app.handleMotion(250, 158);
+ app.handleMotion(310, 158);
app.handleButton(0x110, true);
app.handleButton(0x110, false);
try std.testing.expect(!app.items.items[1].selected);
@@ -6888,11 +6921,11 @@ test "file drag threshold preserves multi-selection and ordinary release collaps
app.last_click_index = null;
app.handleButton(0x110, true);
try std.testing.expect(app.items.items[0].selected);
- app.handleMotion(270, 158);
+ app.handleMotion(330, 158);
try std.testing.expect(app.drag_ready);
app.handleButton(0x110, false);
try std.testing.expect(app.items.items[0].selected);
- app.handleMotion(250, 158);
+ app.handleMotion(310, 158);
app.handleButton(0x110, true);
app.handleButton(0x110, false);
try std.testing.expect(!app.items.items[0].selected);
diff --git a/src/files/settings.zig b/src/files/settings.zig
index 54b86e3..94cc69c 100644
--- a/src/files/settings.zig
+++ b/src/files/settings.zig
@@ -272,13 +272,16 @@ test "Files keeps theme colours and font names alive after parsing" {
defer _ = c.close(fd);
defer _ = c.unlink(&theme_path);
const io = std.testing.io;
- try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = &theme_path, .data = "[theme]\nfont = \"Inter\"\napp_bg = \"#102030\"\n" });
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = &theme_path, .data = "[theme]\nfont = \"Inter\"\napp_bg = \"#102030\"\napp_surface_hover = \"rgba(229,214,195,0.96)\"\napp_sidebar_hover = \"rgba(116,92,72,0.96)\"\n" });
var settings = Settings{ .theme_path = &theme_path };
const t = settings.poll(std.testing.allocator, io).?;
defer t.deinit();
try std.testing.expectApproxEqAbs(@as(f32, 0x20) / 255.0, t.value.app_bg[1], 1e-6);
try std.testing.expectEqualStrings("Inter", t.value.font);
try std.testing.expectEqualStrings((theme.Theme{}).mono_font, t.value.mono_font);
+ try std.testing.expectEqual(t.value.app_surface_hover.?, t.value.forApp().surface_hover);
+ try std.testing.expectEqual(t.value.app_sidebar_hover.?, t.value.sidebarHover());
+ try std.testing.expectEqual((theme.Theme{}).app_item_hover, (theme.Theme{}).sidebarHover());
}
// Reuse the shell's value parsers, without importing compositor dependencies
diff --git a/src/icon_cache.zig b/src/icon_cache.zig
index 4c1fe68..ab1ff3f 100644
--- a/src/icon_cache.zig
+++ b/src/icon_cache.zig
@@ -59,24 +59,31 @@ const pthread = std.posix.system;
var cache_mutex: pthread.pthread_mutex_t = pthread.PTHREAD_MUTEX_INITIALIZER;
var cache: std.StringHashMapUnmanaged(?Entry) = .empty;
-// Keyed by "<size_px>:<icon_name>", not name alone: the taskbar and the
-// window titlebar each ask for their own fixed size for the life of the
-// process (Server.scale never changes after startup), but they're different
-// sizes from each other, and a name-only key would let whichever asked first
-// silently hand its wrong-size raster to the other. A cached `null` records
-// "looked up, not found" so a repeatedly-unmatched app_id doesn't re-walk
-// the filesystem on every caller.
+// Generation, lookup scope and raster size are part of the key: a pack-only
+// miss must not hide an installed icon, or a small sidebar raster replace a
+// larger desktop one. Missing icons are cached too, avoiding filesystem work
+// on every repaint.
pub fn get(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32) ?Entry {
+ return getScoped(cfg, io, icon_name, size_px, false);
+}
+
+/// Pack artwork for places that otherwise keep their built-in glyphs.
+pub fn getPack(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32) ?Entry {
+ if (cfg.override_root.len == 0) return null;
+ return getScoped(cfg, io, icon_name, size_px, true);
+}
+
+fn getScoped(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32, pack_only: bool) ?Entry {
_ = pthread.pthread_mutex_lock(&cache_mutex);
defer _ = pthread.pthread_mutex_unlock(&cache_mutex);
if (icon_name.len == 0) return null;
var key_buf: [512]u8 = undefined;
- const key = std.fmt.bufPrint(&key_buf, "{d}:{d}:{s}", .{ cfg.generation, size_px, icon_name }) catch
- return lookup(cfg, io, icon_name, size_px) catch null;
+ const key = std.fmt.bufPrint(&key_buf, "{d}:{}:{d}:{s}", .{ cfg.generation, pack_only, size_px, icon_name }) catch
+ return lookupScoped(cfg, io, icon_name, size_px, pack_only) catch null;
if (cache.get(key)) |entry| return entry;
- const entry = lookup(cfg, io, icon_name, size_px) catch |err| blk: {
+ const entry = lookupScoped(cfg, io, icon_name, size_px, pack_only) catch |err| blk: {
log.warn("get: icon lookup failed for '{s}': {}", .{ icon_name, err });
break :blk null;
};
@@ -92,7 +99,11 @@ pub fn get(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32)
// `cache` also hold the same pixel buffers would leave it handing out a
// dangling pointer the moment icon_service frees an evicted raster.
pub fn lookup(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32) !?Entry {
- if (std.mem.eql(u8, icon_name, "builtin:redi-logo")) {
+ return lookupScoped(cfg, io, icon_name, size_px, false);
+}
+
+fn lookupScoped(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i32, pack_only: bool) !?Entry {
+ if (!pack_only and std.mem.eql(u8, icon_name, "builtin:redi-logo")) {
const bytes = ui.shell_icons.redi_logo;
var err: ?*GError = null;
const handle = rsvg_handle_new_from_data(bytes.ptr, bytes.len, &err) orelse {
@@ -102,7 +113,7 @@ pub fn lookup(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i3
defer g_object_unref(handle);
return Entry{ .pixels = renderSvg(handle, size_px) orelse return null, .size = size_px };
}
- if (std.mem.startsWith(u8, icon_name, "/")) {
+ if (!pack_only and std.mem.startsWith(u8, icon_name, "/")) {
const is_svg = std.mem.endsWith(u8, icon_name, ".svg");
const is_png = std.mem.endsWith(u8, icon_name, ".png");
if (is_svg) {
@@ -136,7 +147,7 @@ pub fn lookup(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px: i3
}
}
- const found = (try icon_theme.find(gpa, io, cfg, icon_name, size_px)) orelse return null;
+ const found = (if (pack_only) try icon_theme.findPack(gpa, io, cfg, icon_name) else try icon_theme.find(gpa, io, cfg, icon_name, size_px)) orelse return null;
defer gpa.free(found.path);
if (found.svg) {
diff --git a/src/icon_theme.zig b/src/icon_theme.zig
index d12757e..b31b7ad 100644
--- a/src/icon_theme.zig
+++ b/src/icon_theme.zig
@@ -105,11 +105,8 @@ const Theme = struct {
}
};
-// theme -> theme's Inherits (recursive, deduped) -> "hicolor" (mandatory
-// fallback even if undeclared) -> flat /usr/share/pixmaps.
-pub fn find(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8, target_px: i32) !?Found {
- _ = pthread.pthread_mutex_lock(&index_mutex);
- defer _ = pthread.pthread_mutex_unlock(&index_mutex);
+/// Flat artwork supplied by the active pack, without an installed-theme fallback.
+pub fn findPack(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8) !?Found {
if (cfg.override_root.len > 0 and @import("config").theme_pack.relative(icon_name) and std.mem.indexOfScalar(u8, icon_name, '/') == null) {
for ([_][]const u8{ "svg", "png" }) |ext| {
const rel = try std.fmt.allocPrint(allocator, "icons/{s}.{s}", .{ icon_name, ext });
@@ -120,6 +117,15 @@ pub fn find(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8, ta
} else |_| {}
}
}
+ return null;
+}
+
+// pack -> theme -> theme's Inherits (recursive, deduped) -> "hicolor"
+// (mandatory fallback even if undeclared) -> flat /usr/share/pixmaps.
+pub fn find(allocator: Allocator, io: Io, cfg: Config, icon_name: []const u8, target_px: i32) !?Found {
+ if (try findPack(allocator, io, cfg, icon_name)) |found| return found;
+ _ = pthread.pthread_mutex_lock(&index_mutex);
+ defer _ = pthread.pthread_mutex_unlock(&index_mutex);
// Every theme-name string this call ever allocates (Inherits= entries),
// freed once at the end. `pending`/`visited` below only ever hold slices
// borrowed from here or from `cfg.theme_name`, so nothing can dangle.
diff --git a/src/ipc/animations.zig b/src/ipc/animations.zig
index 09ad109..02852d0 100644
--- a/src/ipc/animations.zig
+++ b/src/ipc/animations.zig
@@ -90,6 +90,8 @@ fn appendWindow(
try appendLive(allocator, list, zoom_site, toplevel.zoom_anim, now_ms);
const boost_site = try std.fmt.allocPrint(allocator, "window.{d}.zoom_boost", .{toplevel.id});
try appendLive(allocator, list, boost_site, toplevel.zoom_boost, now_ms);
+ const lift_site = try std.fmt.allocPrint(allocator, "window.{d}.drag_lift", .{toplevel.id});
+ try appendLive(allocator, list, lift_site, toplevel.drag_lift, now_ms);
const mix_site = try std.fmt.allocPrint(allocator, "window.{d}.peek_mix", .{toplevel.id});
try appendLive(allocator, list, mix_site, toplevel.peek_mix, now_ms);
const level_site = try std.fmt.allocPrint(allocator, "window.{d}.peek_level", .{toplevel.id});
@@ -209,8 +211,10 @@ fn captureWindow(
try anim.captureIfLive(allocator, list, &toplevel.chip_alpha, .titlebar_chip_fade, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.zoom_anim, .window_zoom, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.zoom_boost, .window_zoom, now_ms);
+ try anim.captureIfLive(allocator, list, &toplevel.drag_lift, .window_drag, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.peek_mix, .window_peek, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.peek_level, .window_peek, now_ms);
+ try anim.captureIfLive(allocator, list, &toplevel.dim_anim, .window_dim, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.map_motion, .window_open, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.map_opacity, if (toplevel.closing) .window_close else .window_open, now_ms);
try anim.captureIfLive(allocator, list, &toplevel.move_x, .window_move, now_ms);
diff --git a/src/ipc/handlers.zig b/src/ipc/handlers.zig
index eb83d70..48bafb2 100644
--- a/src/ipc/handlers.zig
+++ b/src/ipc/handlers.zig
@@ -286,7 +286,7 @@ pub fn handleRequest(
.window_id = chip.toplevel.id,
.title = chip.toplevel.title(),
.box = .{
- .x = tb.box.x + @as(i32, @intFromFloat(chip.target_x)),
+ .x = tb.box.x + @as(i32, @intFromFloat(@round(chip.renderX(now)))),
.y = tb.box.y + @divTrunc(tb.box.height - 42, 2),
.width = @as(i32, @intFromFloat(chip.width)),
.height = 42,
@@ -298,6 +298,8 @@ pub fn handleRequest(
var right_items = std.ArrayList(protocol.TaskbarItemData).empty;
const items = server.config.compositor.taskbar_items;
for (items.order) |item| {
+ // Keep the existing status-item IPC contract.
+ if (item == .start or item == .windows or item == .tray) continue;
const box = tb.itemBox(item);
try right_items.append(allocator, .{
.name = @tagName(item),
@@ -2256,7 +2258,7 @@ pub fn buildTaskbarWidgetTree(
.label = "Start",
.box = .{ .x = sbox.x - bar.box.x, .y = sbox.y - bar.box.y, .width = sbox.width, .height = sbox.height },
.global_box = .{ .x = sbox.x, .y = sbox.y, .width = sbox.width, .height = sbox.height },
- .visible = true,
+ .visible = server.config.compositor.taskbar_items.shown(.start),
.is_disabled = false,
});
diff --git a/src/network/popup.zig b/src/network/popup.zig
index ff0f2a2..48b36bc 100644
--- a/src/network/popup.zig
+++ b/src/network/popup.zig
@@ -1,4 +1,6 @@
const std = @import("std");
+const popup_style = @import("../popup_style.zig");
+const glass = @import("../glass.zig");
const wlr = @import("wlroots");
const xkb = @import("xkbcommon");
const Output = @import("../Output.zig");
@@ -51,6 +53,7 @@ pub const Popup = struct {
sonar_shown: bool = false,
sonar_fade_start: i64 = -1,
node_data: scene.SceneData = undefined,
+ glass_effect: ?*glass.Effect = null,
caret: Caret,
factor: f32 = 1,
height: f32 = 400,
@@ -130,6 +133,7 @@ pub const Popup = struct {
pub fn tick(self: *Popup, now: i64) bool {
_ = self.slide.sampleChanged(now, anim.quantum_alpha);
present.applySlide(self.buffer_node, self.panel_box, self.slide.value(now), if (self.output.server.config.compositor.taskbar_position == .top) -20 else 20);
+ popup_style.configureGlass(&self.glass_effect, self.output.server.glass_engine, self.buffer_node, self.factor);
if (self.caret.placed) |*p| p.origin_y = @floatFromInt(self.buffer_node.node.y);
const active = self.caret.frame(now);
self.paintSonar(now);
@@ -550,24 +554,9 @@ pub const Popup = struct {
var r: paint.Renderer = .{ .pixels = buf.pixels, .width = buf.width, .height = buf.height, .scale = scale * self.factor };
const t = theme.shellPalette();
r.palette = t;
- var bg = t.window_bg;
- bg[3] = 1;
- r.fillRect(0, 0, width, self.height - 12, .{ .color = bg, .radius = 9, .border_width = 1, .border_color = t.border_hover });
const tip = std.math.clamp(@as(f32, @floatFromInt(anchor.x + @divTrunc(anchor.width, 2) - left)) / self.factor, 24, width - 24);
- // Same taskbar pointer as the battery/calendar panels.
- for (0..@intCast(buf.height)) |iy| {
- const y = (@as(f32, @floatFromInt(iy)) + 0.5) / r.scale;
- if (y < self.height - 13) continue;
- for (0..@intCast(buf.width)) |ix| {
- const x = (@as(f32, @floatFromInt(ix)) + 0.5) / r.scale;
- const d = (@abs(x - tip) + y - self.height) / @sqrt(@as(f32, 2));
- const coverage = std.math.clamp(0.5 - d * r.scale, 0, 1);
- if (coverage == 0) continue;
- const mix = (1 - std.math.clamp((-d - 1) * r.scale + 0.5, 0, 1)) * t.border_hover[3];
- buf.pixels[iy * @as(usize, @intCast(buf.width)) + ix] = (@import("../color.zig").Straight{ .r = bg[0] * (1 - mix) + t.border_hover[0] * mix, .g = bg[1] * (1 - mix) + t.border_hover[1] * mix, .b = bg[2] * (1 - mix) + t.border_hover[2] * mix, .a = coverage }).argb();
- }
- }
- if (self.output.server.config.compositor.taskbar_position == .top) buf.flipVertical();
+ popup_style.background(&r, buf, width, self.height, 12, tip, self.output.server.config.compositor.taskbar_position == .top);
+ const card_t = popup_style.cardPalette(t);
self.hit_count = 0;
label(&r, 24, 14, 180, 42, "Wi-Fi", 23, t.window_fg, true);
// Same switch as Settings; the hit target is padded for the pointer.
@@ -577,7 +566,7 @@ 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| {
+ if (t.popup_card_bg == null and 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;
@@ -595,16 +584,29 @@ pub const Popup = struct {
const extra = self.shownHeight(net);
const box: Rect = .{ .x = 12, .y = y, .w = width - 24, .h = row_height };
_ = 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;
+ if (t.popup_card_bg != null) {
+ popup_style.card(&r, 16, y + 3, width - 32, row_height - 6);
+ const hover_alpha = self.item_hover.frame.alpha * @max(0, 1 - @abs(self.item_hover.frame.row - @as(f32, @floatFromInt(i))));
+ const alpha: f32 = if (selected or self.focused(.row, i)) 1 else hover_alpha;
+ if (alpha > 0) {
+ var fill = card_t.surface_hover;
+ var border = t.accent;
+ fill[3] *= alpha;
+ border[3] *= alpha;
+ r.fillRect(16, y + 3, width - 32, row_height - 6, .{ .color = fill, .radius = t.popup_card_radius, .border_width = 1, .border_color = border });
+ }
+ } else 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) {
+ if (t.popup_card_bg != null) r.fillRect(19, y + 16, 3, row_height - 32, .{ .color = t.accent, .radius = 1 }) else r.fillRect(12, y + 5, 3, row_height - 10 + extra, .{ .color = t.accent, .radius = 1 });
+ }
+ var signal_color = card_t.window_fg;
signal_color[3] *= 0.45 + @as(f32, @floatFromInt(net.strength)) / 100 * 0.55;
r.drawIcon(30, y + 18, 28, 28, .{ .id = .wifi, .color = signal_color });
- label(&r, 78, y + 8, 272, 26, network.networkName(&net), 16, t.window_fg, false);
+ label(&r, 78, y + 8, 272, 26, network.networkName(&net), 16, card_t.window_fg, false);
const subtitle = network.networkSubtitle(net);
- label(&r, 78, y + 34, 270, 22, subtitle, 12, t.window_dim, false);
- if (net.security != .open) r.drawIcon(353, y + 23, 18, 18, .{ .id = .lock, .color = t.window_dim });
- if (selected or net.connected) r.drawIcon(379, y + 25, 14, 14, .{ .id = if (selected) .chevron_up else .chevron_right, .color = t.window_fg });
+ label(&r, 78, y + 34, 270, 22, subtitle, 12, card_t.window_dim, false);
+ if (net.security != .open) r.drawIcon(353, y + 23, 18, 18, .{ .id = .lock, .color = card_t.window_dim });
+ if (selected or net.connected) r.drawIcon(379, y + 25, 14, 14, .{ .id = if (selected) .chevron_up else .chevron_right, .color = card_t.window_fg });
y += row_height;
if (selected) self.paintFormClipped(&r, y, extra);
y += extra;
@@ -636,6 +638,7 @@ pub const Popup = struct {
self.buffer_node.setBuffer(&buf.base);
self.buffer_node.setDestSize(w, h);
present.applySlide(self.buffer_node, self.panel_box, self.slide.value(anim.nowMs()), if (self.output.server.config.compositor.taskbar_position == .top) -20 else 20);
+ popup_style.configureGlass(&self.glass_effect, self.output.server.glass_engine, self.buffer_node, self.factor);
self.sonar_step = -1;
self.paintSonar(anim.nowMs());
if (self.caret.placed) |*p| {
diff --git a/src/popup_style.zig b/src/popup_style.zig
new file mode 100644
index 0000000..19a41bf
--- /dev/null
+++ b/src/popup_style.zig
@@ -0,0 +1,74 @@
+//! Shared taskbar popup surfaces; controls still use the shared widgets.
+const std = @import("std");
+const wlr = @import("wlroots");
+const ui = @import("ui");
+const glass = @import("glass.zig");
+const PanelBuffer = @import("panel_buffer.zig").PanelBuffer;
+
+pub fn configureGlass(effect: *?*glass.Effect, engine: ?*glass.Engine, node: *wlr.SceneBuffer, factor: f32) void {
+ const t = ui.theme.global;
+ if (!t.popup_blur) {
+ glass.Effect.detach(effect.*);
+ effect.* = null;
+ return;
+ }
+ if (effect.* == null) effect.* = glass.Engine.attach(engine, node, &node.node, .panel);
+ glass.Effect.configure(effect.*, t.popup_radius * factor, node.opacity);
+}
+
+pub fn background(r: *ui.paint.Renderer, buf: *PanelBuffer, width: f32, height: f32, tail: f32, tip: f32, top: bool) void {
+ const t = r.palette.?;
+ var bg = t.popup_bg orelse t.window_bg;
+ if (t.popup_bg == null) bg[3] = 1;
+ const border = t.popup_border orelse t.border_hover;
+ // A glass panel uses one rounded footprint, matching the backdrop clip.
+ r.fillRect(0, 0, width, height - (if (t.popup_blur) @as(f32, 0) else tail), .{ .color = bg, .radius = t.popup_radius, .border_width = 1, .border_color = border });
+ if (t.popup_blur) {
+ // Soft light along the inside edge gives the glass a little depth.
+ r.fillRect(1, 1, width - 2, height - 2, .{ .color = .{ 0, 0, 0, 0 }, .radius = @max(0, t.popup_radius - 1), .border_width = 1, .border_color = .{ border[0], border[1], border[2], border[3] * 0.18 } });
+ return;
+ }
+ for (0..@intCast(buf.height)) |iy| {
+ const y = (@as(f32, @floatFromInt(iy)) + 0.5) / r.scale;
+ if (y < height - tail - 1) continue;
+ for (0..@intCast(buf.width)) |ix| {
+ const x = (@as(f32, @floatFromInt(ix)) + 0.5) / r.scale;
+ const d = (@abs(x - tip) + y - height) / @sqrt(@as(f32, 2));
+ const coverage = std.math.clamp(0.5 - d * r.scale, 0, 1);
+ if (coverage == 0) continue;
+ const mix = (1 - std.math.clamp((-d - 1) * r.scale + 0.5, 0, 1)) * border[3];
+ buf.pixels[iy * @as(usize, @intCast(buf.width)) + ix] = (@import("color.zig").Straight{
+ .r = bg[0] * (1 - mix) + border[0] * mix,
+ .g = bg[1] * (1 - mix) + border[1] * mix,
+ .b = bg[2] * (1 - mix) + border[2] * mix,
+ .a = coverage * bg[3],
+ }).argb();
+ }
+ }
+ if (top) buf.flipVertical();
+}
+
+pub fn cardPalette(t: ui.theme.Theme) ui.theme.Theme {
+ var result = t;
+ result.window_fg = t.popup_card_fg orelse t.window_fg;
+ result.fg = t.popup_card_fg orelse t.fg;
+ result.window_dim = t.popup_card_dim orelse t.window_dim;
+ result.dim = t.popup_card_dim orelse t.dim;
+ result.faint = t.popup_card_dim orelse t.faint;
+ if (t.popup_card_bg != null) {
+ result.surface_hover = t.accent;
+ result.surface_hover[3] = 0.18;
+ result.border_soft = t.popup_card_border orelse t.border_soft;
+ }
+ return result;
+}
+
+pub fn card(r: *ui.paint.Renderer, x: f32, y: f32, w: f32, h: f32) void {
+ const t = r.palette.?;
+ r.fillRect(x, y, w, h, .{
+ .color = t.popup_card_bg orelse t.surface_hover,
+ .radius = t.popup_card_radius,
+ .border_width = if (t.popup_card_border != null) 1 else 0,
+ .border_color = t.popup_card_border orelse t.border_soft,
+ });
+}
diff --git a/src/projection.c b/src/projection.c
index aed044b..ba6162f 100644
--- a/src/projection.c
+++ b/src/projection.c
@@ -132,18 +132,27 @@ struct leaf {
// evaluates it after this tree's own zoom and scale, so it follows its window
// and an inner scale never changes it. A clipped tree inside another replaces
// the outer shape for its own leaves; nothing intersects them;
-// * unclipped: ends the inherited clip for the subtree. A popup's scene tree is a
-// child of its parent surface's, so it sits under the window's clipped tree in
-// the source graph while belonging to no window shape. The subtree's own clip,
-// if it sets one, still applies;
+// * unclipped: ends the inherited clip and dim for the subtree. A popup's scene
+// tree is a child of its parent surface's, so it sits under the window's clipped
+// tree in the source graph while belonging to no window frame. The subtree's own
+// clip or dim, if it sets one, still applies;
+// * dim: every leaf under the tree loses this fraction of its brightness and of
+// its colour (`rediwm_content.dim_*`), inherited like the clip. It is a field of
+// the item, so a change of it damages what the leaves show with no rule of its
+// own, and the pass applies it per draw. A subtree's own dim replaces the outer
+// one, and `unclipped` ends it as it ends the clip;
// * shadow: every leaf under the tree is the analytic shadow of this shape
// (REDIWM_ITEM_SHADOW), resolved like the clip;
// * inert: the subtree is shown but takes no input: the pick passes through it
// to what is below (a window sliding off a workspace it has left).
+struct dim {
+ float brightness, saturation;
+};
struct tree_props {
struct wlr_addon addon;
- bool has_zoom, has_scale, has_clip, unclipped, has_shadow, inert;
+ bool has_zoom, has_scale, has_clip, unclipped, has_shadow, inert, has_dim;
double zoom, scale;
+ struct dim dim;
struct rediwm_clip_spec clip;
struct rediwm_shadow_spec shadow;
// The clip as the last resolve() saw it in layout space, to tell a changed
@@ -226,6 +235,22 @@ bool rediwm_projection_set_tree_shadow(struct wlr_scene_node *node,
props->has_shadow = true;
return true;
}
+bool rediwm_projection_set_tree_dim(struct wlr_scene_node *node, float brightness, float saturation) {
+ if (!isfinite(brightness) || !isfinite(saturation) || brightness < 0 || brightness > 1 ||
+ saturation < 0 || saturation > 1)
+ return false;
+ if (brightness == 0 && saturation == 0) {
+ // Nothing taken away is no dim; a tree that has none gets no addon for it.
+ struct tree_props *props = tree_props_find(node);
+ if (props) props->has_dim = false;
+ return true;
+ }
+ struct tree_props *props = tree_props_get(node);
+ if (!props) return false;
+ props->dim = (struct dim){brightness, saturation};
+ props->has_dim = true;
+ return true;
+}
bool rediwm_projection_set_tree_unclipped(struct wlr_scene_node *node, bool unclipped) {
struct tree_props *props = unclipped ? tree_props_get(node) : tree_props_find(node);
if (unclipped && !props) return false;
@@ -559,7 +584,7 @@ static void damage_clip_change(struct rediwm_projection *p, const struct rediwm_
static void resolve_node(struct rediwm_projection *p, struct group *g,
struct wlr_scene_node *node, double x, double y,
bool enabled, bool inert, struct rediwm_xform t,
- const struct rediwm_clip *clip,
+ const struct rediwm_clip *clip, const struct dim *dim,
const struct rediwm_shadow *shadow) {
x += node->x;
y += node->y;
@@ -572,8 +597,12 @@ static void resolve_node(struct rediwm_projection *p, struct group *g,
// Window zoom composes with the camera, around the frame origin.
if (props->has_zoom) t = rediwm_xform_scale_about(t, props->zoom, x, y);
if (props->has_scale) t = rediwm_xform_scale_about(t, props->scale, x, y);
- if (props->unclipped) clip = NULL;
+ if (props->unclipped) {
+ clip = NULL;
+ dim = NULL;
+ }
if (props->inert) inert = true;
+ if (props->has_dim) dim = &props->dim;
if (props->has_clip) {
here = rediwm_clip_resolve(t, x, y, &props->clip);
clip = &here;
@@ -594,7 +623,7 @@ static void resolve_node(struct rediwm_projection *p, struct group *g,
}
struct wlr_scene_node *child;
wl_list_for_each(child, &wlr_scene_tree_from_node(node)->children, link)
- resolve_node(p, g, child, x, y, enabled, inert, t, clip, shadow);
+ resolve_node(p, g, child, x, y, enabled, inert, t, clip, dim, shadow);
return;
}
struct leaf *l = get_leaf(p, node);
@@ -655,6 +684,10 @@ static void resolve_node(struct rediwm_projection *p, struct group *g,
content->color_encoding = b->color_encoding;
content->color_range = b->color_range;
}
+ if (dim) {
+ item->content.dim_brightness = dim->brightness;
+ item->content.dim_saturation = dim->saturation;
+ }
if (shadow && node->type == WLR_SCENE_NODE_BUFFER) {
item->kind = REDIWM_ITEM_SHADOW;
l->shadow = *shadow;
@@ -1055,7 +1088,7 @@ static void resolve(struct rediwm_projection *p, double z, double cx, double cy,
g->seen = true;
g->enabled = node->enabled;
wl_list_insert(p->paint.prev, &g->paint);
- resolve_node(p, g, node, 0, 0, true, false, t, NULL, NULL);
+ resolve_node(p, g, node, 0, 0, true, false, t, NULL, NULL, NULL);
}
}
static void damage_restacked(struct rediwm_projection *p);
diff --git a/src/projection.h b/src/projection.h
index dcd4f9f..bcfe4a2 100644
--- a/src/projection.h
+++ b/src/projection.h
@@ -61,8 +61,13 @@ bool rediwm_projection_set_tree_clip(struct wlr_scene_node *, const struct rediw
// radius or softness that is negative or not finite.
struct rediwm_shadow_spec;
bool rediwm_projection_set_tree_shadow(struct wlr_scene_node *, const struct rediwm_shadow_spec *);
-// Ends the clip inherited from an ancestor for this subtree (an xdg popup lives
-// under its parent's tree but is no part of the window's shape).
+// Every leaf under the tree is drawn with this fraction of its brightness and of
+// its colour taken away (both 0 to 1; 0 and 0 removes the dim): a window that is not
+// the focus. It is part of what the leaf shows, so a change damages the leaves
+// under the tree; a shadow is not drawn dimmed. False for a value outside 0 to 1.
+bool rediwm_projection_set_tree_dim(struct wlr_scene_node *, float brightness, float saturation);
+// Ends the clip and the dim inherited from an ancestor for this subtree (an xdg
+// popup lives under its parent's tree but is no part of the window's frame).
bool rediwm_projection_set_tree_unclipped(struct wlr_scene_node *, bool);
// Shows the subtree but lets the pick pass through it to what is below.
bool rediwm_projection_set_tree_inert(struct wlr_scene_node *, bool);
diff --git a/src/projection.zig b/src/projection.zig
index 83480bc..729b5aa 100644
--- a/src/projection.zig
+++ b/src/projection.zig
@@ -79,8 +79,14 @@ pub fn setTreeShadow(node: *wlr.SceneNode, spec: ?ShadowSpec) bool {
if (spec) |value| return rediwm_projection_set_tree_shadow(node, &value);
return rediwm_projection_set_tree_shadow(node, null);
}
-/// Ends the clip inherited from an ancestor for this subtree: an xdg popup or a
-/// window's shadow hangs under the window's tree but is no part of its shape.
+/// Every leaf under the tree loses this fraction of its brightness and of its
+/// colour in the output pass (see `rediwm_projection_set_tree_dim`); both zero
+/// removes it. False for a fraction outside 0 to 1.
+extern fn rediwm_projection_set_tree_dim(node: *wlr.SceneNode, brightness: f32, saturation: f32) bool;
+pub const setTreeDim = rediwm_projection_set_tree_dim;
+/// Ends the clip and the dim inherited from an ancestor for this subtree: an xdg
+/// popup or a window's shadow hangs under the window's tree but is no part of its
+/// frame.
extern fn rediwm_projection_set_tree_unclipped(node: *wlr.SceneNode, unclipped: bool) bool;
pub const setTreeUnclipped = rediwm_projection_set_tree_unclipped;
/// Shows the subtree but lets the pick pass through it to what is below: a
diff --git a/src/projection_test.c b/src/projection_test.c
index 368b30c..7d5881b 100644
--- a/src/projection_test.c
+++ b/src/projection_test.c
@@ -796,6 +796,94 @@ static void test_damage_events(struct wlr_scene *scene) {
wlr_scene_node_destroy(&source->node);
wlr_buffer_drop(buffer);
}
+// A window's dim is a field of what its leaves show: inherited down the tree like
+// its shape, ended where a popup hangs under it, and a change of it restyles (so
+// damages) every leaf under the tree and no other.
+static void test_dim(struct wlr_scene *scene) {
+ struct wlr_scene_tree *source = wlr_scene_tree_create(&scene->tree);
+ struct rediwm_projection *p = rediwm_projection_create(source, scene);
+ assert(p);
+ uint64_t cursor = rediwm_projection_damage_cursor(p);
+ struct wlr_scene_tree *window = wlr_scene_tree_create(source);
+ struct wlr_scene_tree *content = wlr_scene_tree_create(window);
+ struct wlr_scene_tree *popup = wlr_scene_tree_create(content);
+ struct wlr_scene_tree *sibling = wlr_scene_tree_create(source);
+ float color[4] = {.2, .3, .1, 1};
+ struct wlr_buffer *buffer = buffer_create();
+ struct wlr_scene_rect *ring = wlr_scene_rect_create(window, 10, 10, color);
+ struct wlr_scene_buffer *client = wlr_scene_buffer_create(content, buffer);
+ struct wlr_scene_buffer *menu = wlr_scene_buffer_create(popup, buffer);
+ struct wlr_scene_buffer *other = wlr_scene_buffer_create(sibling, buffer);
+ assert(ring && client && menu && other);
+ wlr_scene_node_set_position(&window->node, 40, 30);
+ wlr_scene_node_set_position(&client->node, 0, 10);
+ wlr_scene_buffer_set_dest_size(client, 100, 60);
+ wlr_scene_node_set_position(&popup->node, 50, 20);
+ wlr_scene_buffer_set_dest_size(menu, 30, 30);
+ wlr_scene_node_set_position(&sibling->node, 300, 200);
+ wlr_scene_buffer_set_dest_size(other, 20, 20);
+ assert(rediwm_projection_set_tree_unclipped(&popup->node, true));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ struct leaf *lring = get_leaf(p, &ring->node), *lclient = get_leaf(p, &client->node),
+ *lmenu = get_leaf(p, &menu->node), *lother = get_leaf(p, &other->node);
+ assert(events_since(p, &cursor, NULL).count == 4); // Appearing.
+
+ // Nothing is dimmed until a tree asks, and taking nothing away makes no addon.
+ assert(rediwm_projection_set_tree_dim(&sibling->node, 0, 0));
+ assert(!lring->item.content.dim_brightness && !lclient->item.content.dim_saturation);
+
+ // Every leaf of the window, not the popup under it and not another window.
+ assert(rediwm_projection_set_tree_dim(&window->node, .08f, .1f));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(lring->item.content.dim_brightness == .08f && lring->item.content.dim_saturation == .1f);
+ assert(lclient->item.content.dim_brightness == .08f && lclient->item.content.dim_saturation == .1f);
+ assert(!lmenu->item.content.dim_brightness && !lmenu->item.content.dim_saturation);
+ assert(!lother->item.content.dim_brightness && !lother->item.content.dim_saturation);
+ // The change restyles those two leaves (each reports its box as it was and as it
+ // is) and no other.
+ struct events_seen seen = events_since(p, &cursor, NULL);
+ assert(seen.count == 4 && event_is(&seen.last[1], lclient->item.id, 40, 40, 100, 60) &&
+ event_is(&seen.last[3], lring->item.id, 40, 30, 10, 10));
+ for (int i = 0; i < 4; i++) assert(seen.last[i].leaf == lclient->item.id || seen.last[i].leaf == lring->item.id);
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(events_since(p, &cursor, NULL).count == 0); // Unchanged is no damage.
+ assert(rediwm_projection_set_tree_dim(&window->node, .1f, .1f));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(events_since(p, &cursor, NULL).count == 4);
+
+ // A fraction outside 0 to 1 is refused and the old dim stays.
+ assert(!rediwm_projection_set_tree_dim(&window->node, -.1f, 0));
+ assert(!rediwm_projection_set_tree_dim(&window->node, 0, 1.5f));
+ assert(!rediwm_projection_set_tree_dim(&window->node, NAN, 0));
+ assert(!rediwm_projection_set_tree_dim(&window->node, 0, INFINITY));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(lclient->item.content.dim_brightness == .1f && events_since(p, &cursor, NULL).count == 0);
+
+ // The barrier does not hide a dim the subtree sets for itself, and lifting it
+ // gives the popup the window's.
+ assert(rediwm_projection_set_tree_dim(&popup->node, .5f, 0));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(lmenu->item.content.dim_brightness == .5f && lmenu->item.content.dim_saturation == 0);
+ assert(rediwm_projection_set_tree_dim(&popup->node, 0, 0));
+ assert(rediwm_projection_set_tree_unclipped(&popup->node, false));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(lmenu->item.content.dim_brightness == .1f);
+ assert(rediwm_projection_set_tree_unclipped(&popup->node, true));
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(!lmenu->item.content.dim_brightness);
+
+ // Taking nothing away undoes it, and restyles the leaves back.
+ events_since(p, &cursor, NULL);
+ assert(rediwm_projection_set_tree_dim(&window->node, 0, 0));
+ assert(rediwm_projection_set_tree_dim(&window->node, 0, 0)); // Again is fine.
+ rediwm_projection_sync(p, 1, 0, 0, 0, 0);
+ assert(!lring->item.content.dim_brightness && !lclient->item.content.dim_saturation);
+ assert(events_since(p, &cursor, NULL).count == 4);
+
+ rediwm_projection_destroy(p);
+ wlr_scene_node_destroy(&source->node);
+ wlr_buffer_drop(buffer);
+}
// The output pass hides what a client's opaque region covers, from the region as
// the surface node keeps it. The buffers of a client reveal no format, like a
// wlr_client_buffer, so only the node's own region can say they are opaque: it
@@ -1322,6 +1410,7 @@ int main(void) {
test_clip_output(scene, out);
test_shadow_output(scene, out);
test_damage_events(scene);
+ test_dim(scene);
test_graph_damage(scene, out);
test_feedback(scene, backend, out, output);
test_opaque();
diff --git a/src/scene_graph.h b/src/scene_graph.h
index 3af505a..9e57ce3 100644
--- a/src/scene_graph.h
+++ b/src/scene_graph.h
@@ -230,6 +230,10 @@ enum rediwm_item_kind {
// What a leaf draws, apart from where. `color` is premultiplied.
struct rediwm_content {
float opacity;
+ // How much of the brightness and of the colour the window the leaf belongs to
+ // has lost (a fraction, set on its tree: `rediwm_projection_set_tree_dim`). 0
+ // draws the leaf as it is, so a zeroed content is the plain one.
+ float dim_brightness, dim_saturation;
float color[4];
struct wlr_fbox src_box;
enum wl_output_transform transform;
@@ -243,7 +247,8 @@ struct rediwm_content {
// compiler-rt's bytewise bcmp, which cost more than the work it skipped.
static inline bool rediwm_content_equal(const struct rediwm_content *a,
const struct rediwm_content *b) {
- return a->opacity == b->opacity && a->color[0] == b->color[0] &&
+ return a->opacity == b->opacity && a->dim_brightness == b->dim_brightness &&
+ a->dim_saturation == b->dim_saturation && a->color[0] == b->color[0] &&
a->color[1] == b->color[1] && a->color[2] == b->color[2] &&
a->color[3] == b->color[3] && a->src_box.x == b->src_box.x &&
a->src_box.y == b->src_box.y && a->src_box.width == b->src_box.width &&
diff --git a/src/scene_output.c b/src/scene_output.c
index 9645751..daa87fb 100644
--- a/src/scene_output.c
+++ b/src/scene_output.c
@@ -400,7 +400,9 @@ static bool try_scanout(struct entry *e, struct wlr_scene_output *out,
!wlr_output_is_direct_scanout_allowed(out->output)) return false;
struct wlr_scene_buffer *b = wlr_scene_buffer_from_node(e->transport);
const struct rediwm_content *c = &e->item.content;
- if (!b->buffer || c->transform != v->transform || c->opacity != 1) return false;
+ // Scanout shows the client's buffer as it is: a dimmed window needs the pass.
+ if (!b->buffer || c->transform != v->transform || c->opacity != 1 ||
+ c->dim_brightness > 0 || c->dim_saturation > 0) return false;
const struct wlr_output_image_description *desc = state->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION ?
state->image_description : out->output->image_description;
if (desc) {
@@ -656,7 +658,12 @@ static void render_effect(struct entry *e, struct wlr_render_pass *pass, const s
o.front_opacity = f->item.content.opacity;
break;
}
+ // The effect shows what is behind its window: it is dimmed with the window.
+ const struct rediwm_content *content = &e->item.content;
+ const bool graded = content->dim_brightness > 0 || content->dim_saturation > 0;
+ if (graded) rediwm_scene_pass_set_dim(pass, content->dim_brightness, content->dim_saturation);
rediwm_scene_pass_add_backdrop(pass, &shape, dst, &o);
+ if (graded) rediwm_scene_pass_set_dim(pass, 0, 0);
}
// `backdrop`: drawing into an effect's quarter-size image (stage 5f), where an
// item counts with its whole box, not what is visible of it on screen, and
@@ -669,6 +676,7 @@ static bool render_entry(struct rediwm_output_renderer *r, struct entry *e, stru
pixman_region32_init(&clip);
pixman_region32_init(&blend);
pixman_region32_init(&core);
+ bool graded = false;
if (backdrop) pixman_region32_init_rect(&clip, dst.x, dst.y, dst.width, dst.height);
else {
pixman_region32_copy(&clip, &e->visible);
@@ -706,6 +714,10 @@ static bool render_entry(struct rediwm_output_renderer *r, struct entry *e, stru
pixman_region32_subtract(&clip, &clip, &core);
}
const struct rediwm_content *c = &e->item.content;
+ // A window that is not the focus is drawn dimmed, whole: the pass grades each
+ // draw (the interior, the rim and the ring alike) until it is reset below.
+ graded = c->dim_brightness > 0 || c->dim_saturation > 0;
+ if (graded) rediwm_scene_pass_set_dim(pass, c->dim_brightness, c->dim_saturation);
if (e->item.kind == REDIWM_ITEM_SHADOW) {
// The offset is taken to device pixels as the difference of two snapped
// boxes, so an output transform turns it with them.
@@ -778,6 +790,8 @@ static bool render_entry(struct rediwm_output_renderer *r, struct entry *e, stru
e->sampled = true;
}
done:
+ // What is drawn next (the next item, the software cursor) is not this item's.
+ if (graded) rediwm_scene_pass_set_dim(pass, 0, 0);
pixman_region32_fini(&clip);
pixman_region32_fini(&blend);
pixman_region32_fini(&core);
diff --git a/src/scene_pass.c b/src/scene_pass.c
index 02fa3bb..c5776f2 100644
--- a/src/scene_pass.c
+++ b/src/scene_pass.c
@@ -22,7 +22,9 @@ struct program {
unsigned bit; // which bit of pass.targets_set tracks this program's target size
GLint target, dst, color, alpha, opaque, sampler, coords;
// Shaped programs only (-1 elsewhere): the shape, and the shadow's own terms.
- GLint mode, origin, size, radii, border, bcolor, glow, gcolor, offset, softness, hide, use_shape;
+ GLint mode, origin, size, radii, border, bcolor, glow, gcolor, offset, softness, hide, use_shape, dim;
+ // What `dim` holds now (a uniform keeps its value between draws and passes).
+ float dim_brightness, dim_saturation;
// The backdrop composite (shaped mode 3) and the blur program.
GLint bmap, fmap, saturation, front, front_alpha, has_front;
GLint step_uv, sigma, limits, src_scale;
@@ -80,6 +82,7 @@ struct pass {
GLuint program;
unsigned targets_set;
int blend_mode;
+ float dim_brightness, dim_saturation; // rediwm_scene_pass_set_dim
// Between begin_backdrop and end_backdrop draws land in a quarter-size image
// of `region` (stage 5f): boxes move by its origin, scissors shrink by four.
bool redirected;
@@ -194,13 +197,18 @@ static const char shaped_vertex[] =
// when `hide` is set, which matters under translucent windows. One program for the
// three because a program costs the driver 130-150 KiB however small it is.
static const char shaped_fragment[] = SHAPED_HEAD
- "uniform float alpha, opaque, mode, softness, hide; uniform vec2 offset;"
+ "uniform float alpha, opaque, mode, softness, hide; uniform vec2 offset, dim;"
"uniform sampler2D front; uniform vec4 bmap, fmap; uniform float saturation, front_alpha, has_front, use_shape;"
+ // A dimmed window (rediwm_scene_pass_set_dim): colour pulled toward its
+ // luminance, then darker. Linear in the colour, so a premultiplied pixel and
+ // its straight colour come out the same, and an undimmed one is not touched.
+ "vec3 grade(vec3 c){ if(dim.x<=0.&&dim.y<=0.) return c;"
+ "float l=dot(c,vec3(.213,.715,.072)); return mix(vec3(l),c,1.-dim.y)*(1.-dim.x); }"
"void main(){"
// 3: a backdrop composite (stage 5b). `tex` is the kept blur; the alpha is
// chosen against the surface drawn over it, so the pair has the coverage.
"if(mode>2.5){ vec3 rgb=texture2D(tex,(local+bmap.xy)*bmap.zw).rgb;"
- "float l=dot(rgb,vec3(.213,.715,.072)); rgb=clamp(vec3(l)+(rgb-vec3(l))*saturation,0.,1.);"
+ "float l=dot(rgb,vec3(.213,.715,.072)); rgb=clamp(vec3(l)+(rgb-vec3(l))*saturation,0.,1.);rgb=grade(rgb);"
"float c=cov(sdf(local,radii))*alpha;"
"float f=has_front>.5?texture2D(front,(local+fmap.xy)*fmap.zw).a*front_alpha:0.;"
"float a=f>=.99999?0.:clamp((c-f)/(1.-f),0.,1.); gl_FragColor=vec4(rgb*a,a); return; }"
@@ -209,7 +217,7 @@ static const char shaped_fragment[] = SHAPED_HEAD
"vec4 c=color; if(mode<.5){ c=texture2D(tex,uv); if(opaque>.5)c.a=1.; c*=alpha; }"
// Without a shape (every plain draw) the colour is written as it is: the
// plain programs are gone (stage 5, D4), and this costs one uniform branch.
- "if(use_shape<.5){ gl_FragColor=c; return; }"
+ "if(use_shape<.5){ gl_FragColor=vec4(grade(c.rgb),c.a); return; }"
"float d=sdf(local,radii);"
"float w=border>0.?1.-cov(d+border):0.;"
"vec4 o=c*(1.-bcolor.a*w)+bcolor*w;"
@@ -218,7 +226,7 @@ static const char shaped_fragment[] = SHAPED_HEAD
"if(glow.z>0.){ float g=clamp(1.-length(local-glow.xy)/glow.z,0.,1.); g=g*g*(3.-2.*g);"
"float t=glow.w>0.?1.-smoothstep(0.,1.,(-d-border)/glow.w):w;"
"o=o*(1.-gcolor.a*g*t)+gcolor*(g*t); }"
- "gl_FragColor=o*cov(d); }";
+ "o.rgb=grade(o.rgb); gl_FragColor=o*cov(d); }";
// The backdrop blur (stage 5b): glass.c's kernel, 49 taps, sigma in texels of the
// target, reading a source texture that may be larger than the region (scratch),
@@ -297,6 +305,7 @@ static bool program_init(struct program *p, unsigned bit, const char *vertex_sou
p->softness = glGetUniformLocation(p->id, "softness");
p->hide = glGetUniformLocation(p->id, "hide");
p->use_shape = glGetUniformLocation(p->id, "use_shape");
+ p->dim = glGetUniformLocation(p->id, "dim");
p->bmap = glGetUniformLocation(p->id, "bmap");
p->fmap = glGetUniformLocation(p->id, "fmap");
p->saturation = glGetUniformLocation(p->id, "saturation");
@@ -447,6 +456,14 @@ static void set_shape(const struct pass *p, const struct program *g, const struc
glUniform4f(g->glow, s->glow_center[0], s->glow_center[1], s->glow_radius, s->glow_depth);
glUniform4f(g->gcolor, s->glow_color[0], s->glow_color[1], s->glow_color[2], s->glow_color[3]);
}
+// The pass's dim for a draw of `g`. The uniform keeps its value, so it is set only
+// when this program last held something else (a program starts at 0, as a pass does).
+static void apply_dim(struct pass *p, struct program *g) {
+ if (g->dim_brightness == p->dim_brightness && g->dim_saturation == p->dim_saturation) return;
+ glUniform2f(g->dim, p->dim_brightness, p->dim_saturation);
+ g->dim_brightness = p->dim_brightness;
+ g->dim_saturation = p->dim_saturation;
+}
static void add_rect(struct wlr_render_pass *base, const struct wlr_render_rect_options *o) {
struct pass *p = wl_container_of(base, p, base);
if (p->failed || (o->clip && !pixman_region32_not_empty(o->clip))) return;
@@ -457,6 +474,7 @@ static void add_rect(struct wlr_render_pass *base, const struct wlr_render_rect_
glUniform4f(g->color, o->color.r, o->color.g, o->color.b, o->color.a);
glUniform1f(g->mode, 1.f);
glUniform1f(g->use_shape, 0.f);
+ apply_dim(p, g);
draw(p, o->clip);
}
static void rect_shaped(struct pass *p, const struct wlr_render_rect_options *o,
@@ -470,6 +488,7 @@ static void rect_shaped(struct pass *p, const struct wlr_render_rect_options *o,
glUniform4f(g->color, o->color.r, o->color.g, o->color.b, o->color.a);
glUniform1f(g->mode, 1.f);
set_shape(p, g, shape);
+ apply_dim(p, g);
draw(p, o->clip);
}
static bool wait_point(struct pass *p, struct wlr_drm_syncobj_timeline *timeline, uint64_t point) {
@@ -527,6 +546,7 @@ static void texture_draw(struct pass *p, const struct wlr_render_texture_options
glUniform1f(program->mode, 0.f);
if (shape) set_shape(p, program, shape);
else glUniform1f(program->use_shape, 0.f);
+ apply_dim(p, program);
draw(p, o->clip);
}
static void texture_add(struct wlr_render_pass *base, const struct wlr_render_texture_options *o,
@@ -662,6 +682,16 @@ void rediwm_scene_pass_add_shadow(struct wlr_render_pass *base,
draw(p, shadow->clip);
}
+void rediwm_scene_pass_set_dim(struct wlr_render_pass *base, float brightness, float saturation) {
+ struct pass *p = owned_pass(base);
+ if (!(brightness >= 0 && brightness <= 1 && saturation >= 0 && saturation <= 1)) {
+ p->failed = true;
+ return;
+ }
+ p->dim_brightness = brightness;
+ p->dim_saturation = saturation;
+}
+
// ---- Backdrops (stage 5b) -------------------------------------------------------
bool rediwm_scene_renderer_enable_backdrops(struct rediwm_scene_renderer *r) {
assert(!r->active);
@@ -850,6 +880,7 @@ void rediwm_scene_pass_add_backdrop(struct wlr_render_pass *base, const struct r
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, b->tex);
glUniform1i(g->sampler, 0);
+ apply_dim(p, g);
draw(p, o->clip);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, 0);
diff --git a/src/scene_pass.h b/src/scene_pass.h
index 136134f..619c988 100644
--- a/src/scene_pass.h
+++ b/src/scene_pass.h
@@ -79,6 +79,15 @@ void rediwm_scene_pass_add_texture_shaped(struct wlr_render_pass *,
void rediwm_scene_pass_add_shadow(struct wlr_render_pass *, const struct rediwm_pass_shape *,
const struct rediwm_pass_shadow *);
+// Takes this fraction (0 to 1) of the brightness and of the colour away from every
+// rect, texture and backdrop composite that follows, shaped or not, until it is set
+// again; 0 and 0 is how a pass starts, and what the caller restores after the item
+// it was set for, so what is drawn next (the software cursor) is never graded.
+// Colour is pulled toward the pixel's luminance, then everything is scaled, on
+// premultiplied values, so a translucent pixel keeps its alpha. A shadow is not
+// graded. A fraction outside 0 to 1 fails the pass at submit.
+void rediwm_scene_pass_set_dim(struct wlr_render_pass *, float brightness, float saturation);
+
// Stage 5b of docs/plans/scene-graph.md: backdrop effects (glass). An effect
// blurs what the pass has drawn so far under a region and composites it through
// its shape, under the surface it backs. The blur is kept between frames in a
diff --git a/src/scene_pass_test.c b/src/scene_pass_test.c
index 746f060..705561c 100644
--- a/src/scene_pass_test.c
+++ b/src/scene_pass_test.c
@@ -739,6 +739,108 @@ static void gate_premultiplied(struct rediwm_scene_renderer *r, struct wlr_buffe
puts("PASS: premultiplied edges, opacity and XRGB textures blend correctly through the clip");
}
+// ---- Dimming: a window that is not the focus is graded in the pass ----------------
+// What rediwm_scene_pass_set_dim documents, worked out here on its own: the colour is
+// pulled toward its luminance by the saturation taken away, then everything is scaled
+// by the brightness left. On premultiplied values, as the pass has them.
+static void graded(const double in[3], double brightness, double saturation, double out[3]) {
+ const double l = .213 * in[0] + .715 * in[1] + .072 * in[2];
+ for (int i = 0; i < 3; i++) out[i] = (l + (in[i] - l) * (1 - saturation)) * (1 - brightness);
+}
+static void check_pixel(const struct image *img, int x, int y, const double want[3], const char *what) {
+ for (int ch = 0; ch < 3; ch++)
+ check(diff(at(img, x, y)[ch], (int)lround(255 * want[ch])) <= 2, "%s: (%d,%d) channel %d is %d, not %ld",
+ what, x, y, ch, at(img, x, y)[ch], lround(255 * want[ch]));
+}
+static void gate_dim(struct rediwm_scene_renderer *r, struct wlr_buffer *buf, struct image *img) {
+ const float db = .10f, ds = .20f;
+ const float c[4] = {200 / 255.f, 100 / 255.f, 50 / 255.f, 1};
+ const double cd[3] = {c[0], c[1], c[2]}, bg[3] = {BG[0], BG[1], BG[2]};
+ double want[3];
+ // A plain rect, then one after the dim is taken off: the first is graded, the
+ // second and what was drawn before are not.
+ struct wlr_render_pass *pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_set_dim(pass, db, ds);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){.box = {20, 20, 40, 40}, .color = {c[0], c[1], c[2], 1}});
+ rediwm_scene_pass_set_dim(pass, 0, 0);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){.box = {80, 20, 40, 40}, .color = {c[0], c[1], c[2], 1}});
+ finish(pass);
+ read_image(r, buf, img);
+ graded(cd, db, ds, want);
+ check_pixel(img, 40, 40, want, "a dimmed plain rect");
+ check_pixel(img, 100, 40, cd, "a rect after the dim is taken off");
+ check_pixel(img, 300, 300, bg, "the background before the dim");
+ // A dimmed rect through a shape: the interior and the ring are graded, the
+ // corner the shape cuts away is the backdrop, whole.
+ const struct rediwm_pass_shape ring = {.box = {140, 100, 80, 80}, .radii = {20, 20, 20, 20}, .border = 4,
+ .border_color = {.5f, 0, 0, .5f}};
+ pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_set_dim(pass, db, ds);
+ piece(pass, &ring, ring.box, c, NULL);
+ rediwm_scene_pass_set_dim(pass, 0, 0);
+ finish(pass);
+ read_image(r, buf, img);
+ graded(cd, db, ds, want);
+ check_pixel(img, 180, 140, want, "a dimmed shaped interior");
+ const double under_ring[3] = {cd[0] * .5 + .5, cd[1] * .5, cd[2] * .5};
+ graded(under_ring, db, ds, want);
+ check_pixel(img, 141, 140, want, "a dimmed ring");
+ check_pixel(img, 141, 101, bg, "the corner a dimmed shape cuts away");
+ // A half-transparent texel: graded as premultiplied, then over the backdrop,
+ // so it keeps its alpha.
+ uint32_t half[16];
+ for (int i = 0; i < 16; i++) half[i] = 0x80800000;
+ struct wlr_texture *t_half = wlr_texture_from_pixels(r->renderer, DRM_FORMAT_ARGB8888, 16, 4, 4, half);
+ check(t_half != NULL, "cannot create the test texture");
+ const struct rediwm_pass_shape card = {.box = {240, 100, 80, 80}, .radii = {20, 20, 20, 20}};
+ pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_set_dim(pass, db, ds);
+ rediwm_scene_pass_add_texture_shaped(pass, &(struct wlr_render_texture_options){
+ .texture = t_half, .dst_box = card.box}, &card);
+ rediwm_scene_pass_set_dim(pass, 0, 0);
+ finish(pass);
+ read_image(r, buf, img);
+ const double alpha = 128 / 255., src[3] = {128 / 255., 0, 0};
+ graded(src, db, ds, want);
+ for (int i = 0; i < 3; i++) want[i] += bg[i] * (1 - alpha);
+ check_pixel(img, 280, 140, want, "a dimmed half-transparent texel");
+ wlr_texture_destroy(t_half);
+ // A shadow is not graded, whatever the pass holds.
+ const struct rediwm_pass_shape cast = {.box = {340, 100, 80, 80}, .radii = {20, 20, 20, 20}};
+ const struct rediwm_pass_shadow shadow = {.softness = 12, .color = {.6f, 0, 0, .6f}};
+ uint8_t plain[3];
+ for (int dimmed = 0; dimmed < 2; dimmed++) {
+ pass = begin_fill(r, buf, BG, NULL);
+ if (dimmed) rediwm_scene_pass_set_dim(pass, db, ds);
+ rediwm_scene_pass_add_shadow(pass, &cast, &shadow);
+ finish(pass);
+ read_image(r, buf, img);
+ if (!dimmed) memcpy(plain, at(img, 380, 140), 3);
+ else for (int ch = 0; ch < 3; ch++)
+ check(diff(at(img, 380, 140)[ch], plain[ch]) <= 1, "a dimmed pass graded a shadow (channel %d)", ch);
+ }
+ // A pass that ends with the dim still set leaves none for the next one.
+ pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_set_dim(pass, .5f, .5f);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){.box = {20, 20, 40, 40}, .color = {c[0], c[1], c[2], 1}});
+ finish(pass);
+ pass = begin_fill(r, buf, BG, NULL);
+ wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){.box = {20, 20, 40, 40}, .color = {c[0], c[1], c[2], 1}});
+ finish(pass);
+ read_image(r, buf, img);
+ check_pixel(img, 40, 40, cd, "the first rect of a pass after one that kept its dim");
+ // A fraction outside 0 to 1 fails the pass, and the next one works.
+ const float bad[][2] = {{-.1f, 0}, {0, 1.5f}, {NAN, 0}, {0, INFINITY}};
+ for (size_t i = 0; i < COUNT(bad); i++) {
+ pass = begin_fill(r, buf, BG, NULL);
+ rediwm_scene_pass_set_dim(pass, bad[i][0], bad[i][1]);
+ check(!wlr_render_pass_submit(pass), "a dim of (%g, %g) did not fail the pass", bad[i][0], bad[i][1]);
+ }
+ pass = begin_fill(r, buf, BG, NULL);
+ finish(pass);
+ puts("PASS: a dimmed pass grades rects, shapes, rings and translucent texels, not shadows, and fails closed");
+}
+
// ---- Gate 5: the opaque cover of the model is fully covered in real pixels -------------
// rediwm_clip_opaque promises its rectangles are inside full coverage; the output
// pass will draw them without blending and trust that. Painting them first with
@@ -900,6 +1002,7 @@ static void shaped_gates(struct rediwm_scene_renderer *r, struct wlr_allocator *
gate_no_seams(r, buf, &img);
gate_border_partition(r, buf, &img, &ref);
gate_premultiplied(r, buf, &img);
+ gate_dim(r, buf, &img);
gate_opaque_cover(r, buf, &img, &ref);
gate_shadow(r, buf, &img);
gate_damage_at_clip_edge(r, allocator, &img);
@@ -1138,12 +1241,38 @@ static void gate_backdrop_redirect(struct rediwm_scene_renderer *r, struct wlr_a
wlr_buffer_drop(buf);
puts("PASS: redirected draws land in the quarter-size image with their shape, offset and clip");
}
+// The composite shows what is behind its window, so a dimmed window dims it too.
+static void gate_backdrop_dim(struct rediwm_scene_renderer *r, struct wlr_allocator *allocator, struct image *img) {
+ struct wlr_buffer *buf = target_sized(allocator, GW, GH);
+ struct rediwm_backdrop *b = NULL;
+ const struct wlr_box region = {120, 100, 400, 200}, box = {168, 148, 304, 104};
+ const float c[3] = {.2f, .4f, .6f};
+ const double in[3] = {c[0], c[1], c[2]};
+ double want[3];
+ struct wlr_render_pass *pass = begin_fill(r, buf, (float[4]){c[0], c[1], c[2], 1}, NULL);
+ rediwm_scene_pass_begin_backdrop(pass, region, 4);
+ fill(pass, (float[4]){c[0], c[1], c[2], 1});
+ rediwm_scene_pass_end_backdrop(pass, &b, 16);
+ rediwm_scene_pass_set_dim(pass, .1f, .2f);
+ rediwm_scene_pass_add_backdrop(pass, &(struct rediwm_pass_shape){.box = box}, box,
+ &(struct rediwm_pass_backdrop){.backdrop = b, .saturation = 1, .opacity = 1});
+ rediwm_scene_pass_set_dim(pass, 0, 0);
+ finish(pass);
+ read_image(r, buf, img);
+ graded(in, .1, .2, want);
+ check_pixel(img, 300, 200, want, "a dimmed backdrop");
+ check_pixel(img, 20, 20, in, "outside it");
+ rediwm_scene_renderer_destroy_backdrop(r, b);
+ wlr_buffer_drop(buf);
+ puts("PASS: a dimmed backdrop composite is graded like the window it backs");
+}
static void backdrop_gates(struct rediwm_scene_renderer *r, struct wlr_allocator *allocator) {
struct image img = {0};
gate_backdrop_blur(r, allocator, &img);
gate_backdrop_properties(r, allocator, &img);
gate_backdrop_front(r, allocator, &img);
gate_backdrop_redirect(r, allocator, &img);
+ gate_backdrop_dim(r, allocator, &img);
free(img.p);
}
int main(void) {
diff --git a/src/start_menu/panel.zig b/src/start_menu/panel.zig
index 0e03c92..0a44c6f 100644
--- a/src/start_menu/panel.zig
+++ b/src/start_menu/panel.zig
@@ -790,7 +790,8 @@ pub const StartMenu = struct {
ui.arrange.arrange(&menu.root, 0, 0, target_width, target_height);
const bottom_offset: f32 = @as(f32, @floatFromInt(Taskbar.barHeight())) + theme.global.start_menu_bottom_pad;
- const panel_left: f32 = theme.global.start_menu_left_pad;
+ const start_offset: f32 = if (Output.fromWlr(menu.wlr_output)) |output| if (output.taskbar) |bar| @floatFromInt(bar.startButtonBox().x - output_box.x - Taskbar.startButtonLeft()) else 0 else 0;
+ const panel_left = std.math.clamp(theme.global.start_menu_left_pad + start_offset, 0, @max(0, @as(f32, @floatFromInt(output_box.width)) - target_width));
menu.panel_box = .{
.x = output_box.x + @as(i32, @intFromFloat(panel_left)),
diff --git a/src/taskbar/window_menu.zig b/src/taskbar/window_menu.zig
index 201486d..e68c1e3 100644
--- a/src/taskbar/window_menu.zig
+++ b/src/taskbar/window_menu.zig
@@ -41,14 +41,14 @@ pub const Menu = struct {
pub fn open(self: *Menu, bar: *Taskbar, target: *Toplevel, x: i32) void {
const output = Output.fromWlr(bar.wlr_output) orelse return;
- self.openOn(output, bar, null, target, null, x);
+ self.openOn(output, bar, null, target, null, x, 0);
}
- pub fn openDock(self: *Menu, dock: *Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, x: i32) void {
- self.openOn(dock.output orelse return, null, dock, target, shortcut, x);
+ pub fn openDock(self: *Menu, dock: *Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, x: i32, y: i32) void {
+ self.openOn(dock.output orelse return, null, dock, target, shortcut, x, y);
}
- fn openOn(self: *Menu, output: *Output, bar: ?*Taskbar, dock: ?*Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, x: i32) void {
+ fn openOn(self: *Menu, output: *Output, bar: ?*Taskbar, dock: ?*Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, x: i32, pointer_y: i32) void {
self.close();
const server = output.server;
const input = &server.input;
@@ -68,9 +68,22 @@ pub const Menu = struct {
self.target = target;
const count: i32 = @intCast(self.actions().len);
const height = padding * 2 + row_height * count + separator * (count - 1);
- const y = if (dock) |d| if (d.box.y - height - 4 >= bounds.y) d.box.y - height - 4 else d.box.y + d.box.height + 4 else output.taskbarPopupY(height, 4);
+ var menu_x = x;
+ var y = output.taskbarPopupY(height, 4);
+ if (dock) |d| switch (d.position) {
+ .top => y = d.box.y + d.box.height + 4,
+ .bottom => y = d.box.y - height - 4,
+ .left => {
+ menu_x = d.box.x + d.box.width + 4;
+ y = pointer_y;
+ },
+ .right => {
+ menu_x = d.box.x - width - 4;
+ y = pointer_y;
+ },
+ };
self.box = .{
- .x = std.math.clamp(x, bounds.x, bounds.x + bounds.width - width),
+ .x = std.math.clamp(menu_x, bounds.x, bounds.x + bounds.width - width),
.y = std.math.clamp(y, bounds.y, @max(bounds.y, bounds.y + bounds.height - height)),
.width = width,
.height = height,
diff --git a/src/ui/anim.zig b/src/ui/anim.zig
index 72fa7e6..0f5f4f5 100644
--- a/src/ui/anim.zig
+++ b/src/ui/anim.zig
@@ -90,7 +90,9 @@ pub const Target = enum {
window_move,
window_resize,
window_zoom,
+ window_drag,
window_peek,
+ window_dim,
camera_pan,
camera_zoom,
camera_reveal,
@@ -149,7 +151,8 @@ pub fn defaultSpec(target: Target) TargetSpec {
.window_move, .window_resize => .{ .curve = .{ .spring = springs.window_move } },
// Still duration in the adopted UI; config can overlay a spring.
.window_zoom => .{ .curve = .{ .duration = .{ .ms = 160, .ease = .out_cubic } } },
- .window_peek => .{ .curve = .{ .duration = .{ .ms = 150, .ease = .out_cubic } } },
+ .window_drag => .{ .curve = .{ .spring = .{ .damping_ratio = 1.0, .stiffness = 600, .epsilon = 1e-4 } } },
+ .window_peek, .window_dim => .{ .curve = .{ .duration = .{ .ms = 150, .ease = .out_cubic } } },
.camera_pan => .{ .curve = .{ .duration = .{ .ms = 160, .ease = .out_cubic } }, .decay = .{ .rate = 0.998, .threshold = 0.5 } },
.camera_zoom => .{ .curve = .{ .spring = springs.camera_zoom } },
.camera_reveal => .{ .curve = .{ .duration = .{ .ms = 320, .ease = .out_cubic } } },
diff --git a/src/ui/cairo.zig b/src/ui/cairo.zig
index 17613ce..c5f8678 100644
--- a/src/ui/cairo.zig
+++ b/src/ui/cairo.zig
@@ -60,6 +60,46 @@ pub fn setSource(cr_any: *anyopaque, color: [4]f32) void {
c.cairo_set_source_rgba(@ptrCast(cr_any), color[0], color[1], color[2], color[3]);
}
+/// Sidebar hover fill and optional illuminated leading edge. Keep the glow
+/// inside the row so the existing hover damage and scrolling clips cover it.
+pub fn drawSidebarHover(cr_any: *anyopaque, box: Rect, alpha: f32) void {
+ if (box.w <= 0 or box.h <= 0 or alpha <= 0) return;
+ const cr: *c.cairo_t = @ptrCast(cr_any);
+ c.cairo_save(cr);
+ defer c.cairo_restore(cr);
+ const x: f64 = box.x;
+ const y: f64 = box.y;
+ const w: f64 = box.w;
+ const h: f64 = box.h;
+ const radius = @min(5, @min(w, h) / 2);
+ c.cairo_new_sub_path(cr);
+ c.cairo_arc(cr, x + w - radius, y + radius, radius, -std.math.pi / 2.0, 0);
+ c.cairo_arc(cr, x + w - radius, y + h - radius, radius, 0, std.math.pi / 2.0);
+ c.cairo_arc(cr, x + radius, y + h - radius, radius, std.math.pi / 2.0, std.math.pi);
+ c.cairo_arc(cr, x + radius, y + radius, radius, std.math.pi, 3 * std.math.pi / 2.0);
+ c.cairo_close_path(cr);
+ var fill = theme.global.sidebarHover();
+ fill[3] *= alpha;
+ setSource(cr, fill);
+ c.cairo_fill_preserve(cr);
+ c.cairo_clip(cr);
+ const marker = theme.global.app_sidebar_hover_marker orelse return;
+ const accent = theme.shellPalette().accent;
+ const glow = c.cairo_pattern_create_linear(x, 0, x + @min(w, 28), 0) orelse return;
+ defer c.cairo_pattern_destroy(glow);
+ c.cairo_pattern_add_color_stop_rgba(glow, 0, accent[0], accent[1], accent[2], accent[3] * alpha * 0.85);
+ c.cairo_pattern_add_color_stop_rgba(glow, 0.25, accent[0], accent[1], accent[2], accent[3] * alpha * 0.40);
+ c.cairo_pattern_add_color_stop_rgba(glow, 1, accent[0], accent[1], accent[2], 0);
+ c.cairo_set_source(cr, glow);
+ c.cairo_paint(cr);
+ c.cairo_set_source_rgba(cr, marker[0], marker[1], marker[2], marker[3] * alpha);
+ c.cairo_set_line_width(cr, 3);
+ c.cairo_set_line_cap(cr, c.CAIRO_LINE_CAP_ROUND);
+ c.cairo_move_to(cr, x + 2.5, y + 5);
+ c.cairo_line_to(cr, x + 2.5, y + h - 5);
+ c.cairo_stroke(cr);
+}
+
pub fn drawSplitter(cr_any: *anyopaque, geometry: splitter.Geometry, engaged: bool) void {
const cr: *c.cairo_t = @ptrCast(cr_any);
const rect = geometry.line(engaged);
diff --git a/src/ui/paint.zig b/src/ui/paint.zig
index cc7490c..88e6e4a 100644
--- a/src/ui/paint.zig
+++ b/src/ui/paint.zig
@@ -1126,6 +1126,7 @@ fn paintToggle(widget: *const Widget, data: ToggleData, renderer: *Renderer) voi
/// Shared slider styling and feedback, using the surface's theme palette.
pub fn paintSlider(widget: *const Widget, data: SliderData, renderer: *Renderer) void {
const t = renderer.palette orelse theme.global;
+ if (t.slider_shaded) return @import("widgets/slider.zig").paintShaded(widget, data, renderer);
const w = widget.computed_width;
const cy = widget.computed_y + widget.computed_height / 2;
const settings = data.style == .settings;
diff --git a/src/ui/theme.zig b/src/ui/theme.zig
index 8bc8d7b..6133fe6 100644
--- a/src/ui/theme.zig
+++ b/src/ui/theme.zig
@@ -67,6 +67,9 @@ pub const Theme = struct {
app_fg: ?[4]f32 = null,
app_sidebar_fg: ?[4]f32 = null,
app_sidebar_selected: ?[4]f32 = null,
+ app_sidebar_hover: ?[4]f32 = null,
+ app_sidebar_hover_marker: ?[4]f32 = null,
+ app_surface_hover: ?[4]f32 = null,
app_menu_bg: ?[4]f32 = null,
app_field_bg: ?[4]f32 = null,
app_field_border: ?[4]f32 = null,
@@ -199,8 +202,13 @@ pub const Theme = struct {
// Additional appearance tokens. All fields are parsed and saved through
// the type-derived key lists below; defaults preserve the stock look.
toggle_track: [4]f32 = .{ 1, 1, 1, 0.12 },
+ toggle_on: ?[4]f32 = null,
+ toggle_thumb: ?[4]f32 = null,
+ toggle_shaded: bool = false,
control_thumb: [4]f32 = .{ 1, 1, 1, 1 },
slider_track: [4]f32 = .{ 1, 1, 1, 0.08 },
+ slider_shaded: bool = false,
+ slider_highlight: ?[4]f32 = null,
pill_bg: [4]f32 = .{ 1, 1, 1, 0.05 },
swatch_border: [4]f32 = .{ 1, 1, 1, 0.10 },
swatch_border_selected: [4]f32 = .{ 1, 1, 1, 0.6 },
@@ -218,6 +226,17 @@ pub const Theme = struct {
switcher_dim: [4]f32 = .{ 0.6, 0.62, 0.66, 1 },
switcher_icon_bg: [4]f32 = .{ 0.10, 0.11, 0.13, 1 },
switcher_selected_border: [4]f32 = .{ 1, 0.12, 0.20, 1 },
+ // Taskbar Wi-Fi and battery panels. Unset colours retain the stock look.
+ popup_bg: ?[4]f32 = null,
+ popup_border: ?[4]f32 = null,
+ popup_radius: f32 = 9,
+ popup_blur: bool = false,
+ popup_card_bg: ?[4]f32 = null,
+ popup_card_fg: ?[4]f32 = null,
+ popup_card_dim: ?[4]f32 = null,
+ popup_card_border: ?[4]f32 = null,
+ popup_card_radius: f32 = 12,
+ popup_battery_ring: ?[4]f32 = null,
calendar_border: [4]f32 = .{ 1, 1, 1, 0.16 },
osd_border: [4]f32 = .{ 1, 1, 1, 0.12 },
screenshot_shade: [4]f32 = .{ 0, 0, 0, 0.36 },
@@ -345,6 +364,7 @@ pub const Theme = struct {
result.window_bg = t.app_menu_bg orelse t.window_bg;
result.field_bg = t.app_field_bg orelse t.field_bg;
result.field_border = t.app_field_border orelse t.field_border;
+ result.surface_hover = t.app_surface_hover orelse t.surface_hover;
return result;
}
@@ -356,6 +376,10 @@ pub const Theme = struct {
return t.app_sidebar_selected orelse t.app_nav_selected;
}
+ pub fn sidebarHover(t: Theme) [4]f32 {
+ return t.app_sidebar_hover orelse t.app_item_hover;
+ }
+
pub fn controlFocusColor(t: Theme) [4]f32 {
return t.shell_border_focus orelse t.fg;
}
diff --git a/src/ui/widgets/slider.zig b/src/ui/widgets/slider.zig
index 900784a..c95ed65 100644
--- a/src/ui/widgets/slider.zig
+++ b/src/ui/widgets/slider.zig
@@ -6,6 +6,106 @@ const anim = @import("../anim.zig");
const layout = @import("../layout.zig");
const scrollbar = @import("scrollbar.zig");
const Widget = layout.Widget;
+const Renderer = @import("../paint.zig").Renderer;
+const theme = @import("../theme.zig");
+const sdf = @import("../sdf.zig");
+const text = @import("../text.zig");
+
+/// A recessed rail with a luminous fill and a reflective, round thumb.
+/// All light stays inside the widget so partial repaints erase it completely.
+pub fn paintShaded(widget: *const Widget, data: layout.SliderData, r: *Renderer) void {
+ const t = r.palette orelse theme.global;
+ const w = widget.computed_width;
+ const h = widget.computed_height;
+ if (w <= 2 or h <= 2) return;
+ r.clean = false;
+ const s = r.scale;
+ var left = widget.computed_x * s;
+ var top = widget.computed_y * s;
+ var right = (widget.computed_x + w) * s;
+ var bottom = (widget.computed_y + h) * s;
+ if (r.effectiveClip()) |clip| {
+ left = @max(left, clip.x * s);
+ top = @max(top, clip.y * s);
+ right = @min(right, (clip.x + clip.w) * s);
+ bottom = @min(bottom, (clip.y + clip.h) * s);
+ }
+ const x0: i32 = @intFromFloat(@floor(@max(0, left)));
+ const y0: i32 = @intFromFloat(@floor(@max(0, top)));
+ const x1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.width)), right)));
+ const y1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.height)), bottom)));
+ const settings = data.style == .settings;
+ const track_h = @min(h - 2, @max(0.5, (if (settings) t.slider_settings_track_height else t.slider_track_height) * (1 + t.slider_track_grow * data.feel.wide)));
+ const diameter = @min(@min(w, h) - 2, @max(1, @min(t.slider_thumb_size, if (settings) t.slider_settings_thumb_height else t.slider_thumb_size)));
+ const radius = diameter / 2;
+ const fraction = if (data.max > data.min) std.math.clamp((data.value - data.min) / (data.max - data.min), 0, 1) else 0;
+ const cx = std.math.clamp(fraction * w, radius + 1, w - radius - 1);
+ const cy = h / 2;
+ const highlight = t.slider_highlight orelse t.control_thumb;
+ const intensity = std.math.clamp(data.feel.accent, 0, 1);
+ var py = y0;
+ while (py < y1) : (py += 1) {
+ const y = (@as(f32, @floatFromInt(py)) + 0.5) / s - widget.computed_y;
+ var px = x0;
+ while (px < x1) : (px += 1) {
+ const x = (@as(f32, @floatFromInt(px)) + 0.5) / s - widget.computed_x;
+ const pixel = &r.pixels[@intCast(py * r.width + px)];
+ const dx = x - cx;
+ const dy = y - cy;
+ const rail = sdf.sdRoundedBox(x, y, 0, cy - track_h / 2, w, track_h, track_h / 2);
+ const fill = sdf.sdRoundedBox(x, y, 0, cy - track_h / 2, cx, track_h, track_h / 2);
+ // A warm halo along the filled rail, brightest beside the knob.
+ const tip = falloff(dx / (radius * 3));
+ const edge_fade = std.math.clamp(@min(@min(x, w - x), @min(y, h - y)), 0, 1);
+ const halo = std.math.clamp(1 - @max(0, fill) / 3, 0, 1);
+ if (fraction > 0) blend(pixel, t.accent, halo * halo * (0.12 + 0.16 * tip + 0.10 * intensity) * edge_fade);
+ const rail_y = std.math.clamp((dy + track_h / 2) / track_h, 0, 1);
+ blend(pixel, shade(t.slider_track, -0.24 + 0.32 * rail_y), sdf.coverage(rail * s));
+ if (fraction > 0) {
+ const streak = falloff((dy + track_h * 0.16) / (track_h * 0.38));
+ const gold = mix(t.accent, highlight, 0.18 + 0.50 * streak + 0.25 * tip);
+ blend(pixel, gold, sdf.coverage(fill * s));
+ }
+ const shadow = @sqrt(dx * dx + (dy - 1) * (dy - 1)) - radius;
+ blend(pixel, .{ 0, 0, 0, 0.28 }, std.math.clamp(1 - shadow / 1.5, 0, 1) * edge_fade);
+ const distance = @sqrt(dx * dx + dy * dy) - radius;
+ const coverage = sdf.coverage(distance * s);
+ if (coverage <= 0) continue;
+ const nx = dx / radius;
+ const ny = dy / radius;
+ const nz = @sqrt(@max(0, 1 - nx * nx - ny * ny));
+ const light = std.math.clamp(-0.45 * nx - 0.55 * ny + 0.70 * nz, 0, 1);
+ var knob = shade(t.accent, -0.48 + 0.68 * light);
+ // Broad upper-left reflection and a smaller lower-right glint.
+ const specular = falloff((nx + 0.32) / 0.48) * falloff((ny + 0.42) / 0.43);
+ const glint = falloff((nx - 0.40) / 0.30) * falloff((ny - 0.57) / 0.25);
+ knob = mix(knob, highlight, @min(1, 0.95 * specular + 0.70 * glint));
+ const rim = 1 - std.math.clamp(-distance / 1.2, 0, 1);
+ knob = mix(knob, highlight, rim * (0.50 + 0.35 * light));
+ blend(pixel, knob, coverage);
+ }
+ }
+}
+
+fn falloff(value: f32) f32 {
+ const v = @max(0, 1 - value * value);
+ return v * v;
+}
+
+fn mix(a: [4]f32, b: [4]f32, amount: f32) [4]f32 {
+ var result: [4]f32 = undefined;
+ for (&result, a, b) |*out, start, end| out.* = start + (end - start) * amount;
+ return result;
+}
+
+fn shade(color: [4]f32, amount: f32) [4]f32 {
+ const light: f32 = if (amount > 0) 1 else 0;
+ return mix(color, .{ light, light, light, color[3] }, @abs(amount));
+}
+
+fn blend(pixel: *u32, color: [4]f32, coverage: f32) void {
+ text.blendPixel(pixel, .{ .r = color[0], .g = color[1], .b = color[2], .a = color[3] }, coverage);
+}
fn snap(value: f32, min: f32, max: f32, step: f32) f32 {
const clamped = std.math.clamp(value, min, max);
diff --git a/src/ui/widgets/toggle.zig b/src/ui/widgets/toggle.zig
index d6b8207..fcacac1 100644
--- a/src/ui/widgets/toggle.zig
+++ b/src/ui/widgets/toggle.zig
@@ -8,6 +8,8 @@ const Widget = layout.Widget;
const Renderer = @import("../paint.zig").Renderer;
const theme = @import("../theme.zig");
const Rect = @import("field.zig").Rect;
+const sdf = @import("../sdf.zig");
+const text = @import("../text.zig");
/// Natural switch size, shared by widget trees (measure.zig) and hand-laid panels.
pub const width: f32 = 36;
@@ -23,9 +25,10 @@ pub const Options = struct {
/// Shared switch painter for widget trees and hand-laid panels.
pub fn paint(r: *Renderer, box: Rect, opts: Options) void {
const t = r.palette orelse theme.global;
+ if (t.toggle_shaded) return paintShaded(r, box, opts, t);
const radius: f32 = if (opts.style == .settings) t.toggle_radius else box.h / 2;
- var track: [4]f32 = if (opts.on) t.accent else t.toggle_track;
- var thumb = t.control_thumb;
+ var track: [4]f32 = if (opts.on) t.toggle_on orelse t.accent else t.toggle_track;
+ var thumb = t.toggle_thumb orelse t.control_thumb;
if (opts.disabled) {
track[3] *= 0.5;
thumb[3] *= 0.5;
@@ -42,6 +45,84 @@ pub fn paint(r: *Renderer, box: Rect, opts: Options) void {
r.fillRect(x, box.y + inset, side, side, .{ .color = thumb, .radius = if (opts.style == .settings) t.toggle_thumb_radius else side / 2 });
}
+/// Recessed track and raised knob, contained in the control's damage bounds.
+fn paintShaded(r: *Renderer, box: Rect, opts: Options, t: theme.Theme) void {
+ if (box.w <= 0 or box.h <= 0) return;
+ r.clean = false;
+ const scale = r.scale;
+ var left = box.x * scale;
+ var top = box.y * scale;
+ var right = (box.x + box.w) * scale;
+ var bottom = (box.y + box.h) * scale;
+ if (r.effectiveClip()) |clip| {
+ left = @max(left, clip.x * scale);
+ top = @max(top, clip.y * scale);
+ right = @min(right, (clip.x + clip.w) * scale);
+ bottom = @min(bottom, (clip.y + clip.h) * scale);
+ }
+ const x0: i32 = @intFromFloat(@floor(@max(0, left)));
+ const y0: i32 = @intFromFloat(@floor(@max(0, top)));
+ const x1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.width)), right)));
+ const y1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.height)), bottom)));
+ const radius = if (opts.style == .settings) t.toggle_radius else box.h / 2;
+ const inset = box.h * 0.14;
+ const side = box.h - 2 * inset;
+ const thumb_x = if (opts.on) box.w - inset - side else inset;
+ const thumb_radius = if (opts.style == .settings) t.toggle_thumb_radius else side / 2;
+ const track = if (opts.on) t.toggle_on orelse t.accent else t.toggle_track;
+ const thumb = t.toggle_thumb orelse t.control_thumb;
+ const opacity: f32 = if (opts.disabled) 0.5 else 1;
+ var py = y0;
+ while (py < y1) : (py += 1) {
+ const y = (@as(f32, @floatFromInt(py)) + 0.5) / scale - box.y;
+ const vertical = std.math.clamp(y / box.h, 0, 1);
+ var px = x0;
+ while (px < x1) : (px += 1) {
+ const x = (@as(f32, @floatFromInt(px)) + 0.5) / scale - box.x;
+ const distance = sdf.sdRoundedBox(x, y, 0, 0, box.w, box.h, radius);
+ const coverage = sdf.coverage(distance * scale);
+ if (coverage <= 0) continue;
+ // Dark upper lip fades into the track; the lower lip catches light.
+ const rim = 1 - std.math.clamp(-distance / 1.4, 0, 1);
+ var color = shade(track, -0.07 + 0.10 * vertical + rim * (-0.22 + 0.32 * vertical));
+ // The knob casts a short, soft shadow down into the recess.
+ const shadow_distance = sdf.sdRoundedBox(x, y, thumb_x, inset + 0.8, side, side, thumb_radius);
+ const shadow = std.math.clamp(1 - shadow_distance / 1.6, 0, 1);
+ color = shade(color, -0.24 * shadow * shadow);
+ if (opts.focused and !opts.disabled) {
+ const focus = sdf.coverage((distance + 2) * scale);
+ color = mix(color, t.controlFocusColor(), 1 - focus);
+ }
+ const knob_distance = sdf.sdRoundedBox(x, y, thumb_x, inset, side, side, thumb_radius);
+ const knob_coverage = sdf.coverage(knob_distance * scale);
+ const knob_y = std.math.clamp((y - inset) / side, 0, 1);
+ const knob_rim = 1 - std.math.clamp(-knob_distance / 0.7, 0, 1);
+ const knob = shade(thumb, 0.10 * (1 - knob_y) - 0.04 * knob_y - 0.09 * knob_rim * knob_y);
+ // Mix premultiplied layers before applying disabled opacity once.
+ const alpha = knob[3] * knob_coverage;
+ const out_alpha = alpha + color[3] * (1 - alpha);
+ if (out_alpha <= 0) continue;
+ text.blendPixel(&r.pixels[@intCast(py * r.width + px)], .{
+ .r = (knob[0] * alpha + color[0] * color[3] * (1 - alpha)) / out_alpha,
+ .g = (knob[1] * alpha + color[1] * color[3] * (1 - alpha)) / out_alpha,
+ .b = (knob[2] * alpha + color[2] * color[3] * (1 - alpha)) / out_alpha,
+ .a = out_alpha * opacity,
+ }, coverage);
+ }
+ }
+}
+
+fn mix(a: [4]f32, b: [4]f32, amount: f32) [4]f32 {
+ var result: [4]f32 = undefined;
+ for (&result, a, b) |*out, start, end| out.* = start + (end - start) * amount;
+ return result;
+}
+
+fn shade(color: [4]f32, amount: f32) [4]f32 {
+ const light: f32 = if (amount > 0) 1 else 0;
+ return mix(color, .{ light, light, light, color[3] }, @abs(amount));
+}
+
pub fn toggle(widget: *Widget) void {
switch (widget.kind) {
.toggle => |*data| {
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index e5e4f3f..9483bbc 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -287,6 +287,19 @@ def test_appearance_settings():
assert read_config()["compositor"]["dodge_file_drags"] is True
assert ui.scroll_into_view("dodge_file_drags").get("on") is True
+ # --- 3c. Dim inactive windows (default on) ---
+ dim_toggle = ui.scroll_into_view("inactive_dim")
+ assert dim_toggle is not None
+ assert dim_toggle.get("on") is True, "the setting should default to on"
+ assert "inactive_dim" not in read_config()["compositor"], "an untouched default is not written"
+ click_widget(dim_toggle)
+ assert read_config()["compositor"]["inactive_dim"] is False
+ dim_toggle = ui.scroll_into_view("inactive_dim")
+ assert dim_toggle.get("on") is False
+ click_widget(dim_toggle)
+ assert read_config()["compositor"]["inactive_dim"] is True
+ assert ui.scroll_into_view("inactive_dim").get("on") is True
+
# --- 4. Animation speed segmented control ---
# Options: 0.5× (idx 0), 1.0× (idx 1), 1.5× (idx 2), 2.0× (idx 3)
speed_seg = ui.scroll_into_view("anim_speed")
@@ -529,6 +542,57 @@ def test_appearance_settings():
stop_process(process)
+def test_gold_settings_palette():
+ """Light app content and dark chrome/sidebar must keep separate palettes."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-settings-palette-") as directory:
+ tmp = Path(directory)
+ env = {"DBUS_SESSION_BUS_ADDRESS": "", "REDIWM_FILES_DEVICES": "0",
+ "XDG_CONFIG_HOME": str(tmp / "config"), "XDG_DATA_HOME": str(tmp / "data"),
+ "XDG_CACHE_HOME": str(tmp / "cache")}
+ process, log = spawn_compositor(tmp, config_content='[compositor]\nxwayland = false\n[animations]\nenabled = false\n', env_extra=env)
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ ui = UIDriver(ipc)
+ ipc.action("open_appearance")
+ ipc.wait_for_panel_settled("control_center")
+ ipc.action("theme.apply", {"id": "gold"})
+
+ def capture():
+ ipc.move_cursor(2, 2)
+ ipc.wait_for_panel_settled("control_center")
+ ipc.wait_for_frame()
+ shot = tmp / "settings.png"
+ shot.unlink(missing_ok=True)
+ ipc.screenshot(str(shot))
+ with Image.open(shot) as image:
+ return image.convert("RGB")
+
+ def contains_color(image, widget, color):
+ assert widget["visible"] and not widget["clipped"], widget
+ b = widget["global_box"]
+ crop = image.crop((b["x"], b["y"], b["x"] + b["width"], b["y"] + b["height"]))
+ count = sum(n for n, pixel in crop.getcolors(crop.width * crop.height)
+ if max(abs(a - b) for a, b in zip(pixel, color)) <= 2)
+ assert count > 10, (widget["name"], widget["label"], color, count)
+
+ for reload in (False, True):
+ if reload:
+ ipc.reload_config()
+ ui.scroll_into_view("theme")
+ image = capture()
+ contains_color(image, ui.find("Theme", role="text"), (57, 51, 46))
+ contains_color(image, ui.find("theme", role="select"), (57, 51, 46))
+ contains_color(image, ui.find("general", role="row"), (241, 231, 219))
+ contains_color(image, ui.find("appearance", role="row"), (116, 92, 72))
+ ui.scroll_into_view("apply_gtk_colors")
+ image = capture()
+ contains_color(image, ui.find("apply_gtk_colors"), (57, 51, 46))
+ finally:
+ stop_process(process)
+ log.close()
+ print("PASS: Gold Settings content, controls and sidebar colors, live and reloaded")
+
+
def test_app_colors():
with tempfile.TemporaryDirectory(prefix="rediwm-app-colors-") as directory:
tmp = Path(directory)
@@ -679,6 +743,7 @@ Path(sys.argv[1]).write_text(json.dumps({k: os.environ[k] for k in keys if k in
if __name__ == "__main__":
if "--app-colors-only" not in sys.argv:
+ test_gold_settings_palette()
test_appearance_settings()
print("PASS: appearance settings (chrome opacity, inactive opacity, animations controls, bundled themes)")
test_app_colors()
diff --git a/tests/battery_popup.py b/tests/battery_popup.py
index b0e1365..d86779f 100644
--- a/tests/battery_popup.py
+++ b/tests/battery_popup.py
@@ -6,13 +6,14 @@ from pathlib import Path
import subprocess
import sys
import tempfile
+import time
from PIL import Image, ImageChops
from ipc_client import IPCClient, spawn_compositor, stop_process
from power_profiles import start_fake, stop_fake, read_line, command, wait_for, log_text
-def run(scale):
+def run(scale, gold=False, top=False):
with tempfile.TemporaryDirectory(prefix="rediwm-battery-") as directory:
root = Path(directory)
hook = root / "battery.so"
@@ -25,8 +26,11 @@ def run(scale):
(supply / "scope").write_text("System\n")
(supply / "uevent").write_text(f"POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY={percent}\nPOWER_SUPPLY_STATUS={state}\n" + (
"POWER_SUPPLY_ENERGY_FULL=57000000\nPOWER_SUPPLY_ENERGY_FULL_DESIGN=90000000\nPOWER_SUPPLY_CYCLE_COUNT=482\n" if details else ""))
+ config = '[compositor]\nxwayland = false\ntaskbar_position = "' + ('top' if top else 'bottom') + '"\n'
+ if gold:
+ config += '[theme]\nbase = "gold"\n'
fake = start_fake()
- process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"), config_content='[compositor]\nxwayland = false\n', env_extra={
+ process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"), config_content=config, env_extra={
"LD_PRELOAD": str(hook), "REDIWM_TEST_BATTERY_DIR": str(supply.parent),
"DBUS_SYSTEM_BUS_ADDRESS": os.environ["DBUS_SESSION_BUS_ADDRESS"],
"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": str(tmp),
@@ -44,12 +48,14 @@ def run(scale):
battery, clock = center(boxes["battery"]), center(boxes["clock"])
assert ipc.hit_test(*battery)["widget"] == "battery"
ipc.click_at(*battery)
+ time.sleep(0.35) # Let the panel slide/fade finish before pixel comparisons.
ipc.wait_for_frame()
- point = battery[0], bar["box"]["y"] - 40
+ point = battery[0], bar["box"]["y"] + bar["box"]["height"] + 40 if top else bar["box"]["y"] - 40
hit = ipc.hit_test(*point)
assert hit["target_type"] == "battery_popup", hit
origin = point[0] - hit["local_x"], point[1] - hit["local_y"]
- factor = min(1, (bar["box"]["width"] - 24) / 368, (bar["box"]["y"] - 24) / 496)
+ output_height = ipc.get_outputs()[0]["logical_height"] if top else bar["box"]["y"] + bar["box"]["height"]
+ factor = min(1, (bar["box"]["width"] - 24) / 368, (output_height - bar["box"]["height"] - 24) / 496)
def row(index):
return round(origin[0] + 180 * factor), round(origin[1] + (382 + index * 32) * factor)
@@ -62,7 +68,12 @@ def run(scale):
return image.convert("RGB").copy()
initial = capture("initial")
- initial.save(f"/tmp/rediwm-battery-{state}-{scale}.png")
+ initial.save(f"/tmp/rediwm-battery-{state}-{scale}{'-gold' if gold else ''}{'-top' if top else ''}.png")
+ if gold:
+ raster = float(scale)
+ x, y = round((origin[0] + 24 * factor) * raster), round((origin[1] + 295 * factor) * raster)
+ red, green, blue = initial.getpixel((x, y))
+ assert red > 190 and green > 180 and blue > 155, ("Gold detail card", (red, green, blue))
# Click selection and external changes both update the check.
ipc.click_at(*row(2))
@@ -117,4 +128,8 @@ if __name__ == "__main__":
os.execvpe("dbus-run-session", ["dbus-run-session", "--", sys.executable, __file__, *sys.argv[1:]], {**os.environ, "REDIWM_BATTERY_PRIVATE_BUS": "1"})
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--scale", default="1")
- run(parser.parse_args().scale)
+ parser.add_argument("--gold", action="store_true")
+ parser.add_argument("--top", action="store_true")
+ args = parser.parse_args()
+ os.umask(0o077)
+ run(args.scale, args.gold, args.top)
diff --git a/tests/dock.py b/tests/dock.py
index 1e3c186..0e85960 100644
--- a/tests/dock.py
+++ b/tests/dock.py
@@ -88,6 +88,20 @@ enabled = false
assert not tomllib.loads((tmp / 'rediwm-config.toml').read_text())['compositor']['dock_enabled']
click(ui.scroll_into_view('dock_enabled'))
wait_for(dock, 'dock enabled again')
+ assert ui.scroll_into_view('dock_position')['selected_index'] == 1
+ for index, position in ((0, 'top'), (2, 'left'), (3, 'right'), (1, 'bottom')):
+ area = ui.scroll_into_view('dock_position')['global_box']
+ ipc.click_at(round(area['x'] + area['width'] * (index + .5) / 4),
+ round(area['y'] + area['height'] / 2))
+ wait_for(lambda: tomllib.loads((tmp / 'rediwm-config.toml').read_text())['compositor'].get('dock_position') == position, 'dock position saved')
+ wait_for(lambda: dock()[0]['global_box']['width' if position in ('left', 'right') else 'height'] == 68, 'dock position applied')
+ root = dock()[0]['global_box']
+ assert root['width' if position in ('left', 'right') else 'height'] == 68
+ assert ui.find('dock_position', panel='control_center')['selected_index'] == index
+ ipc.action('close_panel', {'panel': 'control_center'})
+ ipc.action('open_appearance')
+ ipc.wait_for_panel_settled('control_center')
+ assert ui.scroll_into_view('dock_position')['selected_index'] == 1
slider = ui.scroll_into_view('dock_height')
assert (slider['min'], slider['max'], slider['step'], slider['value']) == (48, 96, 2, 68)
root = dock()[0]['global_box']
@@ -126,6 +140,28 @@ enabled = false
ipc.action('open_appearance')
ipc.wait_for_panel_settled('control_center')
assert ui.scroll_into_view('dock_height')['value'] == 96
+ zoom_slider = ui.scroll_into_view('dock_hover_zoom')
+ assert (zoom_slider['min'], zoom_slider['max']) == (1, 1.5)
+ assert abs(zoom_slider['step'] - .05) < .001
+ assert abs(zoom_slider['value'] - 1.05) < .001
+ for zoom in (1, 1.5, 1.05):
+ area = ui.scroll_into_view('dock_hover_zoom')['global_box']
+ for _ in range(3):
+ point = (round(area['x'] + min(area['width'] - 1, area['width'] * (zoom - 1) / .5)),
+ round(area['y'] + area['height'] / 2))
+ if ipc.hit_test(*point)['target_type'] != 'dock':
+ break
+ viewport = next(w['global_box'] for w in ui.widgets() if w['role'] == 'scroll_container')
+ ipc.move_cursor(viewport['x'] + viewport['width'] - 8, viewport['y'] + 40)
+ ipc.scroll(0, -130)
+ wait_for(lambda: ui.find('dock_hover_zoom')['global_box']['y'] < area['y'], 'zoom scrolled above dock')
+ area = ui.scroll_into_view('dock_hover_zoom')['global_box']
+ ipc.click_at(*point)
+ wait_for(lambda: abs(tomllib.loads((tmp / 'rediwm-config.toml').read_text())['compositor'].get('dock_hover_zoom', 0) - zoom) < .001, 'zoom saved')
+ ipc.action('close_panel', {'panel': 'control_center'})
+ ipc.action('open_appearance')
+ ipc.wait_for_panel_settled('control_center')
+ assert abs(ui.scroll_into_view('dock_hover_zoom')['value'] - 1.05) < .001
ipc.action('close_panel', {'panel': 'control_center'})
ipc.wait_for_frame()
assert ipc.get_shell_state()['taskbars'], 'dock must coexist with taskbar'
@@ -525,6 +561,7 @@ def pill_animation():
def pixels(name):
path = tmp / (name + '.png')
+ path.unlink(missing_ok=True)
ipc.screenshot(str(path))
widgets = ui.widgets('dock')
b = next(w['global_box'] for w in widgets if w['name'] == 'terminal')
@@ -534,6 +571,69 @@ def pill_animation():
return image.convert('RGB').crop(tuple(round(v * scale) for v in
(x - 14, y, x + 14, root['y'] + root['height'] - 2)))
+ # Hover shares the dock's frame clock, reverses without jumping,
+ # and exposes the enlarged icon as a clickable widget.
+ def zoom_state():
+ site = f'dock.{primary}.terminal.hover_zoom'
+ return next((a for a in ipc.action('get_animations') if a['site'] == site), None)
+
+ def terminal_box():
+ return next(w['global_box'] for w in ui.widgets('dock') if w['name'] == 'terminal')
+
+ cfg = tmp / 'rediwm-config.toml'
+ cfg.write_text(cfg.read_text().replace('[compositor]', '[compositor]\ndock_hover_zoom = 1.5'))
+ ipc.reload_config()
+ ipc.wait_for_frame(output=primary)
+ base = terminal_box()
+ x, y = round(base['x'] + base['width'] / 2), round(base['y'] + base['height'] / 2)
+ ipc.move_cursor(x, y)
+ assert zoom_state()['target'] == 1.5
+ advance(60)
+ growing_zoom = zoom_state()
+ assert 1 < growing_zoom['value'] < 1.5
+ ipc.move_cursor(5, 5)
+ shrinking_zoom = zoom_state()
+ assert shrinking_zoom['target'] == 1
+ assert abs(shrinking_zoom['value'] - growing_zoom['value']) < .001
+ assert abs(shrinking_zoom['velocity'] - growing_zoom['velocity']) < .001
+ advance(1000)
+ assert zoom_state()['value'] == 1 and zoom_state()['settled']
+ ipc.move_cursor(x, y)
+ advance(1000)
+ expanded = terminal_box()
+ assert zoom_state()['value'] == 1.5 and expanded['width'] > base['width']
+ edge = (round(expanded['x'] + 1), y)
+ assert edge[0] < base['x']
+ ipc.move_cursor(*edge)
+ assert zoom_state()['target'] == 1.5, 'expanded icon lost hover at its edge'
+ assert ipc.hit_test(*edge)['target_type'] == 'dock'
+ # Rebuild at an expanded edge preserves hover and input bounds.
+ cfg.write_text(cfg.read_text() + '\n[theme]\ndock_radius = 17\n')
+ ipc.reload_config()
+ ipc.wait_for_frame(output=primary)
+ assert zoom_state()['target'] == 1.5
+ cfg.write_text(cfg.read_text().replace('dock_hover_zoom = 1.5', 'dock_hover_zoom = 1.0'))
+ ipc.reload_config()
+ ipc.wait_for_frame(output=primary)
+ assert zoom_state() is None, '1.0 must cancel hover animation'
+ assert terminal_box()['width'] == base['width']
+ ipc.move_cursor(5, 5)
+ ipc.move_cursor(x, y)
+ assert zoom_state() is None
+ cfg.write_text(cfg.read_text().replace('dock_hover_zoom = 1.0', 'dock_hover_zoom = 1.5'))
+ ipc.reload_config()
+ ipc.wait_for_frame(output=primary)
+ advance(1000)
+ ipc.reset_perf()
+ before_hover = ipc.get_perf()
+ for _ in range(3):
+ ipc.wait_for_frame(output=primary)
+ after_hover = ipc.get_perf()
+ assert after_hover['anim_frames_scheduled'] == 0
+ assert (after_hover['panel_allocated_bytes'] + after_hover['panel_reused_bytes'] ==
+ before_hover['panel_allocated_bytes'] + before_hover['panel_reused_bytes']), 'settled hover repaints'
+ ipc.move_cursor(5, 5)
+ advance(1000)
idle = pixels('idle')
wid = launch('foot')
assert state()['target'] == 22 and state()['value'] == 0
@@ -617,6 +717,11 @@ def pill_animation():
assert state()['value'] == 22 and state()['settled']
advance(1000)
assert state('opacity')['settled'] and state('opacity')['value'] == 1
+ b = terminal_box()
+ ipc.move_cursor(round(b['x'] + b['width'] / 2), round(b['y'] + b['height'] / 2))
+ assert zoom_state()['value'] == 1.5 and zoom_state()['settled'], 'reduced-motion hover did not jump'
+ ipc.move_cursor(5, 5)
+ assert zoom_state()['value'] == 1 and zoom_state()['settled']
ipc.action('set_anim_time', {'ms': None})
ipc.move_cursor(5, 5)
ipc.wait_for_frame(output=primary)
@@ -628,7 +733,7 @@ def pill_animation():
assert after['anim_frames_scheduled'] == 0, 'settled pills keep requesting frames'
assert (after['panel_allocated_bytes'] + after['panel_reused_bytes'] ==
before['panel_allocated_bytes'] + before['panel_reused_bytes']), 'settled pills keep repainting'
- print(f'PASS: dock pill growth, focus, reversal, fading, rebuild, speed, reduced motion and idle ({scale}x)')
+ print(f'PASS: dock hover zoom, input bounds, disable, pill growth, focus, reversal, fading, rebuild, speed, reduced motion and idle ({scale}x)')
except Exception:
log.flush()
print((tmp / 'compositor.log').read_text()[-4000:])
@@ -640,7 +745,187 @@ def pill_animation():
log.close()
+
+def positions():
+ """Every edge, with either taskbar edge, using real pointer input."""
+ scale = float(os.environ.get('REDIWM_TEST_SCALE', '1'))
+ with tempfile.TemporaryDirectory(prefix='rediwm-dock-position-') as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ env_extra = {'DBUS_SESSION_BUS_ADDRESS': '', 'DBUS_SYSTEM_BUS_ADDRESS': 'unix:path=/nonexistent',
+ 'XDG_CONFIG_HOME': str(tmp / 'config'), 'XDG_DATA_HOME': str(tmp / 'data'),
+ 'XDG_CACHE_HOME': str(tmp / 'cache')}
+ def config(position, taskbar, size):
+ return (f'[compositor]\nxwayland = false\ndock_enabled = true\ndock_position = "{position}"\n'
+ f'taskbar_position = "{taskbar}"\ndock_height = {size}\ndock_hover_zoom = 1.5\n'
+ '[animations]\nenabled = false\n')
+ process, log = spawn_compositor(tmp, scale=scale, outputs=os.environ.get('REDIWM_TEST_OUTPUTS', '1'),
+ config_content=config('bottom', 'bottom', 68), env_extra=env_extra)
+ client = None
+ overflow_clients = []
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for('wallpaper_presented', timeout_ms=10000)
+ ui = UIDriver(ipc)
+ display = wait_for(lambda: next((p.name for p in tmp.glob('wayland-*')
+ if not p.name.endswith('.lock')), None), 'display')
+ client = subprocess.Popen([str(tmp / 'client'), '--app-id', 'dock.position'],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ wid = wait_for(lambda: next((w['id'] for w in ipc.get_windows() if w['app_id'] == 'dock.position'), None), 'position client')
+ ipc.wait_for('window_geometry_settled', window_id=wid)
+ cfg = tmp / 'rediwm-config.toml'
+ def root():
+ return ui.widgets('dock')[0]['global_box']
+ def item(name):
+ return next(w['global_box'] for w in ui.widgets('dock') if w['name'] == name)
+ def center(box):
+ return round(box['x'] + box['width'] / 2), round(box['y'] + box['height'] / 2)
+ def shot(name):
+ path = tmp / (name + '.png')
+ path.unlink(missing_ok=True)
+ ipc.screenshot(str(path))
+ with Image.open(path) as image:
+ return image.convert('RGB')
+ def crop(image, box):
+ return image.crop(tuple(round(v * scale) for v in box))
+ for taskbar in ('bottom', 'top'):
+ for position in ('top', 'left', 'right', 'bottom'):
+ vertical = position in ('left', 'right')
+ for size in (48, 96):
+ cfg.write_text(config(position, taskbar, size))
+ ipc.reload_config()
+ wait_for(lambda: ui.widgets('dock') and root()['width' if vertical else 'height'] == size, 'position reload')
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ box = root()
+ output = next(o for o in ipc.get_outputs() if o['x'] <= box['x'] < o['x'] + o['logical_width'])
+ bar = next(b['box'] for b in ipc.get_shell_state()['taskbars'] if b['box']['x'] == output['x'])
+ x0, y0 = output['x'], output['y'] + (bar['height'] if taskbar == 'top' else 0)
+ width, height = output['logical_width'], output['logical_height'] - bar['height']
+ if vertical:
+ assert box['y'] == y0 + (height - box['height']) // 2, box
+ assert box['x'] == (x0 + 10 if position == 'left' else x0 + width - size - 10), box
+ else:
+ assert box['x'] == x0 + (width - box['width']) // 2, box
+ assert box['y'] == (y0 + 10 if position == 'top' else y0 + height - size - 10), box
+ buttons = [w['global_box'] for w in ui.widgets('dock') if w['name']]
+ along, cross = ('y', 'x') if vertical else ('x', 'y')
+ assert all(a[along] < b[along] and a[cross] == b[cross] for a, b in zip(buttons, buttons[1:])), buttons
+ for button in buttons:
+ assert button['width'] == button['height']
+ assert ipc.hit_test(*center(button))['target_type'] == 'dock'
+ for other in ipc.get_outputs():
+ bx, by = center(button)
+ assert ipc.hit_test(bx + other['x'] - output['x'], by + other['y'] - output['y'])['target_type'] == 'dock'
+ # Compare only the interior-side tooltip area; the
+ # hovered icon and cursor are outside this crop.
+ idle = shot('idle')
+ ipc.move_cursor(*center(item('settings')))
+ ipc.wait_for_frame()
+ hovered = shot('hovered')
+ if position == 'top':
+ tip = (box['x'], box['y'] + box['height'] + 8, box['x'] + box['width'], box['y'] + box['height'] + 38)
+ elif position == 'bottom':
+ tip = (box['x'], box['y'] - 38, box['x'] + box['width'], box['y'] - 8)
+ elif position == 'left':
+ tip = (box['x'] + box['width'] + 8, box['y'], x0 + width, box['y'] + box['height'])
+ else:
+ tip = (x0, box['y'], box['x'] - 8, box['y'] + box['height'])
+ assert ImageChops.difference(crop(idle, tip), crop(hovered, tip)).getbbox(), f'{position} tooltip missing'
+ # A hovered icon is enlarged in either orientation.
+ assert item('settings')['width'] > buttons[-1]['width'], 'hover zoom missing'
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ # Running-window buttons still minimize and restore.
+ window_box = item(f'window_{wid}')
+ cx, cy = center(window_box)
+ thickness = max(2, 4 * size / 68)
+ indicator_cross = (size - round(58 * size / 68) - thickness
+ if position in ('top', 'left') else round(58 * size / 68))
+ if vertical:
+ indicator = (box['x'] + indicator_cross, cy - 12 * size / 68,
+ box['x'] + indicator_cross + thickness, cy + 12 * size / 68)
+ else:
+ indicator = (cx - 12 * size / 68, box['y'] + indicator_cross,
+ cx + 12 * size / 68, box['y'] + indicator_cross + thickness)
+ active = crop(shot('active'), indicator)
+ ipc.click_at(*center(item(f'window_{wid}')))
+ wait_for(lambda: next(w for w in ipc.get_windows() if w['id'] == wid)['is_minimized'], 'side dock minimize')
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ minimized = crop(shot('minimized'), indicator)
+ assert ImageChops.difference(active, minimized).getbbox(), f'{position} running indicator missing'
+ ipc.click_at(*center(item(f'window_{wid}')))
+ wait_for(lambda: not next(w for w in ipc.get_windows() if w['id'] == wid)['is_minimized'], 'side dock restore')
+ ipc.action('fullscreen_window', {'id': wid})
+ wait_for(lambda: not ui.widgets('dock'), 'fullscreen hides positioned dock')
+ ipc.action('fullscreen_window', {'id': wid})
+ wait_for(lambda: ui.widgets('dock'), 'positioned dock restored after fullscreen')
+ # Remove Settings by clicking the actual inward menu.
+ px, py = center(item('settings'))
+ ipc.move_cursor(px, py)
+ ipc.pointer_button(273, True)
+ ipc.pointer_button(273, False)
+ ipc.wait_for_frame()
+ if position == 'top':
+ mx, my = px, box['y'] + box['height'] + 4
+ elif position == 'bottom':
+ mx, my = px, box['y'] - 48
+ elif position == 'left':
+ mx, my = box['x'] + box['width'] + 4, py
+ else:
+ mx, my = box['x'] - 220, py
+ mx = min(max(mx, x0), x0 + width - 216)
+ my = min(max(my, y0), y0 + height - 44)
+ ipc.click_at(mx + 30, my + 22)
+ wait_for(lambda: not any(w['name'] == 'settings' for w in ui.widgets('dock')), f'{position} menu not usable')
+ assert tomllib.loads(cfg.read_text())['compositor']['dock_hidden_shortcuts'] == ['settings']
+ # Restart preserves a side dock without an Appearance window.
+ cfg.write_text(config('right', 'top', 96))
+ ipc.reload_config()
+ wait_for(lambda: root()['width'] == 96, 'overflow dock')
+ capacity = (height - round(12 * 96 / 68) * 2 - 16) // round(56 * 96 / 68) - 4
+ for index in range(capacity + 1):
+ overflow_clients.append(subprocess.Popen([str(tmp / 'client'), '--app-id', f'dock.side.overflow{index}'],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ wait_for(lambda: len(ipc.get_windows()) == capacity + 2, 'vertical overflow clients')
+ def shown():
+ return {w['name'] for w in ui.widgets('dock') if (w['name'] or '').startswith('window_')}
+ wait_for(lambda: len(shown()) == capacity, 'vertical dock capacity')
+ first = shown()
+ ipc.move_cursor(*center(item('terminal')))
+ ipc.scroll(0, -120)
+ try:
+ wait_for(lambda: shown() != first, 'vertical overflow scroll', timeout=2)
+ except AssertionError:
+ ipc.scroll(0, 120)
+ wait_for(lambda: shown() != first, 'vertical overflow windows unreachable')
+ box = root()
+ assert box['y'] >= y0 and box['y'] + box['height'] <= y0 + height, box
+ stop_process(process)
+ log.close()
+ process, log = spawn_compositor(tmp, scale=scale, outputs=os.environ.get('REDIWM_TEST_OUTPUTS', '1'),
+ config_content=cfg.read_text(), env_extra=env_extra)
+ with IPCClient(tmp) as ipc:
+ ui = UIDriver(ipc)
+ wait_for(lambda: ui.widgets('dock'), 'side dock after restart')
+ box = ui.widgets('dock')[0]['global_box']
+ assert box['width'] == 96 and box['height'] > box['width'], box
+ print(f'PASS: dock four edges, both taskbar edges, size, input, hover, tooltips, menus, fullscreen, vertical overflow and restart ({scale}x)')
+ finally:
+ for overflow_client in overflow_clients:
+ stop_process(overflow_client)
+ if client:
+ stop_process(client)
+ stop_process(process)
+ log.close()
+
if __name__ == '__main__':
- run()
- context_menu()
- pill_animation()
+ import sys
+ if '--positions-only' not in sys.argv:
+ run()
+ context_menu()
+ pill_animation()
+ positions()
diff --git a/tests/files_folder_size.py b/tests/files_folder_size.py
index 31ef2a4..563929d 100644
--- a/tests/files_folder_size.py
+++ b/tests/files_folder_size.py
@@ -112,10 +112,10 @@ def run():
time.sleep(.1)
# In grid view, cell width is ~235px. Card 0 starts at x = 228 (sidebar 208 + 20).
- # Subtitle (sizeButtonRect) for item 0 is at (x + 22, y + 102), with y = 112 + 20 = 132.
- # So button 0 is around x = 255, y = 240.
+ # Subtitle (sizeButtonRect) for item 0 is at (x + 6, y + 86), with y = 112 + 20 = 132.
+ # So button 0 is around x = 250, y = 225.
# Click the dash button of item 0 (big_folder)
- click(255, 240)
+ click(250, 225)
time.sleep(.2)
# Clicking dash must NOT select big_folder (item 1 small_folder must still be active/selected)
diff --git a/tests/files_thumbnails.py b/tests/files_thumbnails.py
index 1e44911..de8a9ee 100644
--- a/tests/files_thumbnails.py
+++ b/tests/files_thumbnails.py
@@ -169,13 +169,16 @@ def run():
def screenshot():
win = windows()[0]
+ # Inspect client pixels: the window icon can itself match
+ # a thumbnail colour (the default Files icon contains red).
+ box = request({"version": 1, "command": "get_window_debug", "params": {"id": win["id"]}})["WindowDebug"]["client_box"]
shot.unlink(missing_ok=True)
action('screenshot', {"path": str(shot)})
wait_for(shot.exists, "no screenshot")
time.sleep(0.05)
with Image.open(shot) as full:
- return full.crop((win["x"], win["y"], win["x"] + win["width"],
- win["y"] + win["height"])).convert("RGB")
+ return full.crop((box["x"], box["y"], box["x"] + box["width"],
+ box["y"] + box["height"])).convert("RGB")
def launch(folder=pics, **extra):
p = start("rediwm-files", str(folder), WAYLAND_DISPLAY=display, **extra)
@@ -207,19 +210,19 @@ def run():
# --- First visit: decode, draw, write to the shared cache. ---
files = launch()
- wait_blob(GREEN, (48, 36), "800x600 PNG thumbnail (48x36)")
- wait_blob(BLUE, (16, 48), "300x900 PNG thumbnail keeps its shape (16x48)")
- wait_blob(RED, (48, 36), "1600x1200 JPEG thumbnail (48x36)")
- image = wait_blob(CYAN, (48, 48), "seeded shared-cache entry (48x48)")
+ wait_blob(GREEN, (54, 40), "800x600 PNG thumbnail (54x40)")
+ wait_blob(BLUE, (18, 54), "300x900 PNG thumbnail keeps its shape (18x54)")
+ wait_blob(RED, (54, 40), "1600x1200 JPEG thumbnail (54x40)")
+ image = wait_blob(CYAN, (54, 54), "seeded shared-cache entry (54x54)")
# The seeded entry replaced the real picture: no 900x900 red square
- # in that cell, only the JPEG's 48x36 red one counted above.
+ # in that cell, only the JPEG's 54x40 red one counted above.
yellow_box, _ = blob(image, YELLOW)
magenta_box, _ = blob(image, MAGENTA)
assert yellow_box and magenta_box, "EXIF-rotated thumbnail missing"
- # Orientation 6 turns the landscape picture upright: 24x48, with
+ # Orientation 6 turns the landscape picture upright: 27x54, with
# yellow (the original top half) on the right of magenta.
- assert close(size_of(yellow_box), (12, 48), 3), yellow_box
- assert close(size_of(magenta_box), (12, 48), 3), magenta_box
+ assert close(size_of(yellow_box), (14, 54), 3), yellow_box
+ assert close(size_of(magenta_box), (14, 54), 3), magenta_box
assert magenta_box[0] < yellow_box[0], (magenta_box, yellow_box)
print("Thumbnails drawn with correct shape, colour and EXIF orientation.")
# Nothing was drawn for the corrupt picture or the text file:
@@ -247,7 +250,7 @@ def run():
# --- Editing a file replaces its thumbnail. ---
Image.new("RGB", (1000, 400), LIME).save(pics / "a_red.jpg", quality=90)
- wait_blob(LIME, (48, 19), "edited picture's new thumbnail (48x19)", slack=3)
+ wait_blob(LIME, (54, 22), "edited picture's new thumbnail (54x22)", slack=3)
assert blob(screenshot(), RED)[1] < 100, "stale red thumbnail still drawn"
print("Editing a picture refreshes its thumbnail.")
@@ -262,7 +265,7 @@ def run():
# --- A later visit shows the same pictures from the cache. ---
files = launch()
- wait_blob(GREEN, (48, 36), "cached thumbnail on second visit")
+ wait_blob(GREEN, (54, 40), "cached thumbnail on second visit")
stop(files)
# --- The environment switch turns the feature off. ---
diff --git a/tests/taskbar_sections.py b/tests/taskbar_sections.py
new file mode 100644
index 0000000..a481a05
--- /dev/null
+++ b/tests/taskbar_sections.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+"""Taskbar sections, live settings, input, legacy config and persistence."""
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import tomllib
+
+from desktop_zoom import build_client, wait_for
+from ipc_client import IPCClient, spawn_compositor, stop_process
+from ui_driver import UIDriver
+
+
+def run():
+ scale = float(os.environ.get('REDIWM_TEST_SCALE', '1'))
+ with tempfile.TemporaryDirectory(prefix='rediwm-taskbar-sections-') as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ env_extra = {'DBUS_SESSION_BUS_ADDRESS': '', 'DBUS_SYSTEM_BUS_ADDRESS': 'unix:path=/nonexistent',
+ 'XDG_CONFIG_HOME': str(tmp / 'config'), 'XDG_DATA_HOME': str(tmp / 'data'),
+ 'XDG_CACHE_HOME': str(tmp / 'cache')}
+ original = '# preserve me\n[compositor]\nxwayland = false\n[animations]\nenabled = false\n'
+ process, log = spawn_compositor(tmp, scale=scale, outputs=os.environ.get('REDIWM_TEST_OUTPUTS', '1'),
+ config_content=original, env_extra=env_extra)
+ clients = []
+ cfg = tmp / 'rediwm-config.toml'
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for('wallpaper_presented', timeout_ms=10000)
+ ui = UIDriver(ipc)
+ display = wait_for(lambda: next((p.name for p in tmp.glob('wayland-*') if not p.name.endswith('.lock')), None), 'display')
+ for index in range(2):
+ clients.append(subprocess.Popen([str(tmp / 'client'), '--app-id', f'taskbar.section.{index}'],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
+ wait_for(lambda: len(ipc.get_windows()) == 2, 'windows')
+ ipc.wait_for_frame()
+ def bar():
+ return ui.widgets('taskbar')
+ def box(name):
+ return next(w['global_box'] for w in bar() if w['name'] == name)
+ def center(b):
+ return round(b['x'] + b['width'] / 2), round(b['y'] + b['height'] / 2)
+ def chips():
+ return [w['global_box'] for w in bar() if w['role'] == 'chip']
+ def check_bounds():
+ root = bar()[0]['global_box']
+ items = [w['global_box'] for w in bar()[1:] if w['visible']]
+ items.sort(key=lambda b: b['x'])
+ for b in items:
+ assert root['x'] <= b['x'] and b['x'] + b['width'] <= root['x'] + root['width'], (root, b)
+ assert ipc.hit_test(*center(b))['target_type'] == 'taskbar', b
+ for a, b in zip(items, items[1:]):
+ assert a['x'] + a['width'] <= b['x'] + 1, (a, b)
+ root = bar()[0]['global_box']
+ row = chips()
+ assert abs((row[0]['x'] + row[-1]['x'] + row[-1]['width']) / 2 - (root['x'] + root['width'] / 2)) <= 1, row
+ assert box('start')['x'] < row[0]['x'] < box('clock')['x']
+ check_bounds()
+ ipc.action('open_appearance')
+ ipc.wait_for_panel_settled('control_center')
+ for name, expected in (('start', 0), ('windows', 1), ('tray', 2), ('clock', 2)):
+ assert ui.scroll_into_view(f'taskbar_{name}_section')['selected_index'] == expected
+ # Move fixed controls and both primary groups to every section.
+ for name in ('clock', 'network', 'volume', 'start', 'windows', 'tray'):
+ for zone in (0, 1, 2):
+ widget = ui.scroll_into_view(f'taskbar_{name}_section')
+ area = widget['global_box']
+ ipc.click_at(round(area['x'] + area['width'] * (zone + .5) / 3), round(area['y'] + area['height'] / 2))
+ wait_for(lambda: ui.find(f'taskbar_{name}_section')['selected_index'] == zone, 'section selection')
+ if widget['selected_index'] != zone:
+ wait_for(lambda: any(entry.lstrip('-') == f'{("left", "center", "right")[zone]}:{name}'
+ for entry in tomllib.loads(cfg.read_text())['compositor']['taskbar_items']), 'section saved')
+ ipc.wait_for_frame()
+ ipc.wait_for_panel_settled('control_center')
+ check_bounds()
+ # Drag order and keyboard order stay inside the chosen section.
+ before = tomllib.loads(cfg.read_text())['compositor']['taskbar_items']
+ handle = ui.scroll_into_view('taskbar_network_order')
+ volume = ui.scroll_into_view('taskbar_volume_order')
+ handle = ui.find('taskbar_network_order')
+ fx, fy = center(handle['global_box'])
+ tx, ty = center(volume['global_box'])
+ assert handle['visible'] and not handle['clipped'], handle
+ ipc.drag(fx, fy, tx, ty + (3 if fy < ty else -3))
+ wait_for(lambda: tomllib.loads(cfg.read_text())['compositor']['taskbar_items'] != before, 'drag reorder')
+ ipc.wait_for_panel_settled('control_center')
+ dragged = tomllib.loads(cfg.read_text())['compositor']['taskbar_items']
+ assert (dragged.index('right:network') > dragged.index('right:volume')) != (before.index('right:network') > before.index('right:volume')), dragged
+ handle = ui.scroll_into_view('taskbar_network_order')
+ ipc.click_at(*center(handle['global_box']))
+ ipc.key(108, True)
+ ipc.key(108, False)
+ wait_for(lambda: tomllib.loads(cfg.read_text())['compositor']['taskbar_items'] != dragged, 'keyboard reorder')
+ ipc.wait_for_panel_settled('control_center')
+ assert '# preserve me' in cfg.read_text()
+ # Hide and restore the window group without changing windows.
+ toggle = ui.scroll_into_view('taskbar_windows_visible')
+ ipc.click_at(*center(toggle['global_box']))
+ wait_for(lambda: not chips(), 'hidden window list')
+ assert len([w for w in ipc.get_windows() if w['app_id'].startswith('taskbar.section.')]) == 2
+ toggle = ui.scroll_into_view('taskbar_windows_visible')
+ ipc.click_at(*center(toggle['global_box']))
+ wait_for(lambda: chips(), 'window list restored')
+ ipc.action('close_panel', {'panel': 'control_center'})
+ ipc.wait_for_frame()
+ # Start's hit target and menu follow its moved position.
+ ipc.click_at(*center(box('start')))
+ wait_for(lambda: ipc.get_shell_state()['start_menu'], 'moved Start button opens menu')
+ menu = ipc.get_shell_state()['start_menu']['box']
+ assert root['x'] <= menu['x'] and menu['x'] + menu['width'] <= root['x'] + root['width'], menu
+ ipc.key(1, True)
+ ipc.key(1, False)
+ wait_for(lambda: not ipc.get_shell_state()['start_menu'], 'Start menu dismissed')
+ saved = cfg.read_text()
+ # The original status-only config still preserves order/hiding.
+ cfg.write_text(original.replace('[compositor]', '[compositor]\ntaskbar_items = ["clock", "-network", "volume", "battery"]'))
+ ipc.reload_config()
+ wait_for(lambda: not any(w['name'] == 'tray/1' for w in bar()), 'legacy hidden network')
+ assert box('clock')['x'] < box('tray/0')['x']
+ row = chips()
+ assert abs((row[0]['x'] + row[-1]['x'] + row[-1]['width']) / 2 - (root['x'] + root['width'] / 2)) <= 1
+ cfg.write_text(saved)
+ for client in clients:
+ stop_process(client)
+ clients.clear()
+ stop_process(process)
+ log.close()
+ process, log = spawn_compositor(tmp, scale=scale, config_content=cfg.read_text(), env_extra=env_extra)
+ with IPCClient(tmp) as ipc:
+ ipc.action('open_appearance')
+ ipc.wait_for_panel_settled('control_center')
+ ui = UIDriver(ipc)
+ assert ui.scroll_into_view('taskbar_start_section')['selected_index'] == 2
+ assert ui.scroll_into_view('taskbar_windows_section')['selected_index'] == 2
+ assert ui.scroll_into_view('taskbar_clock_section')['selected_index'] == 2
+ print(f'PASS: taskbar sections, center default, section moves, bounds/input, visibility, Start menu, legacy config and restart ({scale}x)')
+ finally:
+ for client in clients:
+ stop_process(client)
+ stop_process(process)
+ log.close()
+
+
+if __name__ == '__main__':
+ run()
diff --git a/tests/theme_packs.py b/tests/theme_packs.py
index 475ab63..3f1d948 100644
--- a/tests/theme_packs.py
+++ b/tests/theme_packs.py
@@ -21,6 +21,8 @@ ROOT = Path(__file__).resolve().parents[1]
HELPER = ROOT / "zig-out/bin/rediwm-theme"
FIXTURE = ROOT / "tests/fixtures/theme-pack"
PINK = (244, 44, 160)
+HOME_COLOR = (32, 211, 231)
+TRASH_COLOR = (180, 91, 237)
def helper(env, *args, ok=True):
@@ -81,13 +83,16 @@ def run():
env = dict(os.environ, XDG_DATA_HOME=str(tmp / "data"), XDG_STATE_HOME=str(tmp / "state"),
XDG_CONFIG_HOME=str(tmp / "config"), XDG_CACHE_HOME=str(tmp / "cache"),
DBUS_SESSION_BUS_ADDRESS="", DBUS_SYSTEM_BUS_ADDRESS="unix:path=/nonexistent",
- REDIWM_FILES_DEVICES="0", REDIWM_DESKTOP_BUILTINS="0", REDIWM_DESKTOP_DIR=str(tmp / "desktop"))
+ REDIWM_FILES_DEVICES="0", REDIWM_DESKTOP_BUILTINS="1", REDIWM_DESKTOP_DIR=str(tmp / "desktop"))
env.pop("REDIWM_THEME", None)
env.pop("REDIWM_CONFIG", None)
env.pop("REDIWM_SOCKET", None)
hostile_archives(tmp, env)
pack = tmp / "source"
shutil.copytree(FIXTURE, pack)
+ for name, color in (("user-home", HOME_COLOR), ("user-trash", TRASH_COLOR)):
+ fill = "#%02x%02x%02x" % color
+ (pack / f"icons/{name}.svg").write_text((pack / "icons/folder.svg").read_text().replace("#f42ca0", fill))
# A real built cursor with the sole allowed alias form.
(pack / "cursors/cursors").mkdir(parents=True)
shutil.copyfile(ROOT / "zig-out/share/icons/phinger-cursors-dark/cursors/default", pack / "cursors/cursors/left_ptr")
@@ -122,21 +127,25 @@ def run():
gold = ipc.action("get_theme")
assert gold["tokens"]["notification_blur"] is True
assert gold["tokens"]["app_fg"] != gold["tokens"]["window_fg"]
+ assert gold["tokens"]["app_sidebar"][3] == 1
+ for key in ("app_item_hover", "app_sidebar_hover", "app_surface_hover",
+ "surface_hover", "start_menu_selected_bg"):
+ assert abs(gold["tokens"][key][3] - 0.96) < .001, key
wait_for(lambda: UIDriver(ipc).widgets("dock"), "Gold dock did not appear")
assert ipc.get_shell_state()["taskbars"][0]["box"]["y"] == 0
assert UIDriver(ipc).widgets("dock")[0]["global_box"]["height"] == 76
wait_for(lambda: (ipc.query("get_wallpaper")["displayed_path"] or "").endswith("/wallpaper-gold.png"), "Gold wallpaper was not presented")
cfg = tomllib.loads((tmp / "rediwm-config.toml").read_text())
- assert not {"dock_enabled", "dock_height", "taskbar_position"} & cfg["compositor"].keys()
+ assert not {"dock_enabled", "dock_position", "dock_height", "dock_hover_zoom", "taskbar_position"} & cfg["compositor"].keys()
if shutil.which("foot"):
helper(dict(env, REDIWM_CONFIG=str(tmp / "rediwm-config.toml")), "terminal", "foot", "--check-config", "--config=/dev/null")
config_path = tmp / "rediwm-config.toml"
- config_path.write_text(config_path.read_text().replace("[compositor]", '[compositor]\ndock_enabled = false\ntaskbar_position = "bottom"\ndock_height = 48', 1))
+ config_path.write_text(config_path.read_text().replace("[compositor]", '[compositor]\ndock_enabled = false\ndock_position = "left"\ntaskbar_position = "bottom"\ndock_height = 48\ndock_hover_zoom = 1.5', 1))
wait_for(lambda: not UIDriver(ipc).widgets("dock"), "explicit dock override did not win")
assert ipc.get_shell_state()["taskbars"][0]["box"]["y"] > 0
ipc.action("theme.apply", {"id": "gold"})
wait_for(lambda: UIDriver(ipc).widgets("dock"), "reset did not restore Gold layout")
- assert not {"dock_enabled", "dock_height", "taskbar_position"} & tomllib.loads(config_path.read_text())["compositor"].keys()
+ assert not {"dock_enabled", "dock_position", "dock_height", "dock_hover_zoom", "taskbar_position"} & tomllib.loads(config_path.read_text())["compositor"].keys()
# Every other bundled theme restores the standard bar and no dock.
for theme_id in ("rediwm-dark", "rediwm-light", "redi-blue", "redi-mocha"):
ipc.action("theme.apply", {"id": "gold"})
@@ -171,11 +180,13 @@ def run():
ipc.screenshot(str(shot))
colors = dict((color, count) for count, color in Image.open(shot).convert("RGB").getcolors(1280 * 720 * 4))
assert colors.get((18, 90, 130), 0) > 5000, "pack wallpaper pixels missing"
- def desktop_has_folder():
+ def desktop_has_icons():
shot.unlink(missing_ok=True)
ipc.screenshot(str(shot))
- return any(color == PINK for color in Image.open(shot).convert("RGB").getdata())
- wait_for(desktop_has_folder, "desktop folder did not use pack icon")
+ with Image.open(shot) as image:
+ colors = dict((color, count) for count, color in image.convert("RGB").getcolors(image.width * image.height))
+ return all(colors.get(color, 0) > 100 for color in (PINK, HOME_COLOR, TRASH_COLOR))
+ wait_for(desktop_has_icons, "desktop folder, Home or Trash did not use pack icons")
assert colors.get((33, 219, 175), 0) > 10, "pack start logo pixels missing"
# App clients resolve base through their normal settings worker.
display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
@@ -193,16 +204,29 @@ def run():
pixels = Image.open(files_shot).convert("RGB").crop((box["x"], box["y"], box["x"] + box["width"], box["y"] + box["height"]))
return any(color == PINK for color in pixels.getdata())
wait_for(files_has_folder, "Files did not use pack folder icon")
+ def files_has_sidebar_icons():
+ files_shot.unlink(missing_ok=True)
+ ipc.screenshot(str(files_shot))
+ box = ipc.get_window_debug(win["id"])["client_box"]
+ with Image.open(files_shot) as image:
+ sidebar = image.convert("RGB").crop((box["x"], box["y"], box["x"] + 50, box["y"] + box["height"]))
+ colors = dict((color, count) for count, color in sidebar.getcolors(sidebar.width * sidebar.height))
+ return all(colors.get(color, 0) > 50 for color in (PINK, HOME_COLOR, TRASH_COLOR))
+ wait_for(files_has_sidebar_icons, "Files sidebar did not use pack folder, Home and Trash icons")
ipc.action("theme.apply", {"id": "gold"})
def files_has_gold_palette():
files_shot.unlink(missing_ok=True)
ipc.screenshot(str(files_shot))
with Image.open(files_shot) as image:
colors = dict((color, count) for count, color in image.convert("RGB").getcolors(image.width * image.height))
- return colors.get((238, 230, 219), 0) > 5000 and colors.get((57, 51, 46), 0) > 100 and colors.get((241, 231, 219), 0) > 100
+ return (colors.get((238, 230, 219), 0) > 5000
+ and colors.get((68, 61, 58), 0) > 5000
+ and colors.get((57, 51, 46), 0) > 100
+ and colors.get((241, 231, 219), 0) > 100)
wait_for(files_has_gold_palette, "Gold app, sidebar and chrome foregrounds were not separated")
ipc.action("theme.apply", {"id": "test-pack"})
wait_for(files_has_folder, "Files did not restore pack icons after Gold")
+ wait_for(files_has_sidebar_icons, "Files sidebar did not restore pack icons after Gold")
ipc.action("set_accent_color", {"color": "#112233"})
cfg = tomllib.loads((tmp / "rediwm-config.toml").read_text())
assert set(cfg["theme"]) == {"base", "accent"}, cfg["theme"]
diff --git a/tests/wifi_popup.py b/tests/wifi_popup.py
index 4d5a023..368853c 100644
--- a/tests/wifi_popup.py
+++ b/tests/wifi_popup.py
@@ -150,11 +150,14 @@ def start_fake():
return process
-def run(scale):
+def run(scale, gold=False, top=False):
fake = start_fake()
with tempfile.TemporaryDirectory(prefix='rediwm-wifi-') as directory:
tmp = Path(directory)
- process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'), config_content='[compositor]\nxwayland = false\n', env_extra={
+ config = '[compositor]\nxwayland = false\ntaskbar_position = "' + ('top' if top else 'bottom') + '"\n'
+ if gold:
+ config += '[theme]\nbase = "gold"\n'
+ process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get('REDIWM_TEST_RENDERER', 'gles2'), config_content=config, env_extra={
'DBUS_SYSTEM_BUS_ADDRESS': os.environ['DBUS_SESSION_BUS_ADDRESS'], 'DBUS_SESSION_BUS_ADDRESS': '', 'XDG_CACHE_HOME': str(tmp),
})
try:
@@ -165,7 +168,8 @@ def run(scale):
def center(box): return box['x']+box['width']//2, box['y']+box['height']//2
anchor = center(boxes['network'])
factor = min(1, (bar['box']['width']-24)/420)
- point = (anchor[0], bar['box']['y']-40)
+ available_h = ipc.get_outputs()[0]['logical_height'] - bar['box']['height'] - 24
+ point = (anchor[0], bar['box']['y'] + bar['box']['height'] + 40 if top else bar['box']['y']-40)
def settle():
ipc.wait_for_frame()
time.sleep(.25) # panel animation, not network state polling
@@ -178,7 +182,7 @@ def run(scale):
return round(ox+x*factor),round(oy+y*factor)
def click(x,y): ipc.click_at(*at(x,y)); settle()
def locate(widget):
- for y in range(75, int((bar['box']['y']-24)/factor)-64, 10):
+ for y in range(75, int(available_h/factor)-64, 10):
point=at(120,y)
if ipc.hit_test(*point).get('widget')==widget: return point
raise AssertionError(f'{widget} is not visible')
@@ -189,9 +193,14 @@ def run(scale):
assert read_line(fake)=={'done':True}
settle()
def screenshot(name):
- target=Path('/tmp')/f'rediwm-wifi-{name}-{scale}-{os.environ.get("REDIWM_TEST_RENDERER", "gles2")}.png'
+ target=Path('/tmp')/f'rediwm-wifi-{name}-{scale}-{os.environ.get("REDIWM_TEST_RENDERER", "gles2")}{"-gold" if gold else ""}{"-top" if top else ""}.png'
target.unlink(missing_ok=True)
ipc.screenshot(str(target))
+ if gold and name == 'list':
+ x, y = at(70, 90)
+ with Image.open(target) as image:
+ red, green, blue = image.convert('RGB').getpixel((round(x * float(scale)), round(y * float(scale))))
+ assert red > 190 and green > 180 and blue > 155, ('Gold network card', (red, green, blue))
def tray_red():
box,raster,target=boxes['network'],float(scale),tmp/'tray.png'
target.unlink(missing_ok=True)
@@ -208,13 +217,14 @@ def run(scale):
return seen
# The tray icon follows NetworkManager's global state with no popup open:
# red only while nothing is connected, never while connecting.
- assert not tray_red(), 'connected: the wifi icon is red'
- command(global_state=20);phases=tray_phases();assert True in phases, 'disconnected: the wifi icon is not red'
- assert phases == {True, False}, 'disconnected: the wifi icon does not blink'
- command(global_state=40);assert not tray_red(), 'connecting: the wifi icon is red'
- time.sleep(1.2);assert not tray_red(), 'connecting: the wifi icon still blinks'
- command(global_state=10);assert True in tray_phases(), 'asleep: the wifi icon is not red'
- command(global_state=70);assert not tray_red(), 'reconnected: the wifi icon is still red'
+ if '--popup-only' not in sys.argv:
+ assert not tray_red(), 'connected: the wifi icon is red'
+ command(global_state=20);phases=tray_phases();assert True in phases, 'disconnected: the wifi icon is not red'
+ assert phases == {True, False}, 'disconnected: the wifi icon does not blink'
+ command(global_state=40);assert not tray_red(), 'connecting: the wifi icon is red'
+ time.sleep(1.2);assert not tray_red(), 'connecting: the wifi icon still blinks'
+ command(global_state=10);assert True in tray_phases(), 'asleep: the wifi icon is not red'
+ command(global_state=70);assert not tray_red(), 'reconnected: the wifi icon is still red'
open_menu()
wait_for(lambda: ipc.hit_test(*at(100,100)).get('widget')=='row','network rows')
screenshot('searching')
@@ -289,7 +299,7 @@ def run(scale):
fake.terminate();fake.wait(timeout=5);settle();screenshot('unavailable')
fake=start_fake();settle()
wait_for(lambda: ipc.hit_test(*at(100,100)).get('widget')=='row','service restart')
- ipc.click_at(20,20);settle()
+ ipc.click_at(20,200);settle()
assert ipc.hit_test(*point)['target_type']!='wifi_popup'
open_menu()
# The footer opens the same Network page and retires the popup.
@@ -456,5 +466,5 @@ if __name__=='__main__':
os.execvpe('dbus-run-session',['dbus-run-session','--',sys.executable,__file__,*sys.argv[1:]],{**os.environ,'REDIWM_WIFI_PRIVATE_BUS':'1'})
os.umask(0o077)
scale = next((arg for arg in sys.argv[1:] if not arg.startswith('--')), '1')
- if '--settings-only' not in sys.argv: run(scale)
- settings(scale)
+ if '--settings-only' not in sys.argv: run(scale, '--gold' in sys.argv, '--top' in sys.argv)
+ if '--popup-only' not in sys.argv: settings(scale)
diff --git a/tests/window_corners.py b/tests/window_corners.py
index 22994cf..b04e1a0 100644
--- a/tests/window_corners.py
+++ b/tests/window_corners.py
@@ -18,6 +18,84 @@ from ui_driver import UIDriver
# client's corners are transparent and the frame's footer is the border.
+def border_glow_resize(scale):
+ """The edge highlight follows held-button motion and committed geometry."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-resize-glow-") as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ config = ('[compositor]\nxwayland = false\n'
+ '[desktop]\nenabled = false\n[animations]\nenabled = false\n'
+ '[theme]\nwindow_bg = "#101215"\nwindow_border = "#101215"\n'
+ 'shadow = "#00000000"\nborder_glow = "#00ff00ff"\n'
+ 'border_glow_length = 72\n')
+ process, log = spawn_compositor(tmp, scale=str(scale), config_content=config,
+ renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "REDIWM_NO_GLASS": "1",
+ "REDIWM_THEME": str(tmp / "rediwm-config.toml")})
+ client = None
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for("wallpaper_presented", timeout_ms=10000)
+ display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))
+ client = subprocess.Popen([str(tmp / "client"), "--app-id", "resize-glow"],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
+ REDIWM_TEST_DECORATION="server"))
+ id = wait_for(lambda: next((w["id"] for w in ipc.get_windows()
+ if w["app_id"] == "resize-glow"), None), "map resize glow client")
+ ipc.action("move_window_to", {"id": id, "x": 100, "y": 80})
+ ipc.wait_for("window_geometry_settled", window_id=id)
+
+ def frame():
+ if owner == "shell":
+ return next(w for w in ipc.get_windows() if w["id"] == id)
+ return ipc.get_window_debug(id)["chrome_box"]
+
+ def green_at(x, y):
+ path = tmp / "glow.png"
+ ipc.wait_for_frame()
+ path.unlink(missing_ok=True)
+ ipc.screenshot(str(path))
+ with Image.open(path) as image:
+ image = image.convert("RGB")
+ pixels = image.crop((math.floor((x - 2) * scale), math.floor((y - 2) * scale),
+ math.ceil((x + 2) * scale), math.ceil((y + 2) * scale)))
+ return max(g - max(r, b) for r, g, b in pixels.getdata())
+
+ for owner in ("client", "shell"):
+ if owner == "shell":
+ ipc.open_control_center()
+ UIDriver(ipc).wait_settled("control_center")
+ id = next(w["id"] for w in ipc.get_windows()
+ if w.get("app_id") == "rediwm-settings")
+ ipc.action("move_window_to", {"id": id, "x": 100, "y": 80})
+ ipc.wait_for("window_geometry_settled", window_id=id)
+ box = frame()
+ x = box["x"] + box["width"] - 1
+ y = box["y"] + box["height"] * 0.4
+ ipc.move_cursor(round(x), round(y))
+ assert green_at(x, y) > 100, (owner, "initial glow")
+ ipc.pointer_button(0x110, True)
+ assert ipc.get_input_state()["cursor_mode"] == "resize"
+ # Tangential motion changes no size, but must move the glow.
+ ipc.move_cursor(round(x), round(y + 100))
+ assert green_at(x, y + 100) > 100, (owner, "glow stuck during resize")
+ assert green_at(x, y) < 40, (owner, "old glow remains")
+ ipc.move_cursor(round(x + 80), round(y + 100))
+ resized = wait_for(lambda: current if (current := frame())["width"] > box["width"] + 60 else None,
+ "resize configure applied")
+ edge = resized["x"] + resized["width"] - 1
+ assert green_at(edge, y + 100) > 100, (owner, "glow missed resized edge")
+ ipc.pointer_button(0x110, False)
+ ipc.move_cursor(2, 2)
+ assert green_at(edge, y + 100) < 40, (owner, "glow remains after leaving")
+ print(f"PASS scale {scale}: resize glow follows pointer and client/shell geometry")
+ finally:
+ if client is not None:
+ stop_process(client)
+ stop_process(process)
+ log.close()
+
+
def settings_resize(scale):
"""The opaque body joins its skirt, and shadows follow shell resizes."""
with tempfile.TemporaryDirectory(prefix="rediwm-settings-corners-") as directory:
@@ -302,6 +380,7 @@ def run(scale, background=(48, 50, 56), chrome_alpha=0.98):
if __name__ == "__main__":
for scale in (1, 1.25, 1.5, 2):
+ border_glow_resize(scale)
workspace_focus(scale)
settings_resize(scale)
run(scale)