Skip to content

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

rendering improvements

oxydizer0add81212f51
diff --git a/AGENTS.md b/AGENTS.md
index fa2e4b4..487ced9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,6 +8,8 @@ the one for the directory you work in: `src/files`, `src/editor`,
## Working rules
+* Keep this file to cross-cutting rules and pointers; put detailed subsystem
+ notes in the linked documents or the area’s `AGENTS.md`.
* Tool use is costly: no tight polling (wait 15–30 s between checks of long
operations), batch checks, don't re-read unchanged files.
* Add tests only when really needed or asked; prefer extending existing ones.
@@ -18,153 +20,58 @@ the one for the directory you work in: `src/files`, `src/editor`,
## Rendering and damage
-* **Colours are premultiplied** in wlroots rects; theme colours are
- `col.Straight`. Create/recolour rects only via `col.createRect`/`setRect`,
- pack pixels with `Straight.argb()`/`Premul.argb()`. Symptom of a mix-up:
- white border edges.
-* **Window frames are shapes** (`docs/plans/scene-graph-stage4.md`).
- `Toplevel.applyShape` gives `frame_tree` one rounded clip carrying the ring
- colour (× window opacity); the pass composites the ring over the body, so
- something must be drawn under every ring pixel: the titlebar `ChromeBuffer`
- (a plain band) on top and the three `frame_fills` rects beside and below the
- client. The footer is `frame_border`. `shadow_tree`, the resize-grab tree and
- every xdg popup carry `setTreeUnclipped` (a new node that hangs outside the
- window needs it too). The shadow is analytic (`setTreeShadow` on
- `shadow_tree`, the CPU formula's smoothstep); its leaf `shadow_node` has no
- buffer and carries footprint, opacity and input only, so the projection
- damages that footprint itself. CSD windows have no shape and keep the
- `border_rects` outline. A changed clip damages its rim itself
- (`projection.c`); a point the shape cuts away is declined by the pick
- (`pick_world`), so the pick falls to what is below. Window capture draws the client alone and is
- handed the shape explicitly. The ring is one `max(1, round(border * scale))`.
- Without the shaped programs (`chrome.shapes` false) windows are square, with
- no ring or shadow.
-* **Buffer size ≠ scene size** at fractional scale (`round(len*s)` vs
- `round((off+len)*s)-round(off*s)`). Chrome/panel buffers filter bilinearly:
- never re-raster per device-grid phase (`ChromeBuffer.create` costs 2–8 ms).
-* **Nested sessions never set buffer scale:** judge sharpness at
- `REDIWM_SCALE=1`, and debug visuals with IPC screenshots/buffer dumps, not
- host `grim`. Brief vanishing after a startup scale mismatch is not a bug.
-* **GLES can NULL `wlr_scene_buffer.buffer`** after upload (the texture
- stays): persist raster sizes.
-* **Glass is drawn by the output pass** (stage 5, `docs/plans/scene-graph-stage5.md`).
- `glass.c` only registers effects: a bufferless node just below its target, to
- which resolve gives the target's box. When an effect re-blurs, `scene_output.c`
- redirects the pass (`rediwm_scene_pass_begin_backdrop`) and draws the items
- below it into an image a quarter of the logical size of its padded extent
- (target + 3 sigma), blurs that and composites it through the shape (shaped
- program mode 3), keeping one blur per effect and output. A kept blur is
- re-taken only when a damage event from a leaf painted *below* the effect, or
- damage no event explains, meets that extent, or the region or sigma changed.
- Only leaves that put pixels on screen have damage events (an input-only node
- must not, or it reads as a change below glass), and the software cursor's
- damage counts as explained. Damage a new kind of change through the
- projection's events or it counts as below (safe, slower). Collect keeps items an
- effect reads even where surfaces above hide them (`reads`). Holds (a dragged
- titlebar at ≥ 0.98 opacity, camera motion) carry the blur and re-take it once
- released. Per output, so mixed scales stay idle (`glass_hold.py`); attribution
- is checked by `glass_reblur.py`.
-* **Owned GL beside wlroots:** wlroots draws with client-side vertex arrays, so
- any GL work of ours must put `GL_ARRAY_BUFFER` (and the rest of the state it
- touched) back before a wlroots pass runs, as `scene_pass.c`'s `leave()` does; a quad
- VBO left bound makes wlroots draw half a rectangle. A border is drawn in the
- same pass as its body, never over it (`docs/plans/scene-graph-stage1.md`).
-* **Commit only via `Output.commitFrameState`**, never
- `wlr_output_commit_state`. `commitIsRedundant` skips commits with no damage,
- colour change, attach-render lock or cursor change; register anything new
- there. Skipped frames get callbacks from `vblank_timer`, never immediately.
- Build output state through `Server.buildOutputState`, including capture: the
- owned GLES2 pass is the only presenter (the session requires GLES2) and keeps
- one swapchain damage history. It reads graph geometry and the buffers,
- textures and wait points of the source nodes
- (`docs/plans/scene-graph-stage3.md`, `scene-graph-stage6.md`).
-* **Shapes in the owned pass** (`scene_pass.h`): a window's rounded clip, ring
- and shadow are `rediwm_scene_pass_add_*_shaped` calls, device pixels, snapped by
- the caller. The programs cost the driver about 430 KiB (a GL program costs
- 130-150 KiB whatever its size), so `enable_shapes` builds them on request, never
- with the renderer; before it a shaped draw fails the pass. Blend NONE is only
- valid inside `rediwm_clip_opaque`, minus the ring (`scene_output.c` draws a
- clipped item's ring-free core plain and the rest through the shape). The
- distance ramp is not area coverage (up to 18 of 208 levels at one pixel of a
- curved edge): that is expected.
-* **Idle makes no wakeups:** timers only for real deadlines, workers signal an
- eventfd, `text.applySize` instead of re-sizing faces, title changes repaint
- only their span and taskbar chip. Measure with per-thread context switches.
-* **Damage:** each reusable shm buffer tracks damage since its own last paint;
- never write a busy one. `panel_paint.Background` keeps the last full image
- (`paintIncremental` repairs); widget setters `markDirty`/`markPaintDirty`,
- moves damage old and new bounds; convert publish damage at the real raster
- scale. Compositor-owned world buffers send full damage unless reported
- (`Projection.damageBuffer` after `setBuffer`, or `presentOwned`). Cache keys
- include visual state, text, geometry and Cairo transform; round globally
- before subtracting projection group origins.
-* **The dock repaints cells, not itself** (`Dock.zig`). It keeps its last
- raster and, when only some items' looks changed (hover zoom, pills), clears
- and repaints just their `itemCell`s (each item at the largest hover zoom, across
- the dock's thickness) under a clip, publishing that damage alone. Dock-wide
- state (theme, scale, count, drop slot, hover zoom setting) is `base_key` and
- repaints all. Draw nothing outside an item's cell without keying it in
- `base_key`, or it goes stale. `tests/dock.py` compares an animated dock with a
- whole repaint. Icons use `drawImageSmooth` (area average): `drawImageCover`
- samples the nearest pixel and shows stair-steps at the dock's fractional
- downscale.
-* **Projection is resolve, then present** (`projection.c`, `scene_graph.h`).
- `resolve` turns the source tree into typed items (kind, unrounded
- layout-space edges, composed scale, content) listed in paint order per group
- and shows nothing; `present` rounds once (`rediwm_edges_snap`, edges not
- origin+size) and turns what changed into damage events and screen damage.
- Geometry is derived only in `resolve`: a new rule (clip, opacity, fractional
- placement) is a field on the item, not a computation in `present_leaf`. A leaf
- or group leaves its `paint` list before the head is freed (`detach`,
- `destroy_group`). Buffer identity and damage are read from the source node by
- `present`, textures, single-pixel colours, wait points and opaque regions by
- the pass. A tree's rounded clip (`rediwm_projection_set_tree_clip`) is a field
- on each item (`item.clip`), resolved after the tree's own zoom and scale; an
- xdg popup lives under its parent's tree and must carry
- `rediwm_projection_set_tree_unclipped`.
-* **The world has no second tree** (`docs/plans/scene-graph-stage6.md`). The
- source tree is disabled, so wlroots computes no outputs, frame callbacks,
- damage or picks for it; the graph does, with wlroots' own rules on our data.
- *Feedback* (`rediwm_projection_feedback_*`, called by the pass's `collect`):
- per build, the pixels of each client surface that nothing above hides, over
- every output; an output is active when it shows more than a tenth of that, the
- primary one shows most (the later wins a tie); `outputs_update` and
- `output_enter/leave` go out on the *source* buffer, again when an active
- output's scale, transform or subpixel changed. Frame callbacks of the world
- come from `Server.sendFrameDone`, never `wlr_scene_output_send_frame_done`
- alone; the pass emits `output_sample` on the source buffer. A layer-shell
- surface below the world (background, bottom) is no longer occluded by windows
- in wlroots' eyes: it keeps frame callbacks while covered. *Damage*: every
- change reaches `p->pending` through `damage_box` and goes to the outputs once,
- at the end of each sync. A change of what a leaf itself shows is cut to what
- was visible of it at the last build (`l->visible`); a move, restyle or removal
- damages the old box (cut) and the new one; a restack damages what moved
- (`damage_restacked`), shadow footprints included; a destroyed node applies at
- once, because a capture can build before the next sync. A new kind of change
- that moves no leaf has to damage itself there (clip rims and shadows do).
- *Picks*: `rediwm_projection_node_at` (graph for the world, wlroots for the
- layout trees), never `wlr_scene_node_at` on the root. GLES2 lets go of a
- plain buffer once uploaded, so "has content" is a buffer, a texture or a
- single-pixel colour (`present_leaf`, `collect`).
-* **Client buffers:** `wlr_client_buffer_apply_damage` works in place only
- without extra locks, so mark long-held locks ignorable. v4
- `attach(buffer, 0, 0)` still sets OFFSET; only nonzero dx/dy remaps. Don't
- resend unchanged `set_buffer_scale`; prefer compositor v5.
+Read [rendering details](docs/agent-notes/rendering.md) before changing
+projection, the output pass, glass, window shapes, chrome, capture or retained
+panel painting. The key rules:
+
+* **Colours are premultiplied** in wlroots/Cairo buffers; theme colours are
+ `col.Straight`. Use `col.createRect`/`setRect` and
+ `Straight.argb()`/`Premul.argb()`. White border edges suggest a mix-up.
+* **Resolve geometry, then present:** derive geometry only in `resolve`;
+ `present` snaps edges once (`rediwm_edges_snap`), never origin plus size.
+ New clip/opacity/placement rules belong on resolved items. Detach paint-list
+ entries before freeing their heads.
+* **The world has no second tree:** its source tree stays disabled. Pick with
+ `rediwm_projection_node_at`, send callbacks through `Server.sendFrameDone`,
+ and emit feedback/`output_sample` on source buffers. GLES may release
+ `wlr_scene_buffer.buffer` after upload: persist raster sizes and treat a
+ buffer, texture or single-pixel colour as content.
+* **Commit through `Output.commitFrameState`** and build output state through
+ `Server.buildOutputState`, including capture. Register new commit reasons
+ in `commitIsRedundant`; skipped callbacks wait for `vblank_timer`.
+* **Window frames are shapes:** every ring pixel needs body content beneath
+ it. Shadows, resize grabs, popups and other nodes outside the window need
+ `setTreeUnclipped`. Capture the client alone with its shape supplied
+ explicitly. Shaped programs are opt-in; without them windows are square.
+* Restore owned GL state, especially `GL_ARRAY_BUFFER`, before wlroots draws.
+ Draw borders with their bodies; blend NONE only in the opaque, ring-free core.
+* **Glass belongs to the output pass.** Attribute changes through projection
+ damage events; only painted leaves emit them. Input-only nodes must not
+ invalidate glass. Retained blurs and holds are per effect and output.
+* **Damage follows each buffer's history:** never write a busy shm buffer.
+ Use `markDirty`/`markPaintDirty`, damage old and new move bounds, publish at
+ the real raster scale, and report owned-buffer damage via
+ `Projection.damageBuffer` or `presentOwned`. Cache keys include visual state,
+ text, geometry and Cairo transforms. Round globally before group offsets.
+* Fractional buffer size differs from snapped scene size; bilinear chrome and
+ panel buffers must not be rerasterized for device-grid phase changes.
+* **Idle makes no wakeups:** deadline-only timers, eventfd worker wakes,
+ `text.applySize`, and title-span/chip repainting. Measure per-thread context
+ switches. Nested sessions never set buffer scale: judge at `REDIWM_SCALE=1`
+ using IPC screenshots/buffer dumps, not host `grim`.
+* Client-buffer damage needs ignorable long-held locks for in-place updates.
+ Only nonzero v4 attach offsets remap; don't resend unchanged buffer scales;
+ prefer compositor v5.
## Windows and focus
* **Unmapped ≠ destroyed.** `frame_tree` stays disabled until `handleMapped`;
`focusSurface`/`minimize`/`restore` need `in_world`; `destroyNow` asserts
`backend_gone` (or a compositor-owned backend).
-* **The dock reserves space only when it doesn't auto-hide.** `Output.usableBox`
- is `dockAreaBox` (output less the taskbar) less `Dock.reservedStrip`, a pure
- function of config and that box (`Dock.fits`), so it never flips with a lock
- or fullscreen window. The dock and the taskbar's popups/menus are placed in
- `dockAreaBox`, never `usableBox`. A setting that changes the strip calls
- `applyTaskbarPosition` (`Dock.reserves` before/after). Auto-hide fades and
- slides the node (`reveal`, opacity + position, no repaint) and parks it (no
- rebuilds, no frames) once away; reveal/hide wait on one `wl` timer
- (`Dock.pointerAt` from `Input.processCursorMotion`, `retime`).
+* **Dock geometry:** reserve space only without auto-hide; use
+ `dockAreaBox` for the dock and taskbar popups, `usableBox` for windows.
+ Read [dock details](docs/agent-notes/dock.md) before changing the dock,
+ its painting, layout/reservation, OSD clearance, hover or auto-hide.
* **Tiles are compositor-owned geometry** like maximize (`snap.zig`,
`forcedGeometry()`). `Toplevel.layout()` reads the `maximized` field, not
`isMaximized()` (xdg acks later). Leaving a layout without moving goes
@@ -188,12 +95,10 @@ the one for the directory you work in: `src/files`, `src/editor`,
`Input.cancelDrag` (wlroots doesn't); compositor drop targets
(`desktop_drop.Target`) end the grab before negotiating;
`wlr_data_source_send` closes its fd.
-* **Compositor-internal drags** (`dock_drag.zig`: start menu app -> dock pin)
- are not wl_data_device ones: a press arms, motion past a threshold starts,
- and starting rebuilds the menu so its release is no click. Closing the menu
- or Escape (`cancelDrag`, before the menu's own Escape) abandons it. A dock
- holds resolved pins as copies (`pin_arena`); `config_index` maps a slot back
- into `dock_pinned_apps`, which also lists apps no longer installed.
+* **Internal dock drags** use `dock_drag.zig`, not wl_data_device. Pins act
+ on release; Escape cancels through `Input.cancelDrag` before shell panels
+ handle it. Read [dock details](docs/agent-notes/dock.md) for start-menu
+ pinning, reordering and pin storage.
## Xwayland
diff --git a/README.md b/README.md
index 684d74c..232cc6f 100644
--- a/README.md
+++ b/README.md
@@ -199,7 +199,7 @@ older canvas save while in workspace mode updates the saved return-to-canvas sta
- **Mouse:** Alt+drag moves windows, Alt+right-drag resizes. Super+Alt+drag (or middle-drag) pans the desktop, Super+Alt+scroll zooms it, and Alt+scroll zooms a single window.
- **Zoom on window switch:** `[compositor] focus_zoom` (also in Settings → Appearance) controls what Alt+Tab, directional focus and taskbar activation do. `"boost"` (default) shows the window at 100% until you switch away, `"keep"` only pans, and `"camera"` zooms the desktop to the window's depth.
-- **Dock:** enable **RediWM dock** in Settings → Appearance (`[compositor] dock_enabled = true`, off by default). The compact dock sits above a bottom taskbar, with Applications, Files, Terminal, running windows and Settings. Appearance’s **Dock height** slider offers 48–96px (68px by default; `[compositor] dock_height`), resizing icons, spacing and click targets together. A docked dock keeps maximized and tiled windows out of its strip; turn on **Auto-hide dock** (`[compositor] dock_auto_hide`) and it hides until the pointer reaches its screen edge, while windows use the whole area. Files, Terminal and Settings share their shortcut with running windows and show a pill underneath, including configured default apps. The pill smoothly grows, shrinks and fades with focus and app state, following the animation and reduced-motion settings. Click a running icon to focus/restore its app or minimize the focused window; scroll the dock to reach overflow windows. Drag an application from the start menu or launcher onto the dock to pin it: a marker shows where it will land, Escape cancels, and a drop away from the dock does nothing. A pinned icon launches its app, or focuses/minimizes it like a running icon once open, and takes over that app's windows. Pins (up to 16) are saved as desktop entry IDs in `dock_pinned_apps`; right-click a pin for Unpin from dock. Every running app shows in the dock, pinned or not: an unpinned one gets its own icon while it runs, and right-clicking it offers Close and Force Close. Right-click a Files, Terminal, Applications or Settings shortcut to remove it; the choice is remembered in `dock_hidden_shortcuts` (`applications`, `files`, `terminal`, `settings`; delete an entry to restore it). Removal drops only the launcher: that app still shows as an ordinary icon while it runs. The old `dock_hidden_apps` list is gone, as running apps can no longer be hidden. It hides on the focused fullscreen window’s display.
+- **Dock:** enable **RediWM dock** in Settings → Appearance (`[compositor] dock_enabled = true`, off by default). The compact dock sits above a bottom taskbar, with Applications, Files, Terminal, running windows, Settings and the Trash (**Show Trash**, `dock_show_trash`, on by default; it opens the trash in Files). A window launched from a dock icon grows out of that icon as it opens (`[animations.window_launch]`). Appearance’s **Dock height** slider offers 48–96px (68px by default; `[compositor] dock_height`), resizing icons, spacing and click targets together. A docked dock keeps maximized and tiled windows out of its strip; turn on **Auto-hide dock** (`[compositor] dock_auto_hide`) and it hides until the pointer reaches its screen edge, while windows use the whole area. **Dock opacity** (`dock_opacity`), **Dock corner radius** (the theme’s `dock_radius`; by default the windows’ radius) and **Highlight active app** (`dock_active_highlight`, off by default: a rectangle behind the focused app’s icon) sit beside them, and an icon’s tooltip shows its window title after the pointer rests on it for 1.5 s. Files, Terminal and Settings share their shortcut with running windows and show a pill underneath, including configured default apps. The pill smoothly grows, shrinks and fades with focus and app state, following the animation and reduced-motion settings. Click a running icon to focus/restore its app or minimize the focused window; scroll the dock to reach overflow windows. Drag an application from the start menu or launcher onto the dock to pin it: a marker shows where it will land, Escape cancels, and a drop away from the dock does nothing. A pinned icon launches its app, or focuses/minimizes it like a running icon once open, and takes over that app's windows. Pins (up to 16) are saved as desktop entry IDs in `dock_pinned_apps`; drag a pinned icon along the dock to reorder the pins (a marker shows where it will land, Escape cancels, and a drop where it started changes nothing; a pinned icon acts when released, so a plain click still launches or focuses it); right-click a pin for Unpin from dock. Every running app shows in the dock, pinned or not: an unpinned one gets its own icon while it runs, and right-clicking it offers Close and Force Close. Right-click a Files, Terminal, Applications or Settings shortcut to remove it; the choice is remembered in `dock_hidden_shortcuts` (`applications`, `files`, `terminal`, `settings`; delete an entry to restore it). Removal drops only the launcher: that app still shows as an ordinary icon while it runs. The old `dock_hidden_apps` list is gone, as running apps can no longer be hidden. It hides on the focused fullscreen window’s display.
- **Window tabs:** enable per app in Settings → Appearance (saved in `[compositor] window_tab_apps`). **+** opens a new window as a tab. The app needs a desktop entry with a launch command.
- **Lock screen:** covers every output and engages before suspend (`[compositor] lock_on_suspend`) and on `loginctl lock-session`. There's no idle lock; add `swayidle -w timeout 300 'swaylock -f'` to `[[autostart]]`.
- **Desktop icons:** a `.desktop` launcher only runs if it's installed, root-owned, executable, or an exact copy of an installed entry. Otherwise, choose **Allow Launching** from its menu.
diff --git a/TESTING.md b/TESTING.md
index 37162b0..c2706d9 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -135,7 +135,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, 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),
+`keyboard_shortcuts.py`, `dock.py` (opt-in Appearance toggle, four-edge position selector, bounded size and hover-zoom sliders, opacity and corner-radius sliders, the off-by-default active-app rectangle, live placement/resizing and persistence, vertical icon/indicator layout, inward tooltips (after their 1.5 s delay) and menus, launcher/input, dragging pinned icons into a new order (marker, Escape, drop in place), shared shortcut icons and running pills, hover zoom anchored toward the desktop (painted edges and overflow input on all four edges), 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`,
@@ -148,7 +148,9 @@ and off-canvas reachability).
`taskbar_sections.py` checks left/center/right defaults, live section controls,
ordering and visibility, window groups defaulting left, nonoverlapping input bounds,
-the moved Start menu, legacy item lists and restart persistence. It supports
+the moved Start menu, the opt-in Power widget and its menu, capture visibility
+and its warning, 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
@@ -209,7 +211,8 @@ shm and, with a render node, dmabuf; occlusion, camera, resize, destroy,
minimize, idle blank, unplug, `get_capture_state`; under `owned` a captured
server-decorated window has transparent bottom corners), `screencast.py` (portal
config packaging, `rediwm-share-picker --xdpw-dmenu` contract, Stop sharing
-indicator), `screenshot_tool.py`, `screenshot_regressions.py` (save hook
+indicator, independent taskbar placement and saved visibility without stopping
+capture), `screenshot_tool.py`, `screenshot_regressions.py` (save hook
injects write failures).
**Lock, login, authentication**: `lock_screen.py`, `greeter.py`, `dm.py`
diff --git a/assets/themes/gold.toml b/assets/themes/gold.toml
index 464f54f..05adb39 100644
--- a/assets/themes/gold.toml
+++ b/assets/themes/gold.toml
@@ -18,6 +18,12 @@ chrome_height = 40
chrome_control_gap = 8
taskbar_title_size = 12.5
taskbar_size = 38
+taskbar_edge_gap = 0
+taskbar_length = 100
+taskbar_radius = 12
+taskbar_outline_width = 1
+clock_bold = true
+clock_italic = false
start_button_icon_size = 29
chip_gap = 4
chip_width = 220
@@ -50,14 +56,16 @@ 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_sidebar_selected = "rgba(116,92,72,0.96)"
+app_sidebar_hover = "rgba(241,218,188,0.07)"
+app_sidebar_selected_marker = "#FFF1D5"
+app_sidebar_item_radius = 10
app_surface_hover = "rgba(229,214,195,0.96)"
app_divider = "#CFC2B2"
app_icon = "#E4D8C8"
scrollbar_thumb = "#AC9377"
scrollbar_thumb_active = "#B88048"
+scrollbar_glow = 3.5
bg = "#292423"
fg = "#F4ECE1"
dim = "#D7CBBE"
@@ -134,9 +142,9 @@ app_menu_bg = "#EEE6DB"
app_field_bg = "#E0D5C5"
app_field_border = "#C8B59F"
shell_border_focus = "#E0B583"
-border_glow_depth = 7
+border_glow_depth = 4.7
border_glow_length = 80
-border_glow_reach = 504
+border_glow_reach = 126
workspace_active_border = "#DDB282"
dock_bg = "rgba(56,49,46,0.80)"
dock_border = "rgba(237,210,176,0.58)"
@@ -198,6 +206,7 @@ terminal_bright_white = "#FFF0DA"
[layout]
taskbar_position = "top"
+taskbar_items = ["left:start", "-left:windows", "center:clock", "right:capture", "right:tray", "right:battery", "right:network", "right:volume", "right:power"]
dock_enabled = true
dock_height = 76
diff --git a/docs/themes.md b/docs/themes.md
index 094341b..896e55d 100644
--- a/docs/themes.md
+++ b/docs/themes.md
@@ -51,7 +51,8 @@ icon_theme = "Adwaita" # optional installed theme, behind icons/
cursor_theme = "pack" # cursors/, or an installed cursor-theme name
```
-`[taskbar_theme]` optionally supplies the taskbar's own colours. A pack can
+`[taskbar_theme]` optionally supplies the taskbar's own colours and clock style
+(`clock_bold` and `clock_italic`). A pack can
also float the bar with `[theme]` tokens `taskbar_edge_gap`, `taskbar_length`,
`taskbar_radius` and `taskbar_outline_width`, and colour its outline with
`taskbar_outline` (see `docs/wiki/Theme.md`). Unknown
@@ -85,7 +86,10 @@ 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.
+and enables the bottom dock. Its 38-pixel bar has 12-pixel corners, a centered
+bold clock with italics off, Start on the left, the window list hidden, and
+capture, tray, battery, network, volume and Power on the right. 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.
@@ -133,16 +137,20 @@ 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 50% opaque sidebars in Settings and Files.
+`app_sidebar_selected_marker` lights the selected Files sidebar row with a
+bright leading bar and an accent-coloured glow (the older name
+`app_sidebar_hover_marker` still loads); unset leaves the plain fill and accent
+bar. `app_sidebar_item_radius` rounds the hover and selection rows (default 5).
+Gold uses a 96% opaque selection, a faint hover, rounder rows and 50% opaque
+sidebars in Settings and Files.
`app_sidebar_blur = true` lightly blurs the backdrop through their translucent areas;
the content, text and icons keep their own opacity. 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).
+`dock_radius` is in logical pixels (zero follows the window frame radius);
+Appearance's **Dock corner radius** slider sets it.
An explicit dock background uses its own alpha without the inherited dock's
86% minimum. `notification_bg`, `notification_fg`, `notification_dim`,
`notification_border`, `notification_icon_bg` and `notification_radius`
@@ -179,6 +187,9 @@ terminal_opacity` (0.0 to 1.0; Settings, Appearance, "Terminal opacity"). It is
a setting of the user, not of the pack, so switching packs keeps it. Foot
applies it to the background only; text stays opaque. Unset keeps the `alpha`
of Foot's own configuration, and a value, even `1.0`, takes precedence over it.
+kitty, Alacritty, Ghostty and WezTerm get the same opacity as a launch flag
+(no helper, no palette); Konsole, GNOME Terminal and other VTE terminals read
+opacity only from their own profiles and are left alone.
The helper is also available from a terminal:
diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md
index a68ed40..1c878dd 100644
--- a/docs/wiki/Configuration.md
+++ b/docs/wiki/Configuration.md
@@ -68,7 +68,9 @@ Choose top, bottom, left or right; side docks stack upright icons vertically.
(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.
+reduced-motion preferences. A hovered icon springs slightly past its zoom and
+settles back, and dips just under its resting size when the pointer leaves; tune
+the bounce with `[animations.dock_hover]` (`damping_ratio = 1.0` removes it).
A dock keeps maximized, tiled and newly placed windows out of its strip, beside
the taskbar's. **Auto-hide dock** (`dock_auto_hide = true`) lets windows use that
@@ -76,22 +78,60 @@ space instead: the dock hides, and appears when the pointer reaches the screen
edge it is on (and stays while the pointer is on it or its menu is open). Moving
or resizing a window, or holding a button for an app, never reveals it.
+Appearance also sets the dock's look. **Dock opacity** (`dock_opacity`, 0.0 to
+1.0) replaces the alpha of the dock's background, whatever colour the theme gives
+it; unset, the theme's own applies. **Dock corner radius** is the theme's
+`dock_radius` (logical pixels, 1 to 48 in the slider); while that is 0 the dock
+uses the windows' corner radius, and Appearance's **Radius** choice resets it
+to follow them again. **Highlight active app** (`dock_active_highlight`, off by
+default) draws a rectangle behind the focused application's icon; the running
+pill under each icon shows either way. A dock icon's tooltip, the window title,
+appears after the pointer has rested on it for 1.5 seconds.
+
+Hover enlargement keeps each icon's edge nearest the screen fixed: a bottom
+dock's icons grow upward, a top dock's downward, and side docks' toward the desktop.
+
+Pinned apps (`dock_pinned_apps`) can be rearranged by dragging a pinned icon
+along the dock; the order is saved. Applications, Files, Terminal, Settings and
+running apps that are not pinned keep their places.
+
+**Show Trash** (`dock_show_trash`, on by default) puts a Trash icon at the
+dock's far end (right, or bottom on a side dock), past a divider; clicking it
+opens the trash in the default file manager. Right-click it to remove it, which
+turns the switch off.
+
+A window launched from a dock icon (a pinned app, Files or Terminal) grows out
+of that icon into its place. Its timing is `[animations.window_launch]`; with
+animations off or reduced motion it opens like any other window.
+
The taskbar has **Left**, **Center**, and **Right** sections in Appearance.
Start and the window list default to the left, 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.
+icons plus Battery, Network, Volume, and Clock to the right. Drag an item's row
+anywhere into any section to reorder or move it (Escape cancels); an empty
+section shows where to drop. Up/Down on a focused row handle moves it one step,
+into the next section at a section's end. 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", "left:windows", "right:tray",
-"right:battery", "right:network", "right:volume", "right:clock"]` is the default.
+For example, `taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray",
+"right:battery", "right:network", "right:volume", "right:clock", "-right:power"]` is the default.
+Power is off by default on the right; enable it in Appearance to open the same
+power menu as the Start menu’s power icon.
+Screen capture is enabled by default at the start of the right section and
+shows **Stop sharing** while recording or sharing. Move or hide it independently
+in Appearance → Taskbar sections. Use `"-right:capture"` to hide it for recordings;
+capture continues normally. Hiding it is not recommended because recording and
+sharing can continue without a visible indicator or stop button; Settings shows
+a warning while it is hidden. Existing lists gain this item enabled on the right.
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.
A theme pack can set the same list in its `[layout]` section
(see `docs/themes.md`); a `taskbar_items` of your own here takes precedence over
the theme's until you choose a theme again. The bar's gap from the screen edge,
length, corner radius and outline are `[theme]` tokens (`docs/wiki/Theme.md`).
+Appearance's **Bold clock text** and **Italic clock text** switches style both
+time and date (`clock_bold` and `clock_italic` in `[theme]`, or
+`[taskbar_theme]` when a separate taskbar theme is selected).
| Key | Default | Notes |
| --- | --- | --- |
@@ -101,7 +141,10 @@ length, corner radius and outline are `[theme]` tokens (`docs/wiki/Theme.md`).
| `taskbar_position` | `"bottom"` | `top` or `bottom` |
| `dock_position` | `"bottom"` | `top`, `bottom`, `left` or `right`; inside the usable area beside the taskbar |
| `dock_auto_hide` | `false` | `true` hides the dock until the pointer reaches its edge, and frees its strip for windows; `false` reserves it |
-| `taskbar_items` | Start left, window list center, tray/status items right | ordered `section:item` entries; prefix with `-` to hide an item |
+| `dock_opacity` | unset | 0.0 to 1.0, the dock background's alpha; unset keeps the theme's |
+| `dock_active_highlight` | `false` | `true` draws a rectangle behind the focused app's dock icon |
+| `dock_show_trash` | `true` | a Trash icon at the dock's far end that opens the trash in the default file manager |
+| `taskbar_items` | Start and window list left, tray/status items right, Power hidden | 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` | |
@@ -119,7 +162,7 @@ length, corner radius and outline are `[theme]` tokens (`docs/wiki/Theme.md`).
| `drag_scale` | `1.002` | drag lift multiplier, `1.000`–`1.100`; 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` | |
-| `terminal_opacity` | unset | 0.0 to 1.0, background alpha of Foot windows RediWM launches (new windows only; text stays opaque). Unset keeps the `alpha` of your own Foot configuration. Adjustable in Appearance |
+| `terminal_opacity` | unset | 0.0 to 1.0, background alpha of terminals RediWM launches: Foot, kitty, Alacritty, Ghostty and WezTerm (new windows only; text stays opaque). Konsole, GNOME Terminal and other VTE terminals take it only from their own profiles. Unset keeps the opacity of your own terminal configuration. Adjustable in Appearance |
| `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. |
diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.md
index 12361bd..0573a6d 100644
--- a/docs/wiki/Theme.md
+++ b/docs/wiki/Theme.md
@@ -15,7 +15,7 @@ dark tint for contrast. Custom start-button icons retain their own colours.
Appearance also has a **Taskbar theme** picker under Theme, with the same
presets plus "Same as theme". It gives the taskbar the preset's colours and
leaves every other surface on the theme above. It is saved as a
-`[taskbar_theme]` section holding only these keys: `taskbar_bg`,
+`[taskbar_theme]` section holding only these keys: `clock_bold`, `clock_italic`, `taskbar_bg`,
`taskbar_surface`, `taskbar_hover`, `taskbar_border`, `taskbar_outline`, `border_soft`,
`surface_hover`, `window_fg`, `window_dim`, `danger`, `window_close_hover`,
`start_button_hover`, `start_button_indicator`, `start_button_logo_color` and
@@ -24,6 +24,10 @@ body can be pasted under that header; keys it leaves out take the built-in
defaults, not the main theme's. The section's presence selects the taskbar
theme (an empty one is the built-in colours); without it the taskbar follows
`[theme]`. Sizes, gaps and radii always come from `[theme]`.
+Under **Appearance → Taskbar**, **Bold clock text** and **Italic clock text**
+independently style both time and date. They save into the selected taskbar
+theme, or the main theme when the taskbar follows it. Both default to false;
+Gold uses bold with italics off. Clock widths and digit spacing update live.
## GTK and Qt app colors
@@ -147,6 +151,7 @@ geometry retain their content or structural dimensions.
| `app_icon` | `"rgba(214,214,214,1)"` |
| `scrollbar_thumb` | `"rgba(89,98,110,1)"` |
| `scrollbar_thumb_active` | `unset` |
+| `scrollbar_glow` | `1.0` (strength of the thumb's light) |
| `bg` | `"rgba(9,11,24,1)"` |
| `fg` | `"rgba(245,245,245,1)"` |
| `dim` | `"rgba(214,214,214,1)"` |
@@ -278,7 +283,8 @@ Numeric tokens accept 0–4096 unless constrained below. Fractions ending in
| `chrome_height` | `46.0` |
| `chrome_control_gap` | `4.0` |
| `taskbar_title_size` | `12.5` |
-| `taskbar_size` | `48.0` |
+| `clock_bold`, `clock_italic` | `false` |
+| `taskbar_size` | `44.0` |
| `taskbar_edge_gap` | `0.0` |
| `taskbar_length` | `100.0` |
| `taskbar_radius` | `0.0` |
diff --git a/src/Dock.zig b/src/Dock.zig
index d705138..e3c3e63 100644
--- a/src/Dock.zig
+++ b/src/Dock.zig
@@ -22,10 +22,13 @@ const Self = @This();
const max_items = 64;
/// Applications pinned to the dock by dragging them from the start menu.
pub const max_pins = 16;
-pub const Shortcut = enum { applications, files, terminal, settings };
-/// The gap between the dock and its output edge, and again between it and the
+/// `trash` follows `dock_show_trash`; the others `dock_hidden_shortcuts`.
+pub const Shortcut = enum { applications, files, terminal, settings, trash };
+const shortcut_count = std.enums.values(Shortcut).len;
+/// The gap between the dock and its output edge, and the one between it and the
/// windows when it reserves its strip.
-const edge_margin = 10;
+const edge_margin = 5;
+const window_margin = 10;
/// Auto-hide: the outermost pixels of the edge that reveal the dock, how long
/// the pointer must stay (so a pass over the edge shows nothing) or stay away
/// (so a slip off the dock hides nothing), and how far the dock travels while
@@ -34,6 +37,9 @@ const edge_band = 2;
const reveal_delay_ms = 120;
const hide_delay_ms = 400;
const slide_distance = 20;
+/// How long the pointer rests on an icon before its tooltip (the window title)
+/// shows.
+const tooltip_delay_ms = 1500;
/// Scale the original 68px layout in logical pixels, independently of output scale.
const Metrics = struct {
@@ -85,8 +91,13 @@ const ItemAnimation = struct {
output: ?*Output = null,
tree: ?*wlr.SceneTree = null,
node: ?*wlr.SceneBuffer = null,
+/// Transparent, fixed-size anchor: glass follows the dock background, while
+/// the painted buffer may extend inward to fit a fully enlarged icon.
+glass_anchor: ?*wlr.SceneBuffer = null,
tooltip: ?*wlr.SceneBuffer = null,
glass_effect: ?*glass.Effect = null,
+/// The glass corner radius of the last paint; its opacity follows `reveal`.
+glass_radius: f32 = 0,
data: SceneData = undefined,
box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = config.dock_height_default },
position: @import("config").types.DockPosition = .bottom,
@@ -104,9 +115,15 @@ pointer_near: bool = false,
shown: bool = false,
timer: ?*wl.EventSource = null,
timer_target: ?bool = null,
+/// The tooltip waits on `tip_timer` after the pointer moves onto an icon;
+/// `tip_ready` is set once the delay has passed and held until it moves off.
+tip_timer: ?*wl.EventSource = null,
+tip_ready: bool = false,
+tip_armed: bool = false,
reveal: anim.Anim = .{ .property = .opacity },
parked: bool = false,
root: ui.layout.Widget = .{ .kind = .container },
+input_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),
@@ -141,6 +158,7 @@ items_drawn: usize = 0,
pub fn deinit(self: *Self) void {
if (self.timer) |timer| timer.remove();
+ if (self.tip_timer) |timer| timer.remove();
if (self.output) |output| if (output.server.input.window_menu.dock == self) output.server.input.window_menu.close();
self.dispatcher.reset();
if (self.tree) |tree| tree.node.destroy();
@@ -154,6 +172,10 @@ fn ensureNodes(self: *Self, output: *Output) !void {
if (self.tree != null) return;
const tree = try output.server.taskbar_tree.createSceneTree();
errdefer tree.node.destroy();
+ const anchor_buffer = try PanelBuffer.create(1, 1, 1);
+ defer anchor_buffer.base.drop();
+ const anchor = try tree.createSceneBuffer(&anchor_buffer.base);
+ anchor.point_accepts_input = ignoreInput;
const node = try tree.createSceneBuffer(null);
const tooltip = try tree.createSceneBuffer(null);
node.setFilterMode(.bilinear);
@@ -162,10 +184,12 @@ fn ensureNodes(self: *Self, output: *Output) !void {
self.output = output;
self.data = .{ .role = .{ .dock = self } };
self.data.attach(&node.node);
+ node.point_accepts_input = acceptsInput;
self.tree = tree;
self.node = node;
+ self.glass_anchor = anchor;
self.tooltip = tooltip;
- self.glass_effect = glass.Engine.attach(output.server.glass_engine, node, &node.node, .taskbar);
+ self.glass_effect = glass.Engine.attach(output.server.glass_engine, anchor, &anchor.node, .taskbar);
// A dock that auto-hides starts away; one that does not, in place.
self.reveal.cancel(if (output.server.config.compositor.dock_auto_hide) 0 else 1);
}
@@ -174,6 +198,14 @@ fn ignoreInput(_: *wlr.SceneBuffer, _: *f64, _: *f64) callconv(.c) bool {
return false;
}
+fn acceptsInput(node: *wlr.SceneBuffer, x: *f64, y: *f64) callconv(.c) bool {
+ const self = SceneData.fromNode(&node.node).?.role.dock;
+ const raster = self.rasterBox();
+ const lx: f32 = @floatCast(x.* + @as(f64, @floatFromInt(raster.x)));
+ const ly: f32 = @floatCast(y.* + @as(f64, @floatFromInt(raster.y)));
+ return self.root.contains(lx, ly) or self.buttonAt(lx, ly) != null;
+}
+
pub fn tick(self: *Self, output: *Output, now_ms: i64) bool {
const server = output.server;
if (!server.config.compositor.dock_enabled or server.greeter_mode or !output.isAvailable() or output.idle_blanked) {
@@ -240,9 +272,19 @@ pub fn tick(self: *Self, output: *Output, now_ms: i64) bool {
/// gap on either side. Nothing when it floats over them (auto-hide), is off, or
/// does not fit and so shows nothing.
pub fn reservedStrip(server: *const Server, area: wlr.Box) i32 {
+ if (!reserves(&server.config.compositor)) return 0;
+ const reach = footprint(server, area);
+ return if (reach == 0) 0 else reach + window_margin;
+}
+
+/// How far a resting dock reaches in from its edge of `area`: its thickness and
+/// the gap to the edge, whether it reserves that strip or auto-hides. Read from
+/// the configuration alone, like `reservedStrip`, so what keeps clear of it (the
+/// OSD) stays put while an auto-hiding dock comes and goes.
+pub fn footprint(server: *const Server, area: wlr.Box) i32 {
const c = &server.config.compositor;
- if (server.greeter_mode or !reserves(c) or !fits(c, area)) return 0;
- return @as(i32, @intCast(c.dock_height)) + 2 * edge_margin;
+ if (server.greeter_mode or !c.dock_enabled or !fits(c, area)) return 0;
+ return @as(i32, @intCast(c.dock_height)) + edge_margin;
}
/// Whether the dock, as configured, keeps windows out of its strip. A change
@@ -267,7 +309,7 @@ fn fits(c: *const config.CompositorConfig, area: wlr.Box) bool {
fn configuredFixedCount(c: *const config.CompositorConfig) usize {
var count: usize = @min(c.dock_pinned_apps.len, max_pins);
for (std.enums.values(Shortcut)) |shortcut| {
- if (!hidden(c.dock_hidden_shortcuts, @tagName(shortcut))) count += 1;
+ if (shownIn(c, shortcut)) count += 1;
}
return count;
}
@@ -292,7 +334,9 @@ fn syncReveal(self: *Self, now_ms: i64) bool {
}
/// The dock fades and slides toward its edge as `reveal` falls. The raster does
-/// not change: only the node's position and opacity (glass follows both).
+/// not change: only the node's position and opacity. Glass follows the position
+/// as part of the tree, but its opacity is its own and is given here, or the
+/// blurred backdrop would stay solid until the dock parks.
fn applyReveal(self: *Self, now_ms: i64) void {
const t = std.math.clamp(self.reveal.value(now_ms), 0, 1);
var x = self.box.x;
@@ -308,6 +352,7 @@ fn applyReveal(self: *Self, now_ms: i64) void {
}
self.tree.?.node.setPosition(x, y);
self.node.?.setOpacity(t);
+ glass.Effect.configure(self.glass_effect, self.glass_radius, t);
}
fn menuOpen(self: *const Self) bool {
@@ -332,8 +377,9 @@ fn nearPointer(self: *const Self, output: *Output, x: f64, y: f64) bool {
if (at_edge) return true;
// Only a dock that is out can be pointed at: where it would be is windows.
if (!self.shown) return false;
- return px >= self.box.x - edge_margin and px < self.box.x + self.box.width + edge_margin and
- py >= self.box.y - edge_margin and py < self.box.y + self.box.height + edge_margin;
+ return (px >= self.box.x - edge_margin and px < self.box.x + self.box.width + edge_margin and
+ py >= self.box.y - edge_margin and py < self.box.y + self.box.height + edge_margin) or
+ self.buttonAt(@floatCast(x - @as(f64, @floatFromInt(self.box.x))), @floatCast(y - @as(f64, @floatFromInt(self.box.y)))) != null;
}
/// Every pointer motion. `engaged` is false while a window is moved or resized
@@ -380,8 +426,13 @@ fn hidden(items: []const []const u8, name: []const u8) bool {
return false;
}
+fn shownIn(c: *const config.CompositorConfig, shortcut: Shortcut) bool {
+ if (shortcut == .trash) return c.dock_show_trash;
+ return !hidden(c.dock_hidden_shortcuts, @tagName(shortcut));
+}
+
fn shortcutShown(self: *const Self, shortcut: Shortcut) bool {
- return !hidden(self.output.?.server.config.compositor.dock_hidden_shortcuts, @tagName(shortcut));
+ return shownIn(&self.output.?.server.config.compositor, shortcut);
}
fn shortcutCount(self: *const Self) usize {
@@ -472,9 +523,9 @@ const AppMatch = struct {
/// Resolve the same preferred applications and fallbacks as launchPreferred.
/// Snapshot strings stay alive for this rebuild; parsed argv lives in scratch.
-fn shortcutApps(self: *Self, entries: []const apps.AppEntry, scratch: std.mem.Allocator) [4]AppMatch {
+fn shortcutApps(self: *Self, entries: []const apps.AppEntry, scratch: std.mem.Allocator) [shortcut_count]AppMatch {
const server = self.output.?.server;
- var matches: [4]AppMatch = .{ .{}, .{ .id = "rediwm-files" }, .{ .id = "foot" }, .{ .id = Toplevel.settings_app_id } };
+ var matches: [shortcut_count]AppMatch = .{ .{}, .{ .id = "rediwm-files" }, .{ .id = "foot" }, .{ .id = Toplevel.settings_app_id }, .{} };
if (default_apps.find(entries, server.config.compositor.default_file_manager)) |entry| matches[@intFromEnum(Shortcut.files)] = .fromEntry(entry);
if (default_apps.find(entries, server.config.compositor.default_terminal)) |entry| {
matches[@intFromEnum(Shortcut.terminal)] = .fromEntry(entry);
@@ -505,7 +556,7 @@ fn rebuild(self: *Self, capacity: usize, area: wlr.Box) !void {
var scratch = std.heap.ArenaAllocator.init(gpa);
defer scratch.deinit();
const matches = self.shortcutApps(snapshot.entries, scratch.allocator());
- var targets: [4]?*Toplevel = @splat(null);
+ var targets: [shortcut_count]?*Toplevel = @splat(null);
var pin_targets: [max_pins]?*Toplevel = @splat(null);
const focused = @import("ipc/handlers.zig").findFocusedToplevel(output.server);
var tops: std.ArrayList(*Toplevel) = .empty;
@@ -549,6 +600,8 @@ fn rebuild(self: *Self, capacity: usize, area: wlr.Box) !void {
self.dispatcher.reset();
_ = self.arena.reset(.retain_capacity);
self.root = .{ .kind = .container, .children = self.buttons[0..self.count], .computed_width = @floatFromInt(self.box.width), .computed_height = @floatFromInt(self.box.height) };
+ const raster = self.rasterBox();
+ self.input_root = .{ .kind = .container, .children = self.buttons[0..self.count], .computed_x = @floatFromInt(raster.x), .computed_y = @floatFromInt(raster.y), .computed_width = @floatFromInt(raster.width), .computed_height = @floatFromInt(raster.height) };
var index: usize = 0;
self.pin_of = @splat(null);
for ([_]Shortcut{ .applications, .files, .terminal }) |shortcut| {
@@ -566,7 +619,12 @@ fn rebuild(self: *Self, capacity: usize, area: wlr.Box) !void {
self.setButton(index, null, top.id);
index += 1;
}
- if (self.shortcutShown(.settings)) self.setButton(index, .settings, if (targets[@intFromEnum(Shortcut.settings)]) |top| top.id else 0);
+ if (self.shortcutShown(.settings)) {
+ self.setButton(index, .settings, if (targets[@intFromEnum(Shortcut.settings)]) |top| top.id else 0);
+ index += 1;
+ }
+ // The trash is the dock's last item, past a divider; no window is its.
+ if (self.shortcutShown(.trash)) self.setButton(index, .trash, 0);
for (self.animations[0..self.count], 0..) |*pill, i| {
const shortcut = self.shortcuts[i];
const id = self.ids[i];
@@ -580,14 +638,15 @@ fn rebuild(self: *Self, capacity: usize, area: wlr.Box) !void {
break;
}
}
- self.setButtonZoom(i, std.math.clamp(pill.zoom.value(anim.nowMs()), 1, output.server.config.compositor.dock_hover_zoom));
+ const range = self.zoomRange();
+ self.setButtonZoom(i, std.math.clamp(pill.zoom.value(anim.nowMs()), range.min, range.max));
}
// The pointer rests on a replaced button: hover it before painting, so
// the rebuild paints once.
if (hovered) {
self.place(area);
const cursor = output.server.input.cursor;
- self.dispatcher.pointerMotion(&self.root, @floatCast(cursor.x - @as(f64, @floatFromInt(self.box.x))), @floatCast(cursor.y - @as(f64, @floatFromInt(self.box.y))));
+ self.dispatcher.pointerMotion(&self.input_root, @floatCast(cursor.x - @as(f64, @floatFromInt(self.box.x))), @floatCast(cursor.y - @as(f64, @floatFromInt(self.box.y))));
}
self.dirty = false;
}
@@ -620,14 +679,49 @@ fn topAt(self: *Self, index: usize) ?*Toplevel {
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 icon = self.iconBox(index, zoom, 36);
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;
+ const along: f32 = @floatFromInt(@as(i32, @intCast(index)) * m.itemStep() + m.padding());
+ const cross: f32 = @floatFromInt(self.buttonCross());
+ const x = if (self.position.vertical()) cross else along;
+ const y = if (self.position.vertical()) along else cross;
+ button.computed_x = @min(x, icon.x);
+ button.computed_y = @min(y, icon.y);
+ button.computed_width = @max(x + base, icon.x + icon.w) - button.computed_x;
+ button.computed_height = @max(y + base, icon.y + icon.h) - button.computed_y;
+}
+
+/// How far a hovered icon's zoom may go while its spring overshoots past
+/// `dock_hover_zoom` or dips under rest on the way back. Rasters and cells are
+/// sized for `max`, so a bounce never needs a larger buffer or upsamples icons.
+fn zoomRange(self: *const Self) struct { min: f32, max: f32 } {
+ const hover_zoom = self.output.?.server.config.compositor.dock_hover_zoom;
+ const headroom = (hover_zoom - 1) * 0.3;
+ return .{ .min = 1 - headroom, .max = hover_zoom + headroom };
+}
+
+/// Keep the icon's screen-edge side fixed as it grows toward the desktop.
+fn iconBox(self: *const Self, index: usize, zoom: f32, reference: f32) ui.layout.Widget.PaintBounds {
+ const m = self.metrics();
+ const base: f32 = @floatFromInt(m.length(reference));
+ const side = base * zoom;
+ const along = @as(f32, @floatFromInt(@as(i32, @intCast(index)) * m.itemStep() + m.padding())) + @as(f32, @floatFromInt(m.length(48))) / 2;
+ const inward: f32 = if (self.position == .bottom or self.position == .right) -1 else 1;
+ const cross = @as(f32, @floatFromInt(self.buttonCross())) + @as(f32, @floatFromInt(m.length(48))) / 2 + inward * (side - base) / 2;
+ return .{ .x = (if (self.position.vertical()) cross else along) - side / 2, .y = (if (self.position.vertical()) along else cross) - side / 2, .w = side, .h = side };
+}
+
+/// Only the foreground raster extends beyond the background at large zooms.
+fn rasterBox(self: *const Self) wlr.Box {
+ const icon = self.iconBox(0, self.zoomRange().max, 36);
+ const m = self.metrics();
+ const cross = if (self.position.vertical()) icon.x else icon.y;
+ const before: i32 = @intFromFloat(@ceil(@max(0, -cross)));
+ const after: i32 = @intFromFloat(@ceil(@max(0, cross + icon.w - @as(f32, @floatFromInt(m.height)))));
+ return if (self.position.vertical())
+ .{ .x = -before, .y = 0, .width = self.box.width + before + after, .height = self.box.height }
+ else
+ .{ .x = 0, .y = -before, .width = self.box.width, .height = self.box.height + before + after };
}
fn label(self: *Self, index: usize) []const u8 {
@@ -636,6 +730,7 @@ fn label(self: *Self, index: usize) []const u8 {
.files => "Files",
.terminal => "Terminal",
.settings => "Settings",
+ .trash => "Trash",
};
if (self.pin_of[index]) |p| return self.pins[p].name;
return if (self.topAt(index)) |top| top.title() else "Application";
@@ -670,8 +765,7 @@ fn paint(self: *Self, now_ms: i64) !void {
const output = self.output.?;
const m = self.metrics();
const pal = ui.theme.shellPalette();
- var bg = pal.dock_bg orelse ui.theme.taskbar(.taskbar_bg);
- if (pal.dock_bg == null) bg[3] = @max(bg[3], 0.86);
+ const bg = background(&output.server.config.compositor, pal);
const focused = @import("ipc/handlers.zig").findFocusedToplevel(output.server);
var looks: [max_items]Look = undefined;
var item_keys: [max_items]u64 = undefined;
@@ -679,7 +773,7 @@ fn paint(self: *Self, now_ms: i64) !void {
// Dock-wide state: a change repaints the whole raster. Each item's own look is
// keyed apart, so a hover repaints only the icons it moves.
var base_hasher = std.hash.Wyhash.init(0);
- hashValue(&base_hasher, .{ pal, bg, self.scale, self.position, self.box.width, self.box.height, self.count, self.offset, self.windows, self.pin_base, self.drop_slot, output.server.config.compositor.dock_hover_zoom });
+ hashValue(&base_hasher, .{ pal, bg, self.scale, self.position, self.box.width, self.box.height, self.count, self.offset, self.windows, self.pin_base, self.drop_slot, output.server.config.compositor.dock_hover_zoom, output.server.config.compositor.dock_active_highlight });
const base_key = base_hasher.final();
var hasher = std.hash.Wyhash.init(0);
hasher.update(std.mem.asBytes(&base_key));
@@ -690,10 +784,12 @@ fn paint(self: *Self, now_ms: i64) !void {
.files => "rediwm-files",
.terminal => "utilities-terminal",
.settings => ui.shell_icons.settings_icon_name,
+ .trash => "user-trash",
} else if (self.pin_of[index]) |p| self.pins[p].icon else if (top) |t| t.appId() else "";
- // Retain one raster at the configured maximum, not a new size each frame.
+ // Retain one raster at the largest zoom, 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 range = self.zoomRange();
+ const lookup = output.server.iconLookup(icon_name, self.iconRaster(m));
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;
@@ -701,7 +797,7 @@ fn paint(self: *Self, now_ms: i64) !void {
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));
+ } else if (pill.zoom.to != zoom) pill.zoom.retargetTo(now_ms, zoom, anim.curveFor(.dock_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)));
@@ -713,10 +809,10 @@ fn paint(self: *Self, now_ms: i64) !void {
.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),
+ .zoom = std.math.clamp(pill.zoom.last_quantised, range.min, range.max),
};
- // Input covers the painted icon even at 1.5×. Keep centres fixed so
- // moving between neighbours cannot make the row chase the pointer.
+ // Input covers both the resting button and the growing icon. Centres
+ // along the row stay fixed when moving between neighbours.
self.setButtonZoom(index, look.zoom);
const icon_id: ?u64 = if (look.icon) |icon| icon.id else null;
var item_hasher = std.hash.Wyhash.init(0);
@@ -730,6 +826,28 @@ fn paint(self: *Self, now_ms: i64) !void {
try self.paintTooltip();
}
+/// Device pixels of the icon raster the dock asks for: the largest size an icon
+/// is drawn at, so hovering never needs another.
+fn iconRaster(self: *const Self, m: Metrics) i32 {
+ const zoom = self.zoomRange().max;
+ return @import("geometry.zig").devicePixels(@intFromFloat(@ceil(@as(f32, @floatFromInt(m.length(36))) * zoom)), self.scale);
+}
+
+/// The dock's background: the theme's `dock_bg`, else the taskbar's with a
+/// floor on its alpha. `dock_opacity`, when set, replaces the alpha of either.
+pub fn background(c: *const config.CompositorConfig, pal: ui.theme.Theme) [4]f32 {
+ var bg = pal.dock_bg orelse ui.theme.taskbar(.taskbar_bg);
+ if (pal.dock_bg == null) bg[3] = @max(bg[3], 0.86);
+ if (c.dock_opacity) |opacity| bg[3] = std.math.clamp(opacity, 0, 1);
+ return bg;
+}
+
+/// The dock's corner radius: the theme's `dock_radius`, or the window frame's
+/// (Appearance's Radius) while that is zero. Painting caps it at half the dock.
+pub fn cornerRadius(pal: ui.theme.Theme) f32 {
+ return if (pal.dock_radius > 0) pal.dock_radius else ui.window_chrome.frameRadius();
+}
+
/// A device-pixel rectangle of the dock raster.
const DeviceRect = struct {
x0: i32,
@@ -752,11 +870,11 @@ const DeviceRect = struct {
/// Everything item `index` can paint, at the largest hover zoom, across the dock's
/// thickness: the cell a repaint of that item must restore. Neighbours' cells
-/// meet but do not overlap (the icon is narrower than the step).
+/// may overlap at the top of a large zoom's bounce; a partial repaint redraws
+/// every item whose cell meets the dirty box, so that stays exact.
fn itemCell(self: *const Self, m: Metrics, index: usize, width: i32, height: i32) DeviceRect {
- const hover_zoom = self.output.?.server.config.compositor.dock_hover_zoom;
const base: f32 = @floatFromInt(m.length(48));
- const side = @max(base, @as(f32, @floatFromInt(m.length(36))) * hover_zoom);
+ const side = @max(base, @as(f32, @floatFromInt(m.length(36))) * self.zoomRange().max);
const centre = @as(f32, @floatFromInt(@as(i32, @intCast(index)) * m.itemStep() + m.padding())) + base / 2;
const lo: i32 = @intFromFloat(@floor((centre - side / 2) * self.scale));
const hi: i32 = @intFromFloat(@ceil((centre + side / 2) * self.scale));
@@ -786,13 +904,16 @@ fn changedCells(self: *const Self, m: Metrics, base_key: u64, item_keys: []const
fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look, base_key: u64, item_keys: []const u64) !void {
const m = self.metrics();
const geometry = @import("geometry.zig");
- const width = geometry.devicePixels(self.box.width, self.scale);
- const height = geometry.devicePixels(self.box.height, self.scale);
+ const raster = self.rasterBox();
+ const ox: f32 = @floatFromInt(-raster.x);
+ const oy: f32 = @floatFromInt(-raster.y);
+ const width = geometry.devicePixels(raster.width, self.scale);
+ const height = geometry.devicePixels(raster.height, self.scale);
const dirty = self.changedCells(m, base_key, item_keys, width, height);
const image = if (dirty != null)
- try PanelBuffer.createUninitialized(self.box.width, self.box.height, self.scale)
+ try PanelBuffer.createUninitialized(raster.width, raster.height, self.scale)
else
- try PanelBuffer.create(self.box.width, self.box.height, self.scale);
+ try PanelBuffer.create(raster.width, raster.height, self.scale);
defer image.base.drop();
var r = ui.paint.Renderer.init(image.pixels, image.width, image.height, self.scale);
r.palette = pal;
@@ -815,14 +936,15 @@ 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(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 });
+ const radius = @min(cornerRadius(pal), @as(f32, @floatFromInt(m.height)) / 2);
+ self.glass_radius = radius;
+ glass.Effect.configure(self.glass_effect, radius, std.math.clamp(self.reveal.value(anim.nowMs()), 0, 1));
+ r.fillRect(ox, oy, @floatFromInt(self.box.width), @floatFromInt(self.box.height), .{ .color = bg, .radius = radius, .border_width = 1, .border_color = border });
for (looks, 0..) |look, index| {
if (dirty) |box| if (!box.overlaps(self.itemCell(m, index, width, height))) continue;
- self.paintItem(&r, pal, m, index, look);
+ self.paintItem(&r, pal, m, index, look, ox, oy);
}
- self.paintMarks(&r, pal, m);
+ self.paintMarks(&r, pal, m, ox, oy);
if (dirty) |box| {
for (@as(usize, @intCast(box.y0))..@as(usize, @intCast(box.y1))) |y| {
const row = y * stride;
@@ -844,29 +966,34 @@ fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look,
self.base_drawn = base_key;
self.items_drawn = item_keys.len;
@memcpy(self.item_drawn[0..item_keys.len], item_keys);
- self.node.?.setDestSize(self.box.width, self.box.height);
+ self.node.?.node.setPosition(raster.x, raster.y);
+ self.node.?.setDestSize(raster.width, raster.height);
+ self.glass_anchor.?.setDestSize(self.box.width, self.box.height);
}
/// One button: its backdrop, icon and running pill.
-fn paintItem(self: *Self, r: *ui.paint.Renderer, pal: ui.theme.Theme, m: Metrics, index: usize, look: Look) void {
+fn paintItem(self: *Self, r: *ui.paint.Renderer, pal: ui.theme.Theme, m: Metrics, index: usize, look: Look, ox: f32, oy: f32) void {
const zooms = self.output.?.server.config.compositor.dock_hover_zoom > 1;
const button = &self.buttons[index];
- const x = button.computed_x;
- const cx = x + button.computed_width / 2;
- const cy = button.computed_y + button.computed_height / 2;
+ const x = button.computed_x + ox;
+ const y = button.computed_y + oy;
+ const resting = self.iconBox(index, 1, 36);
+ const cx = resting.x + resting.w / 2 + ox;
+ const cy = resting.y + resting.h / 2 + oy;
// An enlarging icon is the hover feedback: no rectangle behind it.
const pointer: ui.layout.ButtonState = if (zooms) .idle else button.kind.button.state;
- 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 = pointer, .selected = look.focused });
+ ui.widgets.button.paintBackground(r, .{ .x = x, .y = y, .w = button.computed_width, .h = button.computed_height }, .{ .variant = .ghost, .radius = m.size(12) }, .{ .pointer = pointer, .selected = look.focused and self.output.?.server.config.compositor.dock_active_highlight });
if (look.icon) |icon| {
- const size = @as(f32, @floatFromInt(m.length(36))) * look.zoom;
- r.drawImageSmooth(cx - size / 2, cy - size / 2, size, size, 0, .{ .pixels = icon.pixels, .width = icon.size, .height = icon.size });
+ const rect = self.iconBox(index, look.zoom, 36);
+ r.drawImageSmooth(rect.x + ox, rect.y + oy, rect.w, rect.h, 0, .{ .pixels = icon.pixels, .width = icon.size, .height = icon.size });
} else {
- 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) {
+ const rect = self.iconBox(index, look.zoom, 34);
+ r.drawIcon(rect.x + ox, rect.y + oy, rect.w, rect.h, .{ .id = if (self.shortcuts[index]) |shortcut| switch (shortcut) {
.applications => .grid,
.files => .folder,
.terminal => .terminal,
.settings => .settings,
+ .trash => .trash_can,
} else .generic, .color = pal.window_fg });
}
if (look.pill_width > 0 and look.pill_opacity > 0) {
@@ -876,14 +1003,14 @@ fn paintItem(self: *Self, r: *ui.paint.Renderer, pal: ui.theme.Theme, m: Metrics
const thickness = @max(2, m.size(4));
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 });
+ r.fillRect(cross + ox, cy - width / 2, thickness, width, .{ .color = accent, .radius = @min(width, thickness) / 2 });
+ } else r.fillRect(cx - width / 2, cross + oy, width, thickness, .{ .color = accent, .radius = @min(width, thickness) / 2 });
}
}
/// What lies between and beside the buttons: the drop gap, the divider after the
/// launcher and the scroll chevrons.
-fn paintMarks(self: *Self, r: *ui.paint.Renderer, pal: ui.theme.Theme, m: Metrics) void {
+fn paintMarks(self: *Self, r: *ui.paint.Renderer, pal: ui.theme.Theme, m: Metrics, ox: f32, oy: f32) void {
if (self.drop_slot) |slot| {
// A dragged application lands in this gap between two buttons.
const gap: f32 = @floatFromInt(m.itemStep() - m.length(48));
@@ -892,29 +1019,68 @@ fn paintMarks(self: *Self, r: *ui.paint.Renderer, pal: ui.theme.Theme, m: Metric
const length = m.size(36);
const cross = (@as(f32, @floatFromInt(m.height)) - length) / 2;
if (self.position.vertical()) {
- r.fillRect(cross, along - thickness / 2, length, thickness, .{ .color = pal.accent, .radius = thickness / 2 });
- } else r.fillRect(along - thickness / 2, cross, thickness, length, .{ .color = pal.accent, .radius = thickness / 2 });
+ r.fillRect(cross + ox, along - thickness / 2 + oy, length, thickness, .{ .color = pal.accent, .radius = thickness / 2 });
+ } else r.fillRect(along - thickness / 2 + ox, cross + oy, thickness, length, .{ .color = pal.accent, .radius = thickness / 2 });
}
var divider = pal.window_fg;
divider[3] = 0.16;
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.position.vertical()) r.fillRect(m.size(18) + ox, along + oy, m.size(30), 1, .{ .color = divider }) else r.fillRect(along + ox, m.size(18) + oy, 1, m.size(30), .{ .color = divider });
+ }
+ if (self.count > 1 and self.shortcuts[self.count - 1] == .trash) {
+ const along: f32 = @floatFromInt(@as(i32, @intCast(self.count - 1)) * m.itemStep() + m.padding() - m.length(4));
+ if (self.position.vertical()) r.fillRect(m.size(18) + ox, along + oy, m.size(30), 1, .{ .color = divider }) else r.fillRect(along + ox, m.size(18) + oy, 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.position.vertical()) r.drawIcon(m.size(28) + ox, 1 + oy, m.size(12), m.size(10), .{ .id = .chevron_up, .color = pal.accent }) else r.drawIcon(1 + ox, m.size(28) + oy, m.size(10), m.size(12), .{ .id = .chevron_left, .color = pal.accent });
}
if (self.offset + self.count - self.fixedCount() < 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 });
+ if (self.position.vertical()) r.drawIcon(m.size(28) + ox, @as(f32, @floatFromInt(self.box.height)) - m.size(11) + oy, m.size(12), m.size(10), .{ .id = .chevron_down, .color = pal.accent }) else r.drawIcon(@as(f32, @floatFromInt(self.box.width)) - m.size(11) + ox, m.size(28) + oy, m.size(10), m.size(12), .{ .id = .chevron_right, .color = pal.accent });
}
}
+/// The pointer is on a new icon (or off every one): its tooltip waits out the
+/// delay again.
+fn restartTip(self: *Self) void {
+ self.cancelTip();
+ const hovered = self.dispatcher.hovered orelse return;
+ if (hovered.kind != .button) return;
+ if (self.tip_timer == null) self.tip_timer = self.output.?.server.wl_server.getEventLoop().addTimer(*Self, onTipTimer, self) catch null;
+ if (self.tip_timer) |timer| {
+ if (timer.timerUpdate(tooltip_delay_ms)) {
+ self.tip_armed = true;
+ return;
+ } else |_| {}
+ }
+ // No timer: show at once.
+ self.tip_ready = true;
+}
+
+fn cancelTip(self: *Self) void {
+ self.tip_ready = false;
+ if (!self.tip_armed) return;
+ self.tip_armed = false;
+ if (self.tip_timer) |timer| timer.timerUpdate(0) catch {};
+}
+
+fn onTipTimer(self: *Self) c_int {
+ self.tip_armed = false;
+ if (self.dispatcher.hovered == null or self.tooltip == null) return 0;
+ self.tip_ready = true;
+ self.paintTooltip() catch {};
+ self.output.?.wlr_output.scheduleFrame();
+ return 0;
+}
+
fn paintTooltip(self: *Self) !void {
const hovered = self.dispatcher.hovered orelse {
+ // A rebuild can leave nothing hovered without a motion.
+ self.cancelTip();
self.tooltip.?.node.setEnabled(false);
return;
};
- if (hovered.kind != .button) {
+ if (hovered.kind != .button or !self.tip_ready) {
self.tooltip.?.node.setEnabled(false);
return;
}
@@ -964,8 +1130,11 @@ fn placeTooltip(self: *Self, hovered: *ui.layout.Widget, width: i32, area: wlr.B
pub fn motion(self: *Self, x: f64, y: f64) void {
const old = self.dispatcher.hovered;
- self.dispatcher.pointerMotion(&self.root, @floatCast(x), @floatCast(y));
- if (old != self.dispatcher.hovered) self.repaint();
+ self.dispatcher.pointerMotion(&self.input_root, @floatCast(x), @floatCast(y));
+ if (old != self.dispatcher.hovered) {
+ self.restartTip();
+ self.repaint();
+ }
}
pub fn leave(self: *Self) void {
@@ -981,14 +1150,40 @@ fn repaint(self: *Self) void {
}
pub fn press(self: *Self, x: f64, y: f64) void {
- // Shell launchers activate on press, like the taskbar.
- self.dispatcher.pointerButtonDown(&self.root, @floatCast(x), @floatCast(y));
- self.dispatcher.pointerButtonUp(&self.root, @floatCast(x), @floatCast(y));
+ // A pinned icon can be dragged to another place among the pins, so it acts
+ // when released in place (`clickPin`); the other launchers act on press, like
+ // the taskbar.
+ if (self.buttonAt(@floatCast(x), @floatCast(y))) |index| if (self.pin_of[index]) |p| {
+ const input = &self.output.?.server.input;
+ input.dock_drag.armReorder(input, self.pins[p].id, self.pins[p].icon, self.scale);
+ return;
+ };
+ self.dispatcher.pointerButtonDown(&self.input_root, @floatCast(x), @floatCast(y));
+ self.dispatcher.pointerButtonUp(&self.input_root, @floatCast(x), @floatCast(y));
+ self.repaint();
+}
+
+fn buttonAt(self: *const Self, x: f32, y: f32) ?usize {
+ for (self.buttons[0..self.count], 0..) |*button, index| {
+ if (button.contains(x, y)) return index;
+ }
+ return null;
+}
+
+/// A pinned icon was pressed and released without being dragged: its click,
+/// if the pointer (at layout position `x`, `y`) is still on that icon.
+pub fn clickPin(self: *Self, x: f64, y: f64, app_id: []const u8) void {
+ const local_x: f32 = @floatCast(x - @as(f64, @floatFromInt(self.box.x)));
+ const local_y: f32 = @floatCast(y - @as(f64, @floatFromInt(self.box.y)));
+ const index = self.buttonAt(local_x, local_y) orelse return;
+ const p = self.pin_of[index] orelse return;
+ if (!std.mem.eql(u8, self.pins[p].id, app_id)) return;
+ clicked(self, index);
self.repaint();
}
pub fn contextMenu(self: *Self, x: f64, y: f64, screen_x: i32) bool {
- self.dispatcher.pointerMotion(&self.root, @floatCast(x), @floatCast(y));
+ self.dispatcher.pointerMotion(&self.input_root, @floatCast(x), @floatCast(y));
const button = self.dispatcher.hovered orelse return false;
if (button.kind != .button) return false;
const index = button.kind.button.id;
@@ -1004,7 +1199,13 @@ pub fn contextMenu(self: *Self, x: f64, y: f64, screen_x: i32) bool {
/// Removes a shortcut's launcher. Its app still shows while it runs.
pub fn removeShortcut(self: *Self, shortcut: Shortcut) void {
const server = self.output.?.server;
- self.saveHidden("dock_hidden_shortcuts", @tagName(shortcut)) catch |err| {
+ if (shortcut == .trash) {
+ @import("config").setting_save.saveCompositor(gpa, server.io, server.config.path, "dock_show_trash", false) catch |err| {
+ std.log.warn("could not remove the dock's trash: {}", .{err});
+ return;
+ };
+ server.config.compositor.dock_show_trash = false;
+ } else self.saveHidden("dock_hidden_shortcuts", @tagName(shortcut)) catch |err| {
std.log.warn("could not remove dock shortcut: {}", .{err});
return;
};
@@ -1048,6 +1249,54 @@ fn slotFor(along: f64, padding: i32, step: i32, base: usize, pins: usize) usize
return @intFromFloat(std.math.clamp(gap - @as(f64, @floatFromInt(base)), 0, @as(f64, @floatFromInt(pins))));
}
+fn pinIndex(self: *const Self, app_id: []const u8) ?usize {
+ for (self.pins[0..self.pin_count], 0..) |pin, i| if (std.mem.eql(u8, pin.id, app_id)) return i;
+ return null;
+}
+
+/// Whether dropping `app_id`'s pin in the gap before pin `slot` changes
+/// nothing: the gaps on either side of the pin itself, or it is gone.
+pub fn staysPut(self: *const Self, app_id: []const u8, slot: usize) bool {
+ const from = self.pinIndex(app_id) orelse return true;
+ return slot == from or slot == from + 1;
+}
+
+/// The icon a pinned application's button shows, once it is loaded.
+pub fn pinIcon(self: *const Self, app_id: []const u8) ?IconEntry {
+ const output = self.output orelse return null;
+ const pin = self.pins[self.pinIndex(app_id) orelse return null];
+ const lookup = output.server.iconLookup(pin.icon, self.iconRaster(self.metrics()));
+ return if (lookup == .ready) lookup.ready else null;
+}
+
+/// Moves a pinned application to the gap before pin `slot` (`pin_count` is the
+/// end). Pins no longer installed keep their places around it.
+pub fn movePin(self: *Self, app_id: []const u8, slot: usize) void {
+ if (self.staysPut(app_id, slot)) return;
+ const from = self.pinIndex(app_id).?;
+ const server = self.output.?.server;
+ const old = server.config.compositor.dock_pinned_apps;
+ const moving = self.pins[from].config_index;
+ const items = server.config.arena.allocator().alloc([]const u8, old.len) catch return;
+ var len: usize = 0;
+ var placed = false;
+ for (old, 0..) |id, i| {
+ if (i == moving) continue;
+ if (!placed and slot < self.pin_count and i == self.pins[slot].config_index) {
+ items[len] = old[moving];
+ len += 1;
+ placed = true;
+ }
+ items[len] = id;
+ len += 1;
+ }
+ if (!placed) {
+ items[len] = old[moving];
+ len += 1;
+ }
+ self.savePinned(items[0..len]);
+}
+
/// Shows (or clears) the drop marker of a drag in progress.
pub fn setDropSlot(self: *Self, slot: ?usize) void {
if (self.drop_slot == slot) return;
@@ -1126,7 +1375,7 @@ pub fn captureAnimations(self: *Self, allocator: std.mem.Allocator, list: *std.A
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);
+ try anim.captureIfLive(allocator, list, &pill.zoom, .dock_hover, now_ms);
}
}
@@ -1160,10 +1409,59 @@ fn clicked(owner: ?*anyopaque, index: usize) void {
defer snapshot.release();
const id = self.pins[pin_index].id;
const entry = default_apps.find(snapshot.entries, id) orelse return;
+ server.launch_feedback.setOrigin(self.launchOrigin(index));
+ defer server.launch_feedback.clearOrigin();
@import("start_menu/launch.zig").launch(gpa, server, entry) catch |err| std.log.warn("could not launch pinned app {s}: {}", .{ id, err });
} else if (self.shortcuts[index]) |shortcut| switch (shortcut) {
.applications => output.toggleAppLauncher(),
- .files, .terminal => @import("config_runtime/actions.zig").executeAction(server, .{ .spawn = if (shortcut == .files) "default-file-manager" else "default-terminal" }),
+ .files, .terminal => {
+ server.launch_feedback.setOrigin(self.launchOrigin(index));
+ defer server.launch_feedback.clearOrigin();
+ @import("config_runtime/actions.zig").executeAction(server, .{ .spawn = if (shortcut == .files) "default-file-manager" else "default-terminal" });
+ },
.settings => output.toggleControlCenter(),
+ .trash => {
+ server.launch_feedback.setOrigin(self.launchOrigin(index));
+ defer server.launch_feedback.clearOrigin();
+ openTrash(server);
+ },
+ };
+}
+
+/// Opens the trash (`$XDG_DATA_HOME/Trash/files`) in the default file manager,
+/// as the desktop's Trash icon does.
+fn openTrash(server: *Server) void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const home = server.environ.getPosix("HOME") orelse return;
+ const data_home = server.environ.getPosix("XDG_DATA_HOME") orelse (std.fmt.allocPrint(a, "{s}/.local/share", .{home}) catch return);
+ const trash = std.fmt.allocPrint(a, "{s}/Trash/files", .{data_home}) catch return;
+ // Files browses the trash by path; it must exist before the first deletion.
+ std.Io.Dir.cwd().createDirPath(server.io, trash) catch {};
+ const id = server.config.compositor.default_file_manager;
+ if (id.len > 0) {
+ const snapshot = server.start_menu_catalog.retainSnapshot();
+ defer snapshot.release();
+ if (default_apps.find(snapshot.entries, id)) |entry| {
+ const uris = @import("desktop/dnd.zig").uriList(a, &.{trash}) catch return;
+ const uri = std.mem.trimEnd(u8, uris, "\r\n");
+ @import("start_menu/launch.zig").launchUris(gpa, server, entry, &.{uri}) catch |err| std.log.warn("could not open the trash in {s}: {}", .{ id, err });
+ return;
+ }
+ }
+ @import("config_runtime/actions.zig").spawnArgv(server, &.{ "rediwm-files", trash });
+}
+
+/// The layout-space square of item `index`'s icon, which a window it launches
+/// grows out of.
+fn launchOrigin(self: *const Self, index: usize) @import("launch_feedback.zig").Origin {
+ const button = &self.buttons[index];
+ const side: f64 = @min(button.computed_width, button.computed_height);
+ return .{
+ .x = @as(f64, @floatFromInt(self.box.x)) + button.computed_x + (button.computed_width - side) / 2,
+ .y = @as(f64, @floatFromInt(self.box.y)) + button.computed_y + (button.computed_height - side) / 2,
+ .width = side,
+ .height = side,
};
}
diff --git a/src/Input.zig b/src/Input.zig
index 683bc3d..a130a1f 100644
--- a/src/Input.zig
+++ b/src/Input.zig
@@ -1649,7 +1649,7 @@ fn passthroughMotion(input: *Input, time_msec: u32) void {
input.clearTaskbarHover();
input.setHover(null, null);
control_center.pointerMotion(res.cc, res.sx, res.sy);
- input.setShellCursor(ui_input.current.overText());
+ if (control_center.overDraggable(res.cc, res.sx, res.sy)) input.setNamedCursor("grab") else input.setShellCursor(ui_input.current.overText());
input.seat.pointerClearFocus();
},
.start_menu => |res| {
diff --git a/src/Keyboard.zig b/src/Keyboard.zig
index 6559c2e..b1a978f 100644
--- a/src/Keyboard.zig
+++ b/src/Keyboard.zig
@@ -440,6 +440,23 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
}
}
+ // Escape drops a pinned dock icon being dragged, whichever shell panel has the
+ // keyboard; its release is ours too.
+ if (state == .pressed and keyboard.server.input.dock_drag.reordering()) {
+ for (xkb_state.keyGetSyms(keycode)) |sym| {
+ if (@intFromEnum(sym) != xkb.Keysym.Escape) continue;
+ _ = keyboard.server.input.cancelDrag();
+ keyboard.consuming_escape = true;
+ return;
+ }
+ } else if (state == .released and keyboard.consuming_escape) {
+ for (xkb_state.keyGetSyms(keycode)) |sym| {
+ if (@intFromEnum(sym) != xkb.Keysym.Escape) continue;
+ keyboard.consuming_escape = false;
+ return;
+ }
+ }
+
if (keyboard.server.input.window_menu.node != null and keyboard.server.screenshot_selector.output == null) {
if (state == .pressed) {
if (event_keycode < keyboard.tray_consumed.len) keyboard.tray_consumed[event_keycode] = true;
diff --git a/src/Server.zig b/src/Server.zig
index 9735dd9..7aab4df 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -1507,7 +1507,8 @@ fn handleAudioWake(fd: c_int, mask: wl.EventMask, server: *Server) c_int {
while (it.next()) |output| {
if (output.taskbar) |bar| bar.markDirty(Taskbar.paint_audio);
}
- if (server.input.open_control_center) |cc| cc.refresh();
+ // Only General and Audio show audio state; elsewhere a rebuild is wasted.
+ if (server.input.open_control_center) |cc| if (cc.page == .general or cc.page == .audio) cc.refresh();
if (server.locker) |lock| lock.controlsChanged();
server.scheduleFrames();
return 0;
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index 007f646..c33eabf 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -177,7 +177,7 @@ tree: *wlr.SceneTree,
buffer_node: *wlr.SceneBuffer,
start_node: *wlr.SceneBuffer,
clock_node: *wlr.SceneBuffer,
-tray_nodes: [2]*wlr.SceneBuffer,
+tray_nodes: [tray_count]*wlr.SceneBuffer,
app_tray_node: *wlr.SceneBuffer,
app_tray_generation: u64 = 0,
capture_node: *wlr.SceneBuffer,
@@ -202,14 +202,14 @@ paint_causes: u8 = 0,
background_dirty: bool = true,
start_dirty: bool = true,
clock_dirty: bool = true,
-tray_dirty: [2]bool = .{ true, true },
+tray_dirty: [tray_count]bool = @splat(true),
capture_dirty: bool = true,
capture_sessions: usize = 0,
start: start_button.State = .{},
start_logo: ?icon_service.Entry = null,
chips: std.ArrayList(ChipState) = .empty,
-tray: [2]TrayState = .{ .{ .kind = .volume }, .{ .kind = .wifi } },
+tray: [tray_count]TrayState = .{ .{ .kind = .volume }, .{ .kind = .wifi }, .{ .kind = .power } },
capture_hover: Anim = .{},
capture_press: Anim = .{ .to = 1 },
hover_target: Target = .none,
@@ -241,6 +241,7 @@ clock_minute: c_time.time_t = 0,
// same (see `updateClockStrings`), so a ticking clock never moves its neighbours.
clock_width: MeasuredWidth = .{},
clock_digit: MeasuredWidth = .{},
+clock_style: u8 = 0,
capture_width: MeasuredWidth = .{},
const MeasuredWidth = struct {
@@ -260,7 +261,8 @@ const MeasuredWidth = struct {
}
};
-const TrayKind = enum { volume, wifi };
+const TrayKind = enum { volume, wifi, power };
+const tray_count = std.meta.fields(TrayKind).len;
pub const AppKind = enum { file_explorer, notes, terminal, settings, text_doc, browser, other };
@@ -407,7 +409,7 @@ pub fn create(server: *Server, wlr_output: *wlr.Output) !*Taskbar {
const buffer_node = try tree.createSceneBuffer(null);
const start_node = try tree.createSceneBuffer(null);
const clock_node = try tree.createSceneBuffer(null);
- var tray_nodes: [2]*wlr.SceneBuffer = undefined;
+ var tray_nodes: [tray_count]*wlr.SceneBuffer = undefined;
for (&tray_nodes) |*node| node.* = try tree.createSceneBuffer(null);
const app_tray_node = try tree.createSceneBuffer(null);
const capture_node = try tree.createSceneBuffer(null);
@@ -485,7 +487,7 @@ pub fn applyBattery(bar: *Taskbar, next: battery.State) void {
bar.battery_dirty = true;
if (layout_changed) {
_ = bar.reconcile(nowMs());
- bar.tray_dirty = .{ true, true };
+ bar.tray_dirty = @splat(true);
bar.clock_dirty = true;
bar.capture_dirty = true;
}
@@ -619,7 +621,7 @@ fn refreshClock(bar: *Taskbar, reset_width: bool) void {
var causes: u8 = paint_clock;
if (width_changed) {
// A wider/narrower clock moves every item to its left, including the tray.
- bar.tray_dirty = .{ true, true };
+ bar.tray_dirty = @splat(true);
bar.capture_dirty = true;
const chips_changed = bar.reconcile(nowMs());
causes |= paint_tray | paint_capture | (if (chips_changed) paint_chips else @as(u8, 0));
@@ -738,7 +740,7 @@ pub fn relayout(bar: *Taskbar, output_box: wlr.Box) void {
bar.background_dirty = true;
bar.start_dirty = true;
bar.clock_dirty = true;
- bar.tray_dirty = .{ true, true };
+ bar.tray_dirty = @splat(true);
bar.capture_dirty = true;
bar.battery_dirty = true;
for (bar.chips.items) |*chip| chip.dirty = true;
@@ -752,6 +754,8 @@ pub fn relayout(bar: *Taskbar, output_box: wlr.Box) void {
if (Output.fromWlr(bar.wlr_output)) |output| if (output.battery_popup) |popup| {
if (bar.itemBox(.battery) == null) output.closeBattery() else popup.refresh();
};
+ // The calendar follows the clock as the bar lays its items out again.
+ if (Output.fromWlr(bar.wlr_output)) |output| if (output.calendar) |calendar| calendar.refresh();
}
// Called whenever world.toplevels changes shape or order (map, unmap,
@@ -778,6 +782,18 @@ const ClockPiece = struct { text: []const u8, x: i32, w: i32 };
const clock_pieces_max = 16;
const ClockLine = struct { pieces: [clock_pieces_max]ClockPiece = undefined, count: usize = 0, width: i32 = 0 };
+fn clockFont() text.Font {
+ return if (ui_theme.taskbar(.clock_bold)) .manrope_heavy else .manrope;
+}
+
+fn clockStyleChanged(bar: *Taskbar) void {
+ const style = @as(u8, @intFromBool(ui_theme.taskbar(.clock_bold))) | (@as(u8, @intFromBool(ui_theme.taskbar(.clock_italic))) << 1);
+ if (style == bar.clock_style) return;
+ bar.clock_style = style;
+ bar.clock_digit.valid = false;
+ bar.clock_width.valid = false;
+}
+
/// The widest digit's advance. Every digit of the time sits in a cell this
/// wide, so the seconds ticking over change neither the line's width nor where
/// its other glyphs are (Manrope's digits are proportional).
@@ -785,7 +801,7 @@ fn clockDigitCell(bar: *Taskbar) !i32 {
const scale = bar.wlr_output.scale;
if (bar.clock_digit.get(scale)) |cell| return @intFromFloat(cell);
var widest: i32 = 0;
- for ("0123456789") |*digit| widest = @max(widest, try text.measureWidth(digit[0..1], .manrope, clock_time_size, scale));
+ for ("0123456789") |*digit| widest = @max(widest, try text.measureWidth(digit[0..1], clockFont(), clock_time_size, scale));
return @intFromFloat(bar.clock_digit.put(scale, @floatFromInt(widest)));
}
@@ -801,7 +817,7 @@ fn clockLine(bar: *Taskbar, time: []const u8) !ClockLine {
while (end < time.len and !std.ascii.isDigit(time[end])) end += 1;
}
const piece = time[i..end];
- const w = try text.measureWidth(piece, .manrope, clock_time_size, scale);
+ const w = try text.measureWidth(piece, clockFont(), clock_time_size, scale);
line.pieces[line.count] = .{ .text = piece, .x = line.width + if (digit) @divTrunc(cell - w, 2) else 0, .w = w };
line.count += 1;
line.width += if (digit) cell else w;
@@ -819,12 +835,14 @@ fn measureClockColumn(bar: *Taskbar) !f32 {
// "%l" pads the hours 1-9 with a blank: keep the room of the second digit
// so that 9:59 turning 10:00 does not resize the column.
if (time.len < raw.len) time_w += try bar.clockDigitCell();
- const date_w = try text.measureWidth(std.mem.sliceTo(&bar.clock_date, 0), .manrope, clock_date_size, scale);
+ const date_w = try text.measureWidth(std.mem.sliceTo(&bar.clock_date, 0), clockFont(), clock_date_size, scale);
// Fit the displayed lines so unused column space cannot widen the left gap.
- return @floatFromInt(@max(time_w, date_w) + 1);
+ const overhang: i32 = if (ui_theme.taskbar(.clock_italic)) @intFromFloat(@ceil(clock_time_size * 0.22) + 1) else 0;
+ return @floatFromInt(@max(time_w, date_w) + 1 + 2 * overhang);
}
fn clockColumnWidth(bar: *Taskbar) f32 {
+ bar.clockStyleChanged();
const scale = bar.wlr_output.scale;
if (bar.clock_width.get(scale)) |width| return width;
// A failed measurement is retried next time rather than remembered.
@@ -841,15 +859,13 @@ fn startX(bar: *Taskbar) i32 {
}
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 items = bar.server.config.compositor.taskbar_items;
+ const app_count = bar.appTrayCount();
+ const app_width: f32 = @floatFromInt(app_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 - rightPad()), @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);
+ return taskbar_items.arrange(items, @floatFromInt(startButtonLeft()), @floatFromInt(bar.box.width - rightPad()), @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, @floatFromInt(trayHit()), capture_width }, tray_gap, clock_gap);
}
pub fn itemBox(bar: *Taskbar, item: taskbar_items.Item) ?wlr.Box {
@@ -869,7 +885,11 @@ fn clockX(bar: *Taskbar) f32 {
}
fn trayItem(index: usize) taskbar_items.Item {
- return if (index == @intFromEnum(TrayKind.volume)) .volume else .network;
+ return switch (@as(TrayKind, @enumFromInt(index))) {
+ .volume => .volume,
+ .wifi => .network,
+ .power => .power,
+ };
}
fn itemShown(bar: *Taskbar, item: taskbar_items.Item) bool {
@@ -877,6 +897,7 @@ fn itemShown(bar: *Taskbar, item: taskbar_items.Item) bool {
}
fn capturing(bar: *Taskbar) bool {
+ if (!bar.itemShown(.capture)) return false;
const cm = bar.server.capture_mgr orelse return false;
return cm.activeCount() > 0;
}
@@ -893,7 +914,7 @@ fn captureLabelWidth(bar: *Taskbar) i32 {
}
fn captureX(bar: *Taskbar) f32 {
- return bar.appTrayLeft() + @as(f32, @floatFromInt(bar.appTrayCount() * @as(usize, @intCast(trayHit() + tray_gap))));
+ return bar.item_layout.x[@intFromEnum(taskbar_items.Item.capture)] orelse 0;
}
pub fn captureIndicatorBox(bar: *Taskbar) ?wlr.Box {
@@ -977,7 +998,7 @@ fn reconcile(bar: *Taskbar, now_ms: i64) bool {
bar.item_layout = layout;
bar.start_dirty = true;
bar.clock_dirty = true;
- bar.tray_dirty = .{ true, true };
+ bar.tray_dirty = @splat(true);
bar.battery_dirty = true;
bar.capture_dirty = true;
bar.app_tray_generation = 0;
@@ -1221,9 +1242,9 @@ fn appendLive(
});
}
-fn trayPositions(bar: *Taskbar) [2]f32 {
+fn trayPositions(bar: *Taskbar) [tray_count]f32 {
const positions = bar.rightLayout().x;
- return .{ positions[@intFromEnum(taskbar_items.Item.volume)] orelse 0, positions[@intFromEnum(taskbar_items.Item.network)] orelse 0 };
+ return .{ positions[@intFromEnum(taskbar_items.Item.volume)] orelse 0, positions[@intFromEnum(taskbar_items.Item.network)] orelse 0, positions[@intFromEnum(taskbar_items.Item.power)] orelse 0 };
}
pub fn hitTest(bar: *Taskbar, sx: f64, sy: f64) Target {
@@ -1344,6 +1365,9 @@ pub fn pointerPress(bar: *Taskbar, sx: f64, sy: f64) void {
if (@as(TrayKind, @enumFromInt(i)) == .wifi) {
if (Output.fromWlr(bar.wlr_output)) |out| out.toggleWifi();
}
+ if (@as(TrayKind, @enumFromInt(i)) == .power) {
+ if (Output.fromWlr(bar.wlr_output)) |out| out.openPowerMenu();
+ }
if (@as(TrayKind, @enumFromInt(i)) == .volume) {
if (bar.server.audio) |mgr| {
mgr.toggleMasterMute();
@@ -1783,6 +1807,7 @@ fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_y: i
const alert = switch (@as(TrayKind, @enumFromInt(i))) {
.volume => bar.audio_muted,
.wifi => bar.network_offline,
+ .power => false,
};
const color = if (alert) blk: {
var danger = Color.fromRgba(ui_theme.taskbar(.danger));
@@ -1791,7 +1816,11 @@ fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_y: i
} 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 } });
+ 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 = switch (@as(TrayKind, @enumFromInt(i))) {
+ .wifi => .wifi,
+ .volume => if (bar.audio_muted) .volume_muted else .volume,
+ .power => .power,
+ }, .color = .{ color.r, color.g, color.b, color.a } });
}
drawPartText(bar, now_ms, part, buf, origin_x, origin_y);
node.node.setPosition(origin_x, origin_y);
@@ -1812,6 +1841,37 @@ fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_y: i
});
}
+/// Bilinear sample of an icon raster. `x`/`y` are logical offsets from the
+/// icon's top-left and `logical` its logical size, so a raster made at the
+/// output's device size lands exactly on its texels when the placement is
+/// aligned, and is filtered (not snapped) when fractional scales shift it.
+/// Texels outside the raster are transparent, which keeps the edge smooth.
+fn sampleIcon(icon: icon_service.Entry, x: f32, y: f32, logical: f32) Color {
+ const ratio = @as(f32, @floatFromInt(icon.size)) / logical;
+ const fx = x * ratio - 0.5;
+ const fy = y * ratio - 0.5;
+ const x0: i32 = @intFromFloat(@floor(fx));
+ const y0: i32 = @intFromFloat(@floor(fy));
+ const tx = fx - @as(f32, @floatFromInt(x0));
+ const ty = fy - @as(f32, @floatFromInt(y0));
+ var sum = [4]f32{ 0, 0, 0, 0 };
+ inline for (.{ .{ 0, 0 }, .{ 1, 0 }, .{ 0, 1 }, .{ 1, 1 } }) |corner| {
+ const cx = x0 + corner[0];
+ const cy = y0 + corner[1];
+ if (cx >= 0 and cx < icon.size and cy >= 0 and cy < icon.size) {
+ const weight = (if (corner[0] == 1) tx else 1 - tx) * (if (corner[1] == 1) ty else 1 - ty);
+ const texel = icon.pixels[@intCast(cy * icon.size + cx)];
+ sum[0] += weight * @as(f32, @floatFromInt((texel >> 16) & 0xff));
+ sum[1] += weight * @as(f32, @floatFromInt((texel >> 8) & 0xff));
+ sum[2] += weight * @as(f32, @floatFromInt(texel & 0xff));
+ sum[3] += weight * @as(f32, @floatFromInt((texel >> 24) & 0xff));
+ }
+ }
+ const a = sum[3] / 255.0;
+ if (a <= 0) return .{ .r = 0, .g = 0, .b = 0, .a = 0 };
+ return .{ .r = sum[0] / 255.0 / a, .g = sum[1] / 255.0 / a, .b = sum[2] / 255.0 / a, .a = a };
+}
+
fn paintPartPixel(bar: *Taskbar, sampled_start: start_button.Paint, hover: f32, press: f32, part_x: f32, part_width: f32, part: Part, px: f32, py: f32, scale: f32) Color {
switch (part) {
.background => return shape.background(Color, .{
@@ -1829,10 +1889,11 @@ fn paintPartPixel(bar: *Taskbar, sampled_start: start_button.Paint, hover: f32,
if (bar.start_logo) |icon| {
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));
- if (ix >= 0 and ix < icon.size and iy >= 0 and iy < icon.size) {
- var sample = Color.fromPremultiplied(icon.pixels[@intCast(iy * icon.size + ix)]);
+ const logical: f32 = @floatFromInt(startIconSize());
+ const ix = mapped.x - (mapped.box_x + pad);
+ const iy = mapped.y - (mapped.box_y + pad);
+ if (ix > -1 and iy > -1 and ix < logical + 1 and iy < logical + 1) {
+ var sample = sampleIcon(icon, ix, iy, logical);
if (ui_theme.global.start_button_icon.len == 0) {
if (ui_theme.taskbar(.start_button_logo_color)) |tint| sample = Color.fromRgba(tint).scaled(sample.a);
}
@@ -1972,9 +2033,8 @@ fn paintChipPixel(paint: *const ChipPaint, px: f32, py: f32, scale: f32) Color {
const tile_cov = edgeCoverage(chrome.sdRoundedBox(lx, ly, tile_x, tile_y, @floatFromInt(tileSize()), @floatFromInt(tileSize()), tile_radius), scale);
if (tile_cov == 0) return color;
if (chip.icon) |icon| {
- const ix: i32 = @intFromFloat(@floor((lx - tile_x) * scale));
- const iy: i32 = @intFromFloat(@floor((ly - tile_y) * scale));
- if (ix >= 0 and ix < icon.size and iy >= 0 and iy < icon.size) color = Color.fromPremultiplied(icon.pixels[@intCast(iy * icon.size + ix)]).scaled(tile_cov).over(color);
+ const logical: f32 = @floatFromInt(tileSize());
+ color = sampleIcon(icon, lx - tile_x, ly - tile_y, logical).scaled(tile_cov).over(color);
} else {
const style = tileStyle(chip.kind);
const fill = switch (style.fill) {
@@ -2108,7 +2168,7 @@ fn drawPartText(bar: *Taskbar, now_ms: i64, part: Part, buf: *BarBuffer, ox: i32
.clock => {
const time = std.mem.trimStart(u8, std.mem.sliceTo(&bar.clock_time, 0), " ");
const date = std.mem.sliceTo(&bar.clock_date, 0);
- const dw = text.measureWidth(date, .manrope, clock_date_size, scale) catch 0;
+ const dw = text.measureWidth(date, clockFont(), clock_date_size, scale) catch 0;
const left: i32 = @intFromFloat(@round(bar.clockX()));
const width: i32 = @intFromFloat(bar.clockColumnWidth());
const clock_h: i32 = if (date.len == 0) 20 else 37;
@@ -2116,17 +2176,24 @@ fn drawPartText(bar: *Taskbar, now_ms: i64, part: Part, buf: *BarBuffer, ox: i32
const date_y = time_y + 21;
if (bar.clockLine(time)) |line| {
// Every piece shares the baseline the digits would centre on.
- const row = text.inkBaseline("0123456789", .manrope, clock_time_size, scale, local(0, time_y, 1, 20, ox, oy)) catch null;
+ const row = text.inkBaseline("0123456789", clockFont(), clock_time_size, scale, local(0, time_y, 1, 20, ox, oy)) catch null;
const start = left + @divTrunc(width - line.width - 1, 2);
for (line.pieces[0..line.count]) |piece| {
- text.drawOpts(buf.pixels, buf.width, buf.height, piece.text, Color.clock_time(), scale, .manrope, clock_time_size, .{
+ text.drawOpts(buf.pixels, buf.width, buf.height, piece.text, Color.clock_time(), scale, clockFont(), clock_time_size, .{
.rect = local(start + piece.x, time_y, piece.w + 1, 20, ox, oy),
+ .clip = local(left, time_y, width, 20, ox, oy),
+ .italic = ui_theme.taskbar(.clock_italic),
.center_ink = row == null,
.baseline = row,
}) catch {};
}
} else |_| {}
- if (date.len != 0) drawCenteredText(buf.pixels, buf.width, buf.height, local(left + @divTrunc(width - dw - 1, 2), date_y, dw + 1, 16, ox, oy), date, Color.clock_date(), scale, .manrope, clock_date_size) catch {};
+ if (date.len != 0) text.drawOpts(buf.pixels, buf.width, buf.height, date, Color.clock_date(), scale, clockFont(), clock_date_size, .{
+ .rect = local(left + @divTrunc(width - dw - 1, 2), date_y, dw + 1, 16, ox, oy),
+ .clip = local(left, date_y, width, 16, ox, oy),
+ .italic = ui_theme.taskbar(.clock_italic),
+ .center_ink = true,
+ }) catch {};
},
.chip => |chip| {
const cx: i32 = @intFromFloat(@round(chip.renderX(now_ms)));
@@ -2381,6 +2448,7 @@ pub fn appTrayCount(bar: *Taskbar) usize {
if (bar.itemShown(.network)) fixed += @floatFromInt(trayHit());
if (bar.itemShown(.volume)) fixed += @floatFromInt(trayHit());
if (bar.itemShown(.clock)) fixed += bar.clockColumnWidth();
+ if (bar.itemShown(.power)) fixed += @floatFromInt(trayHit() + tray_gap);
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)))));
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index 896ce07..7624434 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -220,6 +220,10 @@ peek_mix: @import("ui").anim.Anim = .{ .property = .opacity },
peek_level: @import("ui").anim.Anim = .{ .from = 1, .to = 1, .property = .opacity },
map_motion: anim.Anim = .{ .from = 1, .to = 1 },
map_opacity: anim.Anim = .{ .from = 1, .to = 1, .property = .opacity },
+/// Set while a window launched from the dock grows out of its icon (a
+/// layout-space box): `map_motion` then carries the frame from that box to
+/// its place. Presentation only, like `dodge_x`; input follows what is drawn.
+launch_origin: ?LaunchOrigin = null,
move_x: anim.Anim = .{},
move_y: anim.Anim = .{},
/// Temporary displacement of the frame in world units (`input/drag_dodge.zig`).
@@ -1570,12 +1574,40 @@ 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 * 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) - lift.x,
- visualY(toplevel, now_ms) + animOffset(toplevel.dodge_y, now_ms) + animOffset(toplevel.switch_y, now_ms) - lift.y,
- );
+ const x = visualX(toplevel, now_ms) + animOffset(toplevel.dodge_x, now_ms) + animOffset(toplevel.switch_x, now_ms) - lift.x;
+ const y = visualY(toplevel, now_ms) + animOffset(toplevel.dodge_y, now_ms) + animOffset(toplevel.switch_y, now_ms) - lift.y;
+ if (!toplevel.closing) if (toplevel.launch_origin) |origin| {
+ const grow = launchGrowth(toplevel, origin, x, y, zoom_scale * toplevel.drag_lift_value, toplevel.map_motion.value(now_ms));
+ _ = @import("projection.zig").setTreeZoom(&toplevel.frame_tree.node, grow.zoom);
+ toplevel.frame_tree.node.setPosition(grow.x, grow.y);
+ return;
+ };
+ _ = @import("projection.zig").setTreeZoom(&toplevel.frame_tree.node, zoom_scale * factor * toplevel.drag_lift_value);
+ toplevel.frame_tree.node.setPosition(x, y);
+}
+
+pub const LaunchOrigin = @import("launch_feedback.zig").Origin;
+
+/// The frame on its way from the dock icon it was launched from (`amount` 0)
+/// to its place at `x`, `y` and tree zoom `rest_zoom` (`amount` 1): the icon's
+/// square grows into the frame, centre to centre, keeping the frame's aspect.
+fn launchGrowth(toplevel: *const Toplevel, origin: LaunchOrigin, x: i32, y: i32, rest_zoom: f64, amount: f32) struct { x: i32, y: i32, zoom: f64 } {
+ const world = &toplevel.server.world;
+ const t: f64 = amount;
+ const w = @as(f64, @floatFromInt(@max(toplevel.chrome_width, 1))) * rest_zoom;
+ const h = @as(f64, @floatFromInt(@max(toplevel.chrome_height, 1))) * rest_zoom;
+ const icon = world.toWorld(origin.x + origin.width / 2, origin.y + origin.height / 2);
+ const icon_side = @max(origin.width, origin.height) / world.camera.zoom();
+ const start = std.math.clamp(icon_side / @max(w, h), 0.01, 1);
+ const f = start + (1 - start) * t;
+ const cx = icon.x + (@as(f64, @floatFromInt(x)) + w / 2 - icon.x) * t;
+ const cy = icon.y + (@as(f64, @floatFromInt(y)) + h / 2 - icon.y) * t;
+ return .{
+ .x = @intFromFloat(@round(cx - w * f / 2)),
+ .y = @intFromFloat(@round(cy - h * f / 2)),
+ .zoom = rest_zoom * f,
+ };
}
fn dragLiftOffset(toplevel: *const Toplevel) struct { x: i32, y: i32 } {
@@ -1764,6 +1796,7 @@ pub fn tickMap(toplevel: *Toplevel, now_ms: i64) bool {
if (toplevel.closing) return false;
toplevel.map_motion.cancel(1);
toplevel.map_opacity.cancel(1);
+ toplevel.launch_origin = null;
return false;
}
return true;
@@ -1837,8 +1870,25 @@ fn applySizeClip(toplevel: *Toplevel) void {
toplevel.setSizeClip(.{ .x = 0, .y = 0, .width = xscale.surfaceLength(cw, n), .height = xscale.surfaceLength(ch, n) });
}
-fn beginOpenAnimation(toplevel: *Toplevel) void {
+fn beginOpenAnimation(toplevel: *Toplevel, launch_origin: ?LaunchOrigin) void {
const now_ms = nowMs();
+ toplevel.launch_origin = null;
+ if (launch_origin) |origin| if (!toplevel.isFullscreen() and anim.enabled() and !anim.reducedMotion()) {
+ toplevel.launch_origin = origin;
+ toplevel.map_motion.cancel(0);
+ toplevel.map_opacity.cancel(0);
+ toplevel.map_motion.retargetTo(now_ms, 1, anim.curveFor(.window_launch));
+ // Opaque early: the growing window, not a fade, is the effect.
+ toplevel.map_opacity.retargetTo(now_ms, 1, anim.Curve{ .duration = .{ .ms = 120, .ease = .out_cubic } });
+ if (toplevel.map_motion.settled(now_ms)) {
+ toplevel.map_motion.cancel(1);
+ toplevel.launch_origin = null;
+ }
+ toplevel.applyVisualTransform(now_ms);
+ toplevel.applyOpacity(now_ms);
+ toplevel.server.scheduleFrames();
+ return;
+ };
if (toplevel.isMaximized() or toplevel.isFullscreen()) {
toplevel.map_motion.cancel(1);
toplevel.map_opacity.cancel(1);
@@ -1858,6 +1908,7 @@ fn beginOpenAnimation(toplevel: *Toplevel) void {
}
fn beginCloseAnimation(toplevel: *Toplevel) bool {
+ toplevel.launch_origin = null;
if (!anim.enabled() or anim.speed() <= 0) return false;
if (!snapshotClient(toplevel)) return false;
const now_ms = nowMs();
@@ -2263,7 +2314,7 @@ pub fn handleMapped(toplevel: *Toplevel) void {
toplevel.resolveInitialRules();
if (toplevel.open_rules.focus orelse true) toplevel.server.window_tabs.focusMember(toplevel);
- if (toplevel.backend != .placeholder and toplevel.backend != .shell) toplevel.server.launch_feedback.windowMapped(toplevel);
+ const launch_origin = if (toplevel.backend != .placeholder and toplevel.backend != .shell) toplevel.server.launch_feedback.windowMapped(toplevel) else null;
if (toplevel.open_rules.depth) |d| {
toplevel.setZoomOrigin(d);
@@ -2406,7 +2457,7 @@ pub fn handleMapped(toplevel: *Toplevel) void {
toplevel.applyOpacity(now_ms);
toplevel.server.scheduleFrames();
} else {
- toplevel.beginOpenAnimation();
+ toplevel.beginOpenAnimation(launch_origin);
}
toplevel.server.window_tabs.mapped(toplevel);
toplevel.server.window_tabs.mappedToken(toplevel);
@@ -2620,7 +2671,8 @@ pub fn isGeometrySettled(toplevel: *Toplevel, now_ms: i64) bool {
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);
+ toplevel.switch_x.settled(now_ms) and toplevel.switch_y.settled(now_ms) and
+ (toplevel.launch_origin == null or toplevel.map_motion.settled(now_ms));
}
pub fn chromeAcceptsInput(buffer: *wlr.SceneBuffer, sx: *f64, sy: *f64) callconv(.c) bool {
diff --git a/src/calendar.zig b/src/calendar.zig
index 31dab4d..2a3bfaa 100644
--- a/src/calendar.zig
+++ b/src/calendar.zig
@@ -91,6 +91,19 @@ pub const Calendar = struct {
self.factor = @min(1, @min(@as(f32, @floatFromInt(@max(1, box.width - 24))) / 368, @as(f32, @floatFromInt(available_h)) / full_height));
const width: i32 = @intFromFloat(@round(368 * self.factor));
const height: i32 = @intFromFloat(@round(full_height * self.factor));
+ // Centred over the clock wherever the taskbar puts it, kept on the
+ // output; the pointer aims at the clock. Without one (hidden clock, no
+ // taskbar) it keeps to the right edge.
+ const right = box.x + box.width - width - 12;
+ const clock = if (self.output.taskbar) |bar| bar.itemBox(.clock) else null;
+ const left = if (clock) |anchor|
+ std.math.clamp(anchor.x + @divTrunc(anchor.width - width, 2), box.x + 12, @max(box.x + 12, right))
+ else
+ right;
+ const tip: f32 = if (clock) |anchor|
+ std.math.clamp(@as(f32, @floatFromInt(anchor.x + @divTrunc(anchor.width, 2) - left)) / self.factor, 24, 344)
+ else
+ 316;
const scale = self.output.wlr_output.scale;
const buf = PanelBuffer.create(@max(1, width), @max(1, height), scale) catch return;
defer buf.base.drop();
@@ -99,7 +112,7 @@ pub const Calendar = struct {
const popup_surface = t.popup_bg != null or t.popup_blur;
r.palette = t;
if (popup_surface) {
- popup_style.background(&r, buf, 368, full_height, 16, 316, self.output.server.config.compositor.taskbar_position == .top);
+ popup_style.background(&r, buf, 368, full_height, 16, tip, self.output.server.config.compositor.taskbar_position == .top);
t.text_secondary = t.window_fg;
t.faint = t.window_dim;
} else {
@@ -111,7 +124,7 @@ pub const Calendar = struct {
if (y < body_height - 1) continue;
for (0..@intCast(buf.width)) |ix| {
const x = (@as(f32, @floatFromInt(ix)) + 0.5) / r.scale;
- const distance = (@abs(x - 316) + y - body_height - 16) / @sqrt(@as(f32, 2));
+ const distance = (@abs(x - tip) + y - body_height - 16) / @sqrt(@as(f32, 2));
const coverage = std.math.clamp(0.5 - distance * r.scale, 0, 1);
if (coverage == 0) continue;
const inner = std.math.clamp((-distance - 1) * r.scale + 0.5, 0, 1);
@@ -155,7 +168,7 @@ pub const Calendar = struct {
}
self.buffer_node.setBuffer(&buf.base);
self.buffer_node.setDestSize(@max(1, width), @max(1, height));
- self.panel_box = .{ .x = box.x + box.width - width - 12, .y = self.output.taskbarPopupY(height, 12), .width = @max(1, width), .height = @max(1, height) };
+ self.panel_box = .{ .x = left, .y = self.output.taskbarPopupY(height, 12), .width = @max(1, width), .height = @max(1, height) };
panel_present.applySlide(self.buffer_node, self.panel_box, 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();
diff --git a/src/config/default.zig b/src/config/default.zig
index d829229..95197d2 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -127,11 +127,15 @@ pub const source =
\\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_auto_hide = false # show the dock only when the pointer reaches its edge; false reserves its space
+ \\# dock_opacity = 0.8 # 0.0-1.0 background alpha. Unset keeps the theme's own
+ \\dock_active_highlight = false # draw a rectangle behind the focused app's icon
+ \\dock_show_trash = true # a Trash icon at the dock's far end; opens the trash in Files
\\dock_hidden_shortcuts = [] # applications, files, terminal, settings
\\dock_pinned_apps = [] # desktop entry IDs pinned by dragging them from the start menu
\\# Taskbar sections, ordered within each section; prefix with - to hide an item.
\\taskbar_position = "bottom" # top or bottom
- \\taskbar_items = ["left:start", "left:windows", "right:tray", "right:battery", "right:network", "right:volume", "right:clock"]
+ \\taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray", "right:battery", "right:network", "right:volume", "right:clock", "-right:power"]
+ \\# Hiding capture (-right:capture) removes the recording/sharing indicator; not recommended.
\\focus_follows_mouse = false
\\canvas_columns = 3 # screens wide (1-10)
\\canvas_rows = 3 # screens tall (1-10)
@@ -153,7 +157,7 @@ pub const source =
\\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
- \\# terminal_opacity = 0.9 # 0.0-1.0 Foot background; new windows only. Unset keeps Foot's own alpha
+ \\# terminal_opacity = 0.9 # 0.0-1.0 terminal background (Foot, kitty, Alacritty, Ghostty, WezTerm); new windows only. Unset keeps their own
\\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
@@ -192,6 +196,9 @@ pub const source =
\\# [animations.wheel_scroll] # mouse-wheel glide in shell panels; off = true to step
\\# spring = { damping_ratio = 1.0, stiffness = 800 }
\\#
+ \\# [animations.dock_hover] # dock icon zoom; damping_ratio 1.0 = no bounce
+ \\# spring = { damping_ratio = 0.5, stiffness = 600 }
+ \\#
\\# [animations.taskbar_press]
\\# duration_ms = 90
\\# ease = "out_cubic"
diff --git a/src/config/loader.zig b/src/config/loader.zig
index f007bc2..06475b7 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -135,6 +135,12 @@ pub const CompositorConfig = struct {
dock_height: u32 = dock_height_default,
dock_hover_zoom: f32 = 1.05,
dock_auto_hide: bool = false,
+ /// Alpha of the dock's background. Unset keeps the theme's own (`dock_bg`).
+ dock_opacity: ?f32 = null,
+ /// A rectangle behind the focused application's icon; the running pill shows regardless.
+ dock_active_highlight: bool = false,
+ /// A Trash icon at the dock's far end (right, or bottom on a side dock).
+ dock_show_trash: bool = true,
dock_hidden_shortcuts: []const []const u8 = &.{},
dock_pinned_apps: []const []const u8 = &.{},
taskbar_items: TaskbarItems = .{},
@@ -173,7 +179,7 @@ pub const CompositorConfig = struct {
/// Files opens an item with one click on its icon; names still select.
files_single_click_open: bool = true,
inactive_opacity: f32 = 1.0,
- /// Background alpha handed to Foot at launch (`config/terminal_theme.zig`).
+ /// Background alpha handed to Foot, kitty, Alacritty, Ghostty and WezTerm at launch (`config/terminal_theme.zig`).
/// Unset keeps the `alpha` of the user's own Foot configuration.
terminal_opacity: ?f32 = null,
/// A window that is not the focus loses `inactive_dim_amount` of its
@@ -1071,6 +1077,9 @@ const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(CompositorC
.dock_height = .{ .uint = .{ .min = dock_height_min, .max = dock_height_max } },
.dock_hover_zoom = .{ .float = .{ .min = 1, .max = dock_hover_zoom_max } },
.dock_auto_hide = .boolean,
+ .dock_opacity = .{ .float = .{ .min = 0, .max = 1 } },
+ .dock_active_highlight = .boolean,
+ .dock_show_trash = .boolean,
.dock_hidden_shortcuts = .json_string_list,
.dock_pinned_apps = .json_string_list,
.taskbar_items = .taskbar_items,
@@ -1855,6 +1864,15 @@ test "config field parsing preserves ranges and derived zoom state" {
inline for (.{ "nan", "-0.1", "1.01" }) |v| {
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "terminal_opacity", v));
}
+ try std.testing.expectEqual(@as(?f32, null), c.dock_opacity);
+ try std.testing.expect(!c.dock_active_highlight);
+ try applyCompositorKey(&c, a, "dock_opacity", "0.6");
+ try std.testing.expectEqual(@as(?f32, 0.6), c.dock_opacity);
+ inline for (.{ "nan", "-0.1", "1.01" }) |v| {
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "dock_opacity", v));
+ }
+ try applyCompositorKey(&c, a, "dock_active_highlight", "true");
+ try std.testing.expect(c.dock_active_highlight);
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");
diff --git a/src/config/taskbar_items.zig b/src/config/taskbar_items.zig
index 98b158e..053ad30 100644
--- a/src/config/taskbar_items.zig
+++ b/src/config/taskbar_items.zig
@@ -10,6 +10,8 @@ pub const Item = enum {
start,
windows,
tray,
+ power,
+ capture,
pub fn label(item: Item) []const u8 {
return switch (item) {
@@ -20,21 +22,50 @@ pub const Item = enum {
.start => "Start button",
.windows => "Window list",
.tray => "Application tray",
+ .power => "Power",
+ .capture => "Screen capture",
};
}
};
pub const count = std.meta.fields(Item).len;
pub const Config = struct {
- order: [count]Item = .{ .start, .windows, .tray, .battery, .network, .volume, .clock },
- visible: [count]bool = @splat(true),
- sections: [count]Section = .{ .right, .right, .right, .right, .left, .left, .right },
+ order: [count]Item = .{ .start, .windows, .capture, .tray, .battery, .network, .volume, .clock, .power },
+ visible: [count]bool = .{ true, true, true, true, true, true, true, false, true },
+ sections: [count]Section = .{ .right, .right, .right, .right, .left, .left, .right, .right, .right },
+ /// One keyboard step: swap with the neighbour in the same section, or at
+ /// a section's end step into the next section over (an empty one too).
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]);
+ if (index >= count) return;
+ const item = config.order[index];
+ const other = if (right) index + 1 else index -% 1;
+ if (other < count and config.section(config.order[other]) == config.section(item)) {
+ std.mem.swap(Item, &config.order[index], &config.order[other]);
+ return;
+ }
+ // The item is at its section's edge, so the order stays grouped.
+ const zone = @intFromEnum(config.section(item));
+ if (right and zone < 2) config.sections[@intFromEnum(item)] = @enumFromInt(zone + 1);
+ if (!right and zone > 0) config.sections[@intFromEnum(item)] = @enumFromInt(zone - 1);
+ }
+
+ /// Puts the item at `from` into `zone` as its `slot`th item, counted
+ /// without it (clamped to the end), and returns its new index.
+ pub fn place(config: *Config, from: usize, zone: Section, slot: usize) usize {
+ const item = config.order[from];
+ var rest: [count - 1]Item = undefined;
+ @memcpy(rest[0..from], config.order[0..from]);
+ @memcpy(rest[from..], config.order[from + 1 ..]);
+ var at: usize = 0;
+ while (at < rest.len and @intFromEnum(config.section(rest[at])) < @intFromEnum(zone)) at += 1;
+ var taken: usize = 0;
+ while (at < rest.len and config.section(rest[at]) == zone and taken < slot) : (taken += 1) at += 1;
+ config.sections[@intFromEnum(item)] = zone;
+ @memcpy(config.order[0..at], rest[0..at]);
+ config.order[at] = item;
+ @memcpy(config.order[at + 1 ..], rest[at..]);
+ return at;
}
pub fn section(config: Config, item: Item) Section {
@@ -94,11 +125,31 @@ pub const Config = struct {
index += 1;
}
if (legacy and index == 4) {
- @memcpy(result.order[3..], order[0..4]);
- } else if (index == count) {
- result.order = order;
- } else return error.InvalidValue;
+ result.order = .{ .start, .windows, .tray, order[0], order[1], order[2], order[3], .power, .capture };
+ } else {
+ // Older lists can omit Power and Screen capture. Every other
+ // item remains required, so incomplete lists still fail closed.
+ for (std.enums.values(Item)) |item| {
+ if (item != .power and item != .capture and !seen[@intFromEnum(item)]) return error.InvalidValue;
+ }
+ @memcpy(result.order[0..index], order[0..index]);
+ for ([_]Item{ .power, .capture }) |item| {
+ if (seen[@intFromEnum(item)]) continue;
+ result.order[index] = item;
+ index += 1;
+ }
+ }
result.normalize();
+ if (!seen[@intFromEnum(Item.capture)]) {
+ // Introduce the indicator at the start of the right section,
+ // retaining the order, section and visibility of existing items.
+ for (result.order, 0..) |item, i| {
+ if (item == .capture) {
+ _ = result.place(i, .right, 0);
+ break;
+ }
+ }
+ }
return result;
}
@@ -167,6 +218,18 @@ pub fn arrange(config: Config, left: f32, right: f32, center: f32, widths: [coun
test "taskbar sections and hidden state round trip, migrate old lists and reject malformed lists" {
var config: Config = .{};
+ try std.testing.expect(!config.shown(.power));
+ try std.testing.expect(config.shown(.capture));
+ try std.testing.expectEqual(Section.right, config.section(.capture));
+ try std.testing.expectEqual(Item.capture, config.order[2]);
+ try std.testing.expectEqual(Section.right, config.section(.power));
+ const previous = try Config.parse("[\"left:start\", \"left:windows\", \"right:tray\", \"right:battery\", \"right:network\", \"right:volume\", \"right:clock\"]");
+ try std.testing.expectEqualDeep(config, previous);
+ const previous_eight = try Config.parse("[\"left:start\", \"left:windows\", \"right:tray\", \"right:battery\", \"right:network\", \"right:volume\", \"right:clock\", \"-right:power\"]");
+ try std.testing.expectEqualDeep(config, previous_eight);
+ config.visible[@intFromEnum(Item.power)] = true;
+ config.visible[@intFromEnum(Item.capture)] = false;
+ config.setSection(.capture, .center);
config.setSection(.volume, .left);
config.move(1, false);
config.visible[@intFromEnum(Item.volume)] = false;
@@ -176,8 +239,20 @@ test "taskbar sections and hidden state round trip, migrate old lists and reject
const legacy = try Config.parse("[\"clock\", \"-network\", \"battery\", \"volume\"]");
try std.testing.expectEqual(Section.left, legacy.section(.start));
try std.testing.expectEqual(Section.left, legacy.section(.windows));
- try std.testing.expectEqual(Item.clock, legacy.order[3]);
+ try std.testing.expectEqual(Item.clock, legacy.order[4]);
+ try std.testing.expect(legacy.shown(.capture));
+ try std.testing.expectEqual(Item.capture, legacy.order[2]);
try std.testing.expect(!legacy.shown(.network));
+ try std.testing.expect(!legacy.shown(.power));
+ // Drops land anywhere; keyboard steps cross into the next section at an edge.
+ var moved: Config = .{};
+ try std.testing.expectEqual(@as(usize, 1), moved.place(7, .left, 1));
+ try std.testing.expectEqualSlices(Item, &.{ .start, .clock, .windows, .capture, .tray, .battery, .network, .volume, .power }, &moved.order);
+ try std.testing.expectEqual(Section.left, moved.section(.clock));
+ moved.move(2, true);
+ try std.testing.expectEqual(Section.center, moved.section(.windows));
+ try std.testing.expectEqual(@as(usize, 8), moved.place(2, .right, 9));
+ try std.testing.expectEqual(Item.windows, moved.order[8]);
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));
}
@@ -185,9 +260,10 @@ test "taskbar sections and hidden state round trip, migrate old lists and reject
test "taskbar defaults windows left, supports centering and shrinks windows before fixed items" {
var config: Config = .{};
- const widths = [count]f32{ 0, 34, 34, 96, 42, 200, 0 };
+ const widths = [count]f32{ 0, 34, 34, 96, 42, 200, 0, 34, 120 };
const defaults = arrange(config, 4, 980, 500, widths, 6, 16);
try std.testing.expectEqual(@as(?f32, 52), defaults.x[@intFromEnum(Item.windows)]);
+ try std.testing.expect(defaults.x[@intFromEnum(Item.capture)].? + 120 <= defaults.x[@intFromEnum(Item.network)].?);
config.setSection(.windows, .center);
const full = arrange(config, 4, 980, 500, widths, 6, 16);
try std.testing.expectEqual(@as(?f32, 400), full.x[@intFromEnum(Item.windows)]);
@@ -196,7 +272,7 @@ test "taskbar defaults windows left, supports centering and shrinks windows befo
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);
+ const crowded = arrange(config, 4, 400, 200, .{ 0, 34, 34, 96, 42, 1000, 0, 34, 120 }, 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);
diff --git a/src/config/terminal_theme.zig b/src/config/terminal_theme.zig
index 204cfa0..bbed0b2 100644
--- a/src/config/terminal_theme.zig
+++ b/src/config/terminal_theme.zig
@@ -1,4 +1,4 @@
-//! Per-launch Foot colours and background opacity. No user terminal
+//! Per-launch Foot colours and terminal background opacity. No user terminal
//! configuration is overwritten.
const std = @import("std");
const Theme = @import("ui").theme.Theme;
@@ -15,9 +15,11 @@ pub fn enabled(t: Theme, opacity: ?f32) bool {
/// Uses the caller's short-lived launch arena; original arguments are borrowed.
/// The helper probes Foot's config dialect outside the compositor, then execs
-/// Foot in the same process/scope. Other terminal emulators keep their argv.
+/// Foot in the same process/scope. Terminals with a launch flag for background
+/// opacity get only that (`opacityArgv`); the rest keep their argv.
pub fn wrap(a: A, io: std.Io, args: []const []const u8, t: Theme, opacity: ?f32) ![]const []const u8 {
- if (args.len == 0 or !enabled(t, opacity) or !std.mem.eql(u8, std.fs.path.basename(args[0]), "foot")) return args;
+ if (args.len == 0 or !enabled(t, opacity)) return args;
+ if (!std.mem.eql(u8, std.fs.path.basename(args[0]), "foot")) return opacityArgv(a, args, opacity);
const directory = try std.process.executableDirPathAlloc(io, a);
const result = try a.alloc([]const u8, args.len + 2);
result[0] = try std.fs.path.join(a, &.{ directory, "rediwm-theme" });
@@ -26,6 +28,30 @@ pub fn wrap(a: A, io: std.Io, args: []const []const u8, t: Theme, opacity: ?f32)
return result;
}
+/// Background-only opacity for terminals that take it on the command line,
+/// inserted before any program arguments. Konsole, GNOME Terminal and the VTE
+/// family only read it from a profile, so they keep their argv.
+pub fn opacityArgv(a: A, args: []const []const u8, opacity: ?f32) ![]const []const u8 {
+ const alpha = std.math.clamp(opacity orelse return args, 0, 1);
+ const exe = std.fs.path.basename(args[0]);
+ const flags: []const []const u8 = if (std.mem.eql(u8, exe, "kitty"))
+ &.{ "-o", try std.fmt.allocPrint(a, "background_opacity={d:.2}", .{alpha}) }
+ else if (std.mem.eql(u8, exe, "alacritty"))
+ &.{ "-o", try std.fmt.allocPrint(a, "window.opacity={d:.2}", .{alpha}) }
+ else if (std.mem.eql(u8, exe, "ghostty"))
+ &.{try std.fmt.allocPrint(a, "--background-opacity={d:.2}", .{alpha})}
+ else if (std.mem.eql(u8, exe, "wezterm"))
+ // A global option: it must precede the `start` subcommand.
+ &.{ "--config", try std.fmt.allocPrint(a, "window_background_opacity={d:.2}", .{alpha}) }
+ else
+ return args;
+ const result = try a.alloc([]const u8, args.len + flags.len);
+ result[0] = args[0];
+ @memcpy(result[1 .. 1 + flags.len], flags);
+ @memcpy(result[1 + flags.len ..], args[1..]);
+ return result;
+}
+
fn hex(a: A, color: [4]f32) ![]const u8 {
var rgb: [3]u8 = undefined;
for (&rgb, color[0..3]) |*byte, value| byte.* = @intFromFloat(@round(std.math.clamp(value, 0, 1) * 255));
@@ -104,3 +130,25 @@ test "terminal opacity alone enables the wrapper and names each section's alpha"
const opaque_args = try argv(a, args, .{}, 1.0, true);
try std.testing.expectEqualStrings("--override=colors-dark.alpha=1.00", opaque_args[1]);
}
+
+test "other terminals get only a background opacity flag ahead of their program" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const cases = .{
+ .{ "kitty", &[_][]const u8{ "/usr/bin/kitty", "-o", "background_opacity=0.80", "-e", "top" } },
+ .{ "alacritty", &[_][]const u8{ "/usr/bin/alacritty", "-o", "window.opacity=0.80", "-e", "top" } },
+ .{ "ghostty", &[_][]const u8{ "/usr/bin/ghostty", "--background-opacity=0.80", "-e", "top" } },
+ .{ "wezterm", &[_][]const u8{ "/usr/bin/wezterm", "--config", "window_background_opacity=0.80", "-e", "top" } },
+ };
+ inline for (cases) |case| {
+ const args: []const []const u8 = &.{ "/usr/bin/" ++ case[0], "-e", "top" };
+ const result = try wrap(a, std.testing.io, args, .{}, 0.8);
+ try std.testing.expectEqual(case[1].len, result.len);
+ for (case[1], result) |expected, actual| try std.testing.expectEqualStrings(expected, actual);
+ // A theme palette alone is Foot-only; without opacity nothing changes.
+ try std.testing.expectEqualSlices([]const u8, args, try wrap(a, std.testing.io, args, .{ .terminal_fg = .{ 1, 1, 1, 1 } }, null));
+ }
+ const konsole: []const []const u8 = &.{ "konsole", "-e", "top" };
+ try std.testing.expectEqualSlices([]const u8, konsole, try wrap(a, std.testing.io, konsole, .{}, 0.8));
+}
diff --git a/src/config_runtime/actions.zig b/src/config_runtime/actions.zig
index cb4289d..84392b4 100644
--- a/src/config_runtime/actions.zig
+++ b/src/config_runtime/actions.zig
@@ -109,6 +109,11 @@ pub fn spawnProcess(server: *Server, cmd: []const u8) void {
spawnTracked(server, cmd, false, &.{ "/bin/sh", "-c", cmd });
}
+/// Runs `argv` directly, no shell, as `spawnProcess` would a command line.
+pub fn spawnArgv(server: *Server, argv: []const []const u8) void {
+ spawnTracked(server, argv[0], false, argv);
+}
+
pub fn spawnHelper(server: *Server, cmd: []const u8) void {
if (server.services) |manager| {
if (manager.helperRunning(cmd)) return;
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 7439b0f..c3ff5ec 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -234,6 +234,9 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
old.compositor.dock_height != new.compositor.dock_height or
old.compositor.dock_hover_zoom != new.compositor.dock_hover_zoom or
old.compositor.dock_auto_hide != new.compositor.dock_auto_hide or
+ !std.meta.eql(old.compositor.dock_opacity, new.compositor.dock_opacity) or
+ old.compositor.dock_active_highlight != new.compositor.dock_active_highlight or
+ old.compositor.dock_show_trash != new.compositor.dock_show_trash or
!stringListsEql(old.compositor.dock_hidden_shortcuts, new.compositor.dock_hidden_shortcuts) or
!stringListsEql(old.compositor.dock_pinned_apps, new.compositor.dock_pinned_apps))
{
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index 4cc9b1b..416a483 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -33,3 +33,8 @@ Settings is an ordinary window with a compositor-drawn body (`Backend.shell`).
`Debug.Stats` need it).
* Saving a theme slider rebuilds the page on release: `panel.rebuildTree`
carries named sliders' state across (`src/ui/AGENTS.md`, "Sliders").
+* A rebuild of Appearance costs milliseconds (preset, wallpaper and icon-theme
+ scans) plus a full repaint: background wakes refresh only pages that show
+ their state (audio: General and Audio), and wallpaper thumbnails go straight
+ into their tile (`stripWake`). The nav highlights damage the rows they cross,
+ not the list.
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index 0027bb8..0c240cd 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -81,6 +81,11 @@ fn label(value: []const u8, size: f32, dim: bool) Widget {
return .{ .kind = .{ .text = .{ .content = value, .font_size = size, .weight = if (dim) 400 else 600, .color = if (dim) t.dim else t.fg } } };
}
+/// A card or group title: larger and bolder than the semibold row labels.
+pub fn sectionTitle(value: []const u8) Widget {
+ return .{ .kind = .{ .text = .{ .content = value, .font_size = 17, .weight = 700, .color = palette().fg } } };
+}
+
/// Stands in for a section whose widget tree could not be allocated; it
/// allocates nothing itself.
pub fn outOfMemory() Widget {
@@ -177,7 +182,7 @@ pub const ControlCenter = struct {
content_children: [
2 + @max(
@typeInfo(@FieldType(input_section.Section, "row_storage")).array.len,
- @typeInfo(@FieldType(appearance_section.Section, "row_storage")).array.len,
+ @typeInfo(@FieldType(appearance_section.Section, "group_cards")).array.len,
)
]Widget = undefined,
content_count: usize = 0,
@@ -548,13 +553,13 @@ pub const ControlCenter = struct {
cc.append(audio_card);
cc.buildDevices();
if (cc.device_count > 0) {
- cc.device_title = .{ label("Audio output", 16, false), .{ .kind = .container, .direction = .column, .gap = 4, .children = cc.device_rows[0..cc.device_count] } };
+ cc.device_title = .{ sectionTitle("Audio output"), .{ .kind = .container, .direction = .column, .gap = 4, .children = cc.device_rows[0..cc.device_count] } };
var dev_card = card(&cc.device_title);
dev_card.name = "sound";
cc.append(dev_card);
}
},
- .appearance => for (&cc.appearance.row_storage) |*row| {
+ .appearance => for (&cc.appearance.group_cards) |*row| {
var framed = card(row.children);
framed.name = "appearance";
framed.direction = row.direction;
@@ -606,11 +611,11 @@ pub const ControlCenter = struct {
fn buildGeneral(cc: *ControlCenter) void {
portal_section.build(&cc.portals, cc);
cc.append(cc.portals.root);
- cc.general_volume = .{ label("Master volume", 16, false), if (cc.server.audio != null) cc.sound.body_children[1] else label("Audio unavailable", 13, true) };
+ cc.general_volume = .{ sectionTitle("Master volume"), if (cc.server.audio != null) cc.sound.body_children[1] else label("Audio unavailable", 13, true) };
var vol_card = card(&cc.general_volume);
vol_card.name = "sound";
cc.append(vol_card);
- cc.brightness_children = .{ label("Brightness", 16, false), label(if (cc.server.brightness.failed) "No supported backlight" else "Checking backlight…", 13, true) };
+ cc.brightness_children = .{ sectionTitle("Brightness"), label(if (cc.server.brightness.failed) "No supported backlight" else "Checking backlight…", 13, true) };
if (cc.server.brightness.level) |level| {
cc.brightness_row = .{
.{ .kind = .{ .icon = .{ .id = .brightness, .color = palette().fg } }, .width = .{ .fixed = 24 }, .height = .{ .fixed = 24 } },
@@ -622,7 +627,7 @@ pub const ControlCenter = struct {
}
cc.append(card(&cc.brightness_children));
cc.general_output_text = .{
- label("Audio output", 16, false),
+ sectionTitle("Audio output"),
label(if (cc.sound.output_desc_len > 0) cc.sound.output_desc_buf[0..cc.sound.output_desc_len] else "No audio device available", 13, true),
};
cc.general_output = .{
@@ -633,7 +638,7 @@ pub const ControlCenter = struct {
output_card.direction = .row;
output_card.@"align" = .center;
cc.append(output_card);
- cc.general_display_text = .{ label("Display", 16, false), label(std.mem.span(cc.wlr_output.name), 13, true) };
+ cc.general_display_text = .{ sectionTitle("Display"), label(std.mem.span(cc.wlr_output.name), 13, true) };
cc.general_display = .{
.{ .kind = .container, .direction = .column, .@"align" = .stretch, .width = .{ .flex = 1 }, .gap = 5, .children = &cc.general_display_text },
.{ .kind = .{ .button = .{ .label = "Display settings", .owner = cc, .id = @intFromEnum(Page.displays), .on_click = pageClicked } }, .height = .{ .fixed = 32 } },
@@ -976,7 +981,7 @@ pub const ControlCenter = struct {
cc.scheduleFrame();
}
- fn layoutContent(cc: *ControlCenter) void {
+ pub fn layoutContent(cc: *ControlCenter) void {
cc.background.invalidate();
const width: f32 = @floatFromInt(cc.panel_box.width);
const height: f32 = @floatFromInt(cc.panel_box.height);
@@ -1092,14 +1097,32 @@ pub const ControlCenter = struct {
const q = anim.rasterPixelQuantum(cc.toplevel.render_scale) / pitch;
const pos = cc.nav_selection.value(now_ms);
const selected = if (cc.nav_selection.settled(now_ms)) pos else @round(pos / q) * q;
+ const before = cc.nav_hover.frame;
const hover_changed = cc.nav_hover.step(now_ms, 1, q);
- if (selected == cc.nav_selected_row and !hover_changed) return false;
+ const selection_changed = selected != cc.nav_selected_row;
+ if (!selection_changed and !hover_changed) return false;
+ // Repaint the rows the highlights left and reached, not the whole
+ // list: the hover's opacity also depends on the selection.
+ if (selection_changed) {
+ markNavRows(list, cc.nav_selected_row);
+ markNavRows(list, selected);
+ }
+ if (hover_changed or (selection_changed and before.alpha > 0)) {
+ markNavRows(list, before.row);
+ markNavRows(list, cc.nav_hover.frame.row);
+ }
cc.nav_selected_row = selected;
- list.markPaintDirty();
anim.observeNoteChanged();
return true;
}
+ /// The one or two rows a highlight at fractional row `pos` covers.
+ fn markNavRows(list: *Widget, pos: f32) void {
+ const clamped = std.math.clamp(pos, 0, @as(f32, @floatFromInt(list.children.len - 1)));
+ list.children[@intFromFloat(@floor(clamped))].markPaintDirty();
+ list.children[@intFromFloat(@ceil(clamped))].markPaintDirty();
+ }
+
/// Paint once beneath the rows so the fills can move through their gaps.
fn paintNavHighlights(owner: ?*anyopaque, list: *const Widget, renderer: *ui.paint.Renderer) void {
const cc: *ControlCenter = @ptrCast(@alignCast(owner orelse return));
@@ -1144,7 +1167,7 @@ pub const ControlCenter = struct {
return .{ color[0], color[1], color[2], color[3] * alpha };
}
- fn requestWidgetRepaint(cc: *ControlCenter) void {
+ pub fn requestWidgetRepaint(cc: *ControlCenter) void {
cc.dirty = true;
cc.scheduleFrame();
}
@@ -1160,7 +1183,7 @@ pub const ControlCenter = struct {
// The window's chrome raster scale: the highest output scale it touches.
const scale = cc.toplevel.render_scale;
if (cc.painted_scale != scale) cc.background.invalidate();
- const buf = PanelBuffer.createUninitialized(cc.panel_box.width, cc.panel_box.height, scale) catch |err| {
+ const buf = PanelBuffer.createRetained(cc.panel_box.width, cc.panel_box.height, scale, &cc.background) catch |err| {
log.err("ControlCenter.paintContent: could not create panel buffer: {}", .{err});
return;
};
@@ -1168,7 +1191,7 @@ pub const ControlCenter = struct {
const t0 = panel_present.nowNs();
var renderer = ui.paint.Renderer.init(buf.pixels, buf.width, buf.height, scale);
renderer.palette = palette();
- cc.background.paintIncremental(gpa, &cc.root, &renderer);
+ cc.background.paintIncremental(gpa, &cc.root, &renderer, &buf.stamp);
const elapsed_ns = panel_present.nowNs() -| t0;
// A world node reaches its projected view only with the damage we
@@ -1217,6 +1240,11 @@ pub fn pointerLeave(cc: *ControlCenter) void {
if (revision != ui.layout.paint_revision) cc.requestWidgetRepaint();
}
+/// Over a taskbar item row, which drags from anywhere but its toggle.
+pub fn overDraggable(cc: *ControlCenter, sx: f64, sy: f64) bool {
+ return cc.page == .appearance and appearance_section.itemHandle(&cc.appearance, @floatCast(sx), @floatCast(sy)) != null;
+}
+
pub fn pointerButtonDown(cc: *ControlCenter, sx: f64, sy: f64) void {
cc.pointer_down = true;
if (cc.page == .appearance and appearance_section.beginItemDrag(&cc.appearance, @floatCast(sx), @floatCast(sy))) return;
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index e866c3a..087affa 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -38,6 +38,11 @@ const app_theme = @import("config").app_theme;
const AppColorsJob = @import("../../config_runtime/app_theme.zig").Job;
const segmented_width: f32 = 180;
+/// The dock's corner radius slider. A theme's `dock_radius` of zero means "the
+/// window radius", so the slider starts at 1 px (square to the eye) and a
+/// chosen value is never mistaken for it. Half the tallest dock caps it.
+const dock_radius_min: f32 = 1;
+const dock_radius_max: f32 = 48;
const font_values = [3]f32{ 12, 13, 14 };
const font_labels = [_][]const u8{ "Small", "Medium", "Large" };
@@ -94,6 +99,8 @@ const px_dock_hover_zoom = 16;
const px_taskbar_edge_gap = 17;
const px_taskbar_length = 18;
const px_taskbar_radius = 19;
+const px_dock_opacity = 20;
+const px_dock_radius = 21;
pub const Section = struct {
cc: *panel.ControlCenter = undefined,
@@ -107,11 +114,16 @@ pub const Section = struct {
cursor_themes: ?[]cursor_theme.Theme = null,
cursor_row_children: [2]Widget = undefined,
family_row_children: [2]Widget = undefined,
- row_storage: [31]Widget = undefined,
+ row_storage: [row_count]Widget = undefined,
+ /// The page: `groups`, each one card with a title over its rows.
+ group_storage: [row_count + groups.len]Widget = undefined,
+ group_cards: [groups.len]Widget = undefined,
dock_children: [2]Widget = undefined,
dock_position_children: [2]Widget = undefined,
dock_auto_hide_children: [2]Widget = undefined,
- dock_group_children: [5]Widget = undefined,
+ dock_active_children: [2]Widget = undefined,
+ dock_trash_children: [2]Widget = undefined,
+ dock_group_children: [10]Widget = undefined,
focus_zoom_children: [3]Widget = undefined,
drag_feedback_children: [2]Widget = undefined,
drag_scale_header_children: [2]Widget = undefined,
@@ -179,13 +191,22 @@ pub const Section = struct {
terminal_opacity_header_children: [2]Widget = undefined,
terminal_opacity_group_children: [2]Widget = undefined,
terminal_opacity_value_buf: [16]u8 = undefined,
- px: [20]PxControl = undefined,
- taskbar_section_children: [11]Widget = undefined,
+ px: [22]PxControl = undefined,
+ taskbar_section_children: [13]Widget = undefined,
taskbar_position_children: [2]Widget = undefined,
- items_children: [5]Widget = undefined,
+ clock_bold_children: [2]Widget = undefined,
+ clock_italic_children: [2]Widget = undefined,
+ items_children: [6]Widget = undefined,
+ /// Per section: its title and the well that holds its rows.
items_section_children: [3][2]Widget = undefined,
+ /// What an empty well shows instead of rows.
+ items_placeholder: [3][1]Widget = undefined,
+ /// Spacer, text, spacer: centred, since a lone text in a row is flexed.
+ items_placeholder_body: [3][3]Widget = undefined,
+ /// Rows follow `order`; `syncItems` hands each well its run of them.
item_rows: [taskbar_items.count]Widget = undefined,
- item_controls: [taskbar_items.count][4]Widget = undefined,
+ /// Grip, label, visibility toggle.
+ item_controls: [taskbar_items.count][3]Widget = undefined,
item_drag: ?struct { index: usize, press_y: f32, moved: bool = false, items: taskbar_items.Config } = null,
item_focus: ?taskbar_items.Item = null,
start_menu_section_children: [9]Widget = undefined,
@@ -659,7 +680,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
out.inactive_opacity_group_children = .{ inactive_opacity_header, inactive_opacity_slider };
const inactive_opacity_row: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.inactive_opacity_group_children };
- // Unset means Foot keeps its own alpha; the slider then shows opaque.
+ // Unset means a terminal keeps its own alpha; the slider then shows opaque.
const terminal_val = std.math.clamp(out.cc.server.config.compositor.terminal_opacity orelse 1.0, 0.0, 1.0);
const terminal_formatted = std.fmt.bufPrint(&out.terminal_opacity_value_buf, "{d}%", .{@as(i32, @intFromFloat(@round(terminal_val * 100.0)))}) catch "?";
out.terminal_opacity_header_children = .{ labelWidget("Terminal opacity (new windows)"), pillWidget(terminal_formatted) };
@@ -703,36 +724,52 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
const chip_gap_row = pxGroup(out, px_chip_gap, "Window item gap", std.math.clamp(t.chip_gap, 0.0, 24.0), 0, 24, 2, &PxHandler(px_chip_gap, "chip_gap", true).changed);
const start_gap_row = pxGroup(out, px_start_button_gap, "Start button gap", std.math.clamp(t.start_button_gap, 0.0, 40.0), 0, 40, 2, &PxHandler(px_start_button_gap, "start_button_gap", true).changed);
const start_icon_row = pxGroup(out, px_start_icon_size, "Start button icon size", std.math.clamp(t.start_button_icon_size, 16.0, 42.0), 16, 42, 2, &PxHandler(px_start_icon_size, "start_button_icon_size", true).changed);
- const items = out.cc.server.config.compositor.taskbar_items;
+ out.clock_bold_children = .{
+ labelWidget("Bold clock text"),
+ .{ .name = "clock_bold", .kind = .{ .toggle = .{ .on = theme.taskbar(.clock_bold), .owner = out, .on_change = &ClockStyle("clock_bold").changed } } },
+ };
+ out.clock_italic_children = .{
+ labelWidget("Italic clock text"),
+ .{ .name = "clock_italic", .kind = .{ .toggle = .{ .on = theme.taskbar(.clock_italic), .owner = out, .on_change = &ClockStyle("clock_italic").changed } } },
+ };
+ const clock_bold_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.clock_bold_children };
+ const clock_italic_row: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.clock_italic_children };
+ // Each section is an inset well of raised rows; a whole row is its grip.
inline for (0..taskbar_items.count) |i| {
- 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 } },
- .{ .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 } },
+ .{ .kind = .{ .button = .{ .label = "Drag to move", .icon = .drag_handle, .variant = .ghost, .owner = out, .id = i } }, .width = .{ .fixed = 28 }, .height = .{ .fixed = 28 } },
+ .{ .kind = .{ .text = .{ .content = "", .font_size = 13, .weight = 600, .color = pal.fg } }, .width = .{ .flex = 1 } },
+ .{ .kind = .{ .toggle = .{ .on = false, .owner = out, .on_change = &ItemToggle(i).changed } } },
};
- out.item_rows[i] = .{ .kind = .container, .direction = .row, .gap = 8, .@"align" = .center, .children = &out.item_controls[i] };
+ out.item_rows[i] = .{ .kind = .{ .rect = itemRowStyle(false) }, .direction = .row, .gap = 8, .@"align" = .center, .padding = .{ .top = 6, .right = 10, .bottom = 6, .left = 6 }, .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;
+ inline for (.{ "LEFT", "CENTER", "RIGHT" }, .{ "left", "center", "right" }, 0..) |label, name, zone| {
+ out.items_placeholder_body[zone] = .{
+ .{ .kind = .container, .width = .{ .flex = 1 } },
+ // Slack: a fractional raster scale hints wider than the logical measure.
+ .{ .kind = .{ .text = .{ .content = "Drag items here", .font_size = 12, .color = pal.dim } }, .min_width = @import("ui").measure.textNatural("Drag items here", .sans, 400, 12).w + 6 },
+ .{ .kind = .container, .width = .{ .flex = 1 } },
+ };
+ out.items_placeholder[zone] = .{.{ .kind = .container, .height = .{ .fixed = item_row_height }, .@"align" = .center, .children = &out.items_placeholder_body[zone] }};
out.items_section_children[zone] = .{
sectionLabel(label),
- .{ .kind = .container, .direction = .column, .gap = 8, .children = out.item_rows[item_start..item_end] },
+ .{ .name = "taskbar_zone_" ++ name, .kind = .{ .rect = itemZoneStyle(false) }, .direction = .column, .gap = 6, .padding = layout.Edges.all(6), .@"align" = .stretch },
};
- item_start = item_end;
}
+ _ = syncItems(out, out.cc.server.config.compositor.taskbar_items, null);
out.items_children = .{
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] },
+ .{ .kind = .{ .text = .{ .content = "Drag an item to reorder it or move it to another section. Switch it off to hide it. Battery appears when available.", .font_size = 12, .color = pal.dim } } },
+ .{ .kind = .container, .direction = .column, .gap = 6, .@"align" = .stretch, .children = &out.items_section_children[0] },
+ .{ .kind = .container, .direction = .column, .gap = 6, .@"align" = .stretch, .children = &out.items_section_children[1] },
+ .{ .kind = .container, .direction = .column, .gap = 6, .@"align" = .stretch, .children = &out.items_section_children[2] },
+ .{ .name = "taskbar_capture_notice", .kind = .{ .text = .{ .content = if (out.cc.server.config.compositor.taskbar_items.shown(.capture))
+ "Screen capture appears while recording or sharing your screen. Keeping it enabled is recommended."
+ else
+ "Warning: Screen capture is hidden. Recording and screen sharing can continue without a visible indicator or Stop sharing button. Hiding it is not recommended.", .font_size = 12, .color = pal.dim } } },
};
- const items_group: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.items_children };
- out.taskbar_section_children = .{ sectionLabel("TASKBAR"), position_row, taskbar_row, edge_gap_row, length_row, radius_row, chip_width_row, chip_gap_row, start_gap_row, start_icon_row, items_group };
+ const items_group: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .@"align" = .stretch, .children = &out.items_children };
+ out.taskbar_section_children = .{ panel.sectionTitle("Taskbar"), position_row, taskbar_row, edge_gap_row, length_row, radius_row, chip_width_row, chip_gap_row, start_gap_row, start_icon_row, clock_bold_row, clock_italic_row, items_group };
const taskbar_section: Widget = .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.taskbar_section_children };
var output_box: wlr.Box = undefined;
@@ -793,7 +830,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .name = "start_menu_size_auto", .kind = .{ .button = .{ .label = "Size to screen", .owner = out, .on_click = &onAutoMenuSize, .state = if (menu_pinned) .idle else .disabled } }, .width = .{ .fixed = 124 }, .height = .{ .fixed = 30 } },
};
const menu_size_row: Widget = .{ .kind = .container, .direction = .row, .gap = 8, .@"align" = .center, .children = &out.start_size_children };
- out.start_menu_section_children = .{ sectionLabel("START MENU"), logo_row, menu_width_row, menu_height_row, menu_size_row, menu_left_row, menu_bottom_row, icon_left_row, icon_bottom_row };
+ out.start_menu_section_children = .{ panel.sectionTitle("Start menu"), logo_row, menu_width_row, menu_height_row, menu_size_row, menu_left_row, menu_bottom_row, icon_left_row, icon_bottom_row };
const start_menu_section: Widget = .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.start_menu_section_children };
out.theme_actions = .{
@@ -853,12 +890,32 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
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);
+ // The slider shows the opacity the dock is drawn with, whether the theme or
+ // `dock_opacity` set it; the radius, whether it is the dock's own or the windows'.
+ const dock_pal = theme.shellPalette();
+ const dock_opacity_row = unitGroup(out, px_dock_opacity, "Dock opacity", @round(dock_mod.background(&server.config.compositor, dock_pal)[3] * 100), 0, 100, 1, &onDockOpacityChanged, "%");
+ out.px[px_dock_opacity].group_children[1].name = "dock_opacity";
+ const dock_radius_row = pxGroup(out, px_dock_radius, "Dock corner radius", std.math.clamp(dock_mod.cornerRadius(dock_pal), dock_radius_min, dock_radius_max), dock_radius_min, dock_radius_max, 1, &PxHandler(px_dock_radius, "dock_radius", false).changed);
+ out.px[px_dock_radius].group_children[1].name = "dock_radius";
+ out.dock_active_children = .{
+ labelWidget("Highlight active app"),
+ .{ .name = "dock_active_highlight", .kind = .{ .toggle = .{ .on = server.config.compositor.dock_active_highlight, .owner = out, .on_change = &onDockActiveHighlightChanged } } },
+ };
+ out.dock_trash_children = .{
+ labelWidget("Show Trash"),
+ .{ .name = "dock_show_trash", .kind = .{ .toggle = .{ .on = server.config.compositor.dock_show_trash, .owner = out, .on_change = &onDockShowTrashChanged } } },
+ };
out.dock_group_children = .{
+ panel.sectionTitle("Dock"),
.{ .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 },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_auto_hide_children },
dock_height_row,
dock_zoom_row,
+ dock_opacity_row,
+ dock_radius_row,
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_active_children },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_trash_children },
};
out.row_storage = .{
.{ .kind = .container, .direction = .column, .gap = 8, .children = pack_controls },
@@ -893,14 +950,85 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
taskbar_section,
start_menu_section,
};
+ var at: usize = 0;
+ for (groups, &out.group_cards) |group, *card| {
+ const start = at;
+ if (group.title) |title| {
+ out.group_storage[at] = panel.sectionTitle(title);
+ at += 1;
+ }
+ for (group.rows) |row| {
+ out.group_storage[at] = out.row_storage[@intFromEnum(row)];
+ at += 1;
+ }
+ // An untitled group is one row that brings its own title.
+ card.* = if (group.title == null) out.group_storage[start] else .{ .kind = .container, .direction = .column, .gap = 16, .children = out.group_storage[start..at] };
+ }
out.top_children = .{
.{ .kind = .{ .text = .{ .content = "APPEARANCE", .font_size = 12, .weight = 700, .color = pal.dim } } },
- .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.row_storage },
+ .{ .kind = .container, .direction = .column, .gap = 12, .children = &out.group_cards },
};
out.root = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.top_children };
}
const strip_index = 1;
+
+/// `row_storage`, in the order `build` fills it.
+const Row = enum {
+ theme_pack,
+ icon_theme,
+ theme,
+ taskbar_theme,
+ app_colors,
+ dark_mode,
+ wallpaper,
+ launch_splash,
+ dodge_file_drags,
+ animations,
+ animation_speed,
+ reduced_motion,
+ focus_zoom,
+ drag_feedback,
+ drag_scale,
+ cursor,
+ font_family,
+ font_size,
+ radius,
+ shadow,
+ edge_glow,
+ chrome_opacity,
+ window_tabs,
+ inactive_dim,
+ inactive_opacity,
+ terminal_opacity,
+ window_gap,
+ scrollbar_width,
+ dock,
+ taskbar,
+ start_menu,
+};
+const row_count = std.meta.fields(Row).len;
+
+const groups = [_]struct { title: ?[]const u8, rows: []const Row }{
+ .{ .title = "Themes & colours", .rows = &.{ .theme, .taskbar_theme, .theme_pack, .icon_theme, .dark_mode, .app_colors } },
+ .{ .title = "Wallpaper", .rows = &.{.wallpaper} },
+ .{ .title = "Fonts & cursor", .rows = &.{ .font_family, .font_size, .cursor } },
+ .{ .title = "Windows", .rows = &.{ .radius, .shadow, .edge_glow, .chrome_opacity, .window_tabs, .inactive_dim, .inactive_opacity, .terminal_opacity, .window_gap, .scrollbar_width } },
+ .{ .title = "Motion & feedback", .rows = &.{ .animations, .animation_speed, .reduced_motion, .focus_zoom, .drag_feedback, .drag_scale, .dodge_file_drags, .launch_splash } },
+ .{ .title = null, .rows = &.{.dock} },
+ .{ .title = null, .rows = &.{.taskbar} },
+ .{ .title = null, .rows = &.{.start_menu} },
+};
+
+comptime {
+ // Every row is shown exactly once.
+ var seen = [_]bool{false} ** row_count;
+ for (groups) |group| for (group.rows) |row| {
+ if (seen[@intFromEnum(row)]) @compileError("row in two groups: " ++ @tagName(row));
+ seen[@intFromEnum(row)] = true;
+ };
+ for (seen, 0..) |shown, i| if (!shown) @compileError("row in no group: " ++ @tagName(@as(Row, @enumFromInt(i))));
+}
const tile_w: f32 = wallpaper_strip.thumb_width / 2;
const tile_h: f32 = wallpaper_strip.thumb_height / 2;
const tile_pad: f32 = 3;
@@ -1031,13 +1159,22 @@ fn appColorsReady(_: c_int, _: wl.EventMask, s: *Section) c_int {
return 0;
}
-/// Thumbnails arrive one by one; the panel repaints for each.
+/// Thumbnails arrive one by one; each goes into its tile in the shown strip
+/// and repaints that tile alone. A later build reads them from the strip.
fn stripWake(_: c_int, _: wl.EventMask, out: *Section) c_int {
- if (out.strip) |strip| strip.drain();
- {
- const server = out.cc.server;
- if (server.input.open_control_center) |cc| cc.refresh();
+ const strip = out.strip orelse return 0;
+ strip.drain();
+ const cc = out.cc.server.input.open_control_center orelse return 0;
+ if (cc != out.cc or cc.page != .appearance or !out.strip_built) return 0;
+ const container = &out.wallpaper_children[strip_index];
+ if (container.kind != .scroll_container) return 0;
+ for (container.children, 0..) |*tile, i| {
+ const image = &tile.children[0];
+ if (image.kind != .image or image.kind.image.pixels != null) continue;
+ image.kind.image.pixels = strip.thumb(i) orelse continue;
+ image.markPaintDirty();
}
+ cc.requestWidgetRepaint();
return 0;
}
@@ -1070,7 +1207,7 @@ fn buildWallpaper(out: *Section, arena: std.mem.Allocator) void {
labels = l;
} else |_| {}
out.wallpaper_row_children = .{
- labelWidget("Wallpaper"),
+ labelWidget("Image"),
.{
.name = "wallpaper",
.kind = .{
@@ -1462,7 +1599,7 @@ fn onThemePicked(owner: ?*anyopaque, _: usize, index: usize) void {
};
}
-/// Gives the taskbar the colours of the picked preset (index 0 hands it back
+/// Gives the taskbar the colours and clock style of the picked preset (index 0 hands it back
/// to the main theme). Only the bar changes: `theme.global` keeps whatever the
/// theme row above chose, and so does the saved `[theme]` section.
fn onTaskbarThemePicked(owner: ?*anyopaque, _: usize, index: usize) void {
@@ -1484,6 +1621,24 @@ fn onTaskbarThemePicked(owner: ?*anyopaque, _: usize, index: usize) void {
if (server.input.open_control_center) |cc| cc.refresh();
}
+fn ClockStyle(comptime key: []const u8) type {
+ return struct {
+ fn changed(owner: ?*anyopaque, _: usize, on: bool) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ if (theme.taskbar_override) |*chosen| {
+ @field(chosen, key) = on;
+ if (server.config.path.len > 0) loader.replaceTaskbarThemeSection(main.gpa, server.io, server.config.path, chosen.*);
+ server.refreshTaskbarsGeometry();
+ if (server.input.open_control_center) |cc| cc.refresh();
+ } else {
+ @field(theme.global, key) = on;
+ applyThemeChangeImpl(s, true);
+ }
+ }
+ };
+}
+
fn onFontFamilyChanged(owner: ?*anyopaque, _: usize, index: usize) void {
const s = section(owner);
const families = s.font_families orelse return;
@@ -1570,7 +1725,7 @@ fn onInactiveOpacityChanged(owner: ?*anyopaque, _: usize, value: f32) void {
};
}
-/// Foot reads its alpha at launch, so this only reaches terminals opened
+/// Terminals read their alpha at launch, so this only reaches terminals opened
/// afterwards (`config/terminal_theme.zig`); nothing to apply live.
fn onTerminalOpacityChanged(owner: ?*anyopaque, _: usize, value: f32) void {
const s = section(owner);
@@ -1770,11 +1925,68 @@ fn saveItems(s: *Section, items: taskbar_items.Config) void {
if (server.input.open_control_center) |cc| cc.refresh();
}
+const item_row_height: f32 = 40;
+
+fn itemRowStyle(lifted: bool) layout.RectStyle {
+ const pal = panel.palette();
+ return .{ .color = if (lifted) pal.app_item_selected else pal.app_item, .radius = 8, .border_width = 1, .border_color = if (lifted) pal.accent else pal.app_item_border };
+}
+
+fn itemZoneStyle(target: bool) layout.RectStyle {
+ const pal = panel.palette();
+ return .{ .color = pal.app_bg, .radius = 10, .border_width = 1, .border_color = if (target) pal.accent else pal.app_item_border };
+}
+
+fn itemName(item: taskbar_items.Item, comptime suffix: []const u8) []const u8 {
+ return switch (item) {
+ inline else => |tag| "taskbar_" ++ @tagName(tag) ++ suffix,
+ };
+}
+
+/// Points the rows at `items` (row `i` shows `order[i]`) and gives each
+/// section's well its run of rows, or its placeholder. True when a well's
+/// row count changed, which needs a layout.
+fn syncItems(out: *Section, items: taskbar_items.Config, dragged: ?usize) bool {
+ const pal = panel.palette();
+ for (&out.item_rows, &out.item_controls, items.order, 0..) |*row, *controls, item, i| {
+ const lifted = dragged == i;
+ row.name = itemName(item, "_row");
+ row.kind = .{ .rect = itemRowStyle(lifted) };
+ controls[0].name = itemName(item, "_order");
+ controls[0].kind.button.state = if (lifted) .press else .idle;
+ controls[1].kind.text.content = item.label();
+ // `panel.restyle` colours text by weight: a hidden item's label is dim.
+ controls[1].kind.text.weight = if (items.shown(item)) 600 else 400;
+ controls[1].kind.text.color = if (items.shown(item)) pal.fg else pal.dim;
+ controls[2].name = itemName(item, "_visible");
+ controls[2].kind.toggle.on = items.shown(item);
+ for (controls) |*control| control.markDirty();
+ row.markDirty();
+ }
+ var changed = false;
+ var start: usize = 0;
+ for (&out.items_section_children, &out.items_placeholder, 0..) |*zone, *placeholder, z| {
+ var end = start;
+ while (end < taskbar_items.count and @intFromEnum(items.section(items.order[end])) == z) end += 1;
+ const well = &zone[1];
+ const rows: []Widget = if (end == start) placeholder else out.item_rows[start..end];
+ changed = changed or rows.ptr != well.children.ptr or rows.len != well.children.len;
+ well.children = rows;
+ well.kind = .{ .rect = itemZoneStyle(dragged != null and start <= dragged.? and dragged.? < end) };
+ well.linkParents();
+ well.markDirty();
+ start = end;
+ }
+ return changed;
+}
+
+/// The row whose grip, label or background is at (x, y): a whole row drags,
+/// only its toggle does not.
pub fn itemHandle(s: *Section, x: f32, y: f32) ?usize {
const ui = @import("ui");
const hit = ui.input.hitTest(&s.cc.root, x, y) orelse return null;
- for (&s.item_controls, 0..) |*controls, i| {
- if (hit == &controls[1]) return i;
+ for (&s.item_rows, &s.item_controls, 0..) |*row, *controls, i| {
+ if (hit == row or hit == &controls[0] or hit == &controls[1]) return i;
}
return null;
}
@@ -1793,31 +2005,31 @@ pub fn beginItemDrag(s: *Section, x: f32, y: f32) bool {
fn previewItems(s: *Section) void {
const drag = s.item_drag;
const items = if (drag) |d| d.items else s.cc.server.config.compositor.taskbar_items;
- for (&s.item_controls, items.order, 0..) |*controls, item, i| {
- controls[0].kind.text.content = item.label();
- 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();
- }
+ if (syncItems(s, items, if (drag) |d| d.index else null)) s.cc.layoutContent();
s.cc.requestRepaint();
}
+/// Rows move live: the pointer's section is the one whose title it is at or
+/// below, its slot the count of that section's other rows whose middle it has passed.
pub fn moveItemDrag(s: *Section, y: f32) void {
const drag = if (s.item_drag) |*d| d else return;
if (!drag.moved and @abs(y - drag.press_y) < 4) return;
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 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;
- drag.items.move(drag.index, down);
- if (down) drag.index += 1 else drag.index -= 1;
+ var zone: usize = 0;
+ for (1..3) |z| {
+ if (y >= s.items_children[2 + z].computed_y) zone = z;
+ }
+ const current = @intFromEnum(drag.items.section(drag.items.order[drag.index]));
+ var slot: usize = 0;
+ var current_slot: usize = 0;
+ for (drag.items.order, 0..) |item, i| {
+ const z = @intFromEnum(drag.items.section(item));
+ if (i == drag.index) continue;
+ if (z == current and i < drag.index) current_slot += 1;
+ if (z == zone and y > s.item_rows[i].computed_y + s.item_rows[i].computed_height / 2) slot += 1;
}
+ if (zone == current and slot == current_slot) return;
+ drag.index = drag.items.place(drag.index, @enumFromInt(zone), slot);
previewItems(s);
}
@@ -1825,10 +2037,12 @@ pub fn endItemDrag(s: *Section, commit: bool) void {
const drag = s.item_drag orelse return;
s.item_drag = null;
s.item_focus = drag.items.order[drag.index];
- if (commit and !std.meta.eql(drag.items.order, s.cc.server.config.compositor.taskbar_items.order)) {
+ const saved = s.cc.server.config.compositor.taskbar_items;
+ if (commit and !(std.meta.eql(drag.items.order, saved.order) and std.meta.eql(drag.items.sections, saved.sections))) {
// A config reload during the grab can change visibility independently.
- var items = s.cc.server.config.compositor.taskbar_items;
+ var items = saved;
items.order = drag.items.order;
+ items.sections = drag.items.sections;
items.normalize();
saveItems(s, items);
}
@@ -1839,7 +2053,7 @@ pub fn endItemDrag(s: *Section, commit: bool) void {
pub fn restoreItemFocus(s: *Section) void {
const item = s.item_focus orelse return;
for (s.cc.server.config.compositor.taskbar_items.order, 0..) |candidate, i| {
- if (item == candidate) @import("ui").input.current.focus(&s.cc.root, &s.item_controls[i][1]);
+ if (item == candidate) @import("ui").input.current.focus(&s.cc.root, &s.item_controls[i][0]);
}
s.item_focus = null;
}
@@ -1848,14 +2062,15 @@ pub fn captureItemFocus(s: *Section) void {
if (s.item_focus != null) return;
const focused = @import("ui").input.current.focused orelse return;
for (&s.item_controls) |*controls| {
- if (focused != &controls[1]) continue;
+ if (focused != &controls[0]) continue;
for (std.enums.values(taskbar_items.Item)) |item| {
- if (std.mem.eql(u8, controls[0].kind.text.content, item.label())) s.item_focus = item;
+ if (std.mem.eql(u8, controls[1].kind.text.content, item.label())) s.item_focus = item;
}
return;
}
}
+/// Up/Down on a focused grip moves its item one step, across sections too.
pub fn itemKey(s: *Section, key: @import("ui").input.Key) bool {
if (s.item_drag != null) {
if (key == .escape) endItemDrag(s, false);
@@ -1864,24 +2079,17 @@ pub fn itemKey(s: *Section, key: @import("ui").input.Key) bool {
if (key != .up and key != .down) return false;
const focused = @import("ui").input.current.focused orelse return false;
for (&s.item_controls, 0..) |*controls, i| {
- if (focused != &controls[1]) continue;
- var items = s.cc.server.config.compositor.taskbar_items;
+ if (focused != &controls[0]) continue;
+ const before = s.cc.server.config.compositor.taskbar_items;
+ var items = before;
s.item_focus = items.order[i];
items.move(i, key == .down);
- saveItems(s, items);
+ if (!std.meta.eql(items, before)) saveItems(s, items);
return true;
}
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 {
@@ -1996,6 +2204,54 @@ fn onDockAutoHideChanged(owner: ?*anyopaque, _: usize, on: bool) void {
server.scheduleFrames();
}
+/// The slider is 0-100 %. At 0 the dock is only its icons over the glass.
+fn onDockOpacityChanged(owner: ?*anyopaque, _: usize, value: f32) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ const opacity = std.math.clamp(@round(value), 0, 100) / 100;
+ if (server.config.compositor.dock_opacity) |current| if (current == opacity) return;
+ server.config.compositor.dock_opacity = opacity;
+ s.px[px_dock_opacity].header_children[1].kind.text.content = std.fmt.bufPrint(&s.px[px_dock_opacity].value_buf, "{d}%", .{@as(i32, @intFromFloat(@round(opacity * 100)))}) catch "?";
+ s.px[px_dock_opacity].header_children[1].markDirty();
+ var it = server.outputs.iterator(.forward);
+ while (it.next()) |output| output.dock.invalidate();
+ server.scheduleFrames();
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "dock_opacity", opacity) catch |err| {
+ std.log.warn("could not save dock_opacity: {}", .{err});
+ };
+}
+
+fn onDockActiveHighlightChanged(owner: ?*anyopaque, _: usize, on: bool) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "dock_active_highlight", on) catch |err| {
+ std.log.warn("could not save dock active highlight: {}", .{err});
+ s.dock_active_children[1].kind.toggle.on = server.config.compositor.dock_active_highlight;
+ s.dock_active_children[1].markDirty();
+ return;
+ };
+ server.config.compositor.dock_active_highlight = on;
+ var it = server.outputs.iterator(.forward);
+ while (it.next()) |output| output.dock.invalidate();
+ server.scheduleFrames();
+}
+
+fn onDockShowTrashChanged(owner: ?*anyopaque, _: usize, on: bool) void {
+ const s = section(owner);
+ const server = s.cc.server;
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "dock_show_trash", on) catch |err| {
+ std.log.warn("could not save dock_show_trash: {}", .{err});
+ s.dock_trash_children[1].kind.toggle.on = server.config.compositor.dock_show_trash;
+ s.dock_trash_children[1].markDirty();
+ return;
+ };
+ server.config.compositor.dock_show_trash = on;
+ 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 onDockPositionChanged(owner: ?*anyopaque, _: usize, index: usize) void {
if (index >= 4) return;
const s = section(owner);
diff --git a/src/control_center/sections/bluetooth.zig b/src/control_center/sections/bluetooth.zig
index 887e382..310a94d 100644
--- a/src/control_center/sections/bluetooth.zig
+++ b/src/control_center/sections/bluetooth.zig
@@ -153,7 +153,7 @@ fn deviceList(s: *Section, cc: *panel.ControlCenter, a: A, enabled: bool) !W {
const m = cc.server.bluetooth;
if (s.search_data == null) s.search_data = .{ .placeholder = "Search devices…", .value = try gpa.dupe(u8, ""), .field = .{ .leading_icon = .search }, .owner = cc, .on_change = searchChanged };
var items: std.ArrayList(W) = .empty;
- try items.append(a, text(if (s.nearby) "Available Devices" else "Paired Devices", 18, false));
+ try items.append(a, panel.sectionTitle(if (s.nearby) "Available Devices" else "Paired Devices"));
try items.append(a, .{ .name = "bluetooth_search", .kind = .{ .text_input = s.search_data.? }, .height = .{ .fixed = 36 }, .width = .{ .percent = 1 } });
if (s.nearby) try items.append(a, button(cc, "bluetooth_paired", "Show Paired Devices", 1, false));
var rows: std.ArrayList(W) = .empty;
@@ -197,7 +197,7 @@ fn setting(cc: *panel.ControlCenter, a: A, title: []const u8, description: []con
fn deviceDetails(s: *Section, cc: *panel.ControlCenter, a: A) !W {
const m = cc.server.bluetooth;
const d = if (m) |manager| manager.find(s.selected) else null;
- if (d == null) return card(a, &.{ icon(.bluetooth, 48), text("Select a device", 18, false), text("View its connection, battery and device settings.", 13, true) });
+ if (d == null) return card(a, &.{ icon(.bluetooth, 48), panel.sectionTitle("Select a device"), text("View its connection, battery and device settings.", 13, true) });
const dev = d.?;
const manager = m.?;
const ad = manager.adapter(dev.adapter);
@@ -211,7 +211,7 @@ fn deviceDetails(s: *Section, cc: *panel.ControlCenter, a: A) !W {
var items: std.ArrayList(W) = .empty;
try items.append(a, header);
if (dev.battery != null) try items.append(a, badge);
- if (dev.rssi) |rssi| try items.append(a, try card(a, &.{ text("Connection", 15, false), text(try std.fmt.allocPrint(a, "Last reported signal: {d} dBm", .{rssi}), 13, true) }));
+ if (dev.rssi) |rssi| try items.append(a, try card(a, &.{ panel.sectionTitle("Connection"), text(try std.fmt.allocPrint(a, "Last reported signal: {d} dBm", .{rssi}), 13, true) }));
if (manager.pairing != null and eq(u8, manager.pairing.?.slice(), dev.path.slice())) {
try items.append(a, try pairing(s, cc, a));
} else {
@@ -220,14 +220,14 @@ fn deviceDetails(s: *Section, cc: *panel.ControlCenter, a: A) !W {
try items.append(a, connect);
}
var profiles: std.ArrayList(W) = .empty;
- try profiles.append(a, text("Profiles", 15, false));
+ try profiles.append(a, panel.sectionTitle("Profiles"));
if (dev.audio) try profiles.append(a, try group(a, .row, &.{ icon(.music, 20), text("Audio (A2DP) · High quality audio", 13, true) }));
if (dev.microphone) try profiles.append(a, try group(a, .row, &.{ icon(.mic_outline, 20), text("Headset · Audio and microphone", 13, true) }));
if (dev.input) try profiles.append(a, try group(a, .row, &.{ icon(.keyboard, 20), text("Input · Keyboard, mouse or controller", 13, true) }));
if (profiles.items.len == 1) try profiles.append(a, text(if (dev.paired) "No supported profiles reported" else "Profiles appear after pairing", 12, true));
if (dev.audio or dev.microphone) try profiles.append(a, button(cc, "bluetooth_audio", "Audio Settings", 3, false));
try items.append(a, try card(a, profiles.items));
- try items.append(a, try card(a, &.{ text("Device Settings", 15, false), try setting(cc, a, "Trusted Device", "Allow connections from this device without asking.", "bluetooth_trusted", 1, dev.trusted, manager.busy or !dev.paired), try setting(cc, a, "Blocked", "Prevent this device from connecting.", "bluetooth_blocked", 2, dev.blocked, manager.busy) }));
+ try items.append(a, try card(a, &.{ panel.sectionTitle("Device Settings"), try setting(cc, a, "Trusted Device", "Allow connections from this device without asking.", "bluetooth_trusted", 1, dev.trusted, manager.busy or !dev.paired), try setting(cc, a, "Blocked", "Prevent this device from connecting.", "bluetooth_blocked", 2, dev.blocked, manager.busy) }));
if (s.forgetting) {
try items.append(a, text("Forget this device? Pair it again to reconnect.", 13, true));
try items.append(a, try group(a, .row, &.{ button(cc, "bluetooth_forget_confirm", "Forget Device", 5, manager.busy), button(cc, "bluetooth_forget_cancel", "Cancel", 6, false) }));
@@ -239,7 +239,7 @@ fn deviceDetails(s: *Section, cc: *panel.ControlCenter, a: A) !W {
fn pairing(s: *Section, cc: *panel.ControlCenter, a: A) !W {
const m = cc.server.bluetooth.?;
var items: std.ArrayList(W) = .empty;
- try items.append(a, text("Pairing", 15, false));
+ try items.append(a, panel.sectionTitle("Pairing"));
switch (m.prompt) {
.none => try items.append(a, text("Waiting for the device…", 13, true)),
.confirm => {
diff --git a/src/control_center/sections/desktop.zig b/src/control_center/sections/desktop.zig
index 1570fb7..0c0f4c1 100644
--- a/src/control_center/sections/desktop.zig
+++ b/src/control_center/sections/desktop.zig
@@ -108,9 +108,9 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
// instead of floating in a padded box.
const grid_height = cell_size * @as(f32, @floatFromInt(rows)) + gap * @as(f32, @floatFromInt(rows -| 1));
const grid: W = .{ .kind = .container, .direction = .column, .justify = .center, .gap = gap, .width = .{ .percent = 1 }, .height = .{ .fixed = grid_height }, .children = grid_rows };
- const preview = try card(a, &.{ text("Canvas Preview", 16, false), text("Your desktop panning area.", 12, true), grid, text("Highlighted: bottom-left screen", 12, true) });
+ const preview = try card(a, &.{ panel.sectionTitle("Canvas Preview"), text("Your desktop panning area.", 12, true), grid, text("Highlighted: bottom-left screen", 12, true) });
const controls = try card(a, &.{
- text("Canvas Size", 16, false),
+ panel.sectionTitle("Canvas Size"),
try dimension(a, cc, false, columns),
try dimension(a, cc, true, rows),
text(try std.fmt.allocPrint(a, "{d} × {d} · {d} screens total", .{ columns, rows, columns * rows }), 18, false),
@@ -119,7 +119,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
var body = try container(a, if (cc.panel_box.width < 760) .column else .row, &.{ preview, controls });
body.width = .{ .percent = 1 };
const switching = try card(a, &.{
- text("Desktop Switching", 16, false),
+ panel.sectionTitle("Desktop Switching"),
text("How long Super + arrow keys take to slide to the next desktop.", 12, true),
.{ .name = "desktop_switch_ms", .kind = .{ .segmented = .{ .labels = &switch_labels, .selected = nearestSwitch(cfg.desktop_switch_ms), .owner = cc, .on_change = &switchChanged } }, .width = .{ .percent = 1 } },
});
@@ -139,7 +139,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
if (@abs(@as(i64, delay) - cfg.mini_map_hide_ms) < @abs(@as(i64, map_delays[delay_index]) - cfg.mini_map_hide_ms)) delay_index = i;
}
const mini_map = try card(a, &.{
- text("Mini Map", 16, false),
+ panel.sectionTitle("Mini Map"),
text("See your position while navigating. Drag the highlighted view to pan.", 12, true),
map_toggle,
try mapSelect(cc, a, "Position", "mini_map_position", &map_position_labels, position_index, !map_on, &mapPositionChanged),
@@ -152,7 +152,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
fixed_row.justify = .space_between;
fixed_row.@"align" = .center;
const mode_card = try card(a, &.{
- text("Desktop mode", 14, false),
+ panel.sectionTitle("Desktop mode"),
.{ .name = "desktop_mode", .kind = .{ .segmented = .{ .labels = &.{ "Canvas", "Workspaces" }, .selected = @intFromEnum(cfg.desktop_mode), .owner = cc, .on_change = modeChanged } }, .width = .{ .percent = 1 } },
text(if (cfg.desktop_mode == .workspaces) "Automatic tiles with a fixed view and Hyprland-style shortcuts. Drag tiles to rearrange; Super+V toggles floating." else "Pan and zoom the canvas. Switching back restores your canvas positions and zoom.", 12, true),
});
@@ -282,7 +282,7 @@ fn workspaceTree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator, mo
for (labels, 0..) |*label, i| label.* = try std.fmt.allocPrint(a, "Workspace {d}", .{i + 1});
const slot = manager.slots[id - 1];
const workspace_card = try card(a, &.{
- text("Workspace layout", 16, false),
+ panel.sectionTitle("Workspace layout"),
try mapSelect(cc, a, "Workspace", "workspace_select", labels, id - 1, false, workspaceSelected),
try mapSelect(cc, a, "Placement", "workspace_layout", &.{ "Automatic tiling", "Floating" }, if (slot.automatic) 0 else 1, false, layoutChanged),
text(if (slot.output) |out| try std.fmt.allocPrint(a, "Output: {s}", .{std.mem.span(out.wlr_output.name)}) else "Assigned to the current output when first used.", 12, true),
@@ -294,7 +294,7 @@ fn workspaceTree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator, mo
gap_index = i;
};
const spacing = try card(a, &.{
- text("Window spacing", 16, false),
+ panel.sectionTitle("Window spacing"),
try mapSelect(cc, a, try std.fmt.allocPrint(a, "Gap ({d} px)", .{value}), "workspace_gap", &gap_labels, gap_index, false, gapChanged),
text("Applies to output edges and the space between automatic tiles.", 12, true),
});
@@ -323,7 +323,7 @@ fn workspaceTree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator, mo
item.* = .{ .id = i, .name = try std.fmt.allocPrint(a, "floating_app:{s}", .{app}), .label = app, .checked = checked };
}
const rules = try card(a, &.{
- text("Floating apps", 16, false),
+ panel.sectionTitle("Floating apps"),
text("Checked apps open floating. Super+V can override placement for a window. Dialogs and fixed-size windows float automatically.", 12, true),
try list.build(a, items, cc, floatingChanged, .{}),
text("Open an app to add it here. Advanced title, backend and glob matches use [[window_rules]] floating in your config.", 12, true),
diff --git a/src/control_center/sections/display.zig b/src/control_center/sections/display.zig
index 890521f..f15cda2 100644
--- a/src/control_center/sections/display.zig
+++ b/src/control_center/sections/display.zig
@@ -250,7 +250,6 @@ fn buildArrangement(out: *Section, selected_name: []const u8) void {
}
const canvas_height: f32 = if (3 * (max_y - min_y) > 2 * (max_x - min_x)) 280 else 220;
- const pal = panel.palette();
var hint = valueWidget("Drag displays to match your desk. Click one to edit it.");
hint.kind.text.font_size = 12;
hint.width = .{ .flex = 1 };
@@ -266,7 +265,7 @@ fn buildArrangement(out: *Section, selected_name: []const u8) void {
// The selected display is already main: nothing to offer.
out.main_row_count = if (selected_is_main or out.arrangement_selected == null) 1 else 2;
out.arrangement_children = .{
- .{ .kind = .{ .text = .{ .content = "Arrangement", .font_size = 16, .weight = 600, .color = pal.fg } } },
+ panel.sectionTitle("Arrangement"),
hint,
.{ .name = "arrangement", .kind = .{ .arrangement = .{ .items = out.arrangement_items, .selected = out.arrangement_selected } }, .width = .{ .percent = 1 }, .height = .{ .fixed = canvas_height } },
.{ .kind = .container, .direction = .row, .@"align" = .center, .gap = 12, .children = out.main_row_children[0..out.main_row_count] },
diff --git a/src/control_center/sections/portals.zig b/src/control_center/sections/portals.zig
index ea09808..3a3e248 100644
--- a/src/control_center/sections/portals.zig
+++ b/src/control_center/sections/portals.zig
@@ -35,7 +35,7 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
const content = config.load(a, cc.server.io, cc.server.environ) catch config.defaults;
return .{ .kind = .container, .direction = .column, .gap = 12, .width = .{ .percent = 1 }, .children = try a.dupe(W, &.{
- text("Desktop portals", false),
+ panel.sectionTitle("Desktop portals"),
text("Choose the services apps use for desktop dialogs. The selected backend must be installed.", true),
try row(cc, a, "Default backend", "portal_default", &.{ "GTK", "KDE", "RediWM + GTK" }, &default_values, config.get(content, "default") orelse "gtk", defaultChanged),
try row(cc, a, "File dialogs", "portal_file_chooser", &.{ "RediWM", "GTK", "KDE", "Any available" }, &file_values, config.get(content, config.chooser_key) orelse config.get(content, "default") orelse "gtk", fileChanged),
diff --git a/src/control_center/sections/region.zig b/src/control_center/sections/region.zig
index 098e8d9..8c560d0 100644
--- a/src/control_center/sections/region.zig
+++ b/src/control_center/sections/region.zig
@@ -247,13 +247,13 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
const prefs = cc.server.config.region;
const language = try card(a, &.{
- text("Language", 17, false),
+ panel.sectionTitle("Language"),
text("Application language", 13, false),
try choice(s, cc, a, "language", 1, s.locales.items, localeName(cc, "LC_MESSAGES"), c._NL_IDENTIFICATION_LANGUAGE),
text("RediWM currently uses English. Only installed locales are listed.", 12, true),
});
const region = try card(a, &.{
- text("Region", 17, false),
+ panel.sectionTitle("Region"),
text("Regional formats", 13, false),
try choice(s, cc, a, "formats", 2, s.locales.items, localeName(cc, "LC_TIME"), c._NL_ADDRESS_COUNTRY_NAME),
text("Date format for the taskbar; date, number and currency formats for new apps.", 12, true),
@@ -277,7 +277,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
day_toggle.justify = .space_between;
day_toggle.@"align" = .center;
const timing = try card(a, &.{
- text("Time & Date", 17, false),
+ panel.sectionTitle("Time & Date"),
text("Time zone", 13, false),
try choice(s, cc, a, "timezone", 0, s.zones.items, try timezone(a, cc), null),
toggle,
@@ -289,7 +289,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
.{ .name = "first_day_of_week", .kind = .{ .select = .{ .labels = &days, .selected = @intFromEnum(prefs.first_day_of_week), .owner = cc, .on_change = firstDayChanged } }, .width = .{ .percent = 1 } },
text("Changes the taskbar calendar.", 12, true),
});
- const preview = try card(a, &.{ text("Formats Preview", 17, false), try previews(a, prefs) });
+ const preview = try card(a, &.{ panel.sectionTitle("Formats Preview"), try previews(a, prefs) });
var body = try container(a, if (cc.panel_box.width < 900) .column else .row, &.{
try container(a, .column, &.{ language, timing }),
try container(a, .column, &.{ region, preview }),
diff --git a/src/control_center/sections/users.zig b/src/control_center/sections/users.zig
index db7b8e1..1071d8e 100644
--- a/src/control_center/sections/users.zig
+++ b/src/control_center/sections/users.zig
@@ -94,7 +94,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
const rows = try a.alloc(W, snapshot.users.len + 32);
var count: usize = 0;
const header = try a.alloc(W, 2);
- header[0] = text("Accounts", 16, false);
+ header[0] = panel.sectionTitle("Accounts");
header[0].width = .{ .flex = 1 };
header[1] = .{ .kind = .{ .button = .{
.label = if (s.unlocked) "Lock" else "Unlock",
@@ -146,7 +146,7 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
},
.none => {},
}
- rows[count] = text("Automatic login", 16, false);
+ rows[count] = panel.sectionTitle("Automatic login");
count += 1;
const user_labels = try a.alloc([]const u8, snapshot.users.len + 1);
user_labels[0] = "Off";
@@ -269,7 +269,7 @@ fn buildAddForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W
return buildCard(a, &.{text("Could not allocate locked password storage.", 13, true)});
}
const items = try a.alloc(W, 7);
- items[0] = text("Add user", 16, false);
+ items[0] = panel.sectionTitle("Add user");
items[1] = try textInputRow(cc, a, "Full name", "", "Full name", addFullNameChanged, &s.new_full_name);
items[2] = try textInputRow(cc, a, "Username", "", "lowercase username", addUsernameChanged, &s.new_username);
items[3] = try secretInputRowFocus(a, "Password", &s.password, "Enter password", &s.password_field);
@@ -283,7 +283,7 @@ fn buildDetailsForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator,
populateGroupChoices(s, user, groups);
const visible_count = visibleGroupCount(s);
const items = try a.alloc(W, 9);
- items[0] = text(try std.fmt.allocPrint(a, "Account details · {s}", .{user.name}), 16, false);
+ items[0] = panel.sectionTitle(try std.fmt.allocPrint(a, "Account details · {s}", .{user.name}));
const displayed_full_name = if (s.details_name_dirty) s.details_name_draft[0..s.details_name_len] else user.full_name;
items[1] = try textInputRow(cc, a, "Full name", displayed_full_name, "Full name", detailsNameChanged, &s.details_full_name);
const type_labels = [_][]const u8{ "Standard", "Administrator" };
@@ -294,7 +294,7 @@ fn buildDetailsForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator,
actions[2] = actionButton(cc, "Delete user…", 0, beginDeleteClicked, s.auth != null);
items[3] = .{ .kind = .container, .direction = .row, .justify = .space_between, .gap = 8, .children = actions };
const group_header = try a.alloc(W, 2);
- group_header[0] = text("Groups", 16, false);
+ group_header[0] = panel.sectionTitle("Groups");
group_header[1] = actionButton(cc, if (s.show_all_groups) "Show curated" else "Show all groups", 0, groupVisibilityClicked, s.auth != null);
items[4] = .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = group_header };
const group_widgets = try a.alloc(W, visible_count);
@@ -323,7 +323,7 @@ fn buildDetailsForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator,
fn buildPasswordForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
if (s.password_memory == null or s.confirm_memory == null) return buildCard(a, &.{text("Could not allocate locked password storage.", 13, true)});
const items = try a.alloc(W, 4);
- items[0] = text(try std.fmt.allocPrint(a, "Change password · {s}", .{s.target[0..s.target_len]}), 16, false);
+ items[0] = panel.sectionTitle(try std.fmt.allocPrint(a, "Change password · {s}", .{s.target[0..s.target_len]}));
items[1] = try secretInputRowFocus(a, "New password", &s.password, "Enter new password", &s.password_field);
items[2] = try secretInputRow(a, "Confirm", &s.confirm_password, "Confirm new password");
items[3] = try formButtons(a, cc, "Cancel", 0, cancelFormClicked, "Save password", 0, changePasswordSubmit);
@@ -332,7 +332,7 @@ fn buildPasswordForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator
fn buildDeleteForm(s: *Section, cc: *panel.ControlCenter, a: std.mem.Allocator) !W {
const items = try a.alloc(W, 3);
- items[0] = text(try std.fmt.allocPrint(a, "Delete {s}?", .{s.target[0..s.target_len]}), 16, false);
+ items[0] = panel.sectionTitle(try std.fmt.allocPrint(a, "Delete {s}?", .{s.target[0..s.target_len]}));
items[1] = text("Choose whether to keep the home folder or remove its files.", 12, true);
items[2] = try formButtons(a, cc, "Keep home", 0, deleteKeepHomeClicked, "Delete files", 0, deleteFilesClicked);
return buildCard(a, items);
diff --git a/src/delete_dialog.zig b/src/delete_dialog.zig
index cb1e7e7..3d72c16 100644
--- a/src/delete_dialog.zig
+++ b/src/delete_dialog.zig
@@ -116,6 +116,14 @@ pub const State = struct {
dialog.paintWindowTitle(r, layer.local(), if (self.empty_trash) "Empty Trash?" else if (self.paths.items.len > 1) "Delete items?" else if (self.folder) "Delete folder?" else "Delete file?", .trash, null);
const hover = g.target(mx, my);
button.paint(r, g.close, .{ .variant = .chrome, .icon = .close, .label = "Close" }, .{ .pointer = if (hover == .close) .hover else .idle });
+ // The body is the app surface: it takes the app's foreground, not the dark chrome's.
+ const app = theme.global.forApp();
+ t.fg = app.window_fg;
+ t.dim = app.window_dim;
+ t.field_bg = app.field_bg;
+ t.field_border = app.field_border;
+ t.surface_hover = app.surface_hover;
+ r.palette = t;
r.drawText(16, g.header + 16, g.width - 32, 24, .{
.content = if (self.permanent) "This cannot be undone." else if (self.paths.items.len == 1) "You can restore it later from Trash." else "You can restore them later from Trash.",
.font_size = shell_ui.textSize(),
diff --git a/src/desktop/grid.zig b/src/desktop/grid.zig
index f89f52c..107a86e 100644
--- a/src/desktop/grid.zig
+++ b/src/desktop/grid.zig
@@ -2,6 +2,7 @@ const std = @import("std");
pub const width = 96;
pub const height = 112; // 8 + 56 + 8 + 2*16 + 8: two readable label lines.
pub const margin = 24;
+pub const left_margin = 8; // cells carry their own padding, so the leftmost column may sit close to the edge.
pub const Cell = struct { col: i32 = 0, row: i32 = 0 };
pub const Rect = struct {
x: i32,
@@ -24,7 +25,7 @@ pub const Grid = struct {
return @max(1, @divFloor(g.h - margin - g.top - g.bottom, height));
}
pub fn cols(g: Grid) i32 {
- return @max(1, @divFloor(g.w - 2 * margin, width));
+ return @max(1, @divFloor(g.w - margin - left_margin, width));
}
pub fn rect(g: Grid, position: Cell) Rect {
return .{ .x = g.w - margin - (position.col + 1) * width, .y = g.top + margin + position.row * height };
@@ -37,6 +38,11 @@ pub const Grid = struct {
return .{ .col = @divFloor(n, g.rows()), .row = @mod(n, g.rows()) };
}
};
+test "leftmost column sits near the left edge" {
+ const g = Grid{ .w = 1280, .h = 720 };
+ const r = g.rect(.{ .col = g.cols() - 1 });
+ try std.testing.expect(r.x >= 0 and r.x < width - margin);
+}
test "grid flows down then left and avoids the panel" {
const g = Grid{ .w = 1280, .h = 720 };
try std.testing.expectEqual(Cell{ .col = 1, .row = 0 }, g.cell(@intCast(g.rows())));
diff --git a/src/dock_drag.zig b/src/dock_drag.zig
index e4219ab..7bfc092 100644
--- a/src/dock_drag.zig
+++ b/src/dock_drag.zig
@@ -1,12 +1,15 @@
-//! Dragging an application out of the start menu onto the dock pins it there.
+//! Dragging an application out of the start menu onto the dock pins it there,
+//! and dragging a pinned icon along the dock moves its pin.
//!
//! The menu and the dock are both drawn by the compositor, so this is not a
//! wl_data_device drag (`desktop_drop.zig` is that): a press on an application
-//! row or card arms it, moving `threshold` pixels starts it, and the release
-//! over a dock drops. Starting the drag makes the menu forget the press, so
-//! its release is no click and nothing launches. The dock under the pointer
-//! shows the gap the application would take; Escape and closing the menu
-//! abandon the drag.
+//! row or card, or on a pinned dock icon, arms it, moving `threshold` pixels
+//! starts it, and the release over a dock drops. Starting a menu drag makes the
+//! menu forget the press, so its release is no click and nothing launches. A
+//! pinned icon acts on release instead (`Dock.clickPin`): pressed and released
+//! in place it is a click, dragged it moves. The dock under the pointer shows
+//! the gap the application would take; Escape and closing the menu abandon the
+//! drag.
const std = @import("std");
const wlr = @import("wlroots");
const ui = @import("ui");
@@ -18,10 +21,13 @@ const Self = @This();
/// Logical pixels the pointer travels before a press becomes a drag.
const threshold = 8;
+const Source = enum { menu, dock };
/// The dragged icon: a tile of `tile` px around an image of `image` px.
const tile = 48;
const image = 38;
+/// Where the drag began: an application in the start menu, or a pinned icon.
+source: Source = .menu,
id_bytes: [512]u8 = undefined,
id_len: usize = 0,
icon_bytes: [256]u8 = undefined,
@@ -41,7 +47,16 @@ fn ignoreInput(_: *wlr.SceneBuffer, _: *f64, _: *f64) callconv(.c) bool {
/// The press that just reached the menu went down on `app_id`'s row or card.
pub fn arm(self: *Self, input: *const Input, app_id: []const u8, icon: ?[]const u8, scale: f32) void {
- self.* = .{ .scale = scale, .origin_x = input.cursor.x, .origin_y = input.cursor.y };
+ self.armFrom(.menu, input, app_id, icon, scale);
+}
+
+/// The press that just reached the dock went down on a pinned icon.
+pub fn armReorder(self: *Self, input: *const Input, app_id: []const u8, icon: ?[]const u8, scale: f32) void {
+ self.armFrom(.dock, input, app_id, icon, scale);
+}
+
+fn armFrom(self: *Self, source: Source, input: *const Input, app_id: []const u8, icon: ?[]const u8, scale: f32) void {
+ self.* = .{ .source = source, .scale = scale, .origin_x = input.cursor.x, .origin_y = input.cursor.y };
if (app_id.len == 0 or app_id.len > self.id_bytes.len) return;
@memcpy(self.id_bytes[0..app_id.len], app_id);
self.id_len = app_id.len;
@@ -57,6 +72,11 @@ pub fn active(self: *const Self) bool {
return self.dragging;
}
+/// A pinned icon is being dragged along the dock.
+pub fn reordering(self: *const Self) bool {
+ return self.dragging and self.source == .dock;
+}
+
fn appId(self: *const Self) []const u8 {
return self.id_bytes[0..self.id_len];
}
@@ -73,12 +93,22 @@ pub fn motion(self: *Self, input: *Input) bool {
const dx = input.cursor.x - self.origin_x;
const dy = input.cursor.y - self.origin_y;
if (dx * dx + dy * dy < threshold * threshold) return false;
- const menu = input.open_start_menu orelse {
- self.* = .{};
- return false;
- };
+ switch (self.source) {
+ .menu => {
+ const menu = input.open_start_menu orelse {
+ self.* = .{};
+ return false;
+ };
+ menu.cancelPress();
+ },
+ // The tile stands for the icon now: nothing on the dock stays hovered
+ // (its tooltip would come up under the tile).
+ .dock => {
+ var docks = input.server.outputs.iterator(.forward);
+ while (docks.next()) |output| output.dock.leave();
+ },
+ }
self.dragging = true;
- menu.cancelPress();
self.createIcon(input);
}
if (self.node) |node| node.node.setPosition(
@@ -94,13 +124,20 @@ pub fn motion(self: *Self, input: *Input) bool {
/// A button went up. True when it ended a drag, which the menu must not see.
pub fn release(self: *Self, input: *Input, button: u32) bool {
if (!self.armed or button != Input.btn_left) return false;
- const dragging = self.dragging;
- if (dragging) {
- if (self.dropTarget(input)) |drop| drop.output.dock.pinApp(self.appId(), drop.slot);
- self.markDocks(input, true);
- }
+ const held = self.*;
+ self.markDocks(input, true);
self.finish();
- return dragging;
+ if (held.dragging) {
+ // `held` is the drag as it was; `self` is clear again before the dock acts.
+ if (held.dropTarget(input)) |drop| switch (held.source) {
+ .menu => drop.output.dock.pinApp(held.appId(), drop.slot),
+ .dock => drop.output.dock.movePin(held.appId(), drop.slot),
+ };
+ } else if (held.source == .dock) {
+ var docks = input.server.outputs.iterator(.forward);
+ while (docks.next()) |output| output.dock.clickPin(input.cursor.x, input.cursor.y, held.appId());
+ }
+ return held.dragging;
}
/// Abandons a drag in progress, or a press that might have become one.
@@ -118,11 +155,13 @@ const Drop = struct { output: *Output, slot: usize };
/// The dock under the pointer, unless the menu itself is.
fn dropTarget(self: *const Self, input: *const Input) ?Drop {
- _ = self;
if (input.open_start_menu) |menu| if (menu.containsPoint(input.cursor.x, input.cursor.y)) return null;
var it = input.server.outputs.iterator(.forward);
while (it.next()) |output| {
- if (output.dock.dropSlotAt(input.cursor.x, input.cursor.y)) |slot| return .{ .output = output, .slot = slot };
+ const slot = output.dock.dropSlotAt(input.cursor.x, input.cursor.y) orelse continue;
+ // A pin dropped back where it is has nowhere new to go: no marker.
+ if (self.source == .dock and output.dock.staysPut(self.appId(), slot)) continue;
+ return .{ .output = output, .slot = slot };
}
return null;
}
@@ -149,7 +188,17 @@ fn createIcon(self: *Self, input: *Input) void {
r.fillRect(0, 0, tile, tile, .{ .color = bg, .radius = 12, .border_width = 1, .border_color = pal.accent });
const inset: f32 = (tile - image) / 2;
var drawn = false;
- if (self.has_icon) {
+ if (self.source == .dock) {
+ // The dock already holds the icon it shows for this pin.
+ var docks = server.outputs.iterator(.forward);
+ while (docks.next()) |output| {
+ const icon = output.dock.pinIcon(self.appId()) orelse continue;
+ r.drawImageSmooth(inset, inset, image, image, 0, .{ .pixels = icon.pixels, .width = icon.size, .height = icon.size });
+ drawn = true;
+ break;
+ }
+ }
+ if (!drawn and self.has_icon) {
// The menu showed it at one of these sizes, so it is usually cached.
for ([_]i32{ 48, image }) |logical| {
const lookup = server.iconLookup(self.icon_bytes[0..self.icon_len], geometry.devicePixels(logical, self.scale));
diff --git a/src/files/app.zig b/src/files/app.zig
index e1d307d..2479cdc 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -674,7 +674,7 @@ pub const App = struct {
const width: f64 = @floatFromInt(self.sidebarWidth());
if (self.mouse_x < 0 or self.mouse_x >= width) return null;
if (self.sidebarScrollbar()) |bar| if (self.mouse_x >= @as(f64, bar.track.x)) return null;
- if (self.mouse_y < @as(f64, @floatFromInt(self.contentTop())) or self.mouse_y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) return null;
+ if (self.mouse_y < @as(f64, @floatFromInt(self.contentTop())) or self.mouse_y >= @as(f64, @floatFromInt(self.h - self.sidebarFooter()))) return null;
for (0..self.rowCount()) |i| {
if (!self.placeVisible(i)) continue;
const row = self.placeRect(i);
@@ -753,7 +753,7 @@ pub const App = struct {
self.nav_hover.setTarget(now, if (self.hoveredPlace()) |i| .{ .col = 0, .row = @intCast(i) } else null);
// Rows are at least 32 px apart, so this is at most a pixel.
if (self.nav_hover.step(now, pixel, pixel / 32)) {
- const side: header.Rect = .{ .x = 0, .y = @floatFromInt(self.contentTop()), .w = @floatFromInt(self.sidebarWidth()), .h = @floatFromInt(self.h - self.contentTop() - self.footerHeight()) };
+ const side: header.Rect = .{ .x = 0, .y = @floatFromInt(self.contentTop()), .w = @floatFromInt(self.sidebarWidth()), .h = @floatFromInt(self.h - self.contentTop() - self.sidebarFooter()) };
self.damageHighlight(side, if (before.alpha > 0) self.navHighlight(before) else null, if (self.nav_hover.frame.alpha > 0) self.navHighlight(self.nav_hover.frame) else null);
}
} else self.nav_hover.reset();
@@ -2155,6 +2155,11 @@ pub const App = struct {
pub fn footerHeight(self: *const App) i32 {
return if (self.chooser) |opts| (if (self.w >= 800) @as(i32, 88) else 114) + @as(i32, @intCast(opts.choices.len)) * 36 else 26;
}
+ /// What the sidebar gives up at the bottom: nothing, so it reaches the
+ /// window edge beside the status bar; the chooser's panel spans the width.
+ fn sidebarFooter(self: *const App) i32 {
+ return if (self.chooser != null) self.footerHeight() else 0;
+ }
fn contentTop(self: *App) i32 {
return header.height(self.w, self.inRepository());
}
@@ -2205,7 +2210,7 @@ pub const App = struct {
fn sidebarDivider(self: *App) ?splitter.Geometry {
if (self.w < 500 or self.sidebarWidth() < 160) return null;
- return .{ .x = @floatFromInt(self.sidebarWidth()), .y = @floatFromInt(self.contentTop()), .h = @floatFromInt(@max(0, self.h - self.contentTop() - self.footerHeight())) };
+ return .{ .x = @floatFromInt(self.sidebarWidth()), .y = @floatFromInt(self.contentTop()), .h = @floatFromInt(@max(0, self.h - self.contentTop() - self.sidebarFooter())) };
}
fn overSidebarDivider(self: *App, x: f64, y: f64) bool {
@@ -2254,7 +2259,7 @@ pub const App = struct {
}
fn clampSidebarScroll(self: *App) void {
- self.sidebar_scroll = std.math.clamp(self.sidebar_scroll, 0, @max(0, self.sidebarExtent() - (self.h - self.footerHeight())));
+ self.sidebar_scroll = std.math.clamp(self.sidebar_scroll, 0, @max(0, self.sidebarExtent() - (self.h - self.sidebarFooter())));
}
fn scrollbarGutter(self: *const App) i32 {
@@ -2856,7 +2861,7 @@ pub const App = struct {
fn placeAt(self: *App, x: f64, y: f64) ?usize {
if (x < 0 or x >= @as(f64, @floatFromInt(self.sidebarWidth())) or
- y < @as(f64, @floatFromInt(self.contentTop())) or y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) return null;
+ y < @as(f64, @floatFromInt(self.contentTop())) or y >= @as(f64, @floatFromInt(self.h - self.sidebarFooter()))) return null;
if (self.sidebarScrollbar()) |bar| {
if (bar.overTrack(@floatCast(x), @floatCast(y))) return null;
}
@@ -2918,7 +2923,7 @@ pub const App = struct {
fn pinSlotAt(self: *App, x: f64, y: f64) ?usize {
if (self.dialog != null) return null;
if (x < 0 or x >= @as(f64, @floatFromInt(self.sidebarWidth()))) return null;
- if (y < @as(f64, @floatFromInt(self.contentTop())) or y >= @as(f64, @floatFromInt(self.h - self.footerHeight()))) return null;
+ if (y < @as(f64, @floatFromInt(self.contentTop())) or y >= @as(f64, @floatFromInt(self.h - self.sidebarFooter()))) return null;
if (self.sidebarScrollbar()) |bar| {
if (x >= @as(f64, bar.track.x)) return null;
}
@@ -2932,7 +2937,7 @@ pub const App = struct {
fn setPinDrop(self: *App, slot: ?usize) void {
if (std.meta.eql(self.pin_drop, slot)) return;
- const area: header.Rect = .{ .x = 0, .y = @floatFromInt(self.contentTop()), .w = @floatFromInt(self.sidebarWidth()), .h = @floatFromInt(self.h - self.contentTop() - self.footerHeight()) };
+ const area: header.Rect = .{ .x = 0, .y = @floatFromInt(self.contentTop()), .w = @floatFromInt(self.sidebarWidth()), .h = @floatFromInt(self.h - self.contentTop() - self.sidebarFooter()) };
for ([_]?usize{ self.pin_drop, slot }) |gap| {
const at = gap orelse continue;
self.damageHighlight(area, .{ .x = 0, .y = self.pinBoundary(at) - 6, .w = area.w, .h = 12 }, null);
@@ -3182,7 +3187,6 @@ pub const App = struct {
if (self.device_list.items.len == 0) return;
setSource(cr, ui_theme.global.sidebarForeground());
drawText(cr, "DEVICES", 24, @floatFromInt(self.placeY(self.deviceBase()) - 12), shell_ui.headingSize(), true);
- const accent = ui_theme.shellPalette().accent;
const hovered = self.hoverKey();
for (self.device_list.items, 0..) |*volume, k| {
const index = self.deviceBase() + k;
@@ -3191,12 +3195,7 @@ pub const App = struct {
const alpha: f32 = if (mounted) 1 else 0.5;
if (self.placeActive(index)) {
const row = self.placeRect(index);
- roundedRect(cr, row.x, row.y, row.w, row.h, 5);
- setSource(cr, ui_theme.global.sidebarSelected());
- c.cairo_fill(cr);
- roundedRect(cr, 10, y + 3, 3, 24, 1.5);
- setSource(cr, accent);
- c.cairo_fill(cr);
+ shell_ui.drawSidebarSelected(cr, .{ .x = @floatCast(row.x), .y = @floatCast(row.y), .w = @floatCast(row.w), .h = @floatCast(row.h) });
}
if (shell_ui.Layer.begin(cr, .{ .x = 21, .y = @floatCast(y + 3), .w = 24, .h = 24 })) |icon_layer| {
var layer = icon_layer;
@@ -3252,7 +3251,7 @@ pub const App = struct {
fn sidebarScrollbar(self: *App) ?scrollbar.Geometry {
const width = self.sidebarWidth();
if (width == 0) return null;
- const viewport: f32 = @floatFromInt(self.h - self.contentTop() - self.footerHeight());
+ const viewport: f32 = @floatFromInt(self.h - self.contentTop() - self.sidebarFooter());
const gutter: f32 = @floatFromInt(self.scrollbarGutter());
const track: scrollbar.Rect = .{ .x = @as(f32, @floatFromInt(width)) - gutter, .y = @floatFromInt(self.contentTop()), .w = gutter, .h = viewport };
return scrollbar.Geometry.compute(.vertical, track, viewport, @floatFromInt(self.sidebarExtent() - self.contentTop()), @floatFromInt(self.sidebar_scroll));
@@ -3331,9 +3330,8 @@ pub const App = struct {
const content_width = if (bar) |b| @as(f64, b.track.x) else @as(f64, @floatFromInt(self.sidebarTargetWidth()));
c.cairo_save(cr);
defer c.cairo_restore(cr);
- c.cairo_rectangle(cr, 0, @floatFromInt(self.contentTop()), width, @floatFromInt(self.h - self.contentTop() - self.footerHeight()));
+ c.cairo_rectangle(cr, 0, @floatFromInt(self.contentTop()), width, @floatFromInt(self.h - self.contentTop() - self.sidebarFooter()));
c.cairo_clip(cr);
- const accent = ui_theme.shellPalette().accent;
setSource(cr, ui_theme.global.app_sidebar);
// The sidebar's alpha describes the window, not a tint over app_bg.
c.cairo_set_operator(cr, c.CAIRO_OPERATOR_SOURCE);
@@ -3364,12 +3362,7 @@ pub const App = struct {
const active = std.mem.eql(u8, path, self.history.current);
if (active) {
const row = self.placeRect(i);
- roundedRect(cr, row.x, row.y, row.w, row.h, 5);
- setSource(cr, ui_theme.global.sidebarSelected());
- c.cairo_fill(cr);
- roundedRect(cr, 10, y + 3, 3, 24, 1.5);
- setSource(cr, accent);
- c.cairo_fill(cr);
+ shell_ui.drawSidebarSelected(cr, .{ .x = @floatCast(row.x), .y = @floatCast(row.y), .w = @floatCast(row.w), .h = @floatCast(row.h) });
}
setSource(cr, withAlpha(ui_theme.global.app_icon, alpha));
if (self.drawPackPlaceIcon(cr, i, y, alpha)) {
@@ -3951,7 +3944,7 @@ pub const App = struct {
if (i < 4 and self.listColumn(i).contains(x, y)) return 400 + i;
}
}
- if (x >= 0 and x < @as(f64, @floatFromInt(self.sidebarWidth())) and y >= @as(f64, @floatFromInt(self.contentTop())) and y < @as(f64, @floatFromInt(self.h - self.footerHeight()))) {
+ if (x >= 0 and x < @as(f64, @floatFromInt(self.sidebarWidth())) and y >= @as(f64, @floatFromInt(self.contentTop())) and y < @as(f64, @floatFromInt(self.h - self.sidebarFooter()))) {
if (self.ejectAt(x, y)) |k| return 700 + k;
for (0..self.rowCount()) |i| {
if (!self.placeVisible(i)) continue;
@@ -4141,7 +4134,7 @@ pub const App = struct {
}
fn wheelMax(self: *App) i32 {
- return if (self.wheel_sidebar) @max(0, self.sidebarExtent() - (self.h - self.footerHeight())) else self.maxScroll();
+ return if (self.wheel_sidebar) @max(0, self.sidebarExtent() - (self.h - self.sidebarFooter())) else self.maxScroll();
}
pub fn handleWheel(self: *App, delta_px: f64, now: i64) void {
@@ -4203,7 +4196,7 @@ pub const App = struct {
self.menu = null;
const step: i32 = @intFromFloat(delta_px);
if (self.mouse_x < @as(f64, @floatFromInt(self.sidebarWidth())) and self.mouse_y >= @as(f64, @floatFromInt(self.contentTop()))) {
- const max_sidebar = @max(0, self.sidebarExtent() - (self.h - self.footerHeight()));
+ const max_sidebar = @max(0, self.sidebarExtent() - (self.h - self.sidebarFooter()));
const next = std.math.clamp(self.sidebar_scroll + step, 0, max_sidebar);
if (next != self.sidebar_scroll) self.invalidate();
self.sidebar_scroll = next;
@@ -5156,7 +5149,7 @@ pub const App = struct {
.empty_trash => self.openEmptyTrashDialog(),
.unpin => {
self.unpinned_places |= @as(u8, 1) << @as(u3, @intCast(self.menu_place - places_start));
- self.sidebar_scroll = std.math.clamp(self.sidebar_scroll, 0, @max(0, self.sidebarExtent() - (self.h - self.footerHeight())));
+ self.sidebar_scroll = std.math.clamp(self.sidebar_scroll, 0, @max(0, self.sidebarExtent() - (self.h - self.sidebarFooter())));
self.nav_hover = .{};
self.savePreferences();
},
@@ -6057,15 +6050,17 @@ pub const App = struct {
fn renderStatusBar(self: *App, cr: *c.cairo_t, h_f: f64) void {
const w_f = @as(f64, @floatFromInt(self.w));
const y = h_f - 26;
+ // The sidebar runs to the bottom edge; the bar sits beside it.
+ const x0: f64 = @floatFromInt(self.sidebarWidth());
const accent = ui_theme.shellPalette().accent;
setSource(cr, ui_theme.global.app_bar);
- c.cairo_rectangle(cr, 0, y, w_f, 26);
+ c.cairo_rectangle(cr, x0, y, w_f - x0, 26);
c.cairo_fill(cr);
setSource(cr, ui_theme.global.app_divider);
c.cairo_set_line_width(cr, 1);
- c.cairo_move_to(cr, 0, y + 0.5);
+ c.cairo_move_to(cr, x0, y + 0.5);
c.cairo_line_to(cr, w_f, y + 0.5);
c.cairo_stroke(cr);
@@ -6126,7 +6121,7 @@ pub const App = struct {
}
}
- drawText(cr, status_text, 14, y + 17, shell_ui.statusSize(), false);
+ drawText(cr, status_text, x0 + 14, y + 17, shell_ui.statusSize(), false);
}
fn renderDialog(self: *App, cr: *c.cairo_t) void {
@@ -6600,8 +6595,9 @@ 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 };
+ // Exercise the illuminated selected row and rounder highlights, too.
+ ui_theme.global.app_sidebar_selected_marker = .{ 1, 0.95, 0.84, 1 };
+ ui_theme.global.app_sidebar_item_radius = 10;
ui_theme.global.app_sidebar[3] = 0.5;
const before = anim.currentSettings();
defer anim.applySettings(before);
@@ -7186,7 +7182,7 @@ test "sidebar divider resizes within limits without selecting or sorting" {
try std.testing.expect(!app.overSidebarDivider(340, y));
app.menu = null;
try std.testing.expect(!app.overSidebarDivider(340, 20));
- try std.testing.expect(!app.overSidebarDivider(340, @floatFromInt(app.h - 1)));
+ try std.testing.expect(app.overSidebarDivider(340, @floatFromInt(app.h - 1)));
app.resize(360, 540);
app.stepLayout(2000);
app.stepLayout(3000);
diff --git a/src/ipc/animations.zig b/src/ipc/animations.zig
index 02852d0..d67bc6c 100644
--- a/src/ipc/animations.zig
+++ b/src/ipc/animations.zig
@@ -215,7 +215,7 @@ fn captureWindow(
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_motion, if (toplevel.launch_origin != null) .window_launch else .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);
try anim.captureIfLive(allocator, list, &toplevel.move_y, .window_move, now_ms);
diff --git a/src/ipc/handlers.zig b/src/ipc/handlers.zig
index 48bafb2..4c08312 100644
--- a/src/ipc/handlers.zig
+++ b/src/ipc/handlers.zig
@@ -2342,6 +2342,22 @@ pub fn buildTaskbarWidgetTree(
});
}
+ if (bar.itemBox(.power)) |pbox| {
+ try widgets.append(allocator, .{
+ .id = widgets.items.len + 1,
+ .parent_index = 0,
+ .role = "button",
+ .name = "power",
+ .path = "taskbar/power",
+ .semantic_id = "btn_Power",
+ .label = "Power",
+ .box = .{ .x = pbox.x - bar.box.x, .y = pbox.y - bar.box.y, .width = pbox.width, .height = pbox.height },
+ .global_box = .{ .x = pbox.x, .y = pbox.y, .width = pbox.width, .height = pbox.height },
+ .visible = true,
+ .is_disabled = false,
+ });
+ }
+
// App tray items
if (server.tray) |_| {
for (0..bar.appTrayCount()) |i| {
diff --git a/src/launch_feedback.zig b/src/launch_feedback.zig
index 259f441..a759584 100644
--- a/src/launch_feedback.zig
+++ b/src/launch_feedback.zig
@@ -6,6 +6,9 @@
//! existing window with its token, when its process fails, or after
//! `timeout_ms`. Launchers that exit successfully (single-instance handoff,
//! wrappers) keep waiting for the window.
+//!
+//! A launch can carry where it was started from (a dock icon, `origin`): the
+//! window that ends it grows out of that box as it opens.
const std = @import("std");
const wl = @import("wayland").server.wl;
const Server = @import("Server.zig");
@@ -17,6 +20,14 @@ const Self = @This();
pub const timeout_ms = 15_000;
const max_launches = 16;
+/// A layout-space box the launched window grows out of.
+pub const Origin = struct {
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+};
+
pub const Spec = struct {
pid: i32 = 0,
token: ?[]const u8 = null,
@@ -33,6 +44,7 @@ const Launch = struct {
/// Windows with this id or lower existed before the launch.
after_id: u64,
deadline_ms: i64,
+ origin: ?Origin,
};
fn Str(comptime n: usize) type {
@@ -57,6 +69,9 @@ server: *Server = undefined,
launches: [max_launches]Launch = undefined,
len: usize = 0,
timer: ?*wl.EventSource = null,
+/// Set by a launcher just before it launches (`setOrigin`); the next `begin`
+/// takes it.
+pending_origin: ?Origin = null,
pub fn init(self: *Self, server: *Server) void {
self.* = .{ .server = server };
@@ -72,6 +87,16 @@ pub fn busy(self: *const Self) bool {
return self.len > 0;
}
+/// The next launch started from `origin`. Call `clearOrigin` once the launch
+/// call returns, in case it failed before `begin`.
+pub fn setOrigin(self: *Self, origin: Origin) void {
+ self.pending_origin = origin;
+}
+
+pub fn clearOrigin(self: *Self) void {
+ self.pending_origin = null;
+}
+
pub fn begin(self: *Self, spec: Spec) void {
// Full: the oldest launch is the least likely to still be starting.
if (self.len == max_launches) self.removeAt(0);
@@ -83,29 +108,36 @@ pub fn begin(self: *Self, spec: Spec) void {
.has_wm_class = spec.startup_wm_class != null,
.after_id = self.server.next_toplevel_id -| 1,
.deadline_ms = Toplevel.nowMs() + timeout_ms,
+ .origin = self.pending_origin,
};
+ self.pending_origin = null;
self.len += 1;
self.armTimer();
if (self.len == 1) self.server.input.refreshBusyCursor();
}
-pub fn windowMapped(self: *Self, toplevel: *Toplevel) void {
- if (self.len == 0) return;
+/// Ends the launches `toplevel` belongs to and returns where the first of them
+/// that has one was started from.
+pub fn windowMapped(self: *Self, toplevel: *Toplevel) ?Origin {
+ if (self.len == 0) return null;
const pid = toplevel.clientPid() orelse 0;
const app_id = toplevel.appId();
var i: usize = 0;
var changed = false;
+ var origin: ?Origin = null;
while (i < self.len) {
const launch = &self.launches[i];
const ours = toplevel.id > launch.after_id and
((launch.pid > 0 and pid > 0 and placeholder_match.matchesPidChain(pid, launch.pid)) or
placeholder_match.matchesAppId(app_id, if (launch.has_wm_class) launch.wm_class.get() else null, launch.desktop_id.get()));
if (ours) {
+ if (origin == null) origin = launch.origin;
self.removeAt(i);
changed = true;
} else i += 1;
}
if (changed) self.finish();
+ return origin;
}
/// End the launch holding this activation token: the app used it (it is up,
diff --git a/src/osd.zig b/src/osd.zig
index 0cbdaf9..7406f15 100644
--- a/src/osd.zig
+++ b/src/osd.zig
@@ -20,6 +20,9 @@ last_level: f32 = 0,
fade_start: ?i64 = null,
scale: f32 = 0,
const Osd = @This();
+/// Gap between the OSD and the bottom of the work area, or the top of a dock.
+const edge_gap = 20;
+const dock_gap = 12;
pub fn show(server: *Server, state: State) void {
const output = server.getDefaultOutput() orelse return;
@@ -119,13 +122,21 @@ fn present(self: *Osd, output: *Output, state: State, restart: bool) !void {
}
}
+/// Bottom centre of the work area, or just above a dock on the bottom edge,
+/// auto-hiding or not, so the two never overlap.
fn position(self: *Osd, output: *Output) void {
const state = self.state orelse return;
const box = output.usableBox();
const width = @min(painter.width(state.kind), box.width);
const height = @min(painter.height, box.height);
+ var bottom = box.y + box.height - edge_gap;
+ if (output.server.config.compositor.dock_position == .bottom) {
+ const area = output.dockAreaBox();
+ const dock = @import("Dock.zig").footprint(output.server, area);
+ if (dock > 0) bottom = area.y + area.height - dock - dock_gap;
+ }
self.node.?.setDestSize(width, height);
- self.node.?.node.setPosition(box.x + @divTrunc(box.width - width, 2), box.y + @max(0, box.height - height - 20));
+ self.node.?.node.setPosition(box.x + @divTrunc(box.width - width, 2), @max(box.y, bottom - height));
}
pub fn tick(self: *Osd, output: *Output, now: i64) bool {
diff --git a/src/panel_buffer.zig b/src/panel_buffer.zig
index 406f3bc..2f422d8 100644
--- a/src/panel_buffer.zig
+++ b/src/panel_buffer.zig
@@ -10,6 +10,7 @@ const wlr = @import("wlroots");
const gpa = @import("main.zig").gpa;
const geometry = @import("geometry.zig");
const panel_present = @import("panel_present.zig");
+const panel_paint = @import("panel_paint.zig");
extern "c" fn wlr_buffer_finish(buffer: *wlr.Buffer) void;
@@ -23,6 +24,8 @@ pub const PanelBuffer = struct {
sensitive: bool = false,
/// Off for buffers made by `createUnpooled`, which never enter the pool.
pooled: bool = true,
+ /// What the pixels are, for `createRetained`; cleared for every other use.
+ stamp: panel_paint.Stamp = .{},
const drm_format_argb8888: u32 = 0x34325241;
@@ -74,18 +77,35 @@ pub const PanelBuffer = struct {
/// Cached panel backgrounds overwrite the whole buffer, so clearing it
/// first would be a redundant full-buffer write.
pub fn createUninitialized(logical_width: i32, logical_height: i32, scale: f32) !*PanelBuffer {
+ return take(logical_width, logical_height, scale, null);
+ }
+
+ /// Like `createUninitialized`, preferring the pooled buffer `owner` painted
+ /// last and keeping its `stamp` for `Background.paintIncremental`.
+ pub fn createRetained(logical_width: i32, logical_height: i32, scale: f32, owner: *const panel_paint.Background) !*PanelBuffer {
+ return take(logical_width, logical_height, scale, owner);
+ }
+
+ fn take(logical_width: i32, logical_height: i32, scale: f32, owner: ?*const panel_paint.Background) !*PanelBuffer {
const width = geometry.devicePixels(logical_width, scale);
const height = geometry.devicePixels(logical_height, scale);
const bytes: u64 = @as(u64, @intCast(width)) * @as(u64, @intCast(height)) * @sizeOf(u32);
+ var pick: ?*?*PanelBuffer = null;
for (&pool) |*slot| {
const recycled = slot.* orelse continue;
+ if (pick == null or (owner != null and recycled.stamp.owner == owner)) pick = slot;
+ }
+ if (pick) |slot| {
+ const recycled = slot.*.?;
const length: usize = @intCast(width * height);
+ if (owner == null or recycled.stamp.owner != owner) recycled.stamp = .{};
if (recycled.storage.len < length) {
// Grow geometrically during a resize; never resize a buffer
// until wlroots has released it into this pool.
const capacity = @max(length, recycled.storage.len + recycled.storage.len / 2);
recycled.storage = try gpa.realloc(recycled.storage, capacity);
+ recycled.stamp = .{};
panel_present.addAlloc(@as(u64, @intCast(capacity)) * @sizeOf(u32));
} else panel_present.addReuse(bytes);
slot.* = null;
diff --git a/src/panel_paint.zig b/src/panel_paint.zig
index a536045..ec7db9f 100644
--- a/src/panel_paint.zig
+++ b/src/panel_paint.zig
@@ -3,6 +3,23 @@
const std = @import("std");
const ui = @import("ui");
+/// What a pooled buffer holds: the panel that painted it last, and which of
+/// its paints. A buffer anything else painted carries none.
+pub const Stamp = struct {
+ owner: ?*const Background = null,
+ generation: u64 = 0,
+};
+
+/// Paint numbers are unique across panels, so a buffer painted by a panel
+/// since freed never matches one that took over its address.
+var next_generation: u64 = 0;
+
+/// Paints remembered per panel. Panels alternate between two pooled buffers,
+/// so a recycled one has usually missed a single paint.
+const history_len = 4;
+
+const Repair = union(enum) { all, none, box: ui.paint.ClipRect };
+
pub const Background = struct {
pixels: []u32 = &.{},
pixel_storage: []u32 = &.{},
@@ -15,6 +32,10 @@ pub const Background = struct {
content_palette: ?ui.theme.Theme = null,
/// Logical-pixel damage; null means the entire buffer was painted.
damage: ?ui.paint.ClipRect = null,
+ /// The last paints' generations and damage (null: everything), so a
+ /// recycled buffer is repaired only where it missed a change.
+ history: [history_len]struct { generation: u64 = 0, damage: ?ui.paint.ClipRect = null } = @splat(.{}),
+ painted: u64 = 0,
const Key = struct {
width: i32,
@@ -41,7 +62,12 @@ pub const Background = struct {
/// Own the last complete image independently of the buffers locked by
/// wlroots. Repair a fresh/recycled buffer from it, and only rasterize the
/// changed widget bounds. Repair pixels are not new scene damage.
- pub fn paintIncremental(bg: *Background, allocator: std.mem.Allocator, root: *ui.layout.Widget, renderer: *ui.paint.Renderer) void {
+ /// `stamp` is the buffer's (`PanelBuffer.createRetained`): with it, only
+ /// what the buffer missed since this panel last painted it is repaired.
+ /// Leave it null when something is drawn over the retained image.
+ pub fn paintIncremental(bg: *Background, allocator: std.mem.Allocator, root: *ui.layout.Widget, renderer: *ui.paint.Renderer, stamp: ?*Stamp) void {
+ const held: Stamp = if (stamp) |s| s.* else .{};
+ if (stamp) |s| s.* = .{};
const full = bg.invalid or bg.content.len != renderer.pixels.len or bg.key == null or
bg.content_scale != renderer.scale or !std.meta.eql(bg.content_palette, renderer.palette) or
bg.key.?.width != renderer.width or bg.key.?.height != renderer.height or
@@ -65,13 +91,12 @@ pub const Background = struct {
}
}
if (bg.damage) |damage| {
- @memcpy(renderer.pixels, bg.content);
- const stride: usize = @intCast(renderer.width);
- const x0: usize = @intFromFloat(@floor(damage.x * renderer.scale));
- const y0: usize = @intFromFloat(@floor(damage.y * renderer.scale));
- const x1: usize = @min(stride, @as(usize, @intFromFloat(@ceil((damage.x + damage.w) * renderer.scale))));
- const y1: usize = @min(@as(usize, @intCast(renderer.height)), @as(usize, @intFromFloat(@ceil((damage.y + damage.h) * renderer.scale))));
- for (y0..y1) |y| @memcpy(renderer.pixels[y * stride + x0 .. y * stride + x1], bg.pixels[y * stride + x0 .. y * stride + x1]);
+ switch (bg.missed(held)) {
+ .all => @memcpy(renderer.pixels, bg.content),
+ .none => {},
+ .box => |box| copyBox(renderer, renderer.pixels, bg.content, box),
+ }
+ copyBox(renderer, renderer.pixels, bg.pixels, damage);
const previous = renderer.damage_clip;
renderer.damage_clip = damage;
renderer.clean = false;
@@ -89,11 +114,40 @@ pub const Background = struct {
return;
};
}
- @memcpy(bg.content, renderer.pixels);
+ if (bg.damage) |damage| copyBox(renderer, bg.content, renderer.pixels, damage) else @memcpy(bg.content, renderer.pixels);
bg.invalid = false;
bg.content_scale = renderer.scale;
bg.content_palette = renderer.palette;
root.clearPaintDirty();
+ next_generation += 1;
+ bg.history[bg.painted % history_len] = .{ .generation = next_generation, .damage = bg.damage };
+ bg.painted += 1;
+ if (stamp) |s| s.* = .{ .owner = bg, .generation = next_generation };
+ }
+
+ /// Where a buffer stamped `held` differs from the retained image: the
+ /// union of the paints since its own, or all of it when unknown.
+ fn missed(bg: *const Background, held: Stamp) Repair {
+ if (held.owner != bg) return .all;
+ var result: ?ui.paint.ClipRect = null;
+ for (0..@min(bg.painted, history_len)) |back| {
+ const entry = bg.history[(bg.painted - 1 - back) % history_len];
+ if (entry.generation == held.generation) return if (result) |box| .{ .box = box } else .none;
+ const box = entry.damage orelse return .all;
+ addDamage(.{ .x = box.x, .y = box.y, .w = box.w, .h = box.h }, &result);
+ }
+ return .all;
+ }
+
+ /// Copies the device pixels under logical `box`, on the grid partial paints use.
+ fn copyBox(renderer: *const ui.paint.Renderer, dst: []u32, src: []const u32, box: ui.paint.ClipRect) void {
+ const stride: usize = @intCast(renderer.width);
+ const x0: usize = @intFromFloat(@floor(box.x * renderer.scale));
+ const y0: usize = @intFromFloat(@floor(box.y * renderer.scale));
+ const x1: usize = @min(stride, @as(usize, @intFromFloat(@ceil((box.x + box.w) * renderer.scale))));
+ const y1: usize = @min(@as(usize, @intCast(renderer.height)), @as(usize, @intFromFloat(@ceil((box.y + box.h) * renderer.scale))));
+ if (x0 >= x1) return;
+ for (y0..y1) |y| @memcpy(dst[y * stride + x0 .. y * stride + x1], src[y * stride + x0 .. y * stride + x1]);
}
fn addDamage(box: ui.layout.Widget.PaintBounds, result: *?ui.paint.ClipRect) void {
@@ -296,7 +350,7 @@ test "partial panel paint repairs recycled buffers with exact fractional-scale p
children[0].markDirty();
@memset(pixels, 0xdeadbeef);
var renderer = ui.paint.Renderer.init(pixels, width, height, scale);
- bg.paintIncremental(allocator, &root, &renderer);
+ bg.paintIncremental(allocator, &root, &renderer, null);
@memset(expected, 0);
var reference = ui.paint.Renderer.init(expected, width, height, scale);
reference.clean = true;
@@ -312,12 +366,41 @@ test "partial panel paint repairs recycled buffers with exact fractional-scale p
children[1].markPaintDirty();
@memset(pixels, 0xdeadbeef);
var partial = ui.paint.Renderer.init(pixels, width, height, scale);
- bg.paintIncremental(allocator, &root, &partial);
+ bg.paintIncremental(allocator, &root, &partial, null);
@memset(expected, 0);
var reference = ui.paint.Renderer.init(expected, width, height, scale);
reference.clean = true;
ui.paint.paint(&root, &reference);
try std.testing.expectEqualSlices(u32, expected, pixels);
+
+ // Two stamped buffers taking turns are repaired only where each
+ // missed a change: the button and the rect change on alternate paints,
+ // apart, so a missed one lies outside the current damage. Buffer 1
+ // misses two paints, then carries a stamp of another panel.
+ const other = try allocator.alloc(u32, pixels.len);
+ defer allocator.free(other);
+ const stranger: Background = .{};
+ var stamps: [2]Stamp = .{ .{}, .{} };
+ const buffers = [2][]u32{ pixels, other };
+ children[1].computed_x = 125;
+ children[1].markPaintDirty();
+ for ([_]usize{ 0, 1, 0, 0, 1, 1 }, 0..) |turn, i| {
+ if (i % 2 == 0) {
+ children[0].kind.button.state = if (children[0].kind.button.state == .hover) .idle else .hover;
+ children[0].markDirty();
+ } else {
+ children[1].kind.rect.color[1] += 0.1;
+ children[1].markPaintDirty();
+ }
+ if (i == 5) stamps[turn].owner = &stranger;
+ var stamped = ui.paint.Renderer.init(buffers[turn], width, height, scale);
+ bg.paintIncremental(allocator, &root, &stamped, &stamps[turn]);
+ @memset(expected, 0);
+ var whole = ui.paint.Renderer.init(expected, width, height, scale);
+ whole.clean = true;
+ ui.paint.paint(&root, &whole);
+ try std.testing.expectEqualSlices(u32, expected, buffers[turn]);
+ }
}
}
@@ -332,21 +415,21 @@ test "incremental panel allocation failure falls back to a complete paint" {
var pixels: [40 * 32]u32 = undefined;
var expected: [40 * 32]u32 = @splat(0);
var renderer = ui.paint.Renderer.init(&pixels, 40, 32, 1);
- bg.paintIncremental(allocator, &root, &renderer);
+ bg.paintIncremental(allocator, &root, &renderer, null);
var reference = ui.paint.Renderer.init(&expected, 40, 32, 1);
reference.clean = true;
ui.paint.paint(&root, &reference);
try std.testing.expectEqualSlices(u32, &expected, &pixels);
try std.testing.expect(bg.invalid);
failing.fail_index = std.math.maxInt(usize);
- bg.paintIncremental(allocator, &root, &renderer);
+ bg.paintIncremental(allocator, &root, &renderer, null);
try std.testing.expectEqualSlices(u32, &expected, &pixels);
try std.testing.expect(!bg.invalid);
failing.fail_index = failing.alloc_index;
const allocations = failing.alloc_index;
child[0].computed_x += 4;
child[0].markPaintDirty();
- bg.paintIncremental(allocator, &root, &renderer);
+ bg.paintIncremental(allocator, &root, &renderer, null);
@memset(&expected, 0);
reference.clean = true;
ui.paint.paint(&root, &reference);
diff --git a/src/power_menu.zig b/src/power_menu.zig
index f12a98a..7804b57 100644
--- a/src/power_menu.zig
+++ b/src/power_menu.zig
@@ -492,7 +492,7 @@ pub const PowerMenu = struct {
const t0 = panel_present.nowNs();
var renderer = ui.paint.Renderer.init(buf.pixels, buf.width, buf.height, scale);
- menu.background.paintIncremental(gpa, &menu.root, &renderer);
+ menu.background.paintIncremental(gpa, &menu.root, &renderer, null);
// Keep the moving outline out of the retained pixels. Each glide
// frame repairs the entire card strip before painting it again.
menu.paintHighlight(&renderer);
diff --git a/src/scene_data.zig b/src/scene_data.zig
index 8ff3390..72acc30 100644
--- a/src/scene_data.zig
+++ b/src/scene_data.zig
@@ -188,7 +188,7 @@ pub fn hitTest(server: *@import("Server.zig"), lx: f64, ly: f64) Hit {
break :blk .{ .calendar = .{ .calendar = calendar, .sx = local.x, .sy = local.y } };
},
.dock => |dock| blk: {
- const local = toNodeLocal(&dock.node.?.node, lx, ly);
+ const local = toNodeLocal(&dock.tree.?.node, lx, ly);
break :blk .{ .dock = .{ .dock = dock, .sx = local.x, .sy = local.y } };
},
.taskbar => |bar| blk: {
diff --git a/src/start_menu/panel.zig b/src/start_menu/panel.zig
index b205392..d46d385 100644
--- a/src/start_menu/panel.zig
+++ b/src/start_menu/panel.zig
@@ -1089,7 +1089,7 @@ pub const StartMenu = struct {
fn paintContent(menu: *StartMenu) void {
if (menu.panel_box.width <= 0 or menu.panel_box.height <= 0) return;
const scale = menu.wlr_output.scale;
- const buf = PanelBuffer.createUninitialized(menu.panel_box.width, menu.panel_box.height, scale) catch |err| {
+ const buf = PanelBuffer.createRetained(menu.panel_box.width, menu.panel_box.height, scale, &menu.background) catch |err| {
log.err("StartMenu.paintContent: could not create buffer: {}", .{err});
return;
};
@@ -1099,7 +1099,7 @@ pub const StartMenu = struct {
var renderer = ui.paint.Renderer.init(buf.pixels, buf.width, buf.height, scale);
renderer.palette = menuPalette();
ui.input.active_dispatcher = &menu.dispatcher;
- menu.background.paintIncremental(gpa, &menu.root, &renderer);
+ menu.background.paintIncremental(gpa, &menu.root, &renderer, &buf.stamp);
ui.input.active_dispatcher = null;
const elapsed_ns = panel_present.nowNs() -| t0;
diff --git a/src/ui/anim.zig b/src/ui/anim.zig
index 0f5f4f5..c03d892 100644
--- a/src/ui/anim.zig
+++ b/src/ui/anim.zig
@@ -33,6 +33,9 @@ pub const springs = struct {
pub const taskbar_hover = Spring{ .damping_ratio = 1.0, .stiffness = 1400, .epsilon = 1e-3 };
pub const start_button = taskbar_hover;
pub const titlebar_hover = taskbar_hover;
+ // A hovered dock icon pops past its zoom and settles back (~16% overshoot,
+ // peak at ~150 ms); leaving dips it just under rest the same way.
+ pub const dock_hover = Spring{ .damping_ratio = 0.5, .stiffness = 600, .epsilon = 1e-3 };
// The window-button chip trails the pointer: critically damped so it
// glides without overshoot, ~180 ms to cover most of a button pitch.
pub const titlebar_chip = Spring{ .damping_ratio = 1.0, .stiffness = 450, .epsilon = 1e-3 };
@@ -50,6 +53,9 @@ pub const springs = struct {
pub const osd_level = Spring{ .damping_ratio = 1.0, .stiffness = 1200, .epsilon = 1e-3 };
pub const toast_slide = Spring{ .damping_ratio = 0.8, .stiffness = 600, .epsilon = 1e-3 };
pub const window_open = Spring{ .damping_ratio = 0.85, .stiffness = 700, .epsilon = 1e-4 };
+ // A window launched from the dock grows out of its icon: slower than an
+ // ordinary open so the travel reads, with a touch of settle at the end.
+ pub const window_launch = Spring{ .damping_ratio = 0.88, .stiffness = 260, .epsilon = 1e-4 };
pub const window_move = Spring{ .damping_ratio = 1.0, .stiffness = 800, .epsilon = 1e-4 };
pub const window_peek = Spring{ .damping_ratio = 1.0, .stiffness = 1000, .epsilon = 1e-3 };
pub const camera_pan = Spring{ .damping_ratio = 1.0, .stiffness = 500, .epsilon = 0.5 };
@@ -72,6 +78,7 @@ pub const Target = enum {
panel_slide,
panel_scrim,
taskbar_hover,
+ dock_hover,
taskbar_press,
taskbar_flip,
start_button,
@@ -86,6 +93,7 @@ pub const Target = enum {
start_glide,
start_glide_fade,
window_open,
+ window_launch,
window_close,
window_move,
window_resize,
@@ -137,6 +145,7 @@ pub fn defaultSpec(target: Target) TargetSpec {
return switch (target) {
.panel_slide, .panel_scrim => .{ .curve = .{ .spring = springs.panel_slide } },
.taskbar_hover, .start_button, .titlebar_hover => .{ .curve = .{ .spring = springs.taskbar_hover } },
+ .dock_hover => .{ .curve = .{ .spring = springs.dock_hover } },
.titlebar_chip => .{ .curve = .{ .spring = springs.titlebar_chip } },
.titlebar_chip_fade => .{ .curve = .{ .spring = springs.titlebar_chip_fade } },
.start_glide => .{ .curve = .{ .spring = springs.start_glide } },
@@ -148,6 +157,7 @@ pub fn defaultSpec(target: Target) TargetSpec {
.osd_level => .{ .curve = .{ .spring = springs.osd_level } },
.toast_slide => .{ .curve = .{ .spring = springs.toast_slide } },
.window_open, .window_close => .{ .curve = .{ .spring = springs.window_open } },
+ .window_launch => .{ .curve = .{ .spring = springs.window_launch } },
.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 } } },
diff --git a/src/ui/cairo.zig b/src/ui/cairo.zig
index 278b069..42345a5 100644
--- a/src/ui/cairo.zig
+++ b/src/ui/cairo.zig
@@ -60,39 +60,50 @@ 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.
+/// Sidebar hover: a plain rounded fill at `alpha`.
pub fn drawSidebarHover(cr_any: *anyopaque, box: Rect, alpha: f32) void {
if (box.w <= 0 or box.h <= 0 or alpha <= 0) return;
const cr: *c.cairo_t = @ptrCast(cr_any);
+ sidebarRowPath(cr, box);
+ var fill = theme.global.sidebarHover();
+ fill[3] *= alpha;
+ setSource(cr, fill);
+ c.cairo_fill(cr);
+}
+
+/// The selected sidebar row: its fill and an accent bar, or with
+/// `app_sidebar_selected_marker` an illuminated leading edge. Everything stays
+/// inside the row, so the row's own damage covers it.
+pub fn drawSidebarSelected(cr_any: *anyopaque, box: Rect) void {
+ if (box.w <= 0 or box.h <= 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);
+ sidebarRowPath(cr, box);
+ setSource(cr, theme.global.sidebarSelected());
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 marker = theme.global.app_sidebar_selected_marker orelse {
+ c.cairo_new_path(cr);
+ const bar_h = @min(24, h);
+ roundedPath(cr, x, y + (h - bar_h) / 2, 3, bar_h, 1.5);
+ setSource(cr, accent);
+ c.cairo_fill(cr);
+ return;
+ };
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, 0, accent[0], accent[1], accent[2], accent[3] * 0.85);
+ c.cairo_pattern_add_color_stop_rgba(glow, 0.25, accent[0], accent[1], accent[2], accent[3] * 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_source_rgba(cr, marker[0], marker[1], marker[2], marker[3]);
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);
@@ -100,6 +111,20 @@ pub fn drawSidebarHover(cr_any: *anyopaque, box: Rect, alpha: f32) void {
c.cairo_stroke(cr);
}
+fn sidebarRowPath(cr: *c.cairo_t, box: Rect) void {
+ const radius = @min(theme.global.app_sidebar_item_radius, @min(box.w, box.h) / 2);
+ roundedPath(cr, box.x, box.y, box.w, box.h, radius);
+}
+
+fn roundedPath(cr: *c.cairo_t, x: f64, y: f64, w: f64, h: f64, radius: f64) void {
+ 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);
+}
+
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/measure.zig b/src/ui/measure.zig
index 300295c..ccac217 100644
--- a/src/ui/measure.zig
+++ b/src/ui/measure.zig
@@ -185,9 +185,9 @@ fn naturalSize(widget: *const Widget) Natural {
};
}
-fn textNatural(content: []const u8, family: layout.TextFamily, weight: u32, font_size: f32) Natural {
+pub fn textNatural(content: []const u8, family: layout.TextFamily, weight: u32, font_size: f32) Natural {
const font: text_mod.Font = switch (family) {
- .sans => if (weight >= 600) .manrope_bold else .manrope,
+ .sans => if (weight >= 700) .manrope_heavy else if (weight >= 600) .manrope_bold else .manrope,
.mono => if (weight >= 600) .mono_bold else .mono,
};
const w = text_mod.measureWidth(content, font, font_size, 1.0) catch 0;
diff --git a/src/ui/paint.zig b/src/ui/paint.zig
index ebbc468..b480b02 100644
--- a/src/ui/paint.zig
+++ b/src/ui/paint.zig
@@ -45,7 +45,7 @@ pub const Image = struct { pixels: []const u32, width: i32, height: i32 };
fn fontFor(style: TextStyle) text_mod.Font {
return switch (style.family) {
- .sans => if (style.weight >= 600) .manrope_bold else .manrope,
+ .sans => if (style.weight >= 700) .manrope_heavy else if (style.weight >= 600) .manrope_bold else .manrope,
.mono => if (style.weight >= 600) .mono_bold else .mono,
};
}
diff --git a/src/ui/text.zig b/src/ui/text.zig
index 18329c5..43e2827 100644
--- a/src/ui/text.zig
+++ b/src/ui/text.zig
@@ -26,10 +26,12 @@ pub const Font = enum {
manrope_bold,
mono,
mono_bold,
+ /// Bold (700), for headings above semibold labels and controls.
+ manrope_heavy,
fn bytes(font: Font) []const u8 {
return switch (font) {
- .manrope, .manrope_bold => @embedFile("manrope"),
+ .manrope, .manrope_bold, .manrope_heavy => @embedFile("manrope"),
.mono => @embedFile("jetbrains_mono_regular"),
.mono_bold => @embedFile("jetbrains_mono_bold"),
};
@@ -76,7 +78,8 @@ const color_load_flags: c_int = c.FT_LOAD_DEFAULT | c.FT_LOAD_COLOR;
var ft_library: c.FT_Library = null;
var faces: std.ArrayListUnmanaged(Face) = .empty;
-var chains: [4]std.ArrayListUnmanaged(u32) = .{ .empty, .empty, .empty, .empty };
+var chains: [font_count]std.ArrayListUnmanaged(u32) = @splat(.empty);
+const font_count = std.meta.fields(Font).len;
var coverage: std.AutoHashMapUnmanaged(u64, u32) = .empty;
const no_face = std.math.maxInt(u32);
@@ -95,13 +98,14 @@ fn preferredMono() []const u8 {
fn bundledWeight(font: Font) u32 {
return switch (font) {
.manrope_bold, .mono_bold => 600,
+ .manrope_heavy => 700,
else => 400,
};
}
fn genericFamilyZ(font: Font) [*:0]const u8 {
return switch (font) {
- .manrope, .manrope_bold => "sans-serif",
+ .manrope, .manrope_bold, .manrope_heavy => "sans-serif",
.mono, .mono_bold => "monospace",
};
}
@@ -171,8 +175,8 @@ fn ensureLibrary() !void {
}
fn ensureFaceTable() void {
- if (faces.items.len >= 4) return;
- const fonts = [_]Font{ .manrope, .manrope_bold, .mono, .mono_bold };
+ if (faces.items.len >= font_count) return;
+ const fonts = [_]Font{ .manrope, .manrope_bold, .mono, .mono_bold, .manrope_heavy };
for (fonts) |font| {
faces.append(gpa, .{
.source = .{ .bundled = font },
@@ -193,7 +197,7 @@ fn ensureChain(font: Font) void {
if (chains[idx].items.len != 0) return;
const preferred = switch (font) {
- .manrope, .manrope_bold => preferredSans(),
+ .manrope, .manrope_bold, .manrope_heavy => preferredSans(),
.mono, .mono_bold => preferredMono(),
};
const weight = bundledWeight(font);
@@ -632,7 +636,7 @@ var run_cache: std.HashMapUnmanaged(RunKey, Run, RunKeyContext, std.hash_map.def
/// `fitWithEllipsis` is done with its run before it shapes candidates).
const max_cached_runs = 4096;
-const GlyphKey = struct { face: u32, size: c.FT_F26Dot6, index: u32 };
+const GlyphKey = struct { face: u32, size: c.FT_F26Dot6, index: u32, italic: bool };
/// A rendered glyph, copied out of FreeType's own slot (which the next
/// FT_Load_Glyph would overwrite). `pixels` is 8-bit coverage, `cols` wide,
@@ -800,10 +804,16 @@ fn scaleBgra(src: []const u8, src_w: i32, src_h: i32, dst_w: i32, dst_h: i32) ?[
return dst;
}
-fn glyphBitmap(face: *Face, face_id: u32, index: u32) ?CachedGlyph {
- const key = GlyphKey{ .face = face_id, .size = face.set_size, .index = index };
+fn glyphBitmap(face: *Face, face_id: u32, index: u32, italic: bool) ?CachedGlyph {
+ const slant = italic and !face.color;
+ const key = GlyphKey{ .face = face_id, .size = face.set_size, .index = index, .italic = slant };
if (glyph_cache.get(key)) |cached| return cached;
+ // Manrope has no italic face. Slant the outline after hinting, keeping
+ // advances and baselines intact, and restore the shared face immediately.
+ var matrix: c.FT_Matrix = .{ .xx = 65536, .xy = 13930, .yx = 0, .yy = 65536 };
+ if (slant) c.FT_Set_Transform(face.ft_face, &matrix, null);
+ defer if (slant) c.FT_Set_Transform(face.ft_face, null, null);
const flags: c_int = if (face.color) color_load_flags else load_flags;
if (c.FT_Load_Glyph(face.ft_face, index, flags) != 0) return null;
if (c.FT_Render_Glyph(face.ft_face.*.glyph, c.FT_RENDER_MODE_NORMAL) != 0) return null;
@@ -868,7 +878,7 @@ pub fn warmGlyphs(font: Font, size_px: f32, scale: f32, chars: []const u8) !void
for (run.glyphs) |glyph| {
const face = ensureLoaded(glyph.face) catch continue;
applySize(face, size) catch continue;
- _ = glyphBitmap(face, glyph.face, glyph.index);
+ _ = glyphBitmap(face, glyph.face, glyph.index, false);
}
}
@@ -1012,6 +1022,8 @@ pub const DrawOptions = struct {
/// Center the visible glyph bounds rather than the font line metrics.
/// For standalone labels; editable fields retain their stable baseline.
center_ink: bool = false,
+ /// Synthetic italic; callers allow for horizontal ink overhang in `clip`.
+ italic: bool = false,
/// Buffer-pixel row of the baseline, instead of centring the line in
/// `rect`: for callers that place text by baseline (the Cairo clients,
/// through ui/cairo.zig).
@@ -1091,7 +1103,7 @@ pub fn drawOpts(
pen_y += glyph.y_advance;
continue;
};
- if (glyphBitmap(face, glyph.face, glyph.index)) |bitmap| {
+ if (glyphBitmap(face, glyph.face, glyph.index, options.italic)) |bitmap| {
// Keep the accumulated pen fractional to avoid spacing drift;
// snap only the final bitmap placement to the nearest pixel.
const origin_x = snap26_6(pen_x + glyph.x_offset) + bitmap.left;
@@ -1119,7 +1131,7 @@ fn inkCenteredBaseline(run: Run, size: c.FT_F26Dot6, y0: i32, y1: i32) ?i32 {
defer offset_y += glyph.y_advance;
const face = ensureLoaded(glyph.face) catch continue;
applySize(face, size) catch continue;
- if (glyphBitmap(face, glyph.face, glyph.index)) |bitmap| {
+ if (glyphBitmap(face, glyph.face, glyph.index, false)) |bitmap| {
if (bitmap.cols == 0 or bitmap.rows == 0) continue;
const origin_y = snap26_6(offset_y - glyph.y_offset) - bitmap.top;
top = @min(top, origin_y);
@@ -1313,6 +1325,33 @@ test "text retains grayscale coverage and premultiplied opacity at output scales
}
}
+test "italic glyphs have separate cached rasters and leave upright faces unchanged" {
+ setPreferredFamilies("", "");
+ const color: Color = .{ .r = 1, .g = 1, .b = 1, .a = 1 };
+ for ([_]Font{ .manrope, .manrope_heavy }) |font| {
+ for ([_]f32{ 1, 1.5 }) |scale| {
+ const width = devicePixels(180, scale);
+ const height = devicePixels(40, scale);
+ const count: usize = @intCast(width * height);
+ const upright = try std.testing.allocator.alloc(u32, count);
+ defer std.testing.allocator.free(upright);
+ const italic = try std.testing.allocator.alloc(u32, count);
+ defer std.testing.allocator.free(italic);
+ const again = try std.testing.allocator.alloc(u32, count);
+ defer std.testing.allocator.free(again);
+ @memset(upright, 0);
+ @memset(italic, 0);
+ @memset(again, 0);
+ const rect: Rect = .{ .x = 6, .y = 0, .w = 165, .h = 40 };
+ try drawOpts(upright, width, height, "12:59 AM", color, scale, font, 18, .{ .rect = rect });
+ try drawOpts(italic, width, height, "12:59 AM", color, scale, font, 18, .{ .rect = rect, .italic = true });
+ try drawOpts(again, width, height, "12:59 AM", color, scale, font, 18, .{ .rect = rect });
+ try std.testing.expect(!std.mem.eql(u32, upright, italic));
+ try std.testing.expectEqualSlices(u32, upright, again);
+ }
+ }
+}
+
test "offsetAtX inverts measureWidthF and rounds to the nearer character edge" {
setPreferredFamilies("", "");
const value = "hello world";
diff --git a/src/ui/theme.zig b/src/ui/theme.zig
index 8319a72..c6c97cb 100644
--- a/src/ui/theme.zig
+++ b/src/ui/theme.zig
@@ -69,7 +69,10 @@ pub const Theme = struct {
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,
+ /// Lights the selected sidebar row: a bright leading bar and an accent glow.
+ app_sidebar_selected_marker: ?[4]f32 = null,
+ /// Corners of sidebar row highlights (hover and selection).
+ app_sidebar_item_radius: f32 = 5,
app_surface_hover: ?[4]f32 = null,
app_menu_bg: ?[4]f32 = null,
app_field_bg: ?[4]f32 = null,
@@ -107,7 +110,11 @@ pub const Theme = struct {
scrollbar_thumb: [4]f32 = .{ 89.0 / 255.0, 98.0 / 255.0, 110.0 / 255.0, 1 }, // #59626e
/// Unset follows the surface accent during hover/drag.
scrollbar_thumb_active: ?[4]f32 = null,
+ /// Strength of the light on a hovered/dragged/scrolling thumb (1 = subtle).
+ scrollbar_glow: f32 = 1.0,
taskbar_title_size: f32 = 12.5,
+ clock_bold: bool = false,
+ clock_italic: bool = false,
taskbar_size: f32 = 44.0,
// A floating bar: distance from the output edge it sits on (logical px),
// its length as a percentage of that edge (centred), and its corner
@@ -421,12 +428,14 @@ pub fn shellPalette() Theme {
return t;
}
-/// The colour tokens the taskbar draws with. A taskbar theme (Appearance's
+/// The colour and clock-style tokens the taskbar draws with. A taskbar theme (Appearance's
/// "Task Bar theme", `[taskbar_theme]` in the config) replaces just these, and
/// only on the taskbar: every other surface keeps the main theme. Geometry
/// (`taskbar_size`, chip and start-button sizes and gaps, radii) stays with the
/// main theme, which has sliders for it.
pub const TaskbarToken = enum {
+ clock_bold,
+ clock_italic,
taskbar_bg,
taskbar_surface,
taskbar_hover,
@@ -452,7 +461,7 @@ pub const TaskbarToken = enum {
/// fields mean anything (see `taskbarTokens`).
pub var taskbar_override: ?Theme = null;
-/// A taskbar colour: the taskbar theme's when one is chosen, else the main
+/// A taskbar token: the taskbar theme's when one is chosen, else the main
/// theme's. The taskbar reads these instead of `global` so the two can differ.
pub fn taskbar(comptime token: TaskbarToken) @FieldType(Theme, @tagName(token)) {
if (taskbar_override) |chosen| return @field(chosen, @tagName(token));
@@ -478,6 +487,7 @@ pub fn taskbarTokensEql(a: Theme, b: Theme) bool {
}
fn sameWritten(a: anytype, b: @TypeOf(a)) bool {
+ if (comptime @TypeOf(a) == bool) return a == b;
if (comptime @TypeOf(a) == ?[4]f32) {
const left = a orelse return b == null;
const right = b orelse return false;
@@ -672,8 +682,10 @@ pub fn stripComment(line: []const u8) []const u8 {
return line;
}
-pub fn applyKey(allocator: Allocator, t: *Theme, key: []const u8, value: []const u8) !void {
+pub fn applyKey(allocator: Allocator, t: *Theme, name_in: []const u8, value: []const u8) !void {
@setEvalBranchQuota(10000);
+ // The marker once lit hovers; saved looks may still use that name.
+ const key = if (std.mem.eql(u8, name_in, "app_sidebar_hover_marker")) "app_sidebar_selected_marker" else name_in;
inline for (boolean_keys) |name| {
if (std.mem.eql(u8, key, name)) {
@field(t, name) = if (std.mem.eql(u8, value, "true")) true else if (std.mem.eql(u8, value, "false")) false else return error.InvalidBoolean;
@@ -854,7 +866,9 @@ pub fn writeTaskbarInto(allocator: Allocator, buf: *std.ArrayList(u8), t: Theme)
try buf.appendSlice(allocator, "[taskbar_theme]\n");
inline for (std.meta.fields(TaskbarToken)) |field| {
const value = @field(t, field.name);
- if (comptime @TypeOf(value) == ?[4]f32) {
+ if (comptime @TypeOf(value) == bool) {
+ if (value != @field(defaults, field.name)) try appendLine(allocator, buf, "{s} = {}\n", .{ field.name, value });
+ } else if (comptime @TypeOf(value) == ?[4]f32) {
if (value) |color| try appendColor(allocator, buf, field.name, color);
} else if (!std.meta.eql(quantize(value), quantize(@field(defaults, field.name)))) {
try appendColor(allocator, buf, field.name, value);
@@ -947,6 +961,8 @@ test "parse reads the spec's example theme file" {
test "writeInto then parse round-trips every field" {
var t: Theme = .{};
+ t.clock_bold = true;
+ t.clock_italic = true;
// Exercise every registered field with a non-default value, so omission
// from either parser or serializer cannot pass as a default round-trip.
// Keys defaulting to 0 (automatic sizes) would stay at the default under *= 0.9.
@@ -972,6 +988,18 @@ test "writeInto then parse round-trips every field" {
// writeInto omits unchanged fonts; parse keeps their borrowed defaults.
defer std.testing.allocator.free(parsed.start_button_icon);
try std.testing.expectEqualStrings(t.start_button_icon, parsed.start_button_icon);
+ try std.testing.expect(parsed.clock_bold and parsed.clock_italic);
+
+ var taskbar_buf: std.ArrayList(u8) = .empty;
+ defer taskbar_buf.deinit(std.testing.allocator);
+ try writeTaskbarInto(std.testing.allocator, &taskbar_buf, t);
+ var taskbar_theme: Theme = .{};
+ var lines = std.mem.tokenizeScalar(u8, taskbar_buf.items, '\n');
+ while (lines.next()) |line| {
+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
+ try std.testing.expect(try applyTaskbarKey(std.testing.allocator, &taskbar_theme, std.mem.trim(u8, line[0..eq], " "), std.mem.trim(u8, line[eq + 1 ..], " ")));
+ }
+ try std.testing.expect(taskbarTokensEql(t, taskbar_theme));
inline for (number_keys) |name| try std.testing.expectEqual(@field(t, name), @field(parsed, name));
inline for (color_keys) |name| {
diff --git a/src/ui/widgets/scrollbar.zig b/src/ui/widgets/scrollbar.zig
index 6f1e414..e0db593 100644
--- a/src/ui/widgets/scrollbar.zig
+++ b/src/ui/widgets/scrollbar.zig
@@ -145,6 +145,7 @@ pub const Look = struct {
axis: Axis = .vertical,
highlight: [4]f32 = .{ 1, 1, 1, 1 },
shine: f32 = 0,
+ glow: f32 = 1,
};
/// The thumb for `state`: centred in the gutter across its thickness, as wide
@@ -166,7 +167,7 @@ pub fn look(g: Geometry, state: Appearance, configured: f32, palette: theme.Them
var highlight = palette.border_glow;
// A pale reflection of the frame's glow reads as light on every palette.
for (highlight[0..3]) |*channel| channel.* += (1 - channel.*) * 0.55;
- return .{ .rect = rect, .radius = cornerRadius(thickness), .color = color, .axis = g.axis, .highlight = highlight, .shine = state.shine };
+ return .{ .rect = rect, .radius = cornerRadius(thickness), .color = color, .axis = g.axis, .highlight = highlight, .shine = state.shine, .glow = @max(palette.scrollbar_glow, 0) };
}
/// The light stays inside the thumb, so ordinary scrollbar damage erases it.
@@ -212,7 +213,7 @@ pub fn paint(r: *@import("../paint.zig").Renderer, l: Look) void {
const light = falloff * falloff;
const edge = 1 - std.math.clamp(-distance / 1.1, 0, 1);
const face = @max(0, 1 - @abs(v - 0.30) / 0.65);
- const strength = l.shine * l.highlight[3] * light * (0.24 * face + 0.68 * edge);
+ const strength = @min(1, l.shine * l.glow * l.highlight[3] * light * (0.24 * face + 0.68 * edge));
var color = l.color;
for (color[0..3], l.highlight[0..3]) |*channel, target| channel.* += (target - channel.*) * strength;
text.blendPixel(&r.pixels[@intCast(py * r.width + px)], .{ .r = color[0], .g = color[1], .b = color[2], .a = color[3] }, coverage);
diff --git a/src/ui/widgets/slider.zig b/src/ui/widgets/slider.zig
index 4b4cc4c..d03b2db 100644
--- a/src/ui/widgets/slider.zig
+++ b/src/ui/widgets/slider.zig
@@ -34,6 +34,7 @@ pub fn paintShaded(widget: *const Widget, data: layout.SliderData, r: *Renderer)
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)));
+ if (x0 >= x1 or y0 >= y1) return;
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)));
@@ -43,29 +44,43 @@ pub fn paintShaded(widget: *const Widget, data: layout.SliderData, r: *Renderer)
const cy = h / 2;
const highlight = t.slider_highlight orelse t.control_thumb;
const intensity = std.math.clamp(data.feel.accent, 0, 1);
+ const fill_radius = @min(cx, track_h) / 2;
+ // Include the shadow's 0.4 px offset, its 0.8 px falloff and device AA.
+ const disc_extent = radius + @max(0.4 + 0.8, 0.5 / s);
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 dy = y - cy;
+ const rail_y = std.math.clamp((dy + track_h / 2) / track_h, 0, 1);
+ const rail_color = shade(t.slider_track, -0.10 + 0.14 * rail_y);
+ const streak = falloff((dy + track_h * 0.16) / (track_h * 0.38));
+ const knob_shade = -0.06 * std.math.clamp(dy / radius, 0, 1);
+ const rail_middle = sdf.sdRoundedBox(w / 2, y, 0, cy - track_h / 2, w, track_h, track_h / 2);
+ const fill_middle = sdf.sdRoundedBox(cx / 2, y, 0, cy - track_h / 2, cx, track_h, track_h / 2);
+ // Beyond the rail's halo only the small disc can contribute pixels.
+ const rail_visible = @abs(dy) <= track_h / 2 + @max(3, 0.5 / s);
+ if (!rail_visible and @abs(dy) > disc_extent) continue;
+ const row_x0 = if (rail_visible) x0 else @max(x0, @as(i32, @intFromFloat(@floor((widget.computed_x + cx - disc_extent) * s))));
+ const row_x1 = if (rail_visible) x1 else @min(x1, @as(i32, @intFromFloat(@ceil((widget.computed_x + cx + disc_extent) * s))));
+ var px = row_x0;
+ while (px < row_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);
+ const rail = if (x >= track_h / 2 and x <= w - track_h / 2) rail_middle else sdf.sdRoundedBox(x, y, 0, cy - track_h / 2, w, track_h, track_h / 2);
+ const fill = if (x >= fill_radius and x <= cx - fill_radius) fill_middle else 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.10 + 0.14 * rail_y), sdf.coverage(rail * s));
+ blend(pixel, rail_color, 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.30 + 0.24 * streak + 0.28 * tip);
blend(pixel, gold, sdf.coverage(fill * s));
}
+ // The shadow and metallic reflections are local to the knob.
+ if (@abs(dx) > disc_extent or @abs(dy) > disc_extent) continue;
const shadow = @sqrt(dx * dx + (dy - 0.4) * (dy - 0.4)) - radius;
blend(pixel, .{ 0, 0, 0, 0.12 }, std.math.clamp(1 - shadow / 0.8, 0, 1) * edge_fade);
const distance = @sqrt(dx * dx + dy * dy) - radius;
@@ -77,7 +92,7 @@ pub fn paintShaded(widget: *const Widget, data: layout.SliderData, r: *Renderer)
// Keep the centre continuous and the bevel confined to a fine rim.
const reflection = 0.5 + nx * ny / @max(0.08, nx * nx + ny * ny);
var knob = mix(t.accent, highlight, 0.16 + 0.64 * reflection);
- knob = shade(knob, -0.06 * std.math.clamp(ny, 0, 1));
+ knob = shade(knob, knob_shade);
const rim = 1 - std.math.clamp(-distance / 0.75, 0, 1);
knob = mix(knob, highlight, rim * 0.85);
blend(pixel, knob, coverage);
@@ -102,6 +117,7 @@ fn shade(color: [4]f32, amount: f32) [4]f32 {
}
fn blend(pixel: *u32, color: [4]f32, coverage: f32) void {
+ if (coverage <= 0 or color[3] <= 0) return;
text.blendPixel(pixel, .{ .r = color[0], .g = color[1], .b = color[2], .a = color[3] }, coverage);
}
@@ -382,3 +398,51 @@ test "hover and drag light the slider, and only a drag lights its value pill" {
try std.testing.expectEqual(@as(f32, 0), slider.kind.slider.feel.accent);
try std.testing.expect(!stepFeedback(slider, 2800).active);
}
+
+test "shaded sliders preserve clipped pixels at fractional scales" {
+ const background = 0x98655443;
+ var actual: [320 * 100]u32 = undefined;
+ var expected: [320 * 100]u32 = undefined;
+ for ([_]f32{ 1, 1.25, 1.5, 2 }) |scale| {
+ for ([_]f32{ 0, 0.01, 0.5, 0.99, 1 }) |value| {
+ for ([_]@FieldType(layout.SliderData, "style"){ .standard, .settings }) |style| {
+ const widget = Widget{
+ .kind = .{ .slider = .{
+ .style = style,
+ .value = value,
+ .min = 0,
+ .max = 1,
+ .feel = .{ .accent = 0.7, .wide = 0.6 },
+ .on_change = struct {
+ fn call(_: ?*anyopaque, _: usize, _: f32) void {}
+ }.call,
+ } },
+ .computed_x = 3.3,
+ .computed_y = 4.7,
+ .computed_width = 150.4,
+ .computed_height = 22.3,
+ };
+ for ([_]f32{ 0, 70.3, 140.7, 200 }) |left| {
+ @memset(&actual, background);
+ @memset(&expected, background);
+ var r = Renderer.init(&actual, 320, 100, scale);
+ r.palette = theme.Theme{ .slider_shaded = true, .slider_settings_track_height = 5.5 };
+ var full = r;
+ full.pixels = &expected;
+ paintShaded(&widget, widget.kind.slider, &full);
+ r.clip = .{ .x = left, .y = 6.3, .w = 22.4, .h = 17.2 };
+ r.damage_clip = .{ .x = left + 1, .y = 8.7, .w = 20, .h = 30 };
+ paintShaded(&widget, widget.kind.slider, &r);
+ const clip = r.effectiveClip().?;
+ for (&expected, 0..) |*pixel, i| {
+ const x: f32 = @floatFromInt(i % 320);
+ const y: f32 = @floatFromInt(i / 320);
+ if (x < @floor(clip.x * scale) or x >= @ceil((clip.x + clip.w) * scale) or
+ y < @floor(clip.y * scale) or y >= @ceil((clip.y + clip.h) * scale)) pixel.* = background;
+ }
+ try std.testing.expectEqualSlices(u32, &expected, &actual);
+ }
+ }
+ }
+ }
+}
diff --git a/tests/calendar_popup.py b/tests/calendar_popup.py
index e8143a9..e7ab33c 100644
--- a/tests/calendar_popup.py
+++ b/tests/calendar_popup.py
@@ -29,8 +29,11 @@ def run(scale, gold=False, top=False, popup_only=False):
try:
with IPCClient(tmp, timeout=15) as ipc:
ipc.wait_for("wallpaper_presented", timeout_ms=10000)
- bar = ipc.get_shell_state()["taskbars"][0]["box"]
- clock = (bar["x"] + bar["width"] - 40, bar["y"] + bar["height"] // 2)
+ taskbar = ipc.get_shell_state()["taskbars"][0]
+ bar = taskbar["box"]
+ # Themes may move the clock (Gold centres it).
+ clock_box = next(i["box"] for i in taskbar["right_items"] if i["name"] == "clock")
+ clock = (clock_box["x"] + clock_box["width"] // 2, bar["y"] + bar["height"] // 2)
assert ipc.hit_test(*clock)["widget"] == "clock"
ipc.click_at(*clock)
ipc.wait_for_frame()
@@ -69,6 +72,43 @@ def run(scale, gold=False, top=False, popup_only=False):
ipc.wait_for_frame()
assert ipc.hit_test(*point)["target_type"] == "calendar"
ipc.key_down_up(1)
+ # The calendar opens over the clock wherever the taskbar puts it.
+ cfg_path = tmp / "rediwm-config.toml"
+ plain_cfg = cfg_path.read_text()
+
+ def clock_centre():
+ box = next(i["box"] for i in ipc.get_shell_state()["taskbars"][0]["right_items"] if i["name"] == "clock")
+ return box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
+
+ def calendar_left(x):
+ probe = (round(x), bar["y"] + bar["height"] + 50 if top else bar["y"] - 50)
+ hit = ipc.hit_test(*probe)
+ assert hit["target_type"] == "calendar", hit
+ return probe[0] - hit["local_x"]
+
+ status = '"right:tray", "right:battery", "right:network", "right:volume"'
+ layouts = {
+ "centre": f'["left:start", "left:windows", "center:clock", {status}]',
+ "left": f'["left:start", "left:clock", "left:windows", {status}]',
+ "right": f'["left:start", "left:windows", {status}, "right:clock"]',
+ }
+ for name, items in layouts.items():
+ cfg_path.write_text(plain_cfg.replace("[compositor]\n", f"[compositor]\ntaskbar_items = {items}\n"))
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ x, y = clock_centre()
+ ipc.click_at(round(x), round(y))
+ ipc.wait_for_frame()
+ left = calendar_left(x)
+ # Centred over the clock unless the output edge stops it.
+ assert left + 24 <= x <= left + 344, (name, left, x)
+ if name == "centre":
+ assert abs(left + 184 - x) <= 2, (name, left, x)
+ ipc.key_down_up(1)
+ ipc.wait_for_frame()
+ cfg_path.write_text(plain_cfg)
+ ipc.reload_config()
+ ipc.wait_for_frame()
if popup_only:
print(f"PASS: calendar navigation, dismissal and repainting, gold={gold}, top={top}, scale={scale}")
return
@@ -158,8 +198,8 @@ def run(scale, gold=False, top=False, popup_only=False):
assert tomllib.loads(cfg_path.read_text())["region"]["timezone"] == "UTC"
after_zone = capture()
clock_crop = tuple(round(v * float(scale)) for v in
- (bar["x"] + bar["width"] - 100, bar["y"],
- bar["x"] + bar["width"], bar["y"] + bar["height"]))
+ (clock_box["x"], bar["y"],
+ clock_box["x"] + clock_box["width"], bar["y"] + bar["height"]))
assert ImageChops.difference(before_zone.crop(clock_crop), after_zone.crop(clock_crop)).getbbox(), "clock did not follow timezone"
marker = tmp / "child-env.json"
script = "import json,os; from pathlib import Path; Path(" + repr(str(marker)) + ").write_text(json.dumps(dict(os.environ)))"
diff --git a/tests/dock.py b/tests/dock.py
index 9dcf296..7cae403 100644
--- a/tests/dock.py
+++ b/tests/dock.py
@@ -6,6 +6,7 @@ import shutil
from pathlib import Path
import subprocess
import tempfile
+import time
import tomllib
from PIL import Image, ImageChops
@@ -73,7 +74,7 @@ enabled = false
return shot(screenshot).crop(tuple(round(v * scale) for v in
(x - 12, y, x + 12, root['y'] + root['height'] - 2)))
def shortcuts_only():
- return {w['name'] for w in dock() if w['name']} == {'applications', 'files', 'terminal', 'settings'}
+ return {w['name'] for w in dock() if w['name']} == {'applications', 'files', 'terminal', 'settings', 'trash'}
assert not dock(), 'dock must default off'
ipc.action('open_control_center')
ipc.wait_for_panel_settled('control_center')
@@ -162,6 +163,41 @@ enabled = false
ipc.action('open_appearance')
ipc.wait_for_panel_settled('control_center')
assert abs(ui.scroll_into_view('dock_hover_zoom')['value'] - 1.05) < .001
+ # Opacity, corner radius and the active app's rectangle are settings too.
+ settings_cfg = tmp / 'rediwm-config.toml'
+ settings_before = settings_cfg.read_text()
+ def click_slider(name, fraction):
+ for _ in range(3):
+ area = ui.scroll_into_view(name)['global_box']
+ point = (round(area['x'] + min(area['width'] - 1, area['width'] * fraction)),
+ 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)
+ ipc.click_at(*point)
+ opacity = ui.scroll_into_view('dock_opacity')
+ assert (opacity['min'], opacity['max']) == (0, 100)
+ radius = ui.scroll_into_view('dock_radius')
+ assert (radius['min'], radius['max']) == (1, 48)
+ assert radius['value'] == 10, 'dock radius slider must show the window radius it follows'
+ assert ui.scroll_into_view('dock_active_highlight')['on'] is False, 'active app rectangle must default off'
+ click_slider('dock_opacity', .3)
+ wait_for(lambda: abs(tomllib.loads(settings_cfg.read_text())['compositor'].get('dock_opacity', 9) - .3) < .03, 'dock opacity saved')
+ click_slider('dock_radius', .3)
+ wait_for(lambda: abs(tomllib.loads(settings_cfg.read_text()).get('theme', {}).get('dock_radius', 0) - 15) <= 1, 'dock radius saved')
+ click(ui.scroll_into_view('dock_active_highlight'))
+ wait_for(lambda: tomllib.loads(settings_cfg.read_text())['compositor'].get('dock_active_highlight') is True, 'active app rectangle saved')
+ # The Trash shows by default, last on the dock; the switch removes it.
+ assert ui.scroll_into_view('dock_show_trash')['on'] is True, 'dock trash must default on'
+ assert dock()[-1]['name'] == 'trash', 'trash must be the last dock item'
+ click(ui.scroll_into_view('dock_show_trash'))
+ wait_for(lambda: tomllib.loads(settings_cfg.read_text())['compositor'].get('dock_show_trash') is False, 'dock trash setting saved')
+ wait_for(lambda: all(w['name'] != 'trash' for w in dock()), 'trash leaves the dock')
+ settings_cfg.write_text(settings_before)
+ ipc.reload_config()
+ wait_for(lambda: dock()[-1]['name'] == 'trash', 'reload brings the trash back')
ipc.action('close_panel', {'panel': 'control_center'})
ipc.wait_for_frame()
assert ipc.get_shell_state()['taskbars'], 'dock must coexist with taskbar'
@@ -297,6 +333,35 @@ enabled = false
click(button(name))
wait_for(lambda: not next(w for w in ipc.get_windows() if w['id'] == wid)['is_minimized'], 'dock restore')
assert ipc.get_focused_window()['id'] == wid
+ # The focused app's rectangle is off by default; the setting draws it.
+ # A strip beside the icon, inside the button, shows it.
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ focused_box = button(name)['global_box']
+ beside = tuple(round(v * scale) for v in (focused_box['x'], focused_box['y'] + focused_box['height'] / 2 - 6,
+ focused_box['x'] + 3, focused_box['y'] + focused_box['height'] / 2 + 6))
+ dock_root = dock()[0]['global_box']
+ backdrop = tuple(round(v * scale) for v in (dock_root['x'] + 3, dock_root['y'] + dock_root['height'] / 2 - 6,
+ dock_root['x'] + 8, dock_root['y'] + dock_root['height'] / 2 + 6))
+ base_config = cfg.read_text()
+ def with_dock(lines, name):
+ cfg.write_text(base_config.replace('[compositor]', '[compositor]\n' + lines, 1))
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ return shot(name)
+ plain_dock = shot('dock-plain')
+ highlighted = with_dock('dock_active_highlight = true', 'dock-highlighted')
+ assert ImageChops.difference(plain_dock.crop(beside), highlighted.crop(beside)).getbbox(), 'active app rectangle missing when enabled'
+ assert not ImageChops.difference(plain_dock.crop(backdrop), highlighted.crop(backdrop)).getbbox()
+ # Opacity changes the background and nothing else of the icon strip.
+ solid = with_dock('dock_opacity = 1.0', 'dock-solid')
+ clear = with_dock('dock_opacity = 0.0', 'dock-clear')
+ assert ImageChops.difference(solid.crop(backdrop), clear.crop(backdrop)).getbbox(), 'dock opacity ignored'
+ cfg.write_text(base_config)
+ ipc.reload_config()
+ ipc.wait_for_frame()
fullscreen_point = center(button(name))
ipc.action('fullscreen_window', {'id': wid})
wait_for(lambda: not dock(), 'fullscreen hides dock')
@@ -469,11 +534,13 @@ def context_menu():
cfg.write_text(cfg.read_text().replace('dock_enabled = false', 'dock_enabled = true'))
ipc.reload_config()
wait_for(names, 'dock restored')
- for shortcut in ('files', 'applications', 'settings'):
+ for shortcut in ('files', 'applications', 'settings', 'trash'):
menu(shortcut)
key(103)
key(28)
wait_for(lambda: shortcut not in names(), 'shortcut removed')
+ # Removing the Trash turns its Appearance switch off.
+ assert tomllib.loads(cfg.read_text())['compositor']['dock_show_trash'] is False
assert any(n.startswith('window_') for n in names()), 'running apps left the dock with its shortcuts'
stop_process(first)
stop_process(second)
@@ -604,6 +671,9 @@ def pill_animation():
advance(1000)
expanded = terminal_box()
assert zoom_state()['value'] == 1.5 and expanded['width'] > base['width']
+ assert expanded['y'] < base['y'], 'bottom dock must grow upward'
+ assert expanded['y'] + expanded['height'] == base['y'] + base['height'], 'hover moved the resting bottom edge'
+ assert abs(expanded['x'] + expanded['width'] / 2 - (base['x'] + base['width'] / 2)) <= 1
edge = (round(expanded['x'] + 1), y)
assert edge[0] < base['x']
ipc.move_cursor(*edge)
@@ -907,6 +977,51 @@ def pinning():
# The pin survives a reload, launches its app, and a running app shares its button.
ipc.reload_config()
assert [n for n in names() if n.startswith('pin_')] == ['pin_pin-two.desktop', 'pin_pin-one.desktop']
+
+ # A pinned icon dragged along the dock moves its pin. Dropped where it
+ # was, or abandoned with Escape, nothing changes and nothing launches.
+ def drag_pin(name, x, y, release=True):
+ start = centre(box(name))
+ ipc.move_cursor(*start)
+ ipc.pointer_button(left, True)
+ for step in range(1, 11):
+ ipc.move_cursor(start[0] + (x - start[0]) * step // 10, start[1] + (y - start[1]) * step // 10)
+ ipc.wait_for_frame()
+ if release:
+ ipc.pointer_button(left, False)
+ ipc.wait_for_frame()
+
+ def order():
+ return [n for n in names() if n.startswith('pin_')]
+
+ one_name, two_name = 'pin_pin-one.desktop', 'pin_pin-two.desktop'
+ before_drags = order()
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ resting = shot('pins-resting')
+ x0, y0 = centre(box(one_name))
+ drag_pin(one_name, x0 + 12, y0)
+ assert pins() == ['pin-two.desktop', 'pin-one.desktop'] and not ipc.get_windows(), 'a drop in place moved or launched'
+ two_box = box(two_name)
+ drag_pin(one_name, two_box['x'] + 4, centre(two_box)[1], release=False)
+ assert ImageChops.difference(resting, shot('pins-moving')).getbbox(), 'no marker while moving a pin'
+ ipc.key(1, True)
+ ipc.key(1, False)
+ ipc.wait_for_frame()
+ cancelled = ImageChops.difference(resting, shot('pins-cancelled')).getbbox()
+ assert cancelled is None, f'Escape left the marker: {cancelled}, dock {ui.widgets("dock")[0]["global_box"]}'
+ ipc.pointer_button(left, False)
+ ipc.wait_for_frame()
+ assert order() == before_drags and pins() == ['pin-two.desktop', 'pin-one.desktop'] and not ipc.get_windows(), 'a cancelled move changed the pins or launched'
+ drag_pin(one_name, two_box['x'] + 4, centre(two_box)[1])
+ wait_for(lambda: pins() == ['pin-one.desktop', 'pin-two.desktop'], 'pin moved before the other')
+ wait_for(lambda: order() == [one_name, two_name], 'dock follows the moved pin')
+ assert not ipc.get_windows() and '# keep this comment' in cfg.read_text(), 'moving a pin launched or disturbed the config'
+ end = ui.widgets('dock')[0]['global_box']
+ drag_pin(one_name, end['x'] + end['width'] - 4, centre(end)[1])
+ wait_for(lambda: pins() == ['pin-two.desktop', 'pin-one.desktop'], 'pin moved to the end')
+ wait_for(lambda: order() == before_drags, 'dock follows the pin moved to the end')
+ assert not ipc.get_windows()
ipc.click_at(*centre(box('pin_pin-one.desktop')))
wait_for(lambda: len(ipc.get_windows()) == 1, 'pinned app launched')
assert not any(n.startswith('window_') for n in names()), 'a pinned app also got a window button'
@@ -950,9 +1065,17 @@ def positions():
with tempfile.TemporaryDirectory(prefix='rediwm-dock-position-') as directory:
tmp = Path(directory)
build_client(tmp)
+ # An opaque fixture exposes the exact painted edges, including the
+ # few pixels that extend beyond the dock at maximum hover zoom.
+ theme = tmp / 'data/icons/DockAnchorTest'
+ icons = theme / '64x64/apps'
+ icons.mkdir(parents=True)
+ (theme / 'index.theme').write_text('[Icon Theme]\nName=DockAnchorTest\nDirectories=64x64/apps\n'
+ '[64x64/apps]\nSize=64\nType=Fixed\nContext=Applications\n')
+ Image.new('RGBA', (64, 64), (248, 16, 128, 255)).save(icons / 'rediwm-settings.png')
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')}
+ 'XDG_CACHE_HOME': str(tmp / 'cache'), 'REDIWM_ICON_THEME': 'DockAnchorTest'}
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'
@@ -987,6 +1110,13 @@ def positions():
return image.convert('RGB')
def crop(image, box):
return image.crop(tuple(round(v * scale) for v in box))
+ def icon_bounds(image, region):
+ icon = crop(image, region)
+ red, green, blue = icon.split()
+ mask = ImageChops.multiply(red.point(lambda v: 255 if v > 220 else 0),
+ green.point(lambda v: 255 if v < 40 else 0))
+ mask = ImageChops.multiply(mask, blue.point(lambda v: 255 if 100 < v < 180 else 0))
+ return mask.getbbox()
for taskbar in ('bottom', 'top'):
for position in ('top', 'left', 'right', 'bottom'):
vertical = position in ('left', 'right')
@@ -1003,10 +1133,10 @@ def positions():
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
+ assert box['x'] == (x0 + 5 if position == 'left' else x0 + width - size - 5), 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
+ assert box['y'] == (y0 + 5 if position == 'top' else y0 + height - size - 5), 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
@@ -1018,10 +1148,16 @@ def positions():
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.
+ resting = item('settings')
+ region = (resting['x'] - resting['width'] / 2, resting['y'] - resting['height'] / 2,
+ resting['x'] + resting['width'] * 1.5, resting['y'] + resting['height'] * 1.5)
+ wait_for(lambda: icon_bounds(shot('icon-ready'), region), 'fixture icon loaded')
idle = shot('idle')
+ small = icon_bounds(idle, region)
+ rested = time.monotonic()
ipc.move_cursor(*center(item('settings')))
ipc.wait_for_frame()
- hovered = shot('hovered')
+ early = shot('early')
if position == 'top':
tip = (box['x'], box['y'] + box['height'] + 8, box['x'] + box['width'], box['y'] + box['height'] + 38)
elif position == 'bottom':
@@ -1030,9 +1166,29 @@ def positions():
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'
+ # The title shows only after the pointer has rested on the icon.
+ assert not ImageChops.difference(crop(idle, tip), crop(early, tip)).getbbox(), f'{position} tooltip shown without a delay'
+ wait_for(lambda: ImageChops.difference(crop(idle, tip), crop(shot('hovered'), tip)).getbbox(), f'{position} tooltip missing', timeout=4)
+ print(f'{taskbar}/{position}/{size}: tooltip after {time.monotonic() - rested:.2f}s')
+ assert time.monotonic() - rested >= 1.4, f'{position} tooltip shown before its delay'
# A hovered icon is enlarged in either orientation.
assert item('settings')['width'] > buttons[-1]['width'], 'hover zoom missing'
+ large = icon_bounds(shot('anchored'), region)
+ assert large and large[2] - large[0] > small[2] - small[0], (small, large)
+ fixed = {'left': 0, 'top': 1, 'right': 2, 'bottom': 3}[position]
+ assert abs(large[fixed] - small[fixed]) <= 1, (position, small, large)
+ expected = round(36 * size / 68) * 1.5 * scale
+ assert abs(large[2] - large[0] - expected) <= 2, (position, large, expected)
+ assert abs(large[3] - large[1] - expected) <= 2, (position, large, expected)
+ # The part beyond the background remains a hover target.
+ expanded = item('settings')
+ ex, ey = center(expanded)
+ if position == 'bottom': ey = box['y'] - 1
+ elif position == 'top': ey = box['y'] + box['height']
+ elif position == 'right': ex = box['x'] - 1
+ else: ex = box['x'] + box['width']
+ ipc.move_cursor(ex, ey)
+ assert ipc.hit_test(ex, ey)['target_type'] == 'dock', (position, ex, ey)
ipc.move_cursor(5, 5)
ipc.wait_for_frame()
# Running-window buttons still minimize and restore.
@@ -1083,7 +1239,7 @@ def positions():
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
+ capacity = (height - round(12 * 96 / 68) * 2 - 16) // round(56 * 96 / 68) - 5 # fixed items, the Trash included
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),
diff --git a/tests/screencast.py b/tests/screencast.py
index 93c7615..c890e76 100644
--- a/tests/screencast.py
+++ b/tests/screencast.py
@@ -11,6 +11,7 @@ import tempfile
from desktop_zoom import ROOT, wait_for
from ipc_client import IPCClient, spawn_compositor, stop_process
+from ui_driver import UIDriver
from capture import build_client, get_capture_state, wait_for_capture_sessions
@@ -126,7 +127,9 @@ def test_capture_indicator_stops_sharing(client_binary):
compositor, log = spawn_compositor(
tmp, scale="1", outputs="1",
config_content="[compositor]\nxwayland = false\n",
- env_extra={"XDG_CACHE_HOME": str(tmp / "cache")})
+ env_extra={"XDG_CACHE_HOME": str(tmp / "cache"),
+ "XDG_CONFIG_HOME": str(tmp / "config"),
+ "XDG_DATA_HOME": str(tmp / "data")})
client = None
client_log = tmp / "client.log"
try:
@@ -159,13 +162,61 @@ def test_capture_indicator_stops_sharing(client_binary):
assert hit["target_type"] == "taskbar", hit
assert hit["widget"] == "capture_indicator", hit
+ taskbar = ipc.get_shell_state()["taskbars"][0]
+ root = taskbar["box"]
+ assert box["x"] >= root["x"] + root["width"] // 2, box
+ for item in taskbar["right_items"]:
+ if item["name"] != "capture" and item["box"]:
+ assert box["x"] + box["width"] <= item["box"]["x"], (box, item)
+
+ ipc.action("open_appearance")
+ ipc.wait_for_panel_settled("control_center")
+ ui = UIDriver(ipc)
+
+ def toggle_item(name):
+ widget = ui.scroll_into_view(f"taskbar_{name}_visible")
+ b = widget["global_box"]
+ ipc.click_at(b["x"] + b["width"] // 2, b["y"] + b["height"] // 2)
+ ipc.wait_for_panel_settled("control_center")
+
+ # The capture item remains available with the app tray hidden.
+ toggle_item("tray")
+ assert get_capture_state(ipc).get("indicator"), "hiding tray hid capture"
+ toggle_item("capture")
+ wait_for(lambda: not get_capture_state(ipc).get("indicator"), "capture did not hide")
+ assert wait_for_capture_sessions(ipc, 1, "hiding indicator stopped capture")
+ assert client.poll() is None, "hiding indicator disconnected recorder"
+ notice = ui.find("taskbar_capture_notice")
+ assert "not recommended" in notice["label"], notice
+ assert "without a visible indicator" in notice["label"], notice
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ assert get_capture_state(ipc).get("indicator") is None, "hidden setting was not saved"
+ toggle_item("capture")
+ wait_for(lambda: get_capture_state(ipc).get("indicator"), "capture did not return")
+ ipc.action("close_panel", {"panel": "control_center"})
+ ipc.wait_for_frame()
+
+ # Placement changes move both the rendered button and its hit target.
+ cfg = tmp / "rediwm-config.toml"
+ saved = cfg.read_text()
+ cfg.write_text(saved.replace('"right:capture"', '"center:capture"'))
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ box = get_capture_state(ipc)["indicator"]["box"]
+ assert abs(box["x"] + box["width"] / 2 - (root["x"] + root["width"] / 2)) <= 1, box
+ assert ipc.hit_test(box["x"] + box["width"] // 2, box["y"] + box["height"] // 2)["widget"] == "capture_indicator"
+ cfg.write_text(saved)
+ ipc.reload_config()
+ ipc.wait_for_frame()
+ box = get_capture_state(ipc)["indicator"]["box"]
ipc.click_at(box["x"] + box["width"] // 2, box["y"] + box["height"] // 2)
wait_for_capture_sessions(ipc, 0, "Stop sharing did not clear capture sessions")
wait_for(lambda: client.poll() is not None, "capturing client was not disconnected")
state = get_capture_state(ipc)
assert state["last_failure"] == "stop_all", state
assert state.get("indicator") is None, state
- print("screencast: taskbar Stop sharing indicator revokes a live session")
+ print("screencast: independent capture item hides without stopping capture, moves live and revokes a session")
for keycode in (125, 42):
ipc.action("key", {"keycode": keycode, "pressed": True})
diff --git a/tests/taskbar_sections.py b/tests/taskbar_sections.py
index 3cc5ec4..b84ec31 100644
--- a/tests/taskbar_sections.py
+++ b/tests/taskbar_sections.py
@@ -5,6 +5,7 @@ from pathlib import Path
import subprocess
import tempfile
import tomllib
+from PIL import Image, ImageChops
from desktop_zoom import build_client, wait_for
from ipc_client import IPCClient, spawn_compositor, stop_process
@@ -57,24 +58,94 @@ def run():
assert 0 <= row[0]['x'] - (box('start')['x'] + box('start')['width']) <= 32, row
assert box('start')['x'] < row[0]['x'] < box('clock')['x']
check_bounds()
+ assert not any(w['name'] == 'power' for w in bar()), 'Power defaults off'
ipc.action('open_appearance')
ipc.wait_for_panel_settled('control_center')
- for name, expected in (('start', 0), ('windows', 0), ('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'):
+ def clock_image(name):
+ image_path = tmp / f'clock-{name}.png'
+ ipc.screenshot(str(image_path))
+ b = box('clock')
+ right = b['x'] + b['width']
+ with Image.open(image_path) as image:
+ return image.convert('RGB').crop(tuple(round(v * scale) for v in
+ (right - 180, b['y'], right + 2, b['y'] + b['height'])))
+ def style_toggle(name):
+ toggle = ui.scroll_into_view(name)
+ ipc.click_at(*center(toggle['global_box']))
+ ipc.wait_for_panel_settled('control_center')
+ ipc.wait_for_frame()
+ assert not ui.scroll_into_view('clock_bold')['on']
+ assert not ui.scroll_into_view('clock_italic')['on']
+ for name, label in (('clock_bold', 'bold'), ('clock_italic', 'bold-italic'),
+ ('clock_bold', 'italic'), ('clock_italic', 'regular-again')):
+ before = clock_image('before-' + label)
+ style_toggle(name)
+ after = clock_image(label)
+ assert ImageChops.difference(before, after).getbbox(), f'clock style did not repaint: {label}'
+ check_bounds()
+ style_toggle('clock_bold')
+ style_toggle('clock_italic')
+ saved_theme = tomllib.loads(cfg.read_text())['theme']
+ assert saved_theme['clock_bold'] and saved_theme['clock_italic']
+ zones = ('left', 'center', 'right')
+ def zone_of(name):
+ row = ui.scroll_into_view(f'taskbar_{name}_row')['global_box']
+ for zone, label in enumerate(zones):
+ well = ui.find(f'taskbar_zone_{label}')['global_box']
+ if well['y'] <= row['y'] and row['y'] + row['height'] <= well['y'] + well['height']:
+ return zone
+ for name, expected in (('start', 0), ('windows', 0), ('capture', 2), ('tray', 2), ('clock', 2), ('power', 2)):
+ assert zone_of(name) == expected, name
+ toggle = ui.scroll_into_view('taskbar_capture_visible')
+ assert toggle['on'], 'Screen capture defaults on'
+ ipc.click_at(*center(toggle['global_box']))
+ ipc.wait_for_panel_settled('control_center')
+ assert '-right:capture' in tomllib.loads(cfg.read_text())['compositor']['taskbar_items']
+ assert 'not recommended' in ui.find('taskbar_capture_notice')['label']
+ # Power is opt-in, opens the existing modal, and can be hidden live.
+ toggle = ui.scroll_into_view('taskbar_power_visible')
+ ipc.click_at(*center(toggle['global_box']))
+ wait_for(lambda: any(w['name'] == 'power' for w in bar()), 'Power enabled')
+ assert box('power')['x'] > box('clock')['x']
+ check_bounds()
+ ipc.click_at(*center(box('power')))
+ ipc.wait_for('power_menu_opened')
+ assert len([w for w in ui.widgets('power_menu') if w['role'] == 'row']) == 5
+ ipc.key(1, True)
+ ipc.key(1, False)
+ ipc.wait_for('power_menu_closed')
+ toggle = ui.scroll_into_view('taskbar_power_visible')
+ ipc.click_at(*center(toggle['global_box']))
+ wait_for(lambda: not any(w['name'] == 'power' for w in bar()), 'Power hidden')
+ toggle = ui.scroll_into_view('taskbar_power_visible')
+ ipc.click_at(*center(toggle['global_box']))
+ wait_for(lambda: any(w['name'] == 'power' for w in bar()), 'Power restored')
+ # Drag fixed controls and both primary groups into every section.
+ for name in ('clock', 'network', 'volume', 'start', 'windows', 'tray', 'power', 'capture'):
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')
+ if zone_of(name) == zone:
+ continue
+ ui.scroll_into_view(f'taskbar_zone_{zones[zone]}')
+ row = ui.scroll_into_view(f'taskbar_{name}_row')
+ assert row['visible'] and not row['clipped'], row
+ ipc.move_cursor(*center(row['global_box']))
+ ipc.pointer_button(0x110, True)
+ # Rows reflow live under the pointer: re-aim until the well holds still.
+ aimed = None
+ for _ in range(4):
+ well = ui.find(f'taskbar_zone_{zones[zone]}')['global_box']
+ if well == aimed:
+ break
+ ipc.move_cursor(round(well['x'] + well['width'] / 2), well['y'] + well['height'] - 3)
+ aimed = well
+ ipc.pointer_button(0x110, False)
+ wait_for(lambda: any(entry.lstrip('-') == f'{zones[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')
+ assert zone_of(name) == zone, name
check_bounds()
- # Drag order and keyboard order stay inside the chosen section.
+ # Drag and keyboard order within a 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')
@@ -118,6 +189,7 @@ def run():
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']
+ assert not any(w['name'] == 'power' for w in bar()), 'legacy lists keep Power off'
row = chips()
assert 0 <= row[0]['x'] - (box('start')['x'] + box('start')['width']) <= 32, row
cfg.write_text(saved)
@@ -131,9 +203,27 @@ def run():
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
+ assert ui.scroll_into_view('clock_bold')['on'], 'Bold clock survives restart'
+ assert ui.scroll_into_view('clock_italic')['on'], 'Italic clock survives restart'
+ assert any(w['name'] == 'power' for w in ui.widgets('taskbar')), 'Power survives restart'
+ toggle = ui.scroll_into_view('taskbar_capture_visible')
+ assert not toggle['on'], 'Hidden capture item survives restart'
+ assert 'not recommended' in ui.find('taskbar_capture_notice')['label']
+ for name in ('start', 'windows', 'clock', 'power', 'capture'):
+ row = ui.scroll_into_view(f'taskbar_{name}_row')['global_box']
+ well = ui.find('taskbar_zone_right')['global_box']
+ assert well['y'] <= row['y'] and row['y'] + row['height'] <= well['y'] + well['height'], name
+ # Clock controls edit the selected taskbar theme independently.
+ main_theme = tomllib.loads(cfg.read_text())['theme']
+ cfg.write_text(cfg.read_text() + '\n[taskbar_theme]\nclock_bold = false\nclock_italic = false\n')
+ ipc.reload_config()
+ ipc.wait_for_panel_settled('control_center')
+ assert not ui.scroll_into_view('clock_bold')['on']
+ assert not ui.scroll_into_view('clock_italic')['on']
+ style_toggle('clock_italic')
+ config = tomllib.loads(cfg.read_text())
+ assert config['taskbar_theme']['clock_italic']
+ assert config['theme'] == main_theme, 'taskbar style changed main theme'
print(f'PASS: taskbar sections, left default, section moves, bounds/input, visibility, Start menu, legacy config and restart ({scale}x)')
finally:
for client in clients:
diff --git a/tests/theme_packs.py b/tests/theme_packs.py
index f21e6e8..c2b1fd8 100644
--- a/tests/theme_packs.py
+++ b/tests/theme_packs.py
@@ -129,11 +129,21 @@ def run():
assert gold["tokens"]["app_fg"] != gold["tokens"]["window_fg"]
assert gold["tokens"]["app_sidebar"][3] == .5
assert gold["tokens"]["app_sidebar_blur"] is True
- for key in ("app_item_hover", "app_sidebar_hover", "app_surface_hover",
+ for key in ("app_item_hover", "app_surface_hover",
"surface_hover", "start_menu_selected_bg"):
assert abs(gold["tokens"][key][3] - 0.96) < .001, key
+ assert abs(gold["tokens"]["app_sidebar_hover"][3] - 0.07) < .001
wait_for(lambda: UIDriver(ipc).widgets("dock"), "Gold dock did not appear")
assert ipc.get_shell_state()["taskbars"][0]["box"]["y"] == 0
+ assert gold["tokens"]["clock_bold"] is True
+ assert gold["tokens"]["clock_italic"] is False
+ assert gold["tokens"]["taskbar_radius"] == 12
+ bar_widgets = UIDriver(ipc).widgets("taskbar")
+ assert not any(w["role"] == "chip" for w in bar_widgets), 'Gold window list must default hidden'
+ clock_box = next(w['global_box'] for w in bar_widgets if w['name'] == 'clock')
+ bar_box = bar_widgets[0]['global_box']
+ assert abs(clock_box['x'] + clock_box['width'] / 2 - (bar_box['x'] + bar_box['width'] / 2)) <= 1
+ assert any(w['name'] == 'power' for w in bar_widgets), 'Gold Power item missing'
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())