Skip to content

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

dock updates

oxydizer4c244cb2f251
diff --git a/AGENTS.md b/AGENTS.md
index 2c7d42f..fa2e4b4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -98,6 +98,16 @@ the one for the directory you work in: `src/files`, `src/editor`,
(`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
@@ -146,6 +156,15 @@ the one for the directory you work in: `src/files`, `src/editor`,
* **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`).
* **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
@@ -169,6 +188,12 @@ 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.
## Xwayland
diff --git a/README.md b/README.md
index eccded5..684d74c 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. 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. Right-click a running icon for Close, Force Close, or Remove from dock; idle shortcuts offer Remove from dock. Removal leaves apps running and is remembered across restarts in `dock_hidden_apps` (app IDs) and `dock_hidden_shortcuts` (`applications`, `files`, `terminal`, `settings`). A removed shortcut also hides the app it represents. Remove entries from those lists to restore items. Windows without an app ID are hidden for their lifetime. 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 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.
- **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 7016a68..37162b0 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -147,7 +147,7 @@ never for its own client), `animations.py`, `hotspots.py`, `launch_feedback.py`,
and off-canvas reachability).
`taskbar_sections.py` checks left/center/right defaults, live section controls,
-ordering and visibility, centered window groups, nonoverlapping input bounds,
+ordering and visibility, window groups defaulting left, nonoverlapping input bounds,
the moved Start menu, legacy item lists and restart persistence. It supports
`REDIWM_TEST_SCALE=1.5` and `REDIWM_TEST_OUTPUTS=2`.
diff --git a/assets/icons/rediwm-settings.png b/assets/icons/rediwm-settings.png
new file mode 100644
index 0000000..01d103a
Binary files /dev/null and b/assets/icons/rediwm-settings.png differ
diff --git a/assets/themes/gold.toml b/assets/themes/gold.toml
index c118a10..464f54f 100644
--- a/assets/themes/gold.toml
+++ b/assets/themes/gold.toml
@@ -42,7 +42,8 @@ window_close_hover = "#AD5A4A"
text_secondary = "#6D6257"
app_bg = "#EEE6DB"
app_toolbar = "#E8DFD2"
-app_sidebar = "rgba(68,61,58,1.0)"
+app_sidebar = "rgba(68,61,58,0.5)"
+app_sidebar_blur = true
app_bar = "#E8DED1"
app_item = "#F3ECE2"
app_item_hover = "rgba(229,214,195,0.96)"
diff --git a/build.zig b/build.zig
index 70b8cdf..a7fc220 100644
--- a/build.zig
+++ b/build.zig
@@ -837,6 +837,7 @@ fn addShellUi(b: *std.Build, module: *std.Build.Module) void {
// Bundle shell glyphs so installed binaries never depend on the checkout.
fn addShellIcons(b: *std.Build, module: *std.Build.Module) void {
module.addAnonymousImport("redi-logo", .{ .root_source_file = b.path("assets/redi-logo.svg") });
+ module.addAnonymousImport("rediwm-settings-icon", .{ .root_source_file = b.path("assets/icons/rediwm-settings.png") });
inline for (.{ "git-branch", "home", "folder", "settings", "keyboard", "edit", "mouse", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares" }) |name| {
module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("assets/icons/" ++ name ++ ".svg") });
}
diff --git a/docs/themes.md b/docs/themes.md
index 4f7e538..094341b 100644
--- a/docs/themes.md
+++ b/docs/themes.md
@@ -135,7 +135,9 @@ GTK colour export also uses the app and sidebar foregrounds.
`app_sidebar_hover_marker` adds a bright leading bar and an accent-coloured
glow to Files sidebar hovers. Gold enables it; unset leaves the plain fill.
-Gold uses 96% opaque hover fills and a fully opaque Files sidebar. Its sidebar
+Gold uses 96% opaque hover fills 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.
@@ -147,7 +149,7 @@ An explicit dock background uses its own alpha without the inherited dock's
control notification cards. `notification_blur = true` enables the existing
backdrop renderer behind them. Defaults retain the previous appearance.
-Wi-Fi and battery popups accept `popup_bg`, `popup_border`, `popup_radius`
+Wi-Fi, battery and calendar popups accept `popup_bg`, `popup_border`, `popup_radius`
and `popup_blur`. With blur enabled they use a rounded glass panel without a
pointer. `popup_card_bg`, `popup_card_fg`, `popup_card_dim`,
`popup_card_border` and `popup_card_radius` style the network rows and battery
@@ -172,6 +174,12 @@ explicit launcher overrides. Existing windows, terminals started directly
from another shell, Foot server clients and other terminal emulators retain
their own colours. The palette applies to newly launched Foot windows.
+The same helper passes Foot the background opacity from `[compositor]
+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.
+
The helper is also available from a terminal:
```sh
@@ -215,6 +223,9 @@ Glyph filenames are the names in `assets/icons/`, including `wifi.svg`,
`folder`, `user-home`, `user-desktop`, `folder-documents`, `folder-download`,
`folder-music`, `folder-pictures`, `folder-videos`, `folder-templates`,
`folder-publicshare`, `user-trash`, MIME names, and application icon names.
+The Settings app (its window, dock shortcut and Start menu entry) uses
+`rediwm-settings`; without a pack or installed icon of that name RediWM draws
+its built-in gear (`assets/icons/rediwm-settings.png`).
XDG special directories come from `user-dirs.dirs`.
The small pack in `tests/fixtures/theme-pack/` supplies a glyph, folder icon,
diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md
index 31e9009..a68ed40 100644
--- a/docs/wiki/Configuration.md
+++ b/docs/wiki/Configuration.md
@@ -70,15 +70,21 @@ Choose top, bottom, left or right; side docks stack upright icons vertically.
or up to 1.5. The setting applies immediately and follows the animation and
reduced-motion preferences.
+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
+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.
+
The taskbar has **Left**, **Center**, and **Right** sections in Appearance.
-Start defaults to the left, the window list to the center, and application tray
+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.
The center group stays centered on the display when it fits, and shifts or
narrows the window list to avoid the side groups.
-For example, `taskbar_items = ["left:start", "center:windows", "right:tray",
+For example, `taskbar_items = ["left:start", "left:windows", "right:tray",
"right:battery", "right:network", "right:volume", "right:clock"]` is the default.
Use `"-right:clock"` to hide the clock. Existing four-item status lists still
load, preserving their order and visibility alongside Start and the window list.
@@ -94,6 +100,7 @@ length, corner radius and outline are `[theme]` tokens (`docs/wiki/Theme.md`).
| `default_file_manager`, `default_terminal` | `""` | desktop IDs, empty means Files / auto terminal |
| `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 |
| `focus_follows_mouse` | `false` | |
| `canvas_columns`, `canvas_rows` | `3`, `3` | 1 to 10 |
@@ -109,9 +116,10 @@ length, corner radius and outline are `[theme]` tokens (`docs/wiki/Theme.md`).
| `snap_to_edges` | `true` | |
| `dodge_file_drags` | `true` | file manager slides aside while you drag a file out |
| `drag_feedback` | `true` | softly lift a window during a move drag; suppressed by reduced motion |
-| `drag_scale` | `1.03` | drag lift multiplier, `1.00`–`1.10`; adjustable in Appearance |
+| `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 |
| `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/src/Dock.zig b/src/Dock.zig
index d8bae64..d705138 100644
--- a/src/Dock.zig
+++ b/src/Dock.zig
@@ -1,8 +1,13 @@
//! Optional output-local launcher. Retained rasters; animation uses output frames.
+//! The last raster is kept (`retained`): an icon that animates repaints only its
+//! own cell over it (`itemCell`, `changedCells`) and publishes only that damage.
+//! Anything the dock draws outside every item's cell must key `base_key` instead.
const std = @import("std");
+const wl = @import("wayland").server.wl;
const wlr = @import("wlroots");
const ui = @import("ui");
const Output = @import("Output.zig");
+const Server = @import("Server.zig");
const Toplevel = @import("Toplevel.zig");
const IconEntry = @import("icon_service.zig").Entry;
const PanelBuffer = @import("panel_buffer.zig").PanelBuffer;
@@ -15,7 +20,20 @@ const anim = ui.anim;
const gpa = @import("main.zig").gpa;
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
+/// windows when it reserves its strip.
+const edge_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
+/// it fades.
+const edge_band = 2;
+const reveal_delay_ms = 120;
+const hide_delay_ms = 400;
+const slide_distance = 20;
/// Scale the original 68px layout in logical pixels, independently of output scale.
const Metrics = struct {
@@ -38,8 +56,26 @@ const Metrics = struct {
}
};
+/// A pinned application as the last rebuild resolved it. Strings are copies
+/// (`pin_arena`), so they outlive the catalogue snapshot they came from.
+const PinnedApp = struct {
+ id: []const u8,
+ name: []const u8,
+ icon: []const u8,
+ wm_class: ?[]const u8,
+ /// Never 0: animations use 0 for "not a pin".
+ hash: u64,
+ /// Index in `dock_pinned_apps`, which also lists apps no longer installed.
+ config_index: usize,
+
+ fn match(self: PinnedApp) AppMatch {
+ return .{ .id = self.id, .wm_class = self.wm_class };
+ }
+};
+
const ItemAnimation = struct {
shortcut: ?Shortcut = null,
+ pin: u64 = 0,
id: u64 = 0,
width: anim.Anim = .{},
opacity: anim.Anim = .{ .property = .opacity },
@@ -56,11 +92,33 @@ box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = config.dock_height_defau
position: @import("config").types.DockPosition = .bottom,
scale: f32 = 0,
dirty: bool = true,
+/// The dock could be on screen: sized to fit, no lock, no fullscreen window.
+/// With auto-hide it still shows only while `reveal` is above zero.
visible: bool = false,
+/// Auto-hide. `pointer_near` is where the pointer wants the dock (at the edge,
+/// or on a shown dock); `shown` is what the reveal heads for, which follows it
+/// after a delay (`timer`, armed for `timer_target`). `reveal` runs 0 (away) to
+/// 1 and drives the fade and slide; `parked` is hidden and settled, so nothing
+/// is rebuilt or painted.
+pointer_near: bool = false,
+shown: bool = false,
+timer: ?*wl.EventSource = null,
+timer_target: ?bool = null,
+reveal: anim.Anim = .{ .property = .opacity },
+parked: bool = false,
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),
+/// Index into `pins` for the buttons that show a pinned application.
+pin_of: [max_items]?u8 = @splat(null),
+pins: [max_pins]PinnedApp = undefined,
+pin_count: usize = 0,
+pin_arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator),
+/// Button index the first pin occupies, where a drop at slot 0 lands.
+pin_base: usize = 0,
+/// Where a dragged application would be pinned: the gap before this pin.
+drop_slot: ?usize = null,
animations: [max_items]ItemAnimation = @splat(.{}),
animating: bool = false,
count: usize = 0,
@@ -73,12 +131,22 @@ arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator),
/// repainted.
drawn: u64 = 0,
tip_drawn: u64 = 0,
+/// The last complete raster (`gpa`-owned) and the keys it was painted from. An
+/// animating icon repaints only its own cell on top of it, and only that cell is
+/// published as damage; anything dock-wide repaints the lot.
+retained: []u32 = &.{},
+base_drawn: u64 = 0,
+item_drawn: [max_items]u64 = @splat(0),
+items_drawn: usize = 0,
pub fn deinit(self: *Self) void {
+ if (self.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();
self.arena.deinit();
+ self.pin_arena.deinit();
+ gpa.free(self.retained);
self.* = .{};
}
@@ -98,6 +166,8 @@ fn ensureNodes(self: *Self, output: *Output) !void {
self.node = node;
self.tooltip = tooltip;
self.glass_effect = glass.Engine.attach(output.server.glass_engine, node, &node.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);
}
fn ignoreInput(_: *wlr.SceneBuffer, _: *f64, _: *f64) callconv(.c) bool {
@@ -112,44 +182,197 @@ pub fn tick(self: *Self, output: *Output, now_ms: i64) bool {
}
self.ensureNodes(output) catch return false;
const focused = @import("ipc/handlers.zig").findFocusedToplevel(server);
- const usable = output.usableBox();
+ // The dock sits beside the taskbar, not beside its own reserved strip.
+ const area = output.dockAreaBox();
const m: Metrics = .{ .height = @intCast(server.config.compositor.dock_height) };
- const shortcut_count = self.shortcutCount();
const position = server.config.compositor.dock_position;
- const available_length = if (position.vertical()) usable.height else usable.width;
- const available_thickness = if (position.vertical()) usable.width else usable.height;
- const min_length = @max(260, @as(i32, @intCast(shortcut_count)) * m.itemStep() + m.padding() * 2 + 12);
- const visible = server.locker == null and available_length >= min_length and available_thickness >= @max(140, m.height + 72) and
+ const visible = server.locker == null and fits(&server.config.compositor, area) and
!(if (focused) |top| top.fullscreen and top.currentOutput() == output else false);
- self.tree.?.node.setEnabled(visible);
if (self.visible != visible) {
self.visible = visible;
self.leave();
self.dirty = true;
}
if (!visible) {
+ self.tree.?.node.setEnabled(false);
+ // Coming back (fullscreen ended, unlocked) starts from rest, not from a
+ // reveal the pointer asked for before: it must not flash in.
+ self.parked = false;
+ self.pointer_near = false;
+ self.shown = false;
+ self.disarm();
+ self.reveal.cancel(if (server.config.compositor.dock_auto_hide) 0 else 1);
if (server.input.window_menu.dock == self) server.input.window_menu.close();
return false;
}
+ const revealing = self.syncReveal(now_ms);
+ if (self.parked) {
+ // Away: the next reveal rebuilds and paints before the first frame it shows.
+ self.tree.?.node.setEnabled(false);
+ self.leave();
+ return false;
+ }
+ if (self.dirty) self.resolvePins();
+ const fixed_count = self.fixedCount();
+ const available_length = if (position.vertical()) area.height else area.width;
if (self.scale != output.wlr_output.scale) self.dirty = true;
if (self.position != position or self.metrics().height != m.height) self.dirty = true;
// Output geometry can change without a window or theme notification.
- const capacity: usize = @intCast(@min(max_items - shortcut_count, @max(0, @divTrunc(available_length - m.padding() * 2 - 16, m.itemStep()) - @as(i32, @intCast(shortcut_count)))));
- const wanted = @min(capacity, self.windows) + shortcut_count;
+ const capacity: usize = @intCast(@min(max_items - fixed_count, @max(0, @divTrunc(available_length - m.padding() * 2 - 16, m.itemStep()) - @as(i32, @intCast(fixed_count)))));
+ const wanted = @min(capacity, self.windows) + fixed_count;
if ((if (position.vertical()) self.box.height else self.box.width) != @as(i32, @intCast(wanted)) * m.itemStep() + m.padding() * 2) self.dirty = true;
const rebuilt = self.dirty;
- if (rebuilt) self.rebuild(capacity, usable) catch return false;
+ if (rebuilt) self.rebuild(capacity, area) catch return false;
self.tree.?.node.setEnabled(self.count > 0);
if (self.count == 0) {
self.animating = false;
- return false;
+ return revealing;
}
- self.place(usable);
+ self.place(area);
if (rebuilt or self.animating) {
self.paint(now_ms) catch return false;
} else self.paintTooltip() catch {};
- self.tree.?.node.setPosition(self.box.x, self.box.y);
- return self.animating;
+ self.applyReveal(now_ms);
+ return self.animating or revealing;
+}
+
+/// What a dock reserves along `area`'s edge for windows: its thickness and the
+/// 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 {
+ 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;
+}
+
+/// Whether the dock, as configured, keeps windows out of its strip. A change
+/// to this (or to the dock's edge or size while it holds) moves the work area:
+/// refit windows with `Server.applyTaskbarPosition`.
+pub fn reserves(c: *const config.CompositorConfig) bool {
+ return c.dock_enabled and !c.dock_auto_hide;
+}
+
+/// Whether the dock shows at all in `area` (the output less the taskbar). Read
+/// from the configuration alone, so it agrees with what `reservedStrip` holds
+/// back wherever it is asked.
+fn fits(c: *const config.CompositorConfig, area: wlr.Box) bool {
+ const m: Metrics = .{ .height = @intCast(c.dock_height) };
+ const length = if (c.dock_position.vertical()) area.height else area.width;
+ const thickness = if (c.dock_position.vertical()) area.width else area.height;
+ const min_length = @max(260, @as(i32, @intCast(configuredFixedCount(c))) * m.itemStep() + m.padding() * 2 + 12);
+ return length >= min_length and thickness >= @max(140, m.height + 72);
+}
+
+/// `fixedCount` from the configuration alone: an uninstalled pin counts.
+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;
+ }
+ return count;
+}
+
+/// Auto-hide: lets `reveal` follow the pointer's wish, and parks the dock once
+/// it has gone. True while the reveal still moves.
+fn syncReveal(self: *Self, now_ms: i64) bool {
+ const server = self.output.?.server;
+ var target: f32 = 1;
+ if (server.config.compositor.dock_auto_hide) {
+ self.retime();
+ if (!self.shown) target = 0;
+ } else {
+ self.disarm();
+ self.pointer_near = false;
+ self.shown = false;
+ }
+ if (self.reveal.to != target) self.reveal.retargetTo(now_ms, target, anim.curveFor(.taskbar_hover));
+ const moving = !self.reveal.settled(now_ms);
+ self.parked = target == 0 and !moving;
+ return moving;
+}
+
+/// 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).
+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;
+ var y = self.box.y;
+ if (t < 1 and !anim.reducedMotion()) {
+ const away: i32 = @intFromFloat(@round((1 - t) * slide_distance));
+ switch (self.position) {
+ .top => y -= away,
+ .bottom => y += away,
+ .left => x -= away,
+ .right => x += away,
+ }
+ }
+ self.tree.?.node.setPosition(x, y);
+ self.node.?.setOpacity(t);
+}
+
+fn menuOpen(self: *const Self) bool {
+ return self.output.?.server.input.window_menu.dock == self;
+}
+
+/// Whether the pointer at layout position `x`, `y` wants the dock: it is at the
+/// output edge the dock is on, or on the dock (and the gap beside it) once shown.
+fn nearPointer(self: *const Self, output: *Output, x: f64, y: f64) bool {
+ const c = &output.server.config.compositor;
+ if (!c.dock_auto_hide or !self.visible) return false;
+ const full = output.cached_box;
+ const px: i32 = @intFromFloat(@floor(x));
+ const py: i32 = @intFromFloat(@floor(y));
+ if (px < full.x or py < full.y or px >= full.x + full.width or py >= full.y + full.height) return false;
+ const at_edge = switch (c.dock_position) {
+ .top => py < full.y + edge_band,
+ .bottom => py >= full.y + full.height - edge_band,
+ .left => px < full.x + edge_band,
+ .right => px >= full.x + full.width - edge_band,
+ };
+ 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;
+}
+
+/// Every pointer motion. `engaged` is false while a window is moved or resized
+/// or a button is held for a client, none of which should raise the dock.
+pub fn pointerAt(self: *Self, x: f64, y: f64, engaged: bool) void {
+ const output = self.output orelse return;
+ const near = engaged and self.nearPointer(output, x, y);
+ if (near == self.pointer_near) return;
+ self.pointer_near = near;
+ self.retime();
+}
+
+/// Starts (or drops) the delay before `shown` follows what the pointer wants.
+fn retime(self: *Self) void {
+ const wanted = self.pointer_near or self.menuOpen();
+ if (wanted == self.shown) return self.disarm();
+ if (self.timer_target == wanted) return;
+ self.timer_target = wanted;
+ const delay: i32 = if (wanted) reveal_delay_ms else hide_delay_ms;
+ const output = self.output.?;
+ if (self.timer == null) self.timer = output.server.wl_server.getEventLoop().addTimer(*Self, onTimer, self) catch null;
+ if (self.timer) |timer| {
+ if (timer.timerUpdate(delay)) return else |_| {}
+ }
+ // No timer: follow at once.
+ _ = onTimer(self);
+}
+
+fn disarm(self: *Self) void {
+ if (self.timer_target == null) return;
+ self.timer_target = null;
+ if (self.timer) |timer| timer.timerUpdate(0) catch {};
+}
+
+fn onTimer(self: *Self) c_int {
+ if (self.timer_target) |wanted| self.shown = wanted;
+ self.timer_target = null;
+ if (self.output) |output| output.wlr_output.scheduleFrame();
+ return 0;
}
fn hidden(items: []const []const u8, name: []const u8) bool {
@@ -157,11 +380,11 @@ fn hidden(items: []const []const u8, name: []const u8) bool {
return false;
}
-fn shortcutShown(self: *Self, shortcut: Shortcut) bool {
+fn shortcutShown(self: *const Self, shortcut: Shortcut) bool {
return !hidden(self.output.?.server.config.compositor.dock_hidden_shortcuts, @tagName(shortcut));
}
-fn shortcutCount(self: *Self) usize {
+fn shortcutCount(self: *const Self) usize {
var count: usize = 0;
for (std.enums.values(Shortcut)) |shortcut| if (self.shortcutShown(shortcut)) {
count += 1;
@@ -169,14 +392,58 @@ fn shortcutCount(self: *Self) usize {
return count;
}
-fn place(self: *Self, usable: wlr.Box) void {
- self.box.x = usable.x + @divTrunc(usable.width - self.box.width, 2);
- self.box.y = usable.y + @divTrunc(usable.height - self.box.height, 2);
+/// Buttons that always show, whatever windows are open.
+fn fixedCount(self: *const Self) usize {
+ return self.shortcutCount() + self.pin_count;
+}
+
+/// Looks the configured pins up in the catalogue; apps that are no longer
+/// installed stay in the config but are not shown.
+fn resolvePins(self: *Self) void {
+ _ = self.pin_arena.reset(.retain_capacity);
+ self.pin_count = 0;
+ const server = self.output.?.server;
+ const configured = server.config.compositor.dock_pinned_apps;
+ if (configured.len == 0) return;
+ const snapshot = server.start_menu_catalog.retainSnapshot();
+ defer snapshot.release();
+ const a = self.pin_arena.allocator();
+ for (configured, 0..) |id, config_index| {
+ if (self.pin_count == max_pins) break;
+ const entry = default_apps.find(snapshot.entries, id) orelse continue;
+ self.pins[self.pin_count] = .{
+ .id = a.dupe(u8, entry.id) catch return,
+ .name = a.dupe(u8, entry.name) catch return,
+ .icon = a.dupe(u8, entry.icon orelse entry.id) catch return,
+ .wm_class = if (entry.startup_wm_class) |class| a.dupe(u8, class) catch return else null,
+ .hash = std.hash.Wyhash.hash(0, entry.id) | 1,
+ .config_index = config_index,
+ };
+ self.pin_count += 1;
+ }
+}
+
+fn pinFor(self: *const Self, top: *Toplevel) ?usize {
+ for (self.pins[0..self.pin_count], 0..) |pin, i| if (pin.match().matches(top)) return i;
+ return null;
+}
+
+/// The window standing for an app on its dock button: the focused one, then a
+/// visible one, then the most recent.
+fn prefer(current: ?*Toplevel, top: *Toplevel, focused: ?*Toplevel) bool {
+ const held = current orelse return true;
+ return held != focused and (top == focused or (held.minimized and !top.minimized));
+}
+
+/// Where the dock rests in `area`: centred along its edge, `edge_margin` in.
+fn place(self: *Self, area: wlr.Box) void {
+ self.box.x = area.x + @divTrunc(area.width - self.box.width, 2);
+ self.box.y = area.y + @divTrunc(area.height - self.box.height, 2);
switch (self.position) {
- .top => self.box.y = usable.y + 10,
- .bottom => self.box.y = usable.y + usable.height - self.box.height - 10,
- .left => self.box.x = usable.x + 10,
- .right => self.box.x = usable.x + usable.width - self.box.width - 10,
+ .top => self.box.y = area.y + edge_margin,
+ .bottom => self.box.y = area.y + area.height - self.box.height - edge_margin,
+ .left => self.box.x = area.x + edge_margin,
+ .right => self.box.x = area.x + area.width - self.box.width - edge_margin,
}
}
@@ -229,7 +496,7 @@ fn shortcutApps(self: *Self, entries: []const apps.AppEntry, scratch: std.mem.Al
return matches;
}
-fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
+fn rebuild(self: *Self, capacity: usize, area: wlr.Box) !void {
const output = self.output.?;
const previous_animations = self.animations;
const previous_count = self.count;
@@ -239,22 +506,26 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
defer scratch.deinit();
const matches = self.shortcutApps(snapshot.entries, scratch.allocator());
var targets: [4]?*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;
defer tops.deinit(gpa);
var it = output.server.world.toplevels.iterator(.forward);
windows: while (it.next()) |top| {
- if (!top.in_world or top.closing or top.backend_gone or top.tab_hidden or top.dock_hidden or
- hidden(output.server.config.compositor.dock_hidden_apps, top.appId()) or
+ if (!top.in_world or top.closing or top.backend_gone or top.tab_hidden or
!@import("workspaces.zig").visible(top) or (top.live_rules.skip_taskbar orelse false) or
(output.server.world.workspaces.active and top.currentOutput() != output)) continue;
+ // Every running app shows: on its pin, on its shortcut, or as a window.
+ if (self.pinFor(top)) |pin| {
+ if (prefer(pin_targets[pin], top, focused)) pin_targets[pin] = top;
+ continue;
+ }
for ([_]Shortcut{ .files, .terminal, .settings }) |shortcut| {
- if (!matches[@intFromEnum(shortcut)].matches(top)) continue;
+ // A removed shortcut is only a launcher gone: its app, once
+ // running, is an ordinary window button.
+ if (!self.shortcutShown(shortcut) or !matches[@intFromEnum(shortcut)].matches(top)) continue;
const target = &targets[@intFromEnum(shortcut)];
- // A removed shortcut also hides the app it represents. Keep the
- // focused window, then a visible window, then the most recent one.
- if (self.shortcutShown(shortcut) and (target.* == null or
- (target.*.? != focused and (top == focused or (target.*.?.minimized and !top.minimized))))) target.* = top;
+ if (prefer(target.*, top, focused)) target.* = top;
continue :windows;
}
try tops.append(gpa, top);
@@ -267,7 +538,7 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
self.windows = tops.items.len;
self.offset = @min(self.offset, self.windows -| capacity);
const window_count = @min(capacity, self.windows);
- self.count = window_count + self.shortcutCount();
+ self.count = window_count + self.fixedCount();
self.position = output.server.config.compositor.dock_position;
const m: Metrics = .{ .height = @intCast(output.server.config.compositor.dock_height) };
const length = @as(i32, @intCast(self.count)) * m.itemStep() + m.padding() * 2;
@@ -279,11 +550,18 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
_ = 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) };
var index: usize = 0;
+ self.pin_of = @splat(null);
for ([_]Shortcut{ .applications, .files, .terminal }) |shortcut| {
if (!self.shortcutShown(shortcut)) continue;
self.setButton(index, shortcut, if (targets[@intFromEnum(shortcut)]) |top| top.id else 0);
index += 1;
}
+ self.pin_base = index;
+ for (pin_targets[0..self.pin_count], 0..) |target, pin| {
+ self.pin_of[index] = @intCast(pin);
+ self.setButton(index, null, if (target) |top| top.id else 0);
+ index += 1;
+ }
for (tops.items[self.offset .. self.offset + window_count]) |top| {
self.setButton(index, null, top.id);
index += 1;
@@ -292,11 +570,12 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
for (self.animations[0..self.count], 0..) |*pill, i| {
const shortcut = self.shortcuts[i];
const id = self.ids[i];
- pill.* = .{ .shortcut = shortcut, .id = id };
+ const pin: u64 = if (self.pin_of[i]) |p| self.pins[p].hash else 0;
+ pill.* = .{ .shortcut = shortcut, .pin = pin, .id = id };
// Widget indexes move as windows open or items are removed. A
- // shortcut keeps its animation when its representative window changes.
+ // shortcut or pin keeps its animation when its representative window changes.
for (previous_animations[0..previous_count]) |previous| {
- if (previous.shortcut == shortcut and (shortcut != null or previous.id == id)) {
+ if (previous.shortcut == shortcut and previous.pin == pin and (shortcut != null or pin != 0 or previous.id == id)) {
pill.* = previous;
break;
}
@@ -306,7 +585,7 @@ fn rebuild(self: *Self, capacity: usize, usable: wlr.Box) !void {
// The pointer rests on a replaced button: hover it before painting, so
// the rebuild paints once.
if (hovered) {
- self.place(usable);
+ 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))));
}
@@ -318,7 +597,10 @@ fn setButton(self: *Self, index: usize, shortcut: ?Shortcut, id: u64) void {
self.ids[index] = id;
self.shortcuts[index] = shortcut;
self.buttons[index] = .{
- .name = if (shortcut) |s| @tagName(s) else std.fmt.allocPrint(self.arena.allocator(), "window_{d}", .{id}) catch "window",
+ .name = if (shortcut) |s| @tagName(s) else if (self.pin_of[index]) |p|
+ std.fmt.allocPrint(self.arena.allocator(), "pin_{s}", .{self.pins[p].id}) catch "pin"
+ else
+ std.fmt.allocPrint(self.arena.allocator(), "window_{d}", .{id}) catch "window",
.kind = .{ .button = .{ .label = self.arena.allocator().dupe(u8, self.label(index)) catch "Application", .variant = .ghost, .owner = self, .id = index, .on_click = clicked } },
.computed_x = @floatFromInt(if (self.position.vertical()) self.buttonCross() else @as(i32, @intCast(index)) * m.itemStep() + m.padding()),
.computed_y = @floatFromInt(if (self.position.vertical()) @as(i32, @intCast(index)) * m.itemStep() + m.padding() else self.buttonCross()),
@@ -355,6 +637,7 @@ fn label(self: *Self, index: usize) []const u8 {
.terminal => "Terminal",
.settings => "Settings",
};
+ if (self.pin_of[index]) |p| return self.pins[p].name;
return if (self.topAt(index)) |top| top.title() else "Application";
}
@@ -391,17 +674,23 @@ fn paint(self: *Self, now_ms: i64) !void {
if (pal.dock_bg == null) bg[3] = @max(bg[3], 0.86);
const focused = @import("ipc/handlers.zig").findFocusedToplevel(output.server);
var looks: [max_items]Look = undefined;
+ var item_keys: [max_items]u64 = undefined;
self.animating = false;
+ // 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 });
+ const base_key = base_hasher.final();
var hasher = std.hash.Wyhash.init(0);
- hashValue(&hasher, .{ pal, bg, self.scale, self.position, self.box.width, self.box.height, self.count, self.offset, self.windows });
+ hasher.update(std.mem.asBytes(&base_key));
for (self.buttons[0..self.count], looks[0..self.count], 0..) |button, *look, index| {
const top = self.topAt(index);
const icon_name = if (self.shortcuts[index]) |shortcut| switch (shortcut) {
.applications => "builtin:redi-logo",
.files => "rediwm-files",
.terminal => "utilities-terminal",
- .settings => "preferences-system",
- } else if (top) |t| t.appId() else "";
+ .settings => ui.shell_icons.settings_icon_name,
+ } 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.
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));
@@ -430,53 +719,181 @@ fn paint(self: *Self, now_ms: i64) !void {
// moving between neighbours cannot make the row chase the pointer.
self.setButtonZoom(index, look.zoom);
const icon_id: ?u64 = if (look.icon) |icon| icon.id else null;
- hashValue(&hasher, .{ self.shortcuts[index], button.kind.button.state, look.focused, icon_id, look.pill_width, look.pill_opacity, look.zoom });
+ var item_hasher = std.hash.Wyhash.init(0);
+ hashValue(&item_hasher, .{ self.shortcuts[index], self.pin_of[index], button.kind.button.state, look.focused, icon_id, look.pill_width, look.pill_opacity, look.zoom });
+ item_keys[index] = item_hasher.final();
+ hasher.update(std.mem.asBytes(&item_keys[index]));
}
const key = hasher.final();
- if (key != self.drawn) try self.paintDock(pal, bg, looks[0..self.count]);
+ if (key != self.drawn) try self.paintDock(pal, bg, looks[0..self.count], base_key, item_keys[0..self.count]);
self.drawn = key;
try self.paintTooltip();
}
-fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look) !void {
+/// A device-pixel rectangle of the dock raster.
+const DeviceRect = struct {
+ x0: i32,
+ y0: i32,
+ x1: i32,
+ y1: i32,
+
+ fn area(self: DeviceRect) i64 {
+ return @as(i64, self.x1 - self.x0) * @as(i64, self.y1 - self.y0);
+ }
+
+ fn overlaps(self: DeviceRect, other: DeviceRect) bool {
+ return self.x0 < other.x1 and other.x0 < self.x1 and self.y0 < other.y1 and other.y0 < self.y1;
+ }
+
+ fn join(self: DeviceRect, other: DeviceRect) DeviceRect {
+ return .{ .x0 = @min(self.x0, other.x0), .y0 = @min(self.y0, other.y0), .x1 = @max(self.x1, other.x1), .y1 = @max(self.y1, other.y1) };
+ }
+};
+
+/// 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).
+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 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));
+ return if (self.position.vertical())
+ .{ .x0 = 0, .y0 = @max(0, lo), .x1 = width, .y1 = @min(height, hi) }
+ else
+ .{ .x0 = @max(0, lo), .y0 = 0, .x1 = @min(width, hi), .y1 = height };
+}
+
+/// The cells whose items changed since the retained raster, or null when the whole
+/// dock must be painted: nothing retained, dock-wide state moved, or the changed
+/// cells cover most of it anyway.
+fn changedCells(self: *const Self, m: Metrics, base_key: u64, item_keys: []const u64, width: i32, height: i32) ?DeviceRect {
+ if (self.retained.len != @as(usize, @intCast(width)) * @as(usize, @intCast(height)) or
+ self.base_drawn != base_key or self.items_drawn != item_keys.len) return null;
+ var dirty: ?DeviceRect = null;
+ for (item_keys, self.item_drawn[0..item_keys.len], 0..) |key, drawn, index| {
+ if (key == drawn) continue;
+ const cell = self.itemCell(m, index, width, height);
+ dirty = if (dirty) |d| d.join(cell) else cell;
+ }
+ const box = dirty orelse return null;
+ if (box.area() * 2 > @as(i64, width) * height) return null;
+ return box;
+}
+
+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 image = try PanelBuffer.create(self.box.width, self.box.height, self.scale);
+ const geometry = @import("geometry.zig");
+ const width = geometry.devicePixels(self.box.width, self.scale);
+ const height = geometry.devicePixels(self.box.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)
+ else
+ try PanelBuffer.create(self.box.width, self.box.height, self.scale);
defer image.base.drop();
var r = ui.paint.Renderer.init(image.pixels, image.width, image.height, self.scale);
r.palette = pal;
+ const stride: usize = @intCast(image.width);
+ if (dirty) |box| {
+ // Start from what is on screen and paint the changed cells again, from
+ // clear, exactly as a whole paint would. A quarter pixel in from the cell
+ // edge keeps every shape on whole device pixels.
+ @memcpy(image.pixels, self.retained);
+ for (@as(usize, @intCast(box.y0))..@as(usize, @intCast(box.y1))) |y| @memset(image.pixels[y * stride + @as(usize, @intCast(box.x0)) .. y * stride + @as(usize, @intCast(box.x1))], 0);
+ const x0: f32 = @floatFromInt(box.x0);
+ const y0: f32 = @floatFromInt(box.y0);
+ r.damage_clip = .{
+ .x = (x0 + 0.25) / self.scale,
+ .y = (y0 + 0.25) / self.scale,
+ .w = (@as(f32, @floatFromInt(box.x1)) - x0 - 0.5) / self.scale,
+ .h = (@as(f32, @floatFromInt(box.y1)) - y0 - 0.5) / self.scale,
+ };
+ }
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 });
- for (self.buttons[0..self.count], looks, 0..) |button, look, index| {
- const x = button.computed_x;
- const cx = x + button.computed_width / 2;
- const cy = button.computed_y + button.computed_height / 2;
- ui.widgets.button.paintBackground(&r, .{ .x = x, .y = button.computed_y, .w = button.computed_width, .h = button.computed_height }, .{ .variant = .ghost, .radius = m.size(12) }, .{ .pointer = button.kind.button.state, .selected = look.focused });
- if (look.icon) |icon| {
- const size = @as(f32, @floatFromInt(m.length(36))) * look.zoom;
- r.drawImageCover(cx - size / 2, cy - size / 2, size, size, 0, .{ .pixels = icon.pixels, .width = icon.size, .height = icon.size });
- } else {
- const size = @as(f32, @floatFromInt(m.length(34))) * look.zoom;
- r.drawIcon(cx - size / 2, cy - size / 2, size, size, .{ .id = if (self.shortcuts[index]) |shortcut| switch (shortcut) {
- .applications => .grid,
- .files => .folder,
- .terminal => .terminal,
- .settings => .settings,
- } else .generic, .color = pal.window_fg });
- }
- if (look.pill_width > 0 and look.pill_opacity > 0) {
- var accent = pal.accent;
- accent[3] *= look.pill_opacity;
- const width = m.size(look.pill_width);
- 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 });
+ 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.paintMarks(&r, pal, m);
+ if (dirty) |box| {
+ for (@as(usize, @intCast(box.y0))..@as(usize, @intCast(box.y1))) |y| {
+ const row = y * stride;
+ @memcpy(self.retained[row + @as(usize, @intCast(box.x0)) .. row + @as(usize, @intCast(box.x1))], image.pixels[row + @as(usize, @intCast(box.x0)) .. row + @as(usize, @intCast(box.x1))]);
}
+ var region: @import("pixman").Region32 = undefined;
+ region.initRect(box.x0, box.y0, @intCast(box.x1 - box.x0), @intCast(box.y1 - box.y0));
+ defer region.deinit();
+ self.node.?.setBufferWithDamage(&image.base, &region);
+ } else {
+ self.retained = gpa.realloc(self.retained, image.pixels.len) catch blk: {
+ // Without a copy the next paint is a whole one.
+ gpa.free(self.retained);
+ break :blk &.{};
+ };
+ if (self.retained.len == image.pixels.len) @memcpy(self.retained, image.pixels);
+ self.node.?.setBuffer(&image.base);
+ }
+ 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);
+}
+
+/// 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 {
+ 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;
+ // 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 });
+ 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 });
+ } 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) {
+ .applications => .grid,
+ .files => .folder,
+ .terminal => .terminal,
+ .settings => .settings,
+ } else .generic, .color = pal.window_fg });
+ }
+ if (look.pill_width > 0 and look.pill_opacity > 0) {
+ var accent = pal.accent;
+ accent[3] *= look.pill_opacity;
+ const width = m.size(look.pill_width);
+ 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 });
+ }
+}
+
+/// 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 {
+ if (self.drop_slot) |slot| {
+ // A dragged application lands in this gap between two buttons.
+ const gap: f32 = @floatFromInt(m.itemStep() - m.length(48));
+ const along = @as(f32, @floatFromInt(m.padding() + @as(i32, @intCast(self.pin_base + slot)) * m.itemStep())) - gap / 2;
+ const thickness = @max(2, m.size(3));
+ 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 });
}
var divider = pal.window_fg;
divider[3] = 0.16;
@@ -487,11 +904,9 @@ fn paintDock(self: *Self, pal: ui.theme.Theme, bg: [4]f32, looks: []const Look)
if (self.offset > 0) {
if (self.position.vertical()) r.drawIcon(m.size(28), 1, m.size(12), m.size(10), .{ .id = .chevron_up, .color = pal.accent }) else r.drawIcon(1, m.size(28), m.size(10), m.size(12), .{ .id = .chevron_left, .color = pal.accent });
}
- if (self.offset + self.count - self.shortcutCount() < self.windows) {
+ if (self.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 });
}
- self.node.?.setBuffer(&image.base);
- self.node.?.setDestSize(self.box.width, self.box.height);
}
fn paintTooltip(self: *Self) !void {
@@ -507,16 +922,16 @@ fn paintTooltip(self: *Self) !void {
const pal = ui.theme.shellPalette();
const value = self.label(index);
var hasher = std.hash.Wyhash.init(0);
- const usable = self.output.?.usableBox();
- hashValue(&hasher, .{ pal, self.scale, self.position, self.box.width, usable.width, value });
+ const area = self.output.?.dockAreaBox();
+ hashValue(&hasher, .{ pal, self.scale, self.position, self.box.width, area.width, value });
const key = hasher.final();
if (key == self.tip_drawn) {
// Same text: only the button under it may differ.
- self.placeTooltip(hovered, self.tooltip.?.dst_width, usable);
+ self.placeTooltip(hovered, self.tooltip.?.dst_width, area);
self.tooltip.?.node.setEnabled(true);
return;
}
- const max_width = if (self.position.vertical()) usable.width - self.box.width - 18 else self.box.width;
+ const max_width = if (self.position.vertical()) area.width - self.box.width - 18 else self.box.width;
const width: i32 = @intFromFloat(@min(@as(f32, @floatFromInt(max_width)), @max(80, (ui.text.measureWidthF(value, .manrope, pal.font_size, 1) catch 100) + 24)));
const image = try PanelBuffer.create(width, 30, self.scale);
defer image.base.drop();
@@ -528,12 +943,12 @@ fn paintTooltip(self: *Self) !void {
r.drawText(10, 0, @floatFromInt(width - 20), 30, .{ .content = value, .font_size = pal.font_size, .color = pal.window_fg });
self.tooltip.?.setBuffer(&image.base);
self.tooltip.?.setDestSize(width, 30);
- self.placeTooltip(hovered, width, usable);
+ self.placeTooltip(hovered, width, area);
self.tooltip.?.node.setEnabled(true);
self.tip_drawn = key;
}
-fn placeTooltip(self: *Self, hovered: *ui.layout.Widget, width: i32, usable: wlr.Box) void {
+fn placeTooltip(self: *Self, hovered: *ui.layout.Widget, width: i32, area: wlr.Box) void {
var x = self.box.x + @as(i32, @intFromFloat(hovered.computed_x + hovered.computed_width / 2)) - @divTrunc(width, 2);
var y = self.box.y + @as(i32, @intFromFloat(hovered.computed_y + hovered.computed_height / 2)) - 15;
switch (self.position) {
@@ -542,8 +957,8 @@ fn placeTooltip(self: *Self, hovered: *ui.layout.Widget, width: i32, usable: wlr
.left => x = self.box.x + self.box.width + 8,
.right => x = self.box.x - width - 8,
}
- x = std.math.clamp(x, usable.x, @max(usable.x, usable.x + usable.width - width));
- y = std.math.clamp(y, usable.y, @max(usable.y, usable.y + usable.height - 30));
+ x = std.math.clamp(x, area.x, @max(area.x, area.x + area.width - width));
+ y = std.math.clamp(y, area.y, @max(area.y, area.y + area.height - 30));
self.tooltip.?.node.setPosition(x - self.box.x, y - self.box.y);
}
@@ -579,28 +994,20 @@ pub fn contextMenu(self: *Self, x: f64, y: f64, screen_x: i32) bool {
const index = button.kind.button.id;
const target = self.topAt(index);
const shortcut = self.shortcuts[index];
- if (target == null and shortcut == null) return false;
+ const pin: ?[]const u8 = if (self.pin_of[index]) |p| self.pins[p].id else null;
+ if (target == null and shortcut == null and pin == null) return false;
const input = &self.output.?.server.input;
- input.window_menu.openDock(self, target, shortcut, screen_x, self.box.y + @as(i32, @intFromFloat(y)));
+ input.window_menu.openDock(self, target, shortcut, pin, screen_x, self.box.y + @as(i32, @intFromFloat(y)));
return input.window_menu.node != null;
}
-pub fn remove(self: *Self, shortcut: ?Shortcut, target: ?*Toplevel) void {
+/// 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;
- if (shortcut) |s| {
- self.saveHidden("dock_hidden_shortcuts", @tagName(s)) catch |err| {
- std.log.warn("could not remove dock shortcut: {}", .{err});
- return;
- };
- } else if (target) |top| {
- const id = top.appId();
- if (id.len == 0) {
- top.dock_hidden = true;
- } else self.saveHidden("dock_hidden_apps", id) catch |err| {
- std.log.warn("could not remove dock app: {}", .{err});
- return;
- };
- } else return;
+ self.saveHidden("dock_hidden_shortcuts", @tagName(shortcut)) catch |err| {
+ std.log.warn("could not remove dock shortcut: {}", .{err});
+ return;
+ };
var it = server.outputs.iterator(.forward);
while (it.next()) |output| output.dock.invalidate();
}
@@ -617,16 +1024,100 @@ fn saveHidden(self: *Self, comptime key: []const u8, name: []const u8) !void {
@field(server.config.compositor, key) = items;
}
+/// Where a dragged application would be pinned for a pointer at layout
+/// position `x`, `y`: the gap before that pin. Null when it is not over the dock.
+pub fn dropSlotAt(self: *const Self, x: f64, y: f64) ?usize {
+ if (!self.reachable() or self.count == 0) return null;
+ const local_x = x - @as(f64, @floatFromInt(self.box.x));
+ const local_y = y - @as(f64, @floatFromInt(self.box.y));
+ if (local_x < 0 or local_y < 0 or local_x >= @as(f64, @floatFromInt(self.box.width)) or local_y >= @as(f64, @floatFromInt(self.box.height))) return null;
+ const m = self.metrics();
+ return slotFor(if (self.position.vertical()) local_y else local_x, m.padding(), m.itemStep(), self.pin_base, self.pin_count);
+}
+
+/// The dock is on screen enough to be pointed at: an auto-hidden one is not
+/// there until it has mostly faded in.
+fn reachable(self: *const Self) bool {
+ return self.visible and !self.parked and self.reveal.value(anim.nowMs()) >= 0.5;
+}
+
+/// The nearest gap between buttons, as a pin position: icons sit one `step`
+/// apart after `padding`, the first pin at button `base`.
+fn slotFor(along: f64, padding: i32, step: i32, base: usize, pins: usize) usize {
+ const gap = @round((along - @as(f64, @floatFromInt(padding))) / @as(f64, @floatFromInt(step)));
+ return @intFromFloat(std.math.clamp(gap - @as(f64, @floatFromInt(base)), 0, @as(f64, @floatFromInt(pins))));
+}
+
+/// 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;
+ self.drop_slot = slot;
+ self.repaint();
+}
+
+/// Pins an application, from the start menu, at `slot` among the pins. Quietly
+/// ignores one that is already pinned, is not installed, is a shortcut's own
+/// app, or does not fit.
+pub fn pinApp(self: *Self, app_id: []const u8, slot: usize) void {
+ const server = self.output.?.server;
+ const old = server.config.compositor.dock_pinned_apps;
+ if (old.len >= max_pins or hidden(old, app_id)) return;
+ {
+ const snapshot = server.start_menu_catalog.retainSnapshot();
+ defer snapshot.release();
+ const entry = default_apps.find(snapshot.entries, app_id) orelse return;
+ var scratch = std.heap.ArenaAllocator.init(gpa);
+ defer scratch.deinit();
+ const matches = self.shortcutApps(snapshot.entries, scratch.allocator());
+ for ([_]Shortcut{ .files, .terminal }) |shortcut| {
+ if (self.shortcutShown(shortcut) and std.mem.eql(u8, matches[@intFromEnum(shortcut)].id, entry.id)) return;
+ }
+ }
+ const at = if (slot < self.pin_count) self.pins[slot].config_index else old.len;
+ const a = server.config.arena.allocator();
+ const items = a.alloc([]const u8, old.len + 1) catch return;
+ @memcpy(items[0..at], old[0..at]);
+ items[at] = a.dupe(u8, app_id) catch return;
+ @memcpy(items[at + 1 ..], old[at..]);
+ self.savePinned(items);
+}
+
+pub fn unpinApp(self: *Self, app_id: []const u8) void {
+ const server = self.output.?.server;
+ const old = server.config.compositor.dock_pinned_apps;
+ const a = server.config.arena.allocator();
+ const items = a.alloc([]const u8, old.len) catch return;
+ var len: usize = 0;
+ for (old) |id| {
+ if (std.mem.eql(u8, id, app_id)) continue;
+ items[len] = id;
+ len += 1;
+ }
+ if (len == old.len) return;
+ self.savePinned(items[0..len]);
+}
+
+fn savePinned(self: *Self, items: []const []const u8) void {
+ const server = self.output.?.server;
+ @import("config").setting_save.saveCompositor(gpa, server.io, server.config.path, "dock_pinned_apps", items) catch |err| {
+ std.log.warn("could not save pinned dock apps: {}", .{err});
+ return;
+ };
+ server.config.compositor.dock_pinned_apps = items;
+ var it = server.outputs.iterator(.forward);
+ while (it.next()) |output| output.dock.invalidate();
+}
+
/// Windows, theme or icons changed: rebuild on the output's next frame. A
/// hidden dock rebuilds when it is shown again.
pub fn invalidate(self: *Self) void {
self.dirty = true;
- if (self.visible) self.output.?.wlr_output.scheduleFrame();
+ if (self.visible and !self.parked) self.output.?.wlr_output.scheduleFrame();
}
pub fn scroll(self: *Self, delta: f64) void {
// A pending rebuild may add windows; it clamps the offset.
- if (delta == 0 or (!self.dirty and self.windows + self.shortcutCount() <= self.count)) return;
+ if (delta == 0 or (!self.dirty and self.windows + self.fixedCount() <= self.count)) return;
if (delta > 0) self.offset +|= 1 else self.offset -|= 1;
self.invalidate();
}
@@ -664,8 +1155,14 @@ fn clicked(owner: ?*anyopaque, index: usize) void {
if (top.minimized) top.restore() else server.world.focus(top);
server.world.navigateTo(top, output);
}
+ } else if (self.pin_of[index]) |pin_index| {
+ const snapshot = server.start_menu_catalog.retainSnapshot();
+ defer snapshot.release();
+ const id = self.pins[pin_index].id;
+ const entry = default_apps.find(snapshot.entries, id) orelse return;
+ @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.toggleStartMenu(),
+ .applications => output.toggleAppLauncher(),
.files, .terminal => @import("config_runtime/actions.zig").executeAction(server, .{ .spawn = if (shortcut == .files) "default-file-manager" else "default-terminal" }),
.settings => output.toggleControlCenter(),
};
diff --git a/src/Input.zig b/src/Input.zig
index c1b97b5..683bc3d 100644
--- a/src/Input.zig
+++ b/src/Input.zig
@@ -169,6 +169,8 @@ grab_y: f64 = 0,
grab_box: wlr.Box = undefined,
move_snap: MoveSnap = .{},
tiling_grab: ?@import("tiling_grab.zig") = null,
+/// An application being dragged from the start menu to the dock.
+dock_drag: @import("dock_drag.zig") = .{},
/// The last titlebar press, for double-click-to-maximize.
title_press: ?TitlePress = null,
/// Pointer presses so far: a double-click is two presses in a row.
@@ -1419,11 +1421,21 @@ pub fn warpCursor(input: *Input, x: f64, y: f64, time_msec: u32) void {
}
}
+/// An auto-hiding dock shows when the pointer reaches its edge. Moving or
+/// resizing a window, or holding a button for a client (a selection dragged to
+/// the edge), must not raise it; dragging an app from the start menu does.
+fn updateDockReveal(input: *Input) void {
+ const engaged = input.cursor_mode == .passthrough and (input.active_buttons == 0 or input.dock_drag.active());
+ var it = input.server.outputs.iterator(.forward);
+ while (it.next()) |output| output.dock.pointerAt(input.cursor.x, input.cursor.y, engaged);
+}
+
pub fn processCursorMotion(input: *Input, time_msec: u32) void {
if (input.server.locker != null or input.server.polkit_dialog != null or input.server.switcher.active()) return;
defer input.updateGrabBorderGlow();
input.positionDragIcon();
input.drag_dodge.motion();
+ input.updateDockReveal();
if (input.server.screenshot_selector.output != null) {
input.server.screenshot_selector.motion(input.cursor.x, input.cursor.y);
return;
@@ -1453,6 +1465,7 @@ pub fn processCursorMotion(input: *Input, time_msec: u32) void {
}
fn passthroughMotion(input: *Input, time_msec: u32) void {
+ if (input.dock_drag.motion(input)) return;
// Shell controls keep receiving motion until release, just like a client's
// implicit grab. A scrollbar drag may leave the whole window or panel.
if (input.open_control_center) |cc| {
@@ -1992,10 +2005,11 @@ fn processClientButton(
const local = cc.localPoint(input.cursor.x, input.cursor.y);
control_center.pointerButtonUp(cc, local.x, local.y);
}
- if (input.open_start_menu) |sm| {
+ // A drag onto the dock ends here; the menu must not see it as a click.
+ if (!input.dock_drag.release(input, button)) if (input.open_start_menu) |sm| {
const local = scene_data.toNodeLocal(&sm.buffer_node.node, input.cursor.x, input.cursor.y);
sm.pointerButtonUp(local.x, local.y);
- }
+ };
if (input.open_power_menu) |pm| {
const local = scene_data.toNodeLocal(&pm.buffer_node.node, input.cursor.x, input.cursor.y);
pm.pointerButtonUp(local.x, local.y);
@@ -2155,6 +2169,7 @@ fn processClientButton(
},
.start_menu => |res| {
res.menu.pointerButtonDown(res.sx, res.sy);
+ if (button == btn_left) if (res.menu.pressedApp()) |app| input.dock_drag.arm(input, app.id, app.icon, res.menu.wlr_output.scale);
return;
},
.power_menu => |res| {
@@ -2633,6 +2648,10 @@ pub fn finishTilingGrab(input: *Input, commit: bool) void {
}
pub fn cancelDrag(input: *Input) bool {
+ if (input.dock_drag.active()) {
+ input.dock_drag.cancel(input);
+ return true;
+ }
if (input.tiling_grab != null) {
input.finishTilingGrab(false);
input.processCursorMotion(0);
diff --git a/src/Keyboard.zig b/src/Keyboard.zig
index 8afe3bd..6559c2e 100644
--- a/src/Keyboard.zig
+++ b/src/Keyboard.zig
@@ -536,6 +536,14 @@ pub fn processKey(keyboard: *Keyboard, time_msec: u32, event_keycode: u32, state
}
if (keyboard.server.input.open_start_menu) |sm| {
+ // Escape abandons an application dragged out of the menu, not the menu.
+ if (state == .pressed and keyboard.server.input.dock_drag.active()) for (xkb_state.keyGetSyms(keycode)) |sym| {
+ if (@intFromEnum(sym) == xkb.Keysym.Escape) {
+ _ = keyboard.server.input.cancelDrag();
+ keyboard.consuming_escape = true;
+ return;
+ }
+ };
if (state == .pressed) for (keyboard.bindingSyms(keycode)) |sym| {
if (keyboard.server.input.isToggleStartMenu(wlr_keyboard.getModifiers(), sym)) {
if (event_keycode < keyboard.shortcut_consumed.len) keyboard.shortcut_consumed[event_keycode] = true;
diff --git a/src/Output.zig b/src/Output.zig
index 2bfaef2..f1e8a74 100644
--- a/src/Output.zig
+++ b/src/Output.zig
@@ -694,10 +694,10 @@ pub fn atLayout(server: *Server, lx: f64, ly: f64) ?*Output {
return null;
}
-// The output's usable area for compositor-driven placement (currently just
-// maximize), excluding the taskbar's reserved strip: the bar and its gap. A
-// short bar leaves the strip beside it whole.
-pub fn usableBox(output: *Output) wlr.Box {
+/// The output without the taskbar's reserved strip (the bar and its gap; a
+/// short bar leaves the strip beside it whole). The dock sits in this box and
+/// the taskbar's popups open against it: neither is placed around the dock.
+pub fn dockAreaBox(output: *Output) wlr.Box {
var box: wlr.Box = if (output.idle_blanked) output.cached_box else blk: {
var b: wlr.Box = undefined;
output.server.output_layout.getBox(output.wlr_output, &b);
@@ -710,9 +710,27 @@ pub fn usableBox(output: *Output) wlr.Box {
return box;
}
+/// The output's usable area for compositor-driven placement (maximize, tiles,
+/// new windows, popups): `dockAreaBox` less the strip a docked (not
+/// auto-hiding) dock claims. Windows never open or maximize behind either.
+pub fn usableBox(output: *Output) wlr.Box {
+ var box = output.dockAreaBox();
+ const strip = @import("Dock.zig").reservedStrip(output.server, box);
+ if (strip == 0) return box;
+ switch (output.server.config.compositor.dock_position) {
+ .top => box.y += strip,
+ .left => box.x += strip,
+ .bottom, .right => {},
+ }
+ if (output.server.config.compositor.dock_position.vertical()) {
+ box.width = @max(1, box.width - strip);
+ } else box.height = @max(1, box.height - strip);
+ return box;
+}
+
/// Place a taskbar popup on the inward side of the selected edge.
pub fn taskbarPopupY(output: *Output, height: i32, gap: i32) i32 {
- const box = output.usableBox();
+ const box = output.dockAreaBox();
return if (output.server.config.compositor.taskbar_position == .top)
box.y + gap
else
@@ -847,6 +865,7 @@ fn openMenu(output: *Output, mode: StartMenu.Mode) void {
pub fn closeStartMenu(output: *Output) void {
const sm = output.start_menu orelse return;
+ output.server.input.dock_drag.cancel(&output.server.input);
sm.beginClose();
if (output.server.input.open_start_menu == sm) {
output.server.input.open_start_menu = null;
diff --git a/src/Server.zig b/src/Server.zig
index a777dff..9735dd9 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -1247,8 +1247,8 @@ pub fn refreshTaskbarsGeometry(server: *Server) void {
if (strip_moved) server.applyTaskbarPosition();
}
-/// Apply a changed taskbar edge, or a changed strip (size or gap), to panels,
-/// reserved space and fixed layouts.
+/// Apply a changed taskbar edge, or a changed strip (size or gap, or the
+/// dock's: `Dock.reserves`), to panels, reserved space and fixed layouts.
pub fn applyTaskbarPosition(server: *Server) void {
Output.syncLayout(server);
var it = server.world.toplevels.iterator(.forward);
@@ -1413,7 +1413,7 @@ fn iconNameForAppId(snap: *applications.Snapshot, app_id: []const u8) []const u8
if (app_id.len == 0) return app_id;
// The built-in settings window has no desktop entry.
if (std.mem.eql(u8, app_id, @import("Toplevel.zig").welcome_app_id)) return "builtin:redi-logo";
- if (std.mem.eql(u8, app_id, @import("Toplevel.zig").settings_app_id)) return "preferences-system";
+ if (std.mem.eql(u8, app_id, @import("Toplevel.zig").settings_app_id)) return @import("ui").shell_icons.settings_icon_name;
// Pass 1: exact StartupWMClass match → use the desktop file's Icon= name.
for (snap.entries) |e| {
diff --git a/src/Taskbar.zig b/src/Taskbar.zig
index dffe091..007f646 100644
--- a/src/Taskbar.zig
+++ b/src/Taskbar.zig
@@ -193,6 +193,8 @@ box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = default_bar_height },
reserved: i32 = default_bar_height,
// The original look: edge to edge, on the output's edge, square.
flush: bool = true,
+// How far the background raster reaches past the output's far edges.
+bleed: Bleed = .{},
glass_effect: ?*glass.Effect = null,
item_layout: taskbar_items.Layout = .{},
dirty: bool = true,
@@ -674,10 +676,47 @@ pub fn placement(bar: *Taskbar, output_box: wlr.Box) shape.Placement {
});
}
+/// Logical px the bar's background reaches past the far edges of its output.
+pub const Bleed = struct { x: i32 = 0, y: i32 = 0 };
+
+/// Fractional scale floors an output's logical size (2560 / 1.5 is 1706), so a
+/// flush bar that ends there stops a device pixel short of the panel and
+/// shows whatever is under it. It reaches one logical pixel further, where no
+/// other output starts just past that edge: the raster would draw on it.
+fn bleedFor(bar: *Taskbar, output_box: wlr.Box, placed: wlr.Box) Bleed {
+ if (!shape.flush(output_box, placed, barRadius())) return .{};
+ const out = bar.wlr_output;
+ const turned = @intFromEnum(out.transform) & 1 != 0;
+ const scale: f64 = out.scale;
+ const device_width: f64 = @floatFromInt(if (turned) out.height else out.width);
+ const device_height: f64 = @floatFromInt(if (turned) out.width else out.height);
+ var bleed: Bleed = .{};
+ if (device_width > @round(scale * @as(f64, @floatFromInt(output_box.width)))) bleed.x = 1;
+ if (placed.y + placed.height == output_box.y + output_box.height and
+ device_height > @round(scale * @as(f64, @floatFromInt(output_box.height)))) bleed.y = 1;
+ if (bleed.x == 0 and bleed.y == 0) return bleed;
+ const right: wlr.Box = .{ .x = output_box.x + output_box.width, .y = output_box.y, .width = 1, .height = output_box.height };
+ const below: wlr.Box = .{ .x = output_box.x, .y = output_box.y + output_box.height, .width = output_box.width, .height = 1 };
+ var outputs = bar.server.outputs.iterator(.forward);
+ while (outputs.next()) |other| {
+ if (other.wlr_output == out) continue;
+ var box: wlr.Box = undefined;
+ bar.server.output_layout.getBox(other.wlr_output, &box);
+ if (boxesOverlap(box, right)) bleed.x = 0;
+ if (boxesOverlap(box, below)) bleed.y = 0;
+ }
+ return bleed;
+}
+
+fn boxesOverlap(a: wlr.Box, b: wlr.Box) bool {
+ return a.x < b.x + b.width and b.x < a.x + a.width and a.y < b.y + b.height and b.y < a.y + a.height;
+}
+
/// Whether the bar already sits where `placement` puts it.
pub fn isPlaced(bar: *Taskbar, output_box: wlr.Box) bool {
const wanted = bar.placement(output_box);
- return std.meta.eql(bar.box, wanted.box) and bar.reserved == wanted.reserved;
+ return std.meta.eql(bar.box, wanted.box) and bar.reserved == wanted.reserved and
+ std.meta.eql(bar.bleed, bar.bleedFor(output_box, wanted.box));
}
// Repositions the strip along the configured output edge.
@@ -689,6 +728,7 @@ pub fn relayout(bar: *Taskbar, output_box: wlr.Box) void {
bar.box = placed.box;
bar.reserved = placed.reserved;
bar.flush = shape.flush(output_box, bar.box, barRadius());
+ bar.bleed = bar.bleedFor(output_box, bar.box);
glass.Effect.configure(bar.glass_effect, barRadius(), 1);
bar.tree.node.setPosition(bar.box.x, bar.box.y);
const now_ms = nowMs();
@@ -1624,7 +1664,7 @@ fn render(bar: *Taskbar, now_ms: i64, causes: u8) void {
bar.renderAppTray();
const bh = bar.box.height;
if (bar.background_dirty) {
- renderPart(bar, now_ms, .background, 0, 0, bar.box.width, bh, bar.buffer_node, null);
+ renderPart(bar, now_ms, .background, 0, 0, bar.box.width + bar.bleed.x, bh + bar.bleed.y, bar.buffer_node, null);
bar.background_dirty = false;
}
bar.start_node.node.setEnabled(bar.itemShown(.start));
diff --git a/src/Toplevel.zig b/src/Toplevel.zig
index aa28da7..896ce07 100644
--- a/src/Toplevel.zig
+++ b/src/Toplevel.zig
@@ -150,6 +150,10 @@ shadow_tree: *wlr.SceneTree,
shadow_node: *wlr.SceneBuffer,
resize_grab: *wlr.SceneBuffer,
glass_effect: ?*glass.Effect = null,
+// Backdrop beneath the themed app body; opaque content masks it, leaving only
+// the sidebar frosted. The bufferless target owns geometry, never pixels/input.
+sidebar_glass_target: ?*wlr.SceneBuffer = null,
+sidebar_glass_effect: ?*glass.Effect = null,
titlebar_buffer: *wlr.SceneBuffer,
// Body under the border ring beside and below the client (left, right, bottom).
frame_fills: [3]*wlr.SceneRect,
@@ -281,8 +285,6 @@ needs_attention: bool = false,
maximized: bool = false,
fullscreen: bool = false,
in_world: bool = false,
-/// A dock removal without an app identity lasts for this window's lifetime.
-dock_hidden: bool = false,
placed: bool = false,
placeholder_source: ?*Toplevel = null,
rules_resolved: bool = false,
@@ -2729,6 +2731,7 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !void
defer if (toplevel.server.input.grabbed_toplevel == toplevel) toplevel.server.input.updateGrabBorderGlow();
const geometry_box = toplevel.clientGeometry();
if (geometry_box.width <= 0 or geometry_box.height <= 0) return;
+ defer toplevel.syncSidebarGlass(geometry_box.width, geometry_box.height);
const decorated = toplevel.hasServerDecorations();
toplevel.titlebar_buffer.node.setEnabled(decorated);
@@ -2826,6 +2829,39 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !void
/// How far an easing frame stretches its titlebar raster before rastering anew.
const titlebar_stretch: f32 = 0.12;
+fn syncSidebarGlass(toplevel: *Toplevel, width: i32, height: i32) void {
+ const themed = switch (toplevel.backend) {
+ .shell => |shell| !shell.welcome,
+ .xdg => std.mem.eql(u8, toplevel.appId(), "rediwm-files") or
+ std.mem.eql(u8, toplevel.appId(), "rediwm-file-chooser"),
+ else => false,
+ };
+ const enabled = themed and theme.global.app_sidebar_blur and theme.global.app_sidebar[3] < 1;
+ if (enabled and toplevel.sidebar_glass_target == null) {
+ const target = toplevel.content_tree.createSceneBuffer(null) catch return;
+ target.point_accepts_input = struct {
+ fn accepts(_: *wlr.SceneBuffer, _: *f64, _: *f64) callconv(.c) bool {
+ return false;
+ }
+ }.accepts;
+ target.node.placeBelow(&toplevel.scene_tree.node);
+ const effect = glass.Engine.attach(toplevel.server.glass_engine, target, &target.node, .sidebar) orelse {
+ target.node.destroy();
+ return;
+ };
+ // Both nodes belong to content_tree and are freed with the window.
+ toplevel.sidebar_glass_target = target;
+ toplevel.sidebar_glass_effect = effect;
+ }
+ if (toplevel.sidebar_glass_target) |target| {
+ target.node.setEnabled(enabled);
+ if (enabled) {
+ target.setDestSize(width, height);
+ glass.Effect.configure(toplevel.sidebar_glass_effect, 0, toplevel.shape_opacity);
+ }
+ }
+}
+
/// Whether a frame easing to a new size keeps its titlebar raster, stretched,
/// instead of rastering it for every frame (`ChromeBuffer.create` costs
/// milliseconds, and a reflow eases several frames at once): only the size
@@ -3039,6 +3075,7 @@ pub fn applyOpacity(toplevel: *Toplevel, now_ms: i64) void {
toplevel.applyDim(now_ms);
toplevel.applyShape();
glass.Effect.configure(toplevel.glass_effect, toplevel.cornerRadius(), opacity);
+ glass.Effect.configure(toplevel.sidebar_glass_effect, 0, opacity);
switch (toplevel.backend) {
.placeholder => |*ph| col.setRect(ph.body_rect, col.Straight.fromRgba(theme.global.window_bg).premultiply().scale(opacity)),
else => {},
diff --git a/src/audio/pipewire.zig b/src/audio/pipewire.zig
index 1dba92c..c838f79 100644
--- a/src/audio/pipewire.zig
+++ b/src/audio/pipewire.zig
@@ -653,6 +653,17 @@ fn actionSink(_: ?*pa.pa_context, info: ?*const pa.pa_sink_info, eol: c_int, use
.volume_down => current - 0.05,
else => unreachable,
};
+ // Raising the volume of a muted sink unmutes it, whatever
+ // asked (keys, taskbar scroll, sliders, IPC). `volume_up`
+ // counts even when already at the maximum.
+ const raising = switch (action) {
+ .volume_up => true,
+ .set_volume => volumeToPa(target) > pa.pa_cvolume_max(&sink.volume),
+ else => false,
+ };
+ if (raising and (sink.mute != 0 or self.mute_timer != null)) {
+ if (self.setMasterMuteLocked(sink.index, false, null)) |unmute| pa.pa_operation_unref(unmute);
+ }
if (pa.pa_cvolume_max(&volume) == 0) {
_ = pa.pa_cvolume_set(&volume, volume.channels, volumeToPa(target));
_ = pa.pa_cvolume_set_balance(&volume, &sink.channel_map, balance);
diff --git a/src/calendar.zig b/src/calendar.zig
index 70d4a71..31dab4d 100644
--- a/src/calendar.zig
+++ b/src/calendar.zig
@@ -14,11 +14,14 @@ const theme = @import("ui").theme;
const anim = @import("ui").anim;
const panel_present = @import("panel_present.zig");
const Anim = anim.Anim;
+const glass = @import("glass.zig");
+const popup_style = @import("popup_style.zig");
const slide_distance: f32 = 20;
pub const Calendar = struct {
output: *Output,
buffer_node: *wlr.SceneBuffer,
+ glass_effect: ?*glass.Effect = null,
node_data: scene.SceneData = undefined,
year: i32,
month: i32,
@@ -43,6 +46,7 @@ pub const Calendar = struct {
pub fn tick(self: *Calendar, now_ms: i64) bool {
_ = self.slide.sampleChanged(now_ms, anim.quantum_alpha);
panel_present.applySlide(self.buffer_node, self.panel_box, self.slide.value(now_ms), if (self.output.server.config.compositor.taskbar_position == .top) -slide_distance else slide_distance);
+ popup_style.configureGlass(&self.glass_effect, self.output.server.glass_engine, self.buffer_node, self.factor);
return !self.slide.settled(now_ms);
}
@@ -91,30 +95,38 @@ pub const Calendar = struct {
const buf = PanelBuffer.create(@max(1, width), @max(1, height), scale) catch return;
defer buf.base.drop();
var r: paint.Renderer = .{ .pixels = buf.pixels, .width = buf.width, .height = buf.height, .scale = scale * self.factor };
- const t = theme.shellPalette();
- const fill = [4]f32{ t.window_bg[0], t.window_bg[1], t.window_bg[2], t.calendar_opacity };
- r.fillRect(0, 0, 368, body_height, .{ .color = fill, .radius = t.calendar_radius, .border_width = 1, .border_color = t.calendar_border });
- // The pointer joins the bottom border and points towards the clock.
- for (0..@intCast(buf.height)) |iy| {
- const y = (@as(f32, @floatFromInt(iy)) + 0.5) / r.scale;
- 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 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);
- const border_mix = t.calendar_border[3] * (1 - inner);
- const alpha = (fill[3] + (1 - fill[3]) * border_mix) * coverage;
- var pixel: u32 = @as(u32, @intFromFloat(@round(alpha * 255))) << 24;
- for (0..3) |channel| {
- const value = fill[channel] + (t.calendar_border[channel] - fill[channel]) * border_mix;
- pixel |= @as(u32, @intFromFloat(@round(value * alpha * 255))) << @as(u5, @intCast(16 - channel * 8));
+ var t = theme.shellPalette();
+ 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);
+ t.text_secondary = t.window_fg;
+ t.faint = t.window_dim;
+ } else {
+ const fill = [4]f32{ t.window_bg[0], t.window_bg[1], t.window_bg[2], t.calendar_opacity };
+ r.fillRect(0, 0, 368, body_height, .{ .color = fill, .radius = t.calendar_radius, .border_width = 1, .border_color = t.calendar_border });
+ // The pointer joins the bottom border and points towards the clock.
+ for (0..@intCast(buf.height)) |iy| {
+ const y = (@as(f32, @floatFromInt(iy)) + 0.5) / r.scale;
+ 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 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);
+ const border_mix = t.calendar_border[3] * (1 - inner);
+ const alpha = (fill[3] + (1 - fill[3]) * border_mix) * coverage;
+ var pixel: u32 = @as(u32, @intFromFloat(@round(alpha * 255))) << 24;
+ for (0..3) |channel| {
+ const value = fill[channel] + (t.calendar_border[channel] - fill[channel]) * border_mix;
+ pixel |= @as(u32, @intFromFloat(@round(value * alpha * 255))) << @as(u5, @intCast(16 - channel * 8));
+ }
+ buf.pixels[iy * @as(usize, @intCast(buf.width)) + ix] = pixel;
}
- buf.pixels[iy * @as(usize, @intCast(buf.width)) + ix] = pixel;
}
+ if (self.output.server.config.compositor.taskbar_position == .top) buf.flipVertical();
}
- if (self.output.server.config.compositor.taskbar_position == .top) buf.flipVertical();
const tm = localNow();
var time: [32]u8 = undefined;
var date: [96]u8 = undefined;
@@ -145,6 +157,7 @@ pub const Calendar = struct {
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) };
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 bf7a742..d829229 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -126,11 +126,12 @@ pub const source =
\\dock_position = "bottom" # top, bottom, left or right
\\dock_height = 68 # thickness in logical px; 48-96, icons and spacing resize together
\\dock_hover_zoom = 1.05 # 1.0-1.5; 1.0 disables icon enlargement on hover
- \\dock_hidden_apps = [] # app IDs removed from the dock's context menu
+ \\dock_auto_hide = false # show the dock only when the pointer reaches its edge; false reserves its space
\\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", "center:windows", "right:tray", "right:battery", "right:network", "right:volume", "right:clock"]
+ \\taskbar_items = ["left:start", "left:windows", "right:tray", "right:battery", "right:network", "right:volume", "right:clock"]
\\focus_follows_mouse = false
\\canvas_columns = 3 # screens wide (1-10)
\\canvas_rows = 3 # screens tall (1-10)
@@ -147,11 +148,12 @@ pub const source =
\\# window_gap = 8 # px around and between tiled windows
\\snap_to_edges = true # drag a window to a screen edge to tile or maximize it
\\drag_feedback = true # softly lift a window while dragging it
- \\drag_scale = 1.03 # drag lift multiplier, 1.00-1.10
+ \\drag_scale = 1.002 # drag lift multiplier, 1.000-1.100
\\dodge_file_drags = true # a file manager slides aside while you drag a file out of it
\\files_single_click_open = true # Files: one click on an icon opens the file or folder
\\switcher_opacity = 1.0 # 0.0-1.0, background only; previews stay opaque
\\inactive_opacity = 1.0 # 0.0-1.0, 1.0 = no change
+ \\# terminal_opacity = 0.9 # 0.0-1.0 Foot background; new windows only. Unset keeps Foot's own alpha
\\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
diff --git a/src/config/loader.zig b/src/config/loader.zig
index a4c4057..f007bc2 100644
--- a/src/config/loader.zig
+++ b/src/config/loader.zig
@@ -134,8 +134,9 @@ pub const CompositorConfig = struct {
dock_position: types.DockPosition = .bottom,
dock_height: u32 = dock_height_default,
dock_hover_zoom: f32 = 1.05,
- dock_hidden_apps: []const []const u8 = &.{},
+ dock_auto_hide: bool = false,
dock_hidden_shortcuts: []const []const u8 = &.{},
+ dock_pinned_apps: []const []const u8 = &.{},
taskbar_items: TaskbarItems = .{},
taskbar_position: types.TaskbarPosition = .bottom,
/// App identities opted into compositor tabs. Only + launches join a group.
@@ -165,13 +166,16 @@ pub const CompositorConfig = struct {
snap_to_edges: bool = true,
/// Soft presentation-only lift while moving a window.
drag_feedback: bool = true,
- drag_scale: f32 = 1.03,
+ drag_scale: f32 = 1.002,
/// A file manager slides aside while a file is dragged out of it; see
/// `input/drag_dodge.zig`.
dodge_file_drags: bool = true,
/// Files opens an item with one click on its icon; names still select.
files_single_click_open: bool = true,
inactive_opacity: f32 = 1.0,
+ /// Background alpha handed to Foot 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
/// brightness and of its colour (`Toplevel.applyDim`).
inactive_dim: bool = true,
@@ -1066,8 +1070,9 @@ const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(CompositorC
.dock_position = .enumeration,
.dock_height = .{ .uint = .{ .min = dock_height_min, .max = dock_height_max } },
.dock_hover_zoom = .{ .float = .{ .min = 1, .max = dock_hover_zoom_max } },
- .dock_hidden_apps = .json_string_list,
+ .dock_auto_hide = .boolean,
.dock_hidden_shortcuts = .json_string_list,
+ .dock_pinned_apps = .json_string_list,
.taskbar_items = .taskbar_items,
.taskbar_position = .enumeration,
.icon_theme = .string,
@@ -1097,6 +1102,7 @@ const compositor_rules: std.enums.EnumFieldStruct(std.meta.FieldEnum(CompositorC
.dodge_file_drags = .boolean,
.files_single_click_open = .boolean,
.inactive_opacity = .{ .float = .{ .min = 0, .max = 1 } },
+ .terminal_opacity = .{ .float = .{ .min = 0, .max = 1 } },
.inactive_dim = .boolean,
.inactive_dim_amount = .{ .float = .{ .min = 0, .max = 0.5 } },
.switcher_opacity = .{ .float = .{ .min = 0, .max = 1 } },
@@ -1201,7 +1207,8 @@ fn applyField(target: anytype, allocator: Allocator, comptime rules: anytype, ke
.output_scale => @field(target, field.name) = try parseOutputScale(value),
.output_transform => @field(target, field.name) = try output_transform.parse(value),
.float => |range| {
- const v = try std.fmt.parseFloat(field.type, value);
+ const Float = if (@typeInfo(field.type) == .optional) @typeInfo(field.type).optional.child else field.type;
+ const v = try std.fmt.parseFloat(Float, value);
if (!std.math.isFinite(v) or v < range.min or v > range.max or
(range.exclusive_min and v == range.min)) return error.InvalidValue;
@field(target, field.name) = v;
@@ -1842,6 +1849,12 @@ test "config field parsing preserves ranges and derived zoom state" {
try applyCompositorKey(&c, a, "inactive_opacity", "1");
try std.testing.expectEqual(@as(f32, 1), c.inactive_opacity);
try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "inactive_opacity", "1.01"));
+ try std.testing.expectEqual(@as(?f32, null), c.terminal_opacity);
+ try applyCompositorKey(&c, a, "terminal_opacity", "0.85");
+ try std.testing.expectEqual(@as(?f32, 0.85), c.terminal_opacity);
+ inline for (.{ "nan", "-0.1", "1.01" }) |v| {
+ try std.testing.expectError(error.InvalidValue, applyCompositorKey(&c, a, "terminal_opacity", v));
+ }
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 266c9b3..98b158e 100644
--- a/src/config/taskbar_items.zig
+++ b/src/config/taskbar_items.zig
@@ -28,7 +28,7 @@ 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, .center, .right },
+ sections: [count]Section = .{ .right, .right, .right, .right, .left, .left, .right },
pub fn move(config: *Config, index: usize, right: bool) void {
if (index >= count or (!right and index == 0) or (right and index == count - 1)) return;
@@ -175,7 +175,7 @@ test "taskbar sections and hidden state round trip, migrate old lists and reject
try std.testing.expectEqualDeep(config, try Config.parse(encoded));
const legacy = try Config.parse("[\"clock\", \"-network\", \"battery\", \"volume\"]");
try std.testing.expectEqual(Section.left, legacy.section(.start));
- try std.testing.expectEqual(Section.center, legacy.section(.windows));
+ try std.testing.expectEqual(Section.left, legacy.section(.windows));
try std.testing.expectEqual(Item.clock, legacy.order[3]);
try std.testing.expect(!legacy.shown(.network));
for ([_][]const u8{ "[]", "[\"battery\", \"network\", \"volume\", \"volume\"]", "[\"battery\", \"network\", \"volume\", \"chevron\"]", "[\"left:battery\", \"network\", \"volume\", \"clock\"]" }) |bad| {
@@ -183,9 +183,12 @@ test "taskbar sections and hidden state round trip, migrate old lists and reject
}
}
-test "taskbar centers windows, separates sections and shrinks windows before fixed items" {
+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 defaults = arrange(config, 4, 980, 500, widths, 6, 16);
+ try std.testing.expectEqual(@as(?f32, 52), defaults.x[@intFromEnum(Item.windows)]);
+ 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)]);
try std.testing.expectEqual(@as(?f32, 884), full.x[@intFromEnum(Item.clock)]);
diff --git a/src/config/terminal_theme.zig b/src/config/terminal_theme.zig
index 6c1e8df..204cfa0 100644
--- a/src/config/terminal_theme.zig
+++ b/src/config/terminal_theme.zig
@@ -1,4 +1,5 @@
-//! Per-launch Foot colours. No user terminal configuration is overwritten.
+//! Per-launch Foot colours and background opacity. No user terminal
+//! configuration is overwritten.
const std = @import("std");
const Theme = @import("ui").theme.Theme;
const A = std.mem.Allocator;
@@ -6,16 +7,17 @@ const A = std.mem.Allocator;
const names = .{ "bg", "fg", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "bright_black", "bright_red", "bright_green", "bright_yellow", "bright_blue", "bright_magenta", "bright_cyan", "bright_white" };
const options = .{ "background", "foreground", "regular0", "regular1", "regular2", "regular3", "regular4", "regular5", "regular6", "regular7", "bright0", "bright1", "bright2", "bright3", "bright4", "bright5", "bright6", "bright7" };
-pub fn enabled(t: Theme) bool {
+/// `opacity` is `[compositor] terminal_opacity`: null keeps Foot's own `alpha`.
+pub fn enabled(t: Theme, opacity: ?f32) bool {
inline for (names) |name| if (@field(t, "terminal_" ++ name) != null) return true;
- return t.terminal_cursor != null;
+ return t.terminal_cursor != null or opacity != null;
}
/// 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.
-pub fn wrap(a: A, io: std.Io, args: []const []const u8, t: Theme) ![]const []const u8 {
- if (args.len == 0 or !enabled(t) or !std.mem.eql(u8, std.fs.path.basename(args[0]), "foot")) return args;
+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;
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" });
@@ -33,11 +35,14 @@ fn hex(a: A, color: [4]f32) ![]const u8 {
/// Newer Foot has dark/light palettes; older Foot has a single [colors].
/// Strings are owned by the caller's arena. Pack overrides precede explicit
/// command-line overrides, so a custom launcher can still choose its colours.
-pub fn argv(a: A, args: []const []const u8, t: Theme, modern: bool) ![]const []const u8 {
+pub fn argv(a: A, args: []const []const u8, t: Theme, opacity: ?f32, modern: bool) ![]const []const u8 {
var result: std.ArrayList([]const u8) = .empty;
try result.append(a, args[0]);
const sections: []const []const u8 = if (modern) &.{ "colors-dark", "colors-light" } else &.{"colors"};
for (sections) |section| {
+ if (opacity) |alpha| {
+ try result.append(a, try std.fmt.allocPrint(a, "--override={s}.alpha={d:.2}", .{ section, std.math.clamp(alpha, 0, 1) }));
+ }
inline for (names, options) |name, option| {
if (@field(t, "terminal_" ++ name)) |color| {
try result.append(a, try std.fmt.allocPrint(a, "--override={s}.{s}={s}", .{ section, option, try hex(a, color) }));
@@ -63,7 +68,7 @@ test "Foot palettes preserve arguments and support both config dialects" {
const t: Theme = .{ .terminal_fg = .{ 1, 0.5, 0, 1 }, .terminal_bg = .{ 0, 0, 0, 1 }, .terminal_cursor = .{ 1, 1, 1, 1 } };
const args: []const []const u8 = &.{ "foot", "-D", "/tmp/a b", "-e", "printf", "%s", "literal; text" };
for ([_]bool{ false, true }) |modern| {
- const result = try argv(a, args, t, modern);
+ const result = try argv(a, args, t, null, modern);
try std.testing.expectEqualStrings("foot", result[0]);
for (args[1..], result[result.len - (args.len - 1) ..]) |expected, actual| try std.testing.expectEqualStrings(expected, actual);
const expected = if (modern) "--override=colors-dark.foreground=ff8000" else "--override=colors.foreground=ff8000";
@@ -73,6 +78,29 @@ test "Foot palettes preserve arguments and support both config dialects" {
};
try std.testing.expect(found);
}
- try std.testing.expect(!enabled(.{}));
- try std.testing.expectEqualSlices([]const u8, args, try wrap(a, std.testing.io, args, .{}));
+ try std.testing.expect(!enabled(.{}, null));
+ try std.testing.expectEqualSlices([]const u8, args, try wrap(a, std.testing.io, args, .{}, null));
+}
+
+test "terminal opacity alone enables the wrapper and names each section's alpha" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const args: []const []const u8 = &.{ "foot", "-e", "top" };
+ try std.testing.expect(enabled(.{}, 0.5));
+ for ([_]bool{ false, true }) |modern| {
+ const result = try argv(a, args, .{}, 0.857, modern);
+ var count: usize = 0;
+ for (result) |arg| {
+ if (std.mem.endsWith(u8, arg, ".alpha=0.86")) count += 1;
+ // Opacity alone never invents a palette.
+ try std.testing.expect(std.mem.indexOf(u8, arg, "foreground") == null);
+ }
+ try std.testing.expectEqual(@as(usize, if (modern) 2 else 1), count);
+ try std.testing.expectEqualStrings(if (modern) "--override=colors-dark.alpha=0.86" else "--override=colors.alpha=0.86", result[1]);
+ for (args[1..], result[result.len - 2 ..]) |expected, actual| try std.testing.expectEqualStrings(expected, actual);
+ }
+ // Fully opaque is still an explicit choice, so a Foot config's own alpha loses.
+ const opaque_args = try argv(a, args, .{}, 1.0, true);
+ try std.testing.expectEqualStrings("--override=colors-dark.alpha=1.00", opaque_args[1]);
}
diff --git a/src/config_runtime/actions.zig b/src/config_runtime/actions.zig
index 746577c..cb4289d 100644
--- a/src/config_runtime/actions.zig
+++ b/src/config_runtime/actions.zig
@@ -632,7 +632,7 @@ fn launchPreferred(server: *Server, cmd: []const u8) void {
defer arena.deinit();
const args = @import("../start_menu/launch.zig").parseExec(arena.allocator(), command, null) catch return;
if (args.len == 0) return;
- const themed = @import("config").terminal_theme.wrap(arena.allocator(), server.io, args, server.config.theme) catch return;
+ const themed = @import("config").terminal_theme.wrap(arena.allocator(), server.io, args, server.config.theme, server.config.compositor.terminal_opacity) catch return;
if (themed.ptr == args.ptr) return spawnProcess(server, command);
spawnTracked(server, command, false, themed);
}
diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zig
index 51d376e..7439b0f 100644
--- a/src/config_runtime/apply.zig
+++ b/src/config_runtime/apply.zig
@@ -141,7 +141,9 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
server.scheduleFrames();
if (server.input.open_control_center) |cc| cc.refresh();
}
- if (old.compositor.inactive_opacity != new.compositor.inactive_opacity) {
+ if (old.compositor.inactive_opacity != new.compositor.inactive_opacity or
+ old.compositor.terminal_opacity != new.compositor.terminal_opacity)
+ {
if (server.input.open_control_center) |cc| cc.refresh();
}
if (old.compositor.inactive_dim != new.compositor.inactive_dim or
@@ -214,7 +216,14 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
if (server.input.open_control_center) |cc| cc.refresh();
}
- if (old.compositor.taskbar_position != new.compositor.taskbar_position) server.applyTaskbarPosition();
+ // A docked dock keeps windows out of its strip: refit them as it comes, goes or moves.
+ const dock = @import("../Dock.zig");
+ const dock_strip_moved = (dock.reserves(&old.compositor) or dock.reserves(&new.compositor)) and
+ (old.compositor.dock_enabled != new.compositor.dock_enabled or
+ old.compositor.dock_auto_hide != new.compositor.dock_auto_hide or
+ old.compositor.dock_position != new.compositor.dock_position or
+ old.compositor.dock_height != new.compositor.dock_height);
+ if (old.compositor.taskbar_position != new.compositor.taskbar_position or dock_strip_moved) server.applyTaskbarPosition();
if (old.compositor.dock_enabled != new.compositor.dock_enabled) {
server.scheduleFrames();
@@ -224,14 +233,16 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {
if (old.compositor.dock_position != new.compositor.dock_position or
old.compositor.dock_height != new.compositor.dock_height or
old.compositor.dock_hover_zoom != new.compositor.dock_hover_zoom or
- !stringListsEql(old.compositor.dock_hidden_apps, new.compositor.dock_hidden_apps) or
- !stringListsEql(old.compositor.dock_hidden_shortcuts, new.compositor.dock_hidden_shortcuts))
+ old.compositor.dock_auto_hide != new.compositor.dock_auto_hide or
+ !stringListsEql(old.compositor.dock_hidden_shortcuts, new.compositor.dock_hidden_shortcuts) or
+ !stringListsEql(old.compositor.dock_pinned_apps, new.compositor.dock_pinned_apps))
{
if (server.input.window_menu.dock != null) server.input.window_menu.close();
var output_it = server.outputs.iterator(.forward);
while (output_it.next()) |output| output.dock.invalidate();
- if (old.compositor.dock_position != new.compositor.dock_position) server.scheduleFrames();
- if (old.compositor.dock_position != new.compositor.dock_position or old.compositor.dock_height != new.compositor.dock_height or old.compositor.dock_hover_zoom != new.compositor.dock_hover_zoom) {
+ // A parked dock schedules no frame of its own.
+ if (old.compositor.dock_position != new.compositor.dock_position or old.compositor.dock_auto_hide != new.compositor.dock_auto_hide) server.scheduleFrames();
+ if (old.compositor.dock_position != new.compositor.dock_position or old.compositor.dock_height != new.compositor.dock_height or old.compositor.dock_hover_zoom != new.compositor.dock_hover_zoom or old.compositor.dock_auto_hide != new.compositor.dock_auto_hide) {
if (server.input.open_control_center) |cc| cc.refresh();
}
}
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index 640bcb2..0027bb8 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -564,7 +564,7 @@ pub const ControlCenter = struct {
},
}
cc.body_children = .{
- .{ .name = "nav", .kind = .{ .rect = .{ .color = t.app_sidebar, .radius = t.settings_sidebar_radius, .border_width = 1, .border_color = t.app_item_border } }, .direction = .column, .width = .{ .fixed = if (narrow) 70 else 238 }, .height = .{ .percent = 1 }, .padding = layout.Edges.all(8), .gap = nav_gap, .underlay = .{ .owner = cc, .paint = paintNavHighlights }, .children = cc.nav_rows[0..nav_count] },
+ .{ .name = "nav", .kind = .{ .rect = .{ .color = t.app_sidebar, .replace = t.app_sidebar[3] < 1, .radius = t.settings_sidebar_radius, .border_width = 1, .border_color = t.app_item_border } }, .direction = .column, .width = .{ .fixed = if (narrow) 70 else 238 }, .height = .{ .percent = 1 }, .padding = layout.Edges.all(8), .gap = nav_gap, .underlay = .{ .owner = cc, .paint = paintNavHighlights }, .children = cc.nav_rows[0..nav_count] },
.{ .kind = .{ .scroll_container = .{} }, .direction = .column, .@"align" = .stretch, .width = .{ .flex = 1 }, .height = .{ .percent = 1 }, .padding = layout.Edges.all(12), .gap = 14, .children = cc.content_children[0..cc.content_count] },
};
if (cc.page == .services) {
@@ -574,7 +574,8 @@ pub const ControlCenter = struct {
cc.body_children[1].padding.right += ui.widgets.scrollbar.gutter(theme.global.scrollbar_width);
}
cc.root_children[0] = .{ .kind = .container, .direction = .row, .padding = .{ .left = 16, .top = 16, .bottom = 16, .right = if (cc.page == .services) 16 else 6 }, .gap = 14, .width = .{ .percent = 1 }, .height = .{ .flex = 1 }, .children = &cc.body_children };
- // Opaque like a client's content: only the window chrome is glass.
+ // The content stays opaque; the sidebar replaces its background with
+ // app_sidebar so translucent themes expose the scene beneath it.
cc.root = .{
.kind = .{ .rect = .{ .color = bodyColor() } },
.direction = .column,
@@ -938,15 +939,20 @@ pub const ControlCenter = struct {
}
}
- /// `buildTree`, keeping each slider's hover and feedback look across it
- /// when the page is the same: a theme slider's save rebuilds the page the
- /// moment the button is released, under a pointer that is still on it.
+ /// `buildTree`, keeping each slider's hover and feedback look and each
+ /// switch's slide across it when the page is the same: a theme slider's save
+ /// rebuilds the page the moment the button is released, under a pointer that
+ /// is still on it, and a switch's change rebuilds before its knob has moved.
fn rebuildTree(cc: *ControlCenter) void {
const hovered_nav = cc.nav_hover.target;
const same_page = cc.built_page == cc.page;
const bluetooth_scroll: ?layout.ScrollState = if (same_page and cc.page == .bluetooth) cc.body_children[1].kind.scroll_container else null;
var saved: ui.widgets.slider.Saved = .{};
- if (same_page) ui.widgets.slider.capture(&cc.root, &saved);
+ var knobs: ui.widgets.toggle.Saved = .{};
+ if (same_page) {
+ ui.widgets.slider.capture(&cc.root, &saved);
+ ui.widgets.toggle.capture(&cc.root, &knobs);
+ }
cc.buildTree();
if (hovered_nav) |cell| {
const index: usize = @intCast(cell.row);
@@ -958,6 +964,7 @@ pub const ControlCenter = struct {
if (bluetooth_scroll) |state| cc.body_children[1].kind.scroll_container = state;
if (same_page) {
if (ui.widgets.slider.restore(&cc.root, &saved)) |hovered| ui.input.adoptHover(&cc.root, hovered);
+ ui.widgets.toggle.restore(&cc.root, &knobs);
}
}
@@ -1104,7 +1111,7 @@ pub const ControlCenter = struct {
if (alpha > 0) {
const box = navRowBox(list, hover.row);
renderer.fillRect(box.x, box.y, box.w, box.h, .{
- .color = scaleAlpha(t.surface_hover, alpha),
+ .color = scaleAlpha(t.sidebarHover(), alpha),
.radius = t.radius,
.border_width = 1,
.border_color = scaleAlpha(t.border_soft, alpha),
diff --git a/src/control_center/sections/appearance.zig b/src/control_center/sections/appearance.zig
index c9544b3..e866c3a 100644
--- a/src/control_center/sections/appearance.zig
+++ b/src/control_center/sections/appearance.zig
@@ -19,6 +19,7 @@ const setting_save = @import("config").setting_save;
const settings_portal = @import("../../session/settings_portal.zig");
const loader = @import("config").loader;
const Taskbar = @import("../../Taskbar.zig");
+const dock_mod = @import("../../Dock.zig");
const taskbar_items = @import("config").taskbar_items;
const cursor_theme = @import("../../cursor_theme.zig");
const wallpapers = @import("../../wallpapers.zig");
@@ -106,10 +107,11 @@ pub const Section = struct {
cursor_themes: ?[]cursor_theme.Theme = null,
cursor_row_children: [2]Widget = undefined,
family_row_children: [2]Widget = undefined,
- row_storage: [30]Widget = undefined,
+ row_storage: [31]Widget = undefined,
dock_children: [2]Widget = undefined,
dock_position_children: [2]Widget = undefined,
- dock_group_children: [4]Widget = undefined,
+ dock_auto_hide_children: [2]Widget = undefined,
+ dock_group_children: [5]Widget = undefined,
focus_zoom_children: [3]Widget = undefined,
drag_feedback_children: [2]Widget = undefined,
drag_scale_header_children: [2]Widget = undefined,
@@ -174,6 +176,9 @@ pub const Section = struct {
inactive_opacity_header_children: [2]Widget = undefined,
inactive_opacity_group_children: [2]Widget = undefined,
inactive_opacity_value_buf: [16]u8 = undefined,
+ 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,
taskbar_position_children: [2]Widget = undefined,
@@ -495,7 +500,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.{ .name = "drag_feedback", .kind = .{ .toggle = .{ .on = out.cc.server.config.compositor.drag_feedback, .owner = out, .on_change = &onDragFeedbackChanged } } },
};
const drag_scale = out.cc.server.config.compositor.drag_scale;
- const drag_formatted = std.fmt.bufPrint(&out.drag_scale_value_buf, "{d:.2}×", .{drag_scale}) catch "?";
+ const drag_formatted = std.fmt.bufPrint(&out.drag_scale_value_buf, "{d:.3}×", .{drag_scale}) catch "?";
out.drag_scale_header_children = .{ labelWidget("Drag lift scale"), pillWidget(drag_formatted) };
out.drag_scale_children = .{
.{ .kind = .container, .direction = .row, .justify = .space_between, .children = &out.drag_scale_header_children },
@@ -503,7 +508,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
.value = drag_scale,
.min = loader.drag_scale_min,
.max = loader.drag_scale_max,
- .step = 0.01,
+ .step = 0.001,
.owner = out,
.on_change = &onDragScaleChanged,
} } },
@@ -654,6 +659,25 @@ 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.
+ 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) };
+ const terminal_opacity_header: Widget = .{ .kind = .container, .direction = .row, .justify = .space_between, .children = &out.terminal_opacity_header_children };
+ const terminal_opacity_slider: Widget = .{
+ .name = "terminal_opacity",
+ .kind = .{ .slider = .{
+ .value = terminal_val,
+ .min = 0.0,
+ .max = 1.0,
+ .step = 0.01,
+ .owner = out,
+ .on_change = &onTerminalOpacityChanged,
+ } },
+ };
+ out.terminal_opacity_group_children = .{ terminal_opacity_header, terminal_opacity_slider };
+ const terminal_opacity_row: Widget = .{ .kind = .container, .direction = .column, .gap = 8, .children = &out.terminal_opacity_group_children };
+
const gap_val: f32 = @floatFromInt(@min(out.cc.server.config.compositor.windowGap(), max_window_gap));
const window_gap_row = pxGroup(out, px_window_gap, "Snapped window gap", gap_val, 0, max_window_gap, 1, &onWindowGapChanged);
@@ -820,6 +844,10 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
labelWidget("Dock position"),
.{ .name = "dock_position", .kind = .{ .segmented = .{ .labels = &.{ "Top", "Bottom", "Left", "Right" }, .selected = @intFromEnum(server.config.compositor.dock_position), .owner = out, .on_change = &onDockPositionChanged } }, .width = .{ .fixed = segmented_width } },
};
+ out.dock_auto_hide_children = .{
+ labelWidget("Auto-hide dock"),
+ .{ .name = "dock_auto_hide", .kind = .{ .toggle = .{ .on = server.config.compositor.dock_auto_hide, .owner = out, .on_change = &onDockAutoHideChanged } } },
+ };
const dock_height_row = pxGroup(out, px_dock_height, "Dock size", @floatFromInt(server.config.compositor.dock_height), @floatFromInt(loader.dock_height_min), @floatFromInt(loader.dock_height_max), 2, &onDockHeightChanged);
out.px[px_dock_height].group_children[1].name = "dock_height";
const dock_zoom_row = pxGroup(out, px_dock_hover_zoom, "Dock hover zoom (1.00× disables)", server.config.compositor.dock_hover_zoom, 1, loader.dock_hover_zoom_max, 0.05, &onDockHoverZoomChanged);
@@ -828,6 +856,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
out.dock_group_children = .{
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_children },
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_position_children },
+ .{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dock_auto_hide_children },
dock_height_row,
dock_zoom_row,
};
@@ -857,6 +886,7 @@ pub fn build(out: *Section, cc: *panel.ControlCenter) void {
buildWindowTabs(out),
.{ .kind = .container, .direction = .row, .justify = .space_between, .@"align" = .center, .children = &out.dim_row_children },
inactive_opacity_row,
+ terminal_opacity_row,
window_gap_row,
pxGroup(out, px_scrollbar_width, "Scrollbar width", t.scrollbar_width, 4, 24, 1, &PxHandler(px_scrollbar_width, "scrollbar_width", false).changed),
.{ .kind = .container, .direction = .column, .gap = 12, .children = &out.dock_group_children },
@@ -1540,6 +1570,21 @@ fn onInactiveOpacityChanged(owner: ?*anyopaque, _: usize, value: f32) void {
};
}
+/// Foot reads its 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);
+ const server = s.cc.server;
+ const clamped = std.math.clamp(value, 0.0, 1.0);
+ server.config.compositor.terminal_opacity = clamped;
+ const formatted = std.fmt.bufPrint(&s.terminal_opacity_value_buf, "{d}%", .{@as(i32, @intFromFloat(@round(clamped * 100.0)))}) catch "?";
+ s.terminal_opacity_header_children[1].kind.text.content = formatted;
+ s.terminal_opacity_header_children[1].markDirty();
+ setting_save.saveCompositor(main.gpa, server.io, server.config.path, "terminal_opacity", clamped) catch |err| {
+ std.log.warn("could not save terminal_opacity: {}", .{err});
+ };
+}
+
/// Slider range only; the config accepts up to 512.
const max_window_gap = 64;
@@ -1611,10 +1656,11 @@ fn onDragFeedbackChanged(owner: ?*anyopaque, _: usize, on: bool) void {
fn onDragScaleChanged(owner: ?*anyopaque, _: usize, value: f32) void {
const s = section(owner);
const server = s.cc.server;
- const scale = std.math.clamp(value, loader.drag_scale_min, loader.drag_scale_max);
+ // The slider's f32 steps drift (1.0299999); keep the saved value to its step.
+ const scale = std.math.clamp(@round(value * 1000) / 1000, loader.drag_scale_min, loader.drag_scale_max);
server.config.compositor.drag_scale = scale;
server.scheduleFrames();
- s.drag_scale_header_children[1].kind.text.content = std.fmt.bufPrint(&s.drag_scale_value_buf, "{d:.2}×", .{scale}) catch "?";
+ s.drag_scale_header_children[1].kind.text.content = std.fmt.bufPrint(&s.drag_scale_value_buf, "{d:.3}×", .{scale}) catch "?";
s.drag_scale_header_children[1].markDirty();
setting_save.saveCompositor(main.gpa, server.io, server.config.path, "drag_scale", scale) catch |err| {
std.log.warn("could not save drag_scale: {}", .{err});
@@ -1924,7 +1970,29 @@ fn onDockChanged(owner: ?*anyopaque, _: usize, on: bool) void {
section(owner).dock_children[1].markDirty();
return;
};
+ const reserved = dock_mod.reserves(&server.config.compositor);
server.config.compositor.dock_enabled = on;
+ if (reserved or dock_mod.reserves(&server.config.compositor)) server.applyTaskbarPosition();
+ server.scheduleFrames();
+}
+
+fn onDockAutoHideChanged(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_auto_hide", on) catch |err| {
+ std.log.warn("could not save dock auto-hide: {}", .{err});
+ s.dock_auto_hide_children[1].kind.toggle.on = server.config.compositor.dock_auto_hide;
+ s.dock_auto_hide_children[1].markDirty();
+ return;
+ };
+ const reserved = dock_mod.reserves(&server.config.compositor);
+ server.config.compositor.dock_auto_hide = on;
+ // A docked dock keeps windows out of its strip; one that hides does not.
+ if (reserved or dock_mod.reserves(&server.config.compositor)) server.applyTaskbarPosition();
+ 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();
+ // A parked dock schedules no frame of its own.
server.scheduleFrames();
}
@@ -1940,7 +2008,9 @@ fn onDockPositionChanged(owner: ?*anyopaque, _: usize, index: usize) void {
s.dock_position_children[1].markDirty();
return;
};
+ const reserved = dock_mod.reserves(&server.config.compositor);
server.config.compositor.dock_position = position;
+ if (reserved) server.applyTaskbarPosition();
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();
@@ -1958,7 +2028,9 @@ fn onDockHeightChanged(owner: ?*anyopaque, _: usize, value: f32) void {
s.px[px_dock_height].group_children[1].markDirty();
return;
};
+ const reserved = dock_mod.reserves(&server.config.compositor);
server.config.compositor.dock_height = height;
+ if (reserved) server.applyTaskbarPosition();
const formatted = std.fmt.bufPrint(&s.px[px_dock_height].value_buf, "{d}px", .{height}) catch "?";
s.px[px_dock_height].header_children[1].kind.text.content = formatted;
s.px[px_dock_height].header_children[1].markDirty();
diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zig
index 856c632..1e671bf 100644
--- a/src/desktop/watcher.zig
+++ b/src/desktop/watcher.zig
@@ -577,7 +577,7 @@ pub const Worker = struct {
if (@import("config").loader.load(cfg_path, mem, self.io, self.environ)) |loaded| {
var cfg = loaded;
defer cfg.deinit();
- themed = try @import("config").terminal_theme.wrap(mem, self.io, args.items, cfg.theme);
+ themed = try @import("config").terminal_theme.wrap(mem, self.io, args.items, cfg.theme, cfg.compositor.terminal_opacity);
} else |_| {}
}
var child = try std.process.spawn(self.io, .{ .argv = themed, .cwd = cwd, .environ_map = &self.child_env });
diff --git a/src/dock_drag.zig b/src/dock_drag.zig
new file mode 100644
index 0000000..e4219ab
--- /dev/null
+++ b/src/dock_drag.zig
@@ -0,0 +1,171 @@
+//! Dragging an application out of the start menu onto the dock pins it there.
+//!
+//! 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.
+const std = @import("std");
+const wlr = @import("wlroots");
+const ui = @import("ui");
+const Input = @import("Input.zig");
+const Output = @import("Output.zig");
+const PanelBuffer = @import("panel_buffer.zig").PanelBuffer;
+const geometry = @import("geometry.zig");
+const Self = @This();
+
+/// Logical pixels the pointer travels before a press becomes a drag.
+const threshold = 8;
+/// The dragged icon: a tile of `tile` px around an image of `image` px.
+const tile = 48;
+const image = 38;
+
+id_bytes: [512]u8 = undefined,
+id_len: usize = 0,
+icon_bytes: [256]u8 = undefined,
+icon_len: usize = 0,
+has_icon: bool = false,
+scale: f32 = 1,
+origin_x: f64 = 0,
+origin_y: f64 = 0,
+/// A press on an application is held, and may still turn out to be a click.
+armed: bool = false,
+dragging: bool = false,
+node: ?*wlr.SceneBuffer = null,
+
+fn ignoreInput(_: *wlr.SceneBuffer, _: *f64, _: *f64) callconv(.c) bool {
+ return false;
+}
+
+/// 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 };
+ 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;
+ if (icon) |name| if (name.len <= self.icon_bytes.len) {
+ @memcpy(self.icon_bytes[0..name.len], name);
+ self.icon_len = name.len;
+ self.has_icon = true;
+ };
+ self.armed = true;
+}
+
+pub fn active(self: *const Self) bool {
+ return self.dragging;
+}
+
+fn appId(self: *const Self) []const u8 {
+ return self.id_bytes[0..self.id_len];
+}
+
+/// Pointer motion with the button down. True while the drag owns the pointer.
+pub fn motion(self: *Self, input: *Input) bool {
+ if (!self.armed) return false;
+ if (input.active_buttons == 0) {
+ // The release never reached us (a grab ended it): nothing is held.
+ self.finish();
+ return false;
+ }
+ if (!self.dragging) {
+ 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;
+ };
+ self.dragging = true;
+ menu.cancelPress();
+ self.createIcon(input);
+ }
+ if (self.node) |node| node.node.setPosition(
+ @intFromFloat(@floor(input.cursor.x - tile / 2)),
+ @intFromFloat(@floor(input.cursor.y - tile / 2)),
+ );
+ input.setNamedCursor("grabbing");
+ input.seat.pointerClearFocus();
+ self.markDocks(input, false);
+ return true;
+}
+
+/// 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);
+ }
+ self.finish();
+ return dragging;
+}
+
+/// Abandons a drag in progress, or a press that might have become one.
+pub fn cancel(self: *Self, input: *Input) void {
+ if (self.dragging) self.markDocks(input, true);
+ self.finish();
+}
+
+fn finish(self: *Self) void {
+ if (self.node) |node| node.node.destroy();
+ self.* = .{};
+}
+
+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 };
+ }
+ return null;
+}
+
+/// Shows the drop gap on the dock under the pointer and clears every other.
+fn markDocks(self: *const Self, input: *Input, clear: bool) void {
+ const target = if (clear) null else self.dropTarget(input);
+ var it = input.server.outputs.iterator(.forward);
+ while (it.next()) |output| {
+ output.dock.setDropSlot(if (target) |drop| if (drop.output == output) drop.slot else null else null);
+ }
+}
+
+/// The tile that follows the pointer: the application's icon on a themed backing.
+fn createIcon(self: *Self, input: *Input) void {
+ const server = input.server;
+ const buffer = PanelBuffer.create(tile, tile, self.scale) catch return;
+ defer buffer.base.drop();
+ const pal = ui.theme.shellPalette();
+ var r = ui.paint.Renderer.init(buffer.pixels, buffer.width, buffer.height, self.scale);
+ r.palette = pal;
+ var bg = pal.window_bg;
+ bg[3] = 0.94;
+ 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) {
+ // 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));
+ if (lookup != .ready) continue;
+ const icon = lookup.ready;
+ r.drawImageCover(inset, inset, image, image, 0, .{ .pixels = icon.pixels, .width = icon.size, .height = icon.size });
+ drawn = true;
+ break;
+ }
+ }
+ if (!drawn) r.drawIcon(inset, inset, image, image, .{ .id = .generic, .color = pal.window_fg });
+ const node = server.overlay_tree.createSceneBuffer(null) catch return;
+ node.point_accepts_input = ignoreInput;
+ node.setFilterMode(.bilinear);
+ node.setBuffer(&buffer.base);
+ node.setDestSize(tile, tile);
+ node.node.raiseToTop();
+ self.node = node;
+}
diff --git a/src/files/app.zig b/src/files/app.zig
index 878747b..e1d307d 100644
--- a/src/files/app.zig
+++ b/src/files/app.zig
@@ -3335,7 +3335,10 @@ pub const App = struct {
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);
c.cairo_paint(cr);
+ c.cairo_set_operator(cr, c.CAIRO_OPERATOR_OVER);
self.renderGitSidebar(cr, content_width);
// Under the labels: the glide passes over the PLACES heading.
const glide = self.nav_hover.frame;
@@ -6599,6 +6602,7 @@ test "retained hover repairs match complete Cairo rasters at scale 1 and 1.5" {
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 };
+ ui_theme.global.app_sidebar[3] = 0.5;
const before = anim.currentSettings();
defer anim.applySettings(before);
anim.applySettings(.{ .reduced_motion = .off });
@@ -6623,6 +6627,11 @@ test "retained hover repairs match complete Cairo rasters at scale 1 and 1.5" {
c.cairo_scale(ref, scale, scale);
app.stepHover(0);
app.render(cr);
+ c.cairo_surface_flush(retained);
+ const sidebar_pixels: [*]const u32 = @ptrCast(@alignCast(c.cairo_image_surface_get_data(retained)));
+ const sidebar_x: usize = @intFromFloat(2 * scale);
+ const sidebar_y: usize = @intFromFloat(@as(f64, @floatFromInt(app.contentTop() + 2)) * scale);
+ try std.testing.expectEqual(@as(u32, 128), sidebar_pixels[sidebar_y * @as(usize, @intCast(w)) + sidebar_x] >> 24);
app.dirty = false;
var points: std.ArrayList([2]f64) = .empty;
defer points.deinit(std.testing.allocator);
diff --git a/src/glass.c b/src/glass.c
index 9c53b24..7d39c38 100644
--- a/src/glass.c
+++ b/src/glass.c
@@ -10,7 +10,7 @@
#include <wlr/util/addon.h>
#include "glass.h"
-enum glass_kind { GLASS_TITLEBAR, GLASS_TASKBAR, GLASS_PANEL };
+enum glass_kind { GLASS_TITLEBAR, GLASS_TASKBAR, GLASS_PANEL, GLASS_SIDEBAR };
struct glass_effect;
struct glass_engine {
struct wl_list effects;
@@ -73,8 +73,9 @@ bool rediwm_glass_effect_info(struct wlr_scene_node *node, struct rediwm_glass_i
return false;
*out = (struct rediwm_glass_info){
.target = effect->target,
- .sigma = effect->kind == GLASS_TITLEBAR ? 22 : effect->kind == GLASS_TASKBAR ? 24 : 26,
- .saturation = effect->kind == GLASS_PANEL ? 1.6f : 1.5f,
+ // Sidebars retain background shapes through a lighter frost.
+ .sigma = effect->kind == GLASS_SIDEBAR ? 8 : effect->kind == GLASS_TITLEBAR ? 22 : effect->kind == GLASS_TASKBAR ? 24 : 26,
+ .saturation = effect->kind == GLASS_PANEL || effect->kind == GLASS_SIDEBAR ? 1.6f : 1.5f,
.opacity = effect->opacity,
.radius = effect->radius,
.serial = effect->serial,
diff --git a/src/glass.zig b/src/glass.zig
index fa6a610..2d510f2 100644
--- a/src/glass.zig
+++ b/src/glass.zig
@@ -2,7 +2,7 @@
// (scene_output.c); see glass.c.
const wlr = @import("wlroots");
-pub const Kind = enum(c_int) { titlebar, taskbar, panel };
+pub const Kind = enum(c_int) { titlebar, taskbar, panel, sidebar };
pub const Effect = opaque {
extern fn rediwm_glass_detach(effect: ?*Effect) void;
pub const detach = rediwm_glass_detach;
diff --git a/src/glass_test.c b/src/glass_test.c
index 576ccff..9a54001 100644
--- a/src/glass_test.c
+++ b/src/glass_test.c
@@ -87,9 +87,10 @@ static void registry_checks(void)
rediwm_glass_detach(other);
assert(engine->held == NULL && wl_list_empty(&engine->effects));
assert(wl_list_length(&scene->tree.children) == 1);
- other = rediwm_glass_attach(engine, panel, &panel->node, GLASS_PANEL);
+ other = rediwm_glass_attach(engine, panel, &panel->node, GLASS_SIDEBAR);
assert(other && rediwm_glass_effect_info(&other->node->node, &info));
assert(info.serial != other_info.serial);
+ assert(info.sigma == 8 && info.saturation == 1.6f);
rediwm_glass_destroy(engine);
assert(wl_list_length(&scene->tree.children) == 1); // the panel; its effect went
wlr_scene_node_destroy(&scene->tree.node);
diff --git a/src/icon_cache.zig b/src/icon_cache.zig
index ab1ff3f..2eafe79 100644
--- a/src/icon_cache.zig
+++ b/src/icon_cache.zig
@@ -147,7 +147,10 @@ fn lookupScoped(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px:
}
}
- const found = (if (pack_only) try icon_theme.findPack(gpa, io, cfg, icon_name) else try icon_theme.find(gpa, io, cfg, icon_name, size_px)) orelse return null;
+ const found = (if (pack_only) try icon_theme.findPack(gpa, io, cfg, icon_name) else try icon_theme.find(gpa, io, cfg, icon_name, size_px)) orelse {
+ if (!pack_only and std.mem.eql(u8, icon_name, ui.shell_icons.settings_icon_name)) return builtinPng(ui.shell_icons.settings_icon_png, size_px);
+ return null;
+ };
defer gpa.free(found.path);
if (found.svg) {
@@ -161,6 +164,12 @@ fn lookupScoped(cfg: icon_theme.Config, io: Io, icon_name: []const u8, size_px:
return null;
}
+fn builtinPng(bytes: []const u8, size_px: i32) ?Entry {
+ const decoded = png.decode(gpa, bytes) catch return null;
+ defer decoded.deinit(gpa);
+ return Entry{ .pixels = resample(decoded.pixels, decoded.width, decoded.height, size_px) catch return null, .size = size_px };
+}
+
// A missing icon file is a permanent, expected outcome (most app_ids simply
// have no themed icon) so it collapses to `null` same as a decode failure.
// Anything else reading the file failed for (permission, a transient device
@@ -388,6 +397,17 @@ fn resample(src: []const u32, src_w: i32, src_h: i32, dst_size: i32) ![]u32 {
return dst;
}
+test "the built-in Settings icon decodes at any size" {
+ for ([_]i32{ 36, 54, 96 }) |size| {
+ const entry = builtinPng(ui.shell_icons.settings_icon_png, size) orelse return error.TestUnexpectedResult;
+ defer gpa.free(entry.pixels);
+ var opaque_pixels: usize = 0;
+ for (entry.pixels) |pixel| opaque_pixels += @intFromBool(pixel >> 24 >= 0xf0);
+ // A gear, not an empty or fully opaque square.
+ try std.testing.expect(opaque_pixels > entry.pixels.len / 5 and opaque_pixels < entry.pixels.len * 9 / 10);
+ }
+}
+
test "rectangular PNG icons keep their proportions" {
const src = [_]u32{ 0xffff0000, 0xff0000ff };
const pixels = try resample(&src, 2, 1, 4);
diff --git a/src/panel_paint.zig b/src/panel_paint.zig
index cc0074b..a536045 100644
--- a/src/panel_paint.zig
+++ b/src/panel_paint.zig
@@ -281,7 +281,7 @@ test "partial panel paint repairs recycled buffers with exact fractional-scale p
defer bg.deinit(allocator);
var children = [_]ui.layout.Widget{
.{ .kind = .{ .button = .{ .label = "Hover me" } }, .computed_x = 10, .computed_y = 12, .computed_width = 100, .computed_height = 30 },
- .{ .kind = .{ .rect = .{ .color = .{ 0.5, 0.1, 0.2, 0.4 }, .radius = 4 } }, .computed_x = 95, .computed_y = 25, .computed_width = 30, .computed_height = 35 },
+ .{ .kind = .{ .rect = .{ .color = .{ 0.5, 0.1, 0.2, 0.4 }, .radius = 4, .replace = true } }, .computed_x = 95, .computed_y = 25, .computed_width = 30, .computed_height = 35 },
};
var root: ui.layout.Widget = .{ .kind = .{ .rect = .{ .color = .{ 0.1, 0.2, 0.3, 0.6 }, .radius = 12 } }, .computed_width = 160, .computed_height = 90, .children = &children };
root.linkParents();
diff --git a/src/polkit/dialog.zig b/src/polkit/dialog.zig
index c4af647..b29272c 100644
--- a/src/polkit/dialog.zig
+++ b/src/polkit/dialog.zig
@@ -268,7 +268,10 @@ pub const Dialog = struct {
const t = ui.theme.shellPalette();
r.palette = t;
const dialog = ui.widgets.dialog;
- dialog.paintFrame(&r, .{ .x = 0, .y = 0, .w = 560, .h = 480 });
+ // Pair shell text and controls with the shell background, kept opaque.
+ var background = t.window_bg;
+ background[3] = 1;
+ dialog.paintFrameWithBackground(&r, .{ .x = 0, .y = 0, .w = 560, .h = 480 }, background);
dialog.paintHeader(&r, 28, 28, 504, .{
.icon = .lock,
.title = if (self.hidden) "Enter Password" else "Authentication",
diff --git a/src/start_menu/launch.zig b/src/start_menu/launch.zig
index 898d030..1f94195 100644
--- a/src/start_menu/launch.zig
+++ b/src/start_menu/launch.zig
@@ -307,7 +307,7 @@ fn launchExec(allocator: Allocator, server: *Server, entry: *const AppEntry, uri
}
var palette_arena = std.heap.ArenaAllocator.init(allocator);
defer palette_arena.deinit();
- const themed_argv = try @import("config").terminal_theme.wrap(palette_arena.allocator(), server.io, argv, server.config.theme);
+ const themed_argv = try @import("config").terminal_theme.wrap(palette_arena.allocator(), server.io, argv, server.config.theme, server.config.compositor.terminal_opacity);
const token = server.activation.createToken();
const token_name = if (token) |t| std.mem.span(t.name()) else null;
@@ -672,7 +672,7 @@ fn launchNewWindowBytes(allocator: Allocator, server: *Server, entry: *const App
defer snapshot.release();
const terminal = @import("../config_runtime/default_apps.zig").find(snapshot.entries, server.config.compositor.default_terminal);
const argv = try buildLaunchArgvUris(a, &live, server.environ, &.{}, terminal);
- const themed_argv = try @import("config").terminal_theme.wrap(a, server.io, argv, server.config.theme);
+ const themed_argv = try @import("config").terminal_theme.wrap(a, server.io, argv, server.config.theme, server.config.compositor.terminal_opacity);
var env_map = try server.environ.createMap(a);
defer env_map.deinit();
try server.applyChildEnvWithToken(&env_map, token);
diff --git a/src/start_menu/panel.zig b/src/start_menu/panel.zig
index 98840b1..b205392 100644
--- a/src/start_menu/panel.zig
+++ b/src/start_menu/panel.zig
@@ -1411,6 +1411,29 @@ pub const StartMenu = struct {
if (revision != ui.layout.paint_revision) menu.requestWidgetRepaint();
}
+ /// The application whose row or card the pointer is held down on, which
+ /// can be dragged to the dock. Valid until the results change.
+ pub fn pressedApp(menu: *StartMenu) ?struct { id: []const u8, icon: ?[]const u8 } {
+ const widget = menu.dispatcher.pressed orelse return null;
+ const index = switch (widget.kind) {
+ .row => |data| if (data.owner == @as(?*anyopaque, menu) and (data.on_click == onRowClick or data.on_click == onCardClick)) data.id else return null,
+ else => return null,
+ };
+ if (index >= menu.model.results.len) return null;
+ const result = menu.model.results[index];
+ if (result.app_entry == null) return null;
+ return .{ .id = result.id, .icon = result.icon };
+ }
+
+ /// A press became a drag: rebuild so no row stays pressed and the release
+ /// is not a click.
+ pub fn cancelPress(menu: *StartMenu) void {
+ const scroll = menu.currentScrollOffset();
+ menu.buildTree();
+ menu.restoreScrollOffset(scroll);
+ menu.requestRepaint();
+ }
+
pub fn pointerButtonDown(menu: *StartMenu, sx: f64, sy: f64) void {
menu.dispatcher.pointerButtonDown(&menu.root, @floatCast(sx), @floatCast(sy));
// A click or a drag-select moves the caret, and the next
diff --git a/src/start_menu/search.zig b/src/start_menu/search.zig
index 1626e4d..2548a0f 100644
--- a/src/start_menu/search.zig
+++ b/src/start_menu/search.zig
@@ -77,7 +77,7 @@ pub fn search(
.id = settings_id,
.name = settings_name,
.description = settings_description,
- .icon = "preferences-system",
+ .icon = @import("ui").shell_icons.settings_icon_name,
.is_settings = true,
.app_entry = null,
.score = 50,
@@ -116,7 +116,7 @@ pub fn search(
.id = settings_id,
.name = settings_name,
.description = settings_description,
- .icon = "preferences-system",
+ .icon = @import("ui").shell_icons.settings_icon_name,
.is_settings = true,
.app_entry = null,
.score = sc,
diff --git a/src/taskbar/window_menu.zig b/src/taskbar/window_menu.zig
index e68c1e3..7f259a1 100644
--- a/src/taskbar/window_menu.zig
+++ b/src/taskbar/window_menu.zig
@@ -14,6 +14,11 @@ pub const Menu = struct {
dock: ?*Dock = null,
shortcut: ?Dock.Shortcut = null,
target: ?*Toplevel = null,
+ /// The pinned app a dock button stands for, copied: the dock's own strings
+ /// are replaced by a rebuild while the menu is open.
+ pin_bytes: [512]u8 = undefined,
+ pin_len: usize = 0,
+ pinned: bool = false,
node: ?*wlr.SceneBuffer = null,
box: wlr.Box = .{ .x = 0, .y = 0, .width = 0, .height = 0 },
selected: ?usize = null,
@@ -25,30 +30,35 @@ pub const Menu = struct {
close,
force_close,
remove,
+ unpin,
fn label(action: Action) []const u8 {
return switch (action) {
.close => "Close",
.force_close => "Force Close",
.remove => "Remove from dock",
+ .unpin => "Unpin from dock",
};
}
};
fn actions(self: *const Menu) []const Action {
- return if (self.target == null) &.{.remove} else if (self.dock != null) &.{ .close, .force_close, .remove } else &.{ .close, .force_close };
+ if (self.pinned) return if (self.target == null) &.{.unpin} else &.{ .close, .force_close, .unpin };
+ // Only a shortcut can be removed; a running app always stays.
+ if (self.shortcut != null and self.dock != null) return if (self.target == null) &.{.remove} else &.{ .close, .force_close, .remove };
+ return &.{ .close, .force_close };
}
pub fn open(self: *Menu, bar: *Taskbar, target: *Toplevel, x: i32) void {
const output = Output.fromWlr(bar.wlr_output) orelse return;
- self.openOn(output, bar, null, target, null, x, 0);
+ self.openOn(output, bar, null, target, null, null, x, 0);
}
- pub fn openDock(self: *Menu, dock: *Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, x: i32, y: i32) void {
- self.openOn(dock.output orelse return, null, dock, target, shortcut, x, y);
+ pub fn openDock(self: *Menu, dock: *Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, pin: ?[]const u8, x: i32, y: i32) void {
+ self.openOn(dock.output orelse return, null, dock, target, shortcut, pin, x, y);
}
- fn openOn(self: *Menu, output: *Output, bar: ?*Taskbar, dock: ?*Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, x: i32, pointer_y: i32) void {
+ fn openOn(self: *Menu, output: *Output, bar: ?*Taskbar, dock: ?*Dock, target: ?*Toplevel, shortcut: ?Dock.Shortcut, pin: ?[]const u8, x: i32, pointer_y: i32) void {
self.close();
const server = output.server;
const input = &server.input;
@@ -58,7 +68,7 @@ pub const Menu = struct {
if (input.open_battery) |other| other.output.closeBattery();
if (input.open_calendar) |other| other.output.closeCalendar();
if (server.tray) |tray| tray.closeMenu();
- const bounds = output.usableBox();
+ const bounds = output.dockAreaBox();
const width = @min(216, bounds.width);
self.node = server.overlay_tree.createSceneBuffer(null) catch return;
self.bar = bar;
@@ -66,6 +76,11 @@ pub const Menu = struct {
self.dock = dock;
self.shortcut = shortcut;
self.target = target;
+ if (pin) |id| {
+ self.pin_len = @min(id.len, self.pin_bytes.len);
+ @memcpy(self.pin_bytes[0..self.pin_len], id[0..self.pin_len]);
+ self.pinned = true;
+ }
const count: i32 = @intCast(self.actions().len);
const height = padding * 2 + row_height * count + separator * (count - 1);
var menu_x = x;
@@ -155,12 +170,15 @@ pub const Menu = struct {
const target = self.target;
const dock = self.dock;
const shortcut = self.shortcut;
+ const pin_bytes = self.pin_bytes;
+ const pin = pin_bytes[0..self.pin_len];
// Shell windows can destroy themselves synchronously when closed.
self.close();
switch (action) {
.close => if (target) |t| t.sendClose(),
.force_close => if (target) |t| t.forceClose(),
- .remove => if (dock) |d| d.remove(shortcut, target),
+ .remove => if (dock) |d| if (shortcut) |s| d.removeShortcut(s),
+ .unpin => if (dock) |d| d.unpinApp(pin),
}
}
diff --git a/src/theme_main.zig b/src/theme_main.zig
index 159d94a..eb28a7a 100644
--- a/src/theme_main.zig
+++ b/src/theme_main.zig
@@ -108,14 +108,18 @@ fn run(init: std.process.Init) !void {
if (std.mem.eql(u8, verb, "terminal")) {
if (!std.mem.eql(u8, std.fs.path.basename(input), "foot")) return error.UnsupportedTerminal;
var palette: theme.Theme = .{};
+ var opacity: ?f32 = null;
if (@import("config").path.resolvePath(init.minimal.environ, a)) |path| {
- if (@import("config").loader.load(path, a, io, init.minimal.environ)) |cfg| palette = cfg.theme else |_| {}
+ if (@import("config").loader.load(path, a, io, init.minimal.environ)) |cfg| {
+ palette = cfg.theme;
+ opacity = cfg.compositor.terminal_opacity;
+ } else |_| {}
} else |_| {}
const terminal = @import("config").terminal_theme;
const raw = try a.alloc([]const u8, args.len - 2);
for (raw, args[2..]) |*dest, arg| dest.* = std.mem.span(arg);
var command: []const []const u8 = raw;
- if (terminal.enabled(palette)) {
+ if (terminal.enabled(palette, opacity)) {
// Probe an empty config, never the user's. This work happens only
// in the short-lived helper, outside the compositor event loop.
const probe = std.process.run(a, io, .{
@@ -125,7 +129,7 @@ fn run(init: std.process.Init) !void {
.timeout = .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } },
}) catch null;
const modern = if (probe) |p| p.term == .exited and p.term.exited == 0 else false;
- command = try terminal.argv(a, raw, palette, modern);
+ command = try terminal.argv(a, raw, palette, opacity, modern);
}
const argv = try a.allocSentinel(?[*:0]const u8, command.len, null);
for (argv, command) |*dest, arg| dest.* = (try a.dupeZ(u8, arg)).ptr;
diff --git a/src/tray.zig b/src/tray.zig
index f2ed6f5..246ab3e 100644
--- a/src/tray.zig
+++ b/src/tray.zig
@@ -229,7 +229,7 @@ pub const Tray = struct {
self.menu_item = item.id;
self.menu_scale = bar.wlr_output.scale;
self.menu_bounds = bar.box;
- if (@import("Output.zig").fromWlr(bar.wlr_output)) |out| self.menu_bounds = out.usableBox();
+ if (@import("Output.zig").fromWlr(bar.wlr_output)) |out| self.menu_bounds = out.dockAreaBox();
self.menu_box.x = x;
self.menu_box.y = bar.box.y;
self.showLevel(0);
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index e4b8f06..f7ad709 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -16,6 +16,10 @@ text and colours, secrets) are in the root `AGENTS.md` ("Shared UI").
`.{}` for the rest look. The gutter belongs to the bar: layouts keep content
out of it and a press in it never reaches content. Never change
`Appearance.width` per call site: it is every bar's width.
+ Hover fades in a pale reflection of `border_glow` along the thumb's edge;
+ dragging and the scroll hold brighten it. `Appearance.illumination` shares
+ the existing frame/deadline scheduling (no idle animation). Cairo uses the
+ shared raster for the lit thumb, preserving its fractional device position.
* **Scroll containers** (`.scroll_container`) give widget trees all of the
above: hosts call `scroll_container.stepBars` beside `stepGlides` and carry
`ScrollState.bar` across rebuilds. It scrolls along its `direction`, which
@@ -35,6 +39,17 @@ text and colours, secrets) are in the root `AGENTS.md` ("Shared UI").
so `panel.rebuildTree` carries named sliders' state across on the same page
(`slider.capture`/`restore` + `input.adoptHover`); an unnamed slider starts
fresh.
+* **Switches slide** (`widgets/toggle.zig`): `ToggleData.knob` eases the
+ knob (and the track's off/on colour) over `slide_ms`, and `paint` takes the
+ position (`Options.position`; null rests at `on`, which hand-laid panels such
+ as the network popup still use). `scroll_container.stepBars` calls
+ `toggle.step`, which retargets when `on` changed, repaints only on a changed
+ position and snaps when animations are off or reduced; a switch no frame has
+ seen starts at rest. A page rebuild that follows a click happens before the
+ first frame moves the knob, so `ControlCenter.rebuildTree` carries named
+ switches' knobs across with `toggle.capture`/`restore` (by name hash: arena
+ names don't outlive the rebuild). A host that builds `.toggle` widgets must
+ call `stepBars` or its switches never leave their first position.
* **The battery badge** (`widgets/battery.zig`: frame, glyph, percentage,
charging bolt) is the taskbar's artwork. `sample` is the pixel math (per
device pixel, badge-local units); the taskbar's per-pixel raster calls it and
diff --git a/src/ui/cairo.zig b/src/ui/cairo.zig
index c5f8678..278b069 100644
--- a/src/ui/cairo.zig
+++ b/src/ui/cairo.zig
@@ -112,6 +112,28 @@ pub fn drawSplitter(cr_any: *anyopaque, geometry: splitter.Geometry, engaged: bo
/// `scrollbar.paint` for the widget tree.
pub fn drawScrollbar(cr_any: *anyopaque, look: scrollbar.Look) void {
const cr: *c.cairo_t = @ptrCast(cr_any);
+ if (look.shine > 0) {
+ // Preserve the thumb's fractional placement within the device-aligned
+ // layer, including a Cairo translation, as its animated width changes.
+ const s = scaleOf(cr);
+ var dx: f64 = look.rect.x;
+ var dy: f64 = look.rect.y;
+ c.cairo_user_to_device(cr, &dx, &dy);
+ const inset_x: f32 = @floatCast((dx - @floor(dx)) / s);
+ const inset_y: f32 = @floatCast((dy - @floor(dy)) / s);
+ var layer = Layer.begin(cr, .{
+ .x = look.rect.x - inset_x,
+ .y = look.rect.y - inset_y,
+ .w = look.rect.w + inset_x,
+ .h = look.rect.h + inset_y,
+ }) orelse return;
+ var local = look;
+ local.rect.x = inset_x;
+ local.rect.y = inset_y;
+ scrollbar.paint(&layer.renderer, local);
+ layer.finish();
+ return;
+ }
const x: f64 = look.rect.x;
const y: f64 = look.rect.y;
const w: f64 = look.rect.w;
@@ -275,4 +297,21 @@ test "a scrollbar thumb paints its look through cairo" {
try std.testing.expectEqual(@as(u32, 0xff0000ff), data[15 * 40 + 27]);
try std.testing.expectEqual(@as(u32, 0), data[15 * 40 + 22]);
try std.testing.expectEqual(@as(u32, 0), data[45 * 40 + 27]);
+
+ // Engaged thumbs share the shell raster, including fractional placement,
+ // Cairo translation and clipping. The highlight remains inside the thumb.
+ c.cairo_set_operator(cr, c.CAIRO_OPERATOR_CLEAR);
+ c.cairo_paint(cr);
+ c.cairo_set_operator(cr, c.CAIRO_OPERATOR_OVER);
+ c.cairo_scale(cr, 1.5, 1.5);
+ c.cairo_translate(cr, 0.25, 0.5);
+ var hot = scrollbar.look(g, .{ .wide = 1, .accent = 1, .shine = 1 }, 8, palette);
+ drawScrollbar(cr, hot);
+ c.cairo_surface_flush(surface);
+ var expected = [_]u32{0} ** (40 * 60);
+ var renderer = paint.Renderer.init(&expected, 40, 60, 1.5);
+ hot.rect.x += 0.25;
+ hot.rect.y += 0.5;
+ scrollbar.paint(&renderer, hot);
+ try std.testing.expectEqualSlices(u32, &expected, data[0..expected.len]);
}
diff --git a/src/ui/context_menu.zig b/src/ui/context_menu.zig
index 2e798ca..70a7e01 100644
--- a/src/ui/context_menu.zig
+++ b/src/ui/context_menu.zig
@@ -57,6 +57,8 @@ pub const Row = struct {
pub fn row(cr_any: *anyopaque, box: Rect, opts: Row, context: bool) void {
const cr: *c.cairo_t = @ptrCast(cr_any);
+ // Desktop menus use app surfaces without resolving the compositor's theme forApp.
+ const foreground = theme.global.app_fg orelse theme.global.window_fg;
if (opts.separator) {
ui.setSource(cr, theme.global.app_divider);
c.cairo_set_line_width(cr, 1);
@@ -73,16 +75,16 @@ pub fn row(cr_any: *anyopaque, box: Rect, opts: Row, context: bool) void {
const size: f32 = if (context) 16 else 14;
if (ui.Layer.begin(cr, .{ .x = @floatCast(box.x + (if (context) @as(f64, 10) else 4)), .y = @floatCast(box.y + (box.h - size) / 2), .w = size, .h = size })) |l| {
var layer = l;
- layer.renderer.drawIcon(0, 0, size, size, .{ .id = id, .color = theme.global.window_fg });
+ layer.renderer.drawIcon(0, 0, size, size, .{ .id = id, .color = foreground });
layer.finish();
}
}
const metrics = ui.fontMetrics(cr, ui.textSize());
- ui.setSource(cr, theme.global.window_fg);
+ ui.setSource(cr, foreground);
ui.drawText(cr, opts.label, box.x + (if (context) @as(f64, 36) else 24), box.y + (box.h + metrics.ascent - metrics.descent) / 2, ui.textSize(), false);
if (opts.hint) |hint| {
const hint_metrics = ui.fontMetrics(cr, ui.statusSize());
- var ink = theme.global.window_fg;
+ var ink = foreground;
ink[3] *= 0.4;
ui.setSource(cr, ink);
ui.drawText(cr, hint, box.x + box.w - 12 - ui.measureText(cr, hint, ui.statusSize(), false), box.y + (box.h + hint_metrics.ascent - hint_metrics.descent) / 2, ui.statusSize(), false);
diff --git a/src/ui/layout.zig b/src/ui/layout.zig
index 9c4318f..03f4272 100644
--- a/src/ui/layout.zig
+++ b/src/ui/layout.zig
@@ -154,6 +154,9 @@ pub const TextFamily = enum { sans, mono };
pub const RectStyle = struct {
color: [4]f32,
+ /// Replace the covered background, preserving this fill's alpha. Rounded
+ /// edges still blend by coverage; useful for translucent inset panels.
+ replace: bool = false,
radius: f32 = 0,
border_width: f32 = 0,
border_color: [4]f32 = .{ 0, 0, 0, 0 },
@@ -320,6 +323,12 @@ pub const ToggleData = struct {
style: enum { standard, settings } = .standard,
on: bool,
disabled: bool = false,
+ /// 0 (off) to 1 (on): where the knob slides, eased by `widgets/toggle.zig`'s
+ /// `step` so a change travels instead of jumping.
+ knob: anim.Anim = .{},
+ /// The position last painted; NaN until the first `step`, so a freshly built
+ /// switch starts at rest instead of sliding in.
+ shown: f32 = std.math.nan(f32),
on_change: *const fn (?*anyopaque, usize, bool) void,
};
diff --git a/src/ui/paint.zig b/src/ui/paint.zig
index 88e6e4a..ebbc468 100644
--- a/src/ui/paint.zig
+++ b/src/ui/paint.zig
@@ -62,6 +62,7 @@ const RoundedFill = struct {
border: f32,
fg: text_mod.Color,
border_color: text_mod.Color,
+ replace: bool = false,
inline fn shade(f: RoundedFill, pixels: []u32, index: usize, sx: f32, sy: f32) void {
const outer = sdf.coverage(sdf.sdRoundedBox(sx, sy, f.box_x, f.box_y, f.box_w, f.box_h, f.radius));
@@ -71,7 +72,11 @@ const RoundedFill = struct {
const inner = sdf.coverage(sdf.sdRoundedBox(sx, sy, f.box_x + f.border, f.box_y + f.border, f.box_w - 2 * f.border, f.box_h - 2 * f.border, @max(f.radius - f.border, 0)));
color = lerpColor(f.border_color, f.fg, inner);
}
- blendPixel(&pixels[index], color, outer);
+ if (f.replace) {
+ var source: u32 = 0;
+ blendPixel(&source, color, outer);
+ pixels[index] = blendConstOver(pixels[index], source, 255 - byte(outer));
+ } else blendPixel(&pixels[index], color, outer);
}
};
@@ -180,6 +185,7 @@ pub const Renderer = struct {
.border = style.border_width * s,
.fg = toColor(style.color),
.border_color = toColor(style.border_color),
+ .replace = style.replace,
};
// Interior fast path. Away from the corners the rounded-box SDF is just
@@ -219,7 +225,7 @@ pub const Renderer = struct {
const inv_alpha = 255 - alpha8;
const premul_fg = (alpha8 << 24) | (byte(shape.fg.r * shape.fg.a) << 16) |
(byte(shape.fg.g * shape.fg.a) << 8) | byte(shape.fg.b * shape.fg.a);
- const store_interior = on_clear or style.color[3] >= 1;
+ const store_interior = on_clear or style.replace or style.color[3] >= 1;
var py = y0;
while (py < y1) : (py += 1) {
@@ -325,6 +331,18 @@ pub const Renderer = struct {
/// `pixels` scaled to cover the box, centre-cropped (CSS `object-fit:
/// cover`), and clipped to a rounded rect: an avatar.
pub fn drawImageCover(r: *Renderer, x: f32, y: f32, w: f32, h: f32, radius: f32, image: Image) void {
+ r.drawImageSampled(x, y, w, h, radius, image, false);
+ }
+
+ /// `drawImageCover` for an image that animates in size or sits at a
+ /// fractional position (the dock's hover zoom): every pixel is the area
+ /// average of the source it covers, so edges neither stair-step nor crawl
+ /// from frame to frame.
+ pub fn drawImageSmooth(r: *Renderer, x: f32, y: f32, w: f32, h: f32, radius: f32, image: Image) void {
+ r.drawImageSampled(x, y, w, h, radius, image, true);
+ }
+
+ fn drawImageSampled(r: *Renderer, x: f32, y: f32, w: f32, h: f32, radius: f32, image: Image, comptime smooth: bool) void {
r.clean = false;
if (w <= 0 or h <= 0 or image.width <= 0 or image.height <= 0) return;
const s = r.scale;
@@ -351,18 +369,28 @@ pub const Renderer = struct {
const k = @min(src_w / (w * s), src_h / (h * s));
const off_x = (src_w - w * s * k) / 2;
const off_y = (src_h - h * s * k) / 2;
+ // Source pixels one device pixel spans, at least one so that enlarging
+ // blends neighbours (bilinear) rather than repeating them.
+ const footprint = std.math.clamp(k, 1, max_footprint);
const stride: usize = @intCast(image.width);
var py = y0;
while (py < y1) : (py += 1) {
+ const sy = @as(f32, @floatFromInt(py)) + 0.5;
+ const v = off_y + (sy - y * s) * k;
+ // A row shares its vertical taps.
+ const down = if (smooth) Taps.init(v, footprint / 2, image.height) else undefined;
var px = x0;
while (px < x1) : (px += 1) {
const sx = @as(f32, @floatFromInt(px)) + 0.5;
- const sy = @as(f32, @floatFromInt(py)) + 0.5;
const cov = sdf.coverage(sdf.sdRoundedBox(sx, sy, x * s, y * s, w * s, h * s, radius * s));
if (cov <= 0) continue;
- const ix: usize = @intFromFloat(std.math.clamp(@floor(off_x + (sx - x * s) * k), 0, src_w - 1));
- const iy: usize = @intFromFloat(std.math.clamp(@floor(off_y + (sy - y * s) * k), 0, src_h - 1));
- blendPremultipliedPixel(&r.pixels[@intCast(py * r.width + px)], image.pixels[iy * stride + ix], cov);
+ const u = off_x + (sx - x * s) * k;
+ const sample = if (smooth)
+ boxAverage(image, Taps.init(u, footprint / 2, image.width), down)
+ else
+ image.pixels[@as(usize, @intFromFloat(std.math.clamp(@floor(v), 0, src_h - 1))) * stride +
+ @as(usize, @intFromFloat(std.math.clamp(@floor(u), 0, src_w - 1)))];
+ blendPremultipliedPixel(&r.pixels[@intCast(py * r.width + px)], sample, cov);
}
}
}
@@ -900,6 +928,83 @@ inline fn overPremultiplied(dst: u32, src: u32) u32 {
return src +% (rb_done | ag_done);
}
+/// Wider footprints sample more than a few taps a pixel; the dock only ever
+/// shrinks by its hover zoom (at most 1.5).
+const max_footprint: f32 = 8;
+const max_taps = 10;
+
+/// The source pixels one axis of a footprint covers and how much of each: the
+/// overlap of [centre - half, centre + half], cut to [0, limit], with pixel i
+/// spanning [i, i + 1).
+const Taps = struct {
+ first: usize = 0,
+ count: usize = 0,
+ weight: [max_taps]f32 = undefined,
+ sum: f32 = 0,
+
+ fn init(centre: f32, half: f32, limit: i32) Taps {
+ var taps: Taps = .{};
+ const lo = @max(centre - half, 0);
+ const hi = @min(centre + half, @as(f32, @floatFromInt(limit)));
+ if (lo >= hi) return taps;
+ taps.first = @intFromFloat(@floor(lo));
+ const last = @min(@as(usize, @intFromFloat(@ceil(hi))), @as(usize, @intCast(limit)));
+ taps.count = @min(last -| taps.first, max_taps);
+ for (0..taps.count) |i| {
+ const at: f32 = @floatFromInt(taps.first + i);
+ const weight = @min(at + 1, hi) - @max(at, lo);
+ taps.weight[i] = weight;
+ taps.sum += weight;
+ }
+ return taps;
+ }
+};
+
+/// Area average of the footprint whose axes are `across` and `down`: each source
+/// pixel weighs by how much of the footprint it covers. At a width of one this is
+/// bilinear interpolation. Premultiplied channels average correctly; the part of
+/// the footprint outside the image is left out.
+fn boxAverage(image: Image, across: Taps, down: Taps) u32 {
+ const total = across.sum * down.sum;
+ if (total <= 0) return 0;
+ const stride: usize = @intCast(image.width);
+ var a: f32 = 0;
+ var red: f32 = 0;
+ var green: f32 = 0;
+ var blue: f32 = 0;
+ for (0..down.count) |j| {
+ const row = image.pixels[(down.first + j) * stride + across.first ..][0..across.count];
+ var ra: f32 = 0;
+ var rr: f32 = 0;
+ var rg: f32 = 0;
+ var rb: f32 = 0;
+ for (row, across.weight[0..across.count]) |pixel, weight| {
+ ra += weight * @as(f32, @floatFromInt(pixel >> 24));
+ rr += weight * @as(f32, @floatFromInt((pixel >> 16) & 0xff));
+ rg += weight * @as(f32, @floatFromInt((pixel >> 8) & 0xff));
+ rb += weight * @as(f32, @floatFromInt(pixel & 0xff));
+ }
+ const weight = down.weight[j];
+ a += weight * ra;
+ red += weight * rr;
+ green += weight * rg;
+ blue += weight * rb;
+ }
+ const scale = 1 / total;
+ // Averages of premultiplied channels stay premultiplied: no channel exceeds alpha.
+ const out_a: u32 = @intFromFloat(@round(a * scale));
+ const out_r: u32 = @min(@as(u32, @intFromFloat(@round(red * scale))), out_a);
+ const out_g: u32 = @min(@as(u32, @intFromFloat(@round(green * scale))), out_a);
+ const out_b: u32 = @min(@as(u32, @intFromFloat(@round(blue * scale))), out_a);
+ return out_a << 24 | out_r << 16 | out_g << 8 | out_b;
+}
+
+/// `boxAverage` of the `width`-wide square centred on (u, v), in source pixels.
+fn boxSample(image: Image, u: f32, v: f32, width: f32) u32 {
+ const half = width / 2;
+ return boxAverage(image, Taps.init(u, half, image.width), Taps.init(v, half, image.height));
+}
+
fn blendPremultipliedPixel(dst: *u32, sample: u32, coverage: f32) void {
if (coverage <= 0) return;
const sa_raw = @as(f32, @floatFromInt((sample >> 24) & 0xff)) / 255.0;
@@ -1120,7 +1225,13 @@ fn paintToggle(widget: *const Widget, data: ToggleData, renderer: *Renderer) voi
.y = widget.computed_y,
.w = widget.computed_width,
.h = widget.computed_height,
- }, .{ .on = data.on, .style = data.style, .disabled = data.disabled, .focused = ui_input.isFocused(widget) });
+ }, .{
+ .on = data.on,
+ .position = if (std.math.isNan(data.shown)) null else data.shown,
+ .style = data.style,
+ .disabled = data.disabled,
+ .focused = ui_input.isFocused(widget),
+ });
}
/// Shared slider styling and feedback, using the surface's theme palette.
@@ -1356,6 +1467,24 @@ test "fillRect respects the active clip rect" {
try std.testing.expectEqual(@as(u32, 0), pixels[5 * 10 + 7]); // column 7: outside it
}
+test "replacement fills preserve alpha, rounded corners and damage clips" {
+ for ([_]f32{ 1, 1.5 }) |scale| {
+ var pixels = [_]u32{0xffeeeeee} ** (30 * 30);
+ var r = Renderer.init(&pixels, 30, 30, scale);
+ const style: RectStyle = .{ .color = .{ 0.4, 0.2, 0.1, 0.5 }, .radius = 4, .replace = true };
+ r.fillRect(2, 2, 16, 16, style);
+ const centre: usize = @intFromFloat(10 * scale);
+ try std.testing.expectEqual(@as(u32, 128), pixels[centre * 30 + centre] >> 24);
+ try std.testing.expectEqual(@as(u32, 0xffeeeeee), pixels[0]);
+ const corner: usize = @intFromFloat(2 * scale);
+ try std.testing.expectEqual(@as(u32, 0xffeeeeee), pixels[corner * 30 + corner]);
+ const expected = pixels;
+ r.damage_clip = .{ .x = 8, .y = 8, .w = 4, .h = 4 };
+ r.fillRect(2, 2, 16, 16, style);
+ try std.testing.expectEqualSlices(u32, &expected, &pixels);
+ }
+}
+
test "rounded fill spans match per-pixel shading at fractional scales" {
const cases = [_]struct { w: f32, h: f32, radius: f32, border: f32 }{
.{ .w = 44, .h = 24, .radius = 8, .border = 1 },
@@ -1656,3 +1785,32 @@ test "typing reveals text behind the gliding caret and preserves the suffix" {
}
}
}
+
+test "smooth image sampling is exact at one to one, blends between pixels and shrinks flat colour unchanged" {
+ const black: u32 = 0xff000000;
+ const white: u32 = 0xffffffff;
+ const checker = [_]u32{ black, white, white, black };
+ const image: Image = .{ .pixels = &checker, .width = 2, .height = 2 };
+ // Centred on a source pixel, one pixel wide: that pixel, untouched.
+ try std.testing.expectEqual(black, boxSample(image, 0.5, 0.5, 1));
+ try std.testing.expectEqual(white, boxSample(image, 1.5, 0.5, 1));
+ // Halfway between two columns: an even mix (bilinear).
+ try std.testing.expectEqual(@as(u32, 0xff808080), boxSample(image, 1.0, 0.5, 1));
+ // The whole image averages to mid grey whatever the footprint around its centre.
+ try std.testing.expectEqual(@as(u32, 0xff808080), boxSample(image, 1.0, 1.0, 2));
+
+ // Shrinking a flat translucent image by 1.3 keeps its premultiplied colour,
+ // also at the edge, where the footprint leaves the image.
+ const flat = [_]u32{0x80402010} ** 16;
+ const small: Image = .{ .pixels = &flat, .width = 4, .height = 4 };
+ for ([_]f32{ 0.1, 0.5, 2, 3.9 }) |at| try std.testing.expectEqual(@as(u32, 0x80402010), boxSample(small, at, at, 1.3));
+
+ // Placed 1:1 on a pixel boundary it reproduces the image.
+ var pixels = [_]u32{0} ** 16;
+ var r = Renderer.init(&pixels, 4, 4, 1);
+ r.drawImageSmooth(1, 1, 2, 2, 0, image);
+ try std.testing.expectEqual(black, pixels[1 * 4 + 1]);
+ try std.testing.expectEqual(white, pixels[1 * 4 + 2]);
+ try std.testing.expectEqual(white, pixels[2 * 4 + 1]);
+ try std.testing.expectEqual(black, pixels[2 * 4 + 2]);
+}
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index 9d5d121..76b9a65 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -7,6 +7,10 @@ const c = @cImport({
});
/// The start-button logo; not an `IconId` glyph because it keeps its own colours.
pub const redi_logo = @embedFile("redi-logo");
+/// The Settings app's colour icon (`settings_icon_name`), for when neither the
+/// active pack nor an installed icon theme has one.
+pub const settings_icon_png = @embedFile("rediwm-settings-icon");
+pub const settings_icon_name = "rediwm-settings";
const Handle = opaque {};
const GError = opaque {};
diff --git a/src/ui/theme.zig b/src/ui/theme.zig
index 122bd12..8319a72 100644
--- a/src/ui/theme.zig
+++ b/src/ui/theme.zig
@@ -53,6 +53,7 @@ pub const Theme = struct {
app_bg: [4]f32 = .{ 24.0 / 255.0, 28.0 / 255.0, 34.0 / 255.0, 1 }, // #181c22, main content
app_toolbar: [4]f32 = .{ 29.0 / 255.0, 34.0 / 255.0, 41.0 / 255.0, 1 }, // #1d2229
app_sidebar: [4]f32 = .{ 27.0 / 255.0, 33.0 / 255.0, 40.0 / 255.0, 1 }, // #1b2128
+ app_sidebar_blur: bool = false, // backdrop behind translucent Settings/Files sidebars
app_bar: [4]f32 = .{ 35.0 / 255.0, 42.0 / 255.0, 51.0 / 255.0, 1 }, // #232a33, column headers, status bars
app_item: [4]f32 = .{ 34.0 / 255.0, 40.0 / 255.0, 46.0 / 255.0, 1 }, // #22282e, rows, cards, thumbnails
app_item_hover: [4]f32 = .{ 37.0 / 255.0, 43.0 / 255.0, 50.0 / 255.0, 1 }, // #252b32
diff --git a/src/ui/widgets/scroll_container.zig b/src/ui/widgets/scroll_container.zig
index d233246..7c7df9a 100644
--- a/src/ui/widgets/scroll_container.zig
+++ b/src/ui/widgets/scroll_container.zig
@@ -8,6 +8,7 @@ const anim = @import("../anim.zig");
const wheel = @import("../wheel.zig");
const scrollbar = @import("scrollbar.zig");
const slider = @import("slider.zig");
+const toggle = @import("toggle.zig");
const theme = @import("../theme.zig");
@@ -232,9 +233,10 @@ pub const BarStep = struct {
};
/// Advances the scrollbar feedback of every container under `root` and repaints
-/// each whose drawn thumb changed. Sliders share the feedback (`slider.stepFeedback`),
-/// so hosts drive both with this one call. Edge-triggered on what is painted,
-/// so an idle container or slider costs nothing.
+/// each whose drawn thumb changed. Sliders share the feedback (`slider.stepFeedback`)
+/// and switches slide their knob (`toggle.step`), so hosts drive all with this
+/// one call. Edge-triggered on what is painted, so an idle container, slider or
+/// switch costs nothing.
pub fn stepBars(root: *Widget, now_ms: i64) BarStep {
var result: BarStep = .{};
switch (root.kind) {
@@ -257,6 +259,7 @@ pub fn stepBars(root: *Widget, now_ms: i64) BarStep {
result.active = step.active;
result.deadline = step.deadline;
},
+ .toggle => result.active = toggle.step(root, now_ms),
else => {},
}
for (root.children) |*child| {
diff --git a/src/ui/widgets/scrollbar.zig b/src/ui/widgets/scrollbar.zig
index aa5448c..6f1e414 100644
--- a/src/ui/widgets/scrollbar.zig
+++ b/src/ui/widgets/scrollbar.zig
@@ -8,6 +8,8 @@
const std = @import("std");
const anim = @import("../anim.zig");
const theme = @import("../theme.zig");
+const sdf = @import("../sdf.zig");
+const text = @import("../text.zig");
pub const Axis = enum { vertical, horizontal };
@@ -135,11 +137,14 @@ pub const Drag = struct {
}
};
-/// What to draw: the thumb's rounded box and colour.
+/// What to draw: the thumb's rounded box, colour and illuminated edge.
pub const Look = struct {
rect: Rect,
radius: f32,
color: [4]f32,
+ axis: Axis = .vertical,
+ highlight: [4]f32 = .{ 1, 1, 1, 1 },
+ shine: f32 = 0,
};
/// The thumb for `state`: centred in the gutter across its thickness, as wide
@@ -158,13 +163,61 @@ pub fn look(g: Geometry, state: Appearance, configured: f32, palette: theme.Them
}
var color = palette.scrollbar_thumb;
for (&color, palette.scrollbar_thumb_active orelse palette.accent) |*channel, target| channel.* += (target - channel.*) * state.accent;
- return .{ .rect = rect, .radius = cornerRadius(thickness), .color = color };
+ 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 };
}
-/// Paints `l` into anything with `paint.Renderer`'s `fillRect`; Cairo clients
-/// use `ui/cairo.zig`'s `drawScrollbar`.
-pub fn paint(r: anytype, l: Look) void {
- r.fillRect(l.rect.x, l.rect.y, l.rect.w, l.rect.h, .{ .color = l.color, .radius = l.radius });
+/// The light stays inside the thumb, so ordinary scrollbar damage erases it.
+/// Cairo clients use this same painter through `ui/cairo.zig`'s `drawScrollbar`.
+pub fn paint(r: *@import("../paint.zig").Renderer, l: Look) void {
+ if (l.shine <= 0) {
+ r.fillRect(l.rect.x, l.rect.y, l.rect.w, l.rect.h, .{ .color = l.color, .radius = l.radius });
+ return;
+ }
+ const box = l.rect;
+ if (box.w <= 0 or box.h <= 0) return;
+ const s = r.scale;
+ var left = box.x * s;
+ var top = box.y * s;
+ var right = (box.x + box.w) * s;
+ var bottom = (box.y + box.h) * s;
+ if (r.effectiveClip()) |clip| {
+ left = @max(left, clip.x * s);
+ top = @max(top, clip.y * s);
+ right = @min(right, (clip.x + clip.w) * s);
+ bottom = @min(bottom, (clip.y + clip.h) * s);
+ }
+ const x0: i32 = @intFromFloat(@floor(@max(0, left)));
+ const y0: i32 = @intFromFloat(@floor(@max(0, top)));
+ const x1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.width)), right)));
+ const y1: i32 = @intFromFloat(@ceil(@min(@as(f32, @floatFromInt(r.height)), bottom)));
+ r.clean = false;
+ var py = y0;
+ while (py < y1) : (py += 1) {
+ const y = (@as(f32, @floatFromInt(py)) + 0.5) / s - box.y;
+ var px = x0;
+ while (px < x1) : (px += 1) {
+ const x = (@as(f32, @floatFromInt(px)) + 0.5) / s - box.x;
+ const distance = sdf.sdRoundedBox(x, y, 0, 0, box.w, box.h, l.radius);
+ const coverage = sdf.coverage(distance * s);
+ if (coverage <= 0) continue;
+ const length = if (l.axis == .vertical) box.h else box.w;
+ const thickness = if (l.axis == .vertical) box.w else box.h;
+ const u = (if (l.axis == .vertical) y else x) / length;
+ const v = (if (l.axis == .vertical) x else y) / thickness;
+ const along_light = (u - 0.38) / 0.62;
+ const falloff = @max(0, 1 - along_light * along_light);
+ 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);
+ 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);
+ }
+ }
}
/// Presentation only: callers retain their scroll mechanics and fixed hit area.
@@ -172,32 +225,39 @@ pub fn paint(r: anytype, l: Look) void {
pub const Appearance = struct {
tint: anim.Anim = .{},
expansion: anim.Anim = .{},
+ illumination: anim.Anim = .{},
accent: f32 = 0,
wide: f32 = 0,
+ shine: f32 = 0,
deadline: ?i64 = null,
active: bool = false,
pub fn step(self: *Appearance, now: i64, moved: bool, hovered: bool, dragging: bool, overflowing: bool) bool {
const old_accent = self.accent;
const old_wide = self.wide;
+ const old_shine = self.shine;
if (moved and overflowing) self.deadline = now + 400;
if (!overflowing or (self.deadline != null and now >= self.deadline.?)) self.deadline = null;
const engaged = overflowing and (hovered or dragging);
// Scrolling only tints; hover and drag own expansion independently.
const target: f32 = if (engaged) 1 else if (self.deadline != null) 0.35 else 0;
+ const light: f32 = if (!overflowing) 0 else if (dragging or self.deadline != null) 1 else if (hovered) 0.38 else 0;
const static = anim.reducedMotion() or !anim.enabled();
if (static) {
self.tint.cancel(target);
self.expansion.cancel(0);
+ self.illumination.cancel(light);
} else {
if (self.tint.to != target) self.tint.retarget(now, target, 180, .out_cubic);
const expand: f32 = if (engaged) 1 else 0;
if (self.expansion.to != expand) self.expansion.retarget(now, expand, 180, .out_cubic);
+ if (self.illumination.to != light) self.illumination.retarget(now, light, 180, .out_cubic);
}
self.accent = self.tint.value(now);
self.wide = self.expansion.value(now);
- self.active = !self.tint.settled(now) or !self.expansion.settled(now);
- return self.accent != old_accent or self.wide != old_wide;
+ self.shine = self.illumination.value(now);
+ self.active = !self.tint.settled(now) or !self.expansion.settled(now) or !self.illumination.settled(now);
+ return self.accent != old_accent or self.wide != old_wide or self.shine != old_shine;
}
/// Resting width is 0.75 of `configured`; hover and drag grow it to 1.125.
@@ -216,6 +276,7 @@ test "scrollbar feedback holds, reverses, and respects reduced motion" {
_ = state.step(0, true, false, false, true);
_ = state.step(180, false, false, false, true);
try std.testing.expectEqual(@as(f32, 0.35), state.accent);
+ try std.testing.expectEqual(@as(f32, 1), state.shine);
try std.testing.expectEqual(@as(f32, 6), state.width(8));
try std.testing.expect(!state.active);
_ = state.step(400, false, false, false, true);
@@ -227,13 +288,16 @@ test "scrollbar feedback holds, reverses, and respects reduced motion" {
_ = state.step(890, false, false, false, true);
_ = state.step(1070, false, false, false, true);
try std.testing.expectEqual(@as(f32, 0), state.accent);
+ try std.testing.expectEqual(@as(f32, 0), state.shine);
anim.applySettings(.{ .reduced_motion = .on });
_ = state.step(900, true, true, true, true);
try std.testing.expectEqual(@as(f32, 1), state.accent);
+ try std.testing.expectEqual(@as(f32, 1), state.shine);
try std.testing.expectEqual(@as(f32, 6), state.width(8));
try std.testing.expect(!state.active);
_ = state.step(901, false, false, false, false);
try std.testing.expectEqual(@as(f32, 0), state.accent);
+ try std.testing.expectEqual(@as(f32, 0), state.shine);
try std.testing.expect(state.deadline == null);
}
@@ -245,12 +309,14 @@ test "scrolling after drag release retains only a subtle tint" {
_ = state.step(0, false, true, false, true);
_ = state.step(180, false, true, false, true);
try std.testing.expectEqual(@as(f32, 9), state.width(8));
+ try std.testing.expectEqual(@as(f32, 0.38), state.shine);
_ = state.step(200, true, false, true, true);
try std.testing.expectEqual(@as(f32, 9), state.width(8));
// Release outside the thumb while further wheel/trackpad/key input arrives.
_ = state.step(220, true, false, false, true);
_ = state.step(400, true, false, false, true);
try std.testing.expectEqual(@as(f32, 0.35), state.accent);
+ try std.testing.expectEqual(@as(f32, 1), state.shine);
try std.testing.expectEqual(@as(f32, 6), state.width(8));
try std.testing.expect(!state.active);
_ = state.step(600, true, false, false, true);
diff --git a/src/ui/widgets/slider.zig b/src/ui/widgets/slider.zig
index c95ed65..4b4cc4c 100644
--- a/src/ui/widgets/slider.zig
+++ b/src/ui/widgets/slider.zig
@@ -11,7 +11,7 @@ const theme = @import("../theme.zig");
const sdf = @import("../sdf.zig");
const text = @import("../text.zig");
-/// A recessed rail with a luminous fill and a reflective, round thumb.
+/// A softly lit rail with a luminous fill and a shallow metallic disc thumb.
/// All light stays inside the widget so partial repaints erase it completely.
pub fn paintShaded(widget: *const Widget, data: layout.SliderData, r: *Renderer) void {
const t = r.palette orelse theme.global;
@@ -60,28 +60,26 @@ pub fn paintShaded(widget: *const Widget, data: layout.SliderData, r: *Renderer)
const halo = std.math.clamp(1 - @max(0, fill) / 3, 0, 1);
if (fraction > 0) blend(pixel, t.accent, halo * halo * (0.12 + 0.16 * tip + 0.10 * intensity) * edge_fade);
const rail_y = std.math.clamp((dy + track_h / 2) / track_h, 0, 1);
- blend(pixel, shade(t.slider_track, -0.24 + 0.32 * rail_y), sdf.coverage(rail * s));
+ blend(pixel, shade(t.slider_track, -0.10 + 0.14 * rail_y), sdf.coverage(rail * s));
if (fraction > 0) {
const streak = falloff((dy + track_h * 0.16) / (track_h * 0.38));
- const gold = mix(t.accent, highlight, 0.18 + 0.50 * streak + 0.25 * tip);
+ const gold = mix(t.accent, highlight, 0.30 + 0.24 * streak + 0.28 * tip);
blend(pixel, gold, sdf.coverage(fill * s));
}
- const shadow = @sqrt(dx * dx + (dy - 1) * (dy - 1)) - radius;
- blend(pixel, .{ 0, 0, 0, 0.28 }, std.math.clamp(1 - shadow / 1.5, 0, 1) * edge_fade);
+ const 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;
const coverage = sdf.coverage(distance * s);
if (coverage <= 0) continue;
const nx = dx / radius;
const ny = dy / radius;
- const nz = @sqrt(@max(0, 1 - nx * nx - ny * ny));
- const light = std.math.clamp(-0.45 * nx - 0.55 * ny + 0.70 * nz, 0, 1);
- var knob = shade(t.accent, -0.48 + 0.68 * light);
- // Broad upper-left reflection and a smaller lower-right glint.
- const specular = falloff((nx + 0.32) / 0.48) * falloff((ny + 0.42) / 0.43);
- const glint = falloff((nx - 0.40) / 0.30) * falloff((ny - 0.57) / 0.25);
- knob = mix(knob, highlight, @min(1, 0.95 * specular + 0.70 * glint));
- const rim = 1 - std.math.clamp(-distance / 1.2, 0, 1);
- knob = mix(knob, highlight, rim * (0.50 + 0.35 * light));
+ // Opposing brushed-metal reflections sit across a flat face.
+ // 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));
+ const rim = 1 - std.math.clamp(-distance / 0.75, 0, 1);
+ knob = mix(knob, highlight, rim * 0.85);
blend(pixel, knob, coverage);
}
}
diff --git a/src/ui/widgets/toggle.zig b/src/ui/widgets/toggle.zig
index fcacac1..c35059d 100644
--- a/src/ui/widgets/toggle.zig
+++ b/src/ui/widgets/toggle.zig
@@ -6,6 +6,7 @@ const layout = @import("../layout.zig");
const Widget = layout.Widget;
const Renderer = @import("../paint.zig").Renderer;
+const anim = @import("../anim.zig");
const theme = @import("../theme.zig");
const Rect = @import("field.zig").Rect;
const sdf = @import("../sdf.zig");
@@ -15,8 +16,14 @@ const text = @import("../text.zig");
pub const width: f32 = 36;
pub const height: f32 = 20;
+/// How long the knob takes to travel from one end to the other.
+pub const slide_ms: i64 = 280;
+
pub const Options = struct {
on: bool,
+ /// Where the knob is, 0 (off) to 1 (on). Null rests at the end `on` names;
+ /// hand-laid panels that keep no animation state leave it so.
+ position: ?f32 = null,
style: @FieldType(layout.ToggleData, "style") = .standard,
focused: bool = false,
disabled: bool = false,
@@ -27,7 +34,7 @@ pub fn paint(r: *Renderer, box: Rect, opts: Options) void {
const t = r.palette orelse theme.global;
if (t.toggle_shaded) return paintShaded(r, box, opts, t);
const radius: f32 = if (opts.style == .settings) t.toggle_radius else box.h / 2;
- var track: [4]f32 = if (opts.on) t.toggle_on orelse t.accent else t.toggle_track;
+ var track = trackColor(t, opts);
var thumb = t.toggle_thumb orelse t.control_thumb;
if (opts.disabled) {
track[3] *= 0.5;
@@ -41,7 +48,7 @@ pub fn paint(r: *Renderer, box: Rect, opts: Options) void {
});
const inset: f32 = 2;
const side = @max(0, box.h - inset * 2);
- const x = if (opts.on) box.x + box.w - inset - side else box.x + inset;
+ const x = box.x + inset + (box.w - 2 * inset - side) * restPosition(opts);
r.fillRect(x, box.y + inset, side, side, .{ .color = thumb, .radius = if (opts.style == .settings) t.toggle_thumb_radius else side / 2 });
}
@@ -67,9 +74,9 @@ fn paintShaded(r: *Renderer, box: Rect, opts: Options, t: theme.Theme) void {
const radius = if (opts.style == .settings) t.toggle_radius else box.h / 2;
const inset = box.h * 0.14;
const side = box.h - 2 * inset;
- const thumb_x = if (opts.on) box.w - inset - side else inset;
+ const thumb_x = inset + (box.w - 2 * inset - side) * restPosition(opts);
const thumb_radius = if (opts.style == .settings) t.toggle_thumb_radius else side / 2;
- const track = if (opts.on) t.toggle_on orelse t.accent else t.toggle_track;
+ const track = trackColor(t, opts);
const thumb = t.toggle_thumb orelse t.control_thumb;
const opacity: f32 = if (opts.disabled) 0.5 else 1;
var py = y0;
@@ -112,6 +119,20 @@ fn paintShaded(r: *Renderer, box: Rect, opts: Options, t: theme.Theme) void {
}
}
+fn restPosition(opts: Options) f32 {
+ return opts.position orelse if (opts.on) 1 else 0;
+}
+
+/// The track fades between its off and on colours as the knob travels.
+fn trackColor(t: theme.Theme, opts: Options) [4]f32 {
+ const off = t.toggle_track;
+ const on = t.toggle_on orelse t.accent;
+ const at = std.math.clamp(restPosition(opts), 0, 1);
+ if (at <= 0) return off;
+ if (at >= 1) return on;
+ return mix(off, on, at);
+}
+
fn mix(a: [4]f32, b: [4]f32, amount: f32) [4]f32 {
var result: [4]f32 = undefined;
for (&result, a, b) |*out, start, end| out.* = start + (end - start) * amount;
@@ -123,6 +144,87 @@ fn shade(color: [4]f32, amount: f32) [4]f32 {
return mix(color, .{ light, light, light, color[3] }, @abs(amount));
}
+/// Advances one switch's knob toward the end `on` names and repaints when its
+/// drawn position changed, so an idle switch costs nothing. Returns whether a
+/// slide is still in flight and the host must keep stepping. A switch no frame
+/// has seen yet, or any switch while animations are off, sits at its end.
+pub fn step(widget: *Widget, now_ms: i64) bool {
+ const data = switch (widget.kind) {
+ .toggle => |*data| data,
+ else => return false,
+ };
+ const target: f32 = if (data.on) 1 else 0;
+ const first = std.math.isNan(data.shown);
+ if (first or anim.reducedMotion() or !anim.enabled()) {
+ data.knob.cancel(target);
+ } else if (data.knob.to != target) {
+ data.knob.retarget(now_ms, target, slide_ms, .out_cubic);
+ }
+ const position = data.knob.value(now_ms);
+ if (position != data.shown) {
+ // A switch at rest already looks right: its first step paints nothing.
+ if (!first) {
+ widget.markPaintDirty();
+ anim.observeNoteChanged();
+ }
+ data.shown = position;
+ }
+ const moving = !data.knob.settled(now_ms);
+ if (moving) anim.observeNoteActive(now_ms, now_ms);
+ return moving;
+}
+
+/// What a rebuilt tree needs to keep a slide going: a switch's change often
+/// rebuilds its page before the first frame has moved the knob. Named by hash
+/// because the old names may live in an arena the rebuild resets.
+pub const Saved = struct {
+ pub const capacity = 48;
+ count: usize = 0,
+ names: [capacity]u64 = undefined,
+ knob: [capacity]anim.Anim = undefined,
+ shown: [capacity]f32 = undefined,
+};
+
+fn nameKey(name: []const u8) u64 {
+ return std.hash.Wyhash.hash(0, name);
+}
+
+/// Records the knob of every named switch under `root`. Unnamed switches have
+/// nothing to be matched by and start at rest.
+pub fn capture(root: *const Widget, saved: *Saved) void {
+ switch (root.kind) {
+ .toggle => |data| if (root.name) |name| {
+ if (saved.count < Saved.capacity and !std.math.isNan(data.shown)) {
+ const i = saved.count;
+ saved.count += 1;
+ saved.names[i] = nameKey(name);
+ saved.knob[i] = data.knob;
+ saved.shown[i] = data.shown;
+ }
+ },
+ else => {},
+ }
+ for (root.children) |*child| capture(child, saved);
+}
+
+/// Hands the recorded knobs to the switches of a freshly built `root` with the
+/// same name; their next `step` carries on from where the old one stood.
+pub fn restore(root: *Widget, saved: *const Saved) void {
+ switch (root.kind) {
+ .toggle => |*data| if (root.name) |name| {
+ const key = nameKey(name);
+ for (saved.names[0..saved.count], 0..) |old, i| {
+ if (old != key) continue;
+ data.knob = saved.knob[i];
+ data.shown = saved.shown[i];
+ break;
+ }
+ },
+ else => {},
+ }
+ for (root.children) |*child| restore(child, saved);
+}
+
pub fn toggle(widget: *Widget) void {
switch (widget.kind) {
.toggle => |*data| {
@@ -168,3 +270,52 @@ test "toggle routes changes to its own context and ID" {
try std.testing.expect(two.kind.toggle.on);
try std.testing.expectEqual(@as(u32, 1), second.calls);
}
+
+test "toggle slides to its new end and rests there" {
+ const Sink = struct {
+ fn call(_: ?*anyopaque, _: usize, _: bool) void {}
+ };
+ var widget = Widget{ .kind = .{ .toggle = .{ .on = false, .on_change = Sink.call } } };
+ try std.testing.expect(!step(&widget, 0));
+ try std.testing.expectEqual(@as(f32, 0), widget.kind.toggle.shown);
+
+ toggle(&widget);
+ // The frame that starts the slide has not moved the knob yet.
+ try std.testing.expect(step(&widget, 10));
+ widget.needs_paint = false;
+ try std.testing.expect(step(&widget, 10 + slide_ms / 2));
+ try std.testing.expect(widget.needs_paint);
+ const middle = widget.kind.toggle.shown;
+ try std.testing.expect(middle > 0 and middle < 1);
+ try std.testing.expect(!step(&widget, 10 + slide_ms + 50));
+ try std.testing.expectEqual(@as(f32, 1), widget.kind.toggle.shown);
+
+ // Back the other way from mid-slide: it reverses from where it stands.
+ toggle(&widget);
+ _ = step(&widget, 1000);
+ _ = step(&widget, 1000 + slide_ms / 4);
+ const going_back = widget.kind.toggle.shown;
+ try std.testing.expect(going_back < 1 and going_back > 0);
+ toggle(&widget);
+ _ = step(&widget, 1000 + slide_ms / 4);
+ try std.testing.expect(widget.kind.toggle.knob.to == 1);
+ try std.testing.expect(@abs(widget.kind.toggle.knob.value(1000 + slide_ms / 4) - going_back) < 0.01);
+}
+
+test "a rebuilt switch carries its slide over by name" {
+ const Sink = struct {
+ fn call(_: ?*anyopaque, _: usize, _: bool) void {}
+ };
+ var old = Widget{ .name = "dark_mode", .kind = .{ .toggle = .{ .on = false, .on_change = Sink.call } } };
+ _ = step(&old, 0);
+ old.kind.toggle.on = true;
+ _ = step(&old, 100);
+ _ = step(&old, 160);
+
+ var saved: Saved = .{};
+ capture(&old, &saved);
+ var fresh = Widget{ .name = "dark_mode", .kind = .{ .toggle = .{ .on = true, .on_change = Sink.call } } };
+ restore(&fresh, &saved);
+ try std.testing.expect(step(&fresh, 170));
+ try std.testing.expect(fresh.kind.toggle.shown > 0 and fresh.kind.toggle.shown < 1);
+}
diff --git a/tests/appearance_settings.py b/tests/appearance_settings.py
index 9483bbc..bfd799e 100644
--- a/tests/appearance_settings.py
+++ b/tests/appearance_settings.py
@@ -254,6 +254,17 @@ def test_appearance_settings():
assert abs(read_config()["compositor"]["inactive_opacity"] - 1.0) < 0.02
assert any(w.get("label") == "100%" for w in widgets())
+ # --- 2b. Terminal opacity slider (unset until moved) ---
+ assert "terminal_opacity" not in read_config()["compositor"]
+ terminal_slider = ui.scroll_into_view("terminal_opacity")
+ assert terminal_slider is not None
+ assert any(w.get("label") == "Terminal opacity (new windows)" for w in widgets())
+ click_widget(terminal_slider, fraction=0.5)
+ time.sleep(0.2)
+ terminal_val = read_config()["compositor"]["terminal_opacity"]
+ assert 0.40 <= terminal_val <= 0.60
+ assert any(w.get("label") == f"{round(terminal_val * 100)}%" for w in widgets())
+
# --- 3. Animations toggle ---
anim_toggle = ui.scroll_into_view("animations")
assert anim_toggle is not None
diff --git a/tests/calendar_popup.py b/tests/calendar_popup.py
index 1b1624c..e8143a9 100644
--- a/tests/calendar_popup.py
+++ b/tests/calendar_popup.py
@@ -15,11 +15,16 @@ from PIL import Image, ImageChops
from ipc_client import IPCClient, spawn_compositor, stop_process
-def run(scale):
+def run(scale, gold=False, top=False, popup_only=False):
with tempfile.TemporaryDirectory(prefix="rediwm-calendar-") as directory:
tmp = Path(directory)
# Pixel equality checks need a settled popup, not its opening slide.
- process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"), config_content='[compositor]\nxwayland = false\n[animations]\nenabled = false\n',
+ config = '[compositor]\nxwayland = false\n'
+ config += f'taskbar_position = "{"top" if top else "bottom"}"\n'
+ config += '[animations]\nenabled = false\n'
+ if gold:
+ config += '[theme]\nbase = "gold"\n'
+ process, log = spawn_compositor(tmp, scale=scale, renderer=os.environ.get("REDIWM_TEST_RENDERER", "gles2"), config_content=config,
env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_CACHE_HOME": directory, "TZ": "Pacific/Auckland", "LC_ALL": "C", "LANGUAGE": "en"})
try:
with IPCClient(tmp, timeout=15) as ipc:
@@ -29,7 +34,7 @@ def run(scale):
assert ipc.hit_test(*clock)["widget"] == "clock"
ipc.click_at(*clock)
ipc.wait_for_frame()
- point = (clock[0], bar["y"] - 50)
+ point = (clock[0], bar["y"] + bar["height"] + 50 if top else bar["y"] - 50)
hit = ipc.hit_test(*point)
assert hit["target_type"] == "calendar", hit
origin = (point[0] - hit["local_x"], point[1] - hit["local_y"])
@@ -53,7 +58,7 @@ def run(scale):
ipc.click_at(origin[0] + 100, origin[1] + 50)
assert not ImageChops.difference(original, capture()).getbbox()
# Save an isolated output preview for visual inspection.
- preview = Path(f"/tmp/rediwm-calendar-{scale}.png")
+ preview = Path(f"/tmp/rediwm-calendar-{'gold-' if gold else ''}{'top-' if top else ''}{scale}.png")
preview.unlink(missing_ok=True)
ipc.screenshot(str(preview))
for dismiss in (lambda: ipc.key_down_up(1), lambda: ipc.click_at(*clock), lambda: ipc.click_at(20, 20)):
@@ -64,6 +69,9 @@ def run(scale):
ipc.wait_for_frame()
assert ipc.hit_test(*point)["target_type"] == "calendar"
ipc.key_down_up(1)
+ if popup_only:
+ print(f"PASS: calendar navigation, dismissal and repainting, gold={gold}, top={top}, scale={scale}")
+ return
ui = UIDriver(ipc)
ipc.action("open_control_center")
ui.wait_settled("control_center")
@@ -261,4 +269,8 @@ def run(scale):
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--scale", default="1")
- run(parser.parse_args().scale)
+ parser.add_argument("--gold", action="store_true")
+ parser.add_argument("--top", action="store_true")
+ parser.add_argument("--popup-only", action="store_true")
+ args = parser.parse_args()
+ run(args.scale, args.gold, args.top, args.popup_only)
diff --git a/tests/dock.py b/tests/dock.py
index 0e85960..9dcf296 100644
--- a/tests/dock.py
+++ b/tests/dock.py
@@ -190,6 +190,10 @@ enabled = false
ipc.wait_for_frame()
hover = shot('hover')
assert ImageChops.difference(plain, hover).getbbox(), 'no hover feedback'
+ # The enlarged icon is the feedback: no rectangle behind it, not even in the strip the icon never reaches.
+ edge = button('terminal')['global_box']
+ strip = tuple(round(v * scale) for v in (edge['x'], edge['y'] + edge['height'] / 2 - 6, edge['x'] + 3, edge['y'] + edge['height'] / 2 + 6))
+ assert not ImageChops.difference(plain.crop(strip), hover.crop(strip)).getbbox(), 'hover rectangle shown with hover zoom'
# Leaving in one jump unhovers the dock; motion elsewhere then paints nothing.
ipc.move_cursor(5, 5)
ipc.wait_for_frame()
@@ -268,7 +272,8 @@ enabled = false
ipc.key(code, True)
ipc.key(code, False)
wait_for(lambda: not any(w['name'] == 'files' for w in dock()), 'running shortcut removed')
- assert not any((w['name'] or '').startswith('window_') for w in dock()), 'removed shortcut left a duplicate'
+ # Only the launcher goes: the running app still shows, as a window.
+ wait_for(lambda: sum((w['name'] or '').startswith('window_') for w in dock()) == 1, 'removed shortcut hid its running app')
assert len(ipc.get_windows()) == 1, 'removing shortcut closed the app'
cfg.write_text(before_removal)
ipc.reload_config()
@@ -394,7 +399,7 @@ def context_menu():
ipc.pointer_button(273, True)
ipc.pointer_button(273, False)
ipc.wait_for_frame()
- height = 122 if name.startswith('window_') else 44
+ height = 83 if name.startswith('window_') else 44
return x, ui.widgets('dock')[0]['global_box']['y'] - height - 4
def key(code):
@@ -410,15 +415,12 @@ def context_menu():
menu(f'window_{wid}')
ipc.click_at(5, 5) # Outside dismisses without activating the dock.
assert len(ipc.get_windows()) == 2
- menu(f'window_{wid}')
- key(103) # Up selects Remove from dock.
- key(28)
- wait_for(lambda: not any(n.startswith('window_') for n in names()), 'app removed')
- assert {w['id'] for w in ipc.get_windows()} == {wid, other_id}
- assert len(ipc.get_shell_state()['taskbars'][0]['chips']) == 2
- assert tomllib.loads(cfg.read_text())['compositor']['dock_hidden_apps'] == ['dock.removed']
+ # A running app cannot be removed from the dock (its menu is only
+ # Close and Force Close), whatever the old config said.
+ assert {f'window_{wid}', f'window_{other_id}'} <= names(), 'a running app left the dock'
+ assert 'dock_hidden_apps' not in tomllib.loads(cfg.read_text())['compositor']
ipc.reload_config()
- assert not any(n.startswith('window_') for n in names())
+ assert {f'window_{wid}', f'window_{other_id}'} <= names()
x, y = menu('terminal')
ipc.click_at(x + 20, y + 22)
@@ -448,14 +450,10 @@ def context_menu():
ipc.wait_for_frame()
assert process.poll() is None
- # An anonymous window can be hidden without hiding other anonymous windows.
+ # Windows without an app ID show too.
anonymous, anon_id = launch('')
anonymous2, anon_id2 = launch('')
- menu(f'window_{anon_id}')
- key(103)
- key(28)
- wait_for(lambda: f'window_{anon_id}' not in names(), 'anonymous window removed')
- assert f'window_{anon_id2}' in names()
+ assert {f'window_{anon_id}', f'window_{anon_id2}'} <= names()
assert len(ipc.get_windows()) == 4
stop_process(anonymous)
stop_process(anonymous2)
@@ -476,7 +474,11 @@ def context_menu():
key(103)
key(28)
wait_for(lambda: shortcut not in names(), 'shortcut removed')
- assert not names(), 'empty dock should be hidden'
+ assert any(n.startswith('window_') for n in names()), 'running apps left the dock with its shortcuts'
+ stop_process(first)
+ stop_process(second)
+ wait_for(lambda: not ipc.get_windows(), 'windows closed')
+ wait_for(lambda: not names(), 'empty dock should be hidden')
saved = cfg.read_text()
for client in clients:
@@ -491,19 +493,19 @@ def context_menu():
if not p.name.endswith('.lock')), None), 'display after restart')
assert not names(), 'removed shortcuts returned after restart'
client, reopened = launch('dock.removed')
- assert not names(), 'removed app returned after restart'
+ wait_for(lambda: names() == {f'window_{reopened}'}, 'running app hidden after restart')
assert any(c['window_id'] == reopened for c in ipc.get_shell_state()['taskbars'][0]['chips'])
cfg.write_text(cfg.read_text().replace(
'dock_hidden_shortcuts = ["terminal", "files", "applications", "settings"]',
'dock_hidden_shortcuts = []').replace('[compositor]', '[compositor]\ntaskbar_position = "top"'))
ipc.reload_config()
- wait_for(lambda: names() == {'applications', 'files', 'terminal', 'settings'}, 'shortcuts restored')
+ wait_for(lambda: names() == {'applications', 'files', 'terminal', 'settings', f'window_{reopened}'}, 'shortcuts restored')
assert ui.widgets('dock')[0]['global_box']['height'] == 96, 'dock height lost after restart'
# A dock menu stays above the dock with a top taskbar, too.
x, y = menu('settings')
ipc.click_at(x + 20, y + 22)
wait_for(lambda: 'settings' not in names(), 'menu anchored to dock')
- print(f'PASS: dock context menu, Close, Force Close, removal, dismissal, anonymous windows, persistence ({scale}x)')
+ print(f'PASS: dock context menu, Close, Force Close, shortcut removal, running apps always shown, dismissal, anonymous windows, persistence ({scale}x)')
except Exception:
log.flush()
print((tmp / 'compositor.log').read_text()[-4000:])
@@ -612,6 +614,37 @@ def pill_animation():
ipc.reload_config()
ipc.wait_for_frame(output=primary)
assert zoom_state()['target'] == 1.5
+ # An animation repaints only the cells it moves, over what was last
+ # painted. From a whole repaint at rest, a settled hover must look as
+ # a whole repaint of the hovered dock does (a theme change and back
+ # repaints it all).
+ def dock_image(name):
+ path = tmp / (name + '.png')
+ path.unlink(missing_ok=True)
+ ipc.screenshot(str(path))
+ root = ui.widgets('dock')[0]['global_box']
+ with Image.open(path) as image:
+ return image.convert('RGB').crop(tuple(round(v * scale) for v in
+ (root['x'], root['y'], root['x'] + root['width'], root['y'] + root['height'])))
+
+ def repaint_whole():
+ for radius in (18, 17):
+ cfg.write_text(cfg.read_text().replace(f'dock_radius = {35 - radius}', f'dock_radius = {radius}'))
+ ipc.reload_config()
+ advance(1000)
+
+ ipc.move_cursor(5, 5)
+ advance(1000)
+ repaint_whole()
+ at_rest = dock_image('at_rest')
+ ipc.move_cursor(x, y)
+ advance(60)
+ advance(1000)
+ assert zoom_state()['value'] == 1.5 and zoom_state()['settled']
+ animated = dock_image('animated')
+ assert ImageChops.difference(at_rest, animated).getbbox(), 'hover did not repaint'
+ repaint_whole()
+ assert ImageChops.difference(animated, dock_image('whole')).getbbox() is None, 'animated repaint differs from a whole one'
cfg.write_text(cfg.read_text().replace('dock_hover_zoom = 1.5', 'dock_hover_zoom = 1.0'))
ipc.reload_config()
ipc.wait_for_frame(output=primary)
@@ -746,6 +779,171 @@ def pill_animation():
+def pinning():
+ """Dragging applications from the start menu onto the dock pins them."""
+ scale = float(os.environ.get('REDIWM_TEST_SCALE', '1'))
+ with tempfile.TemporaryDirectory(prefix='rediwm-dock-pin-') as directory:
+ tmp = Path(directory)
+ build_client(tmp)
+ applications = tmp / 'data' / 'applications'
+ applications.mkdir(parents=True)
+ for name, app_id in (('pin-one', 'dock.pin.one'), ('pin-two', 'dock.pin.two')):
+ (applications / f'{name}.desktop').write_text(
+ f'[Desktop Entry]\nType=Application\nName={name}\nStartupWMClass={app_id}\n'
+ f'Exec={tmp / "client"} --app-id {app_id}\n')
+ 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_DATA_DIRS': str(tmp / 'empty'), 'XDG_CACHE_HOME': str(tmp / 'cache'),
+ 'XDG_STATE_HOME': str(tmp / 'state'), 'REDIWM_FILES_DEVICES': '0'}
+ process, log = spawn_compositor(tmp, scale=scale, outputs=os.environ.get('REDIWM_TEST_OUTPUTS', '1'),
+ config_content='# keep this comment\n[compositor]\nxwayland = false\ndock_enabled = true\n'
+ '[animations]\nenabled = false\n', env_extra=env_extra)
+ cfg = tmp / 'rediwm-config.toml'
+ clients = []
+ try:
+ with IPCClient(tmp) as ipc:
+ ipc.wait_for('wallpaper_presented', timeout_ms=10000)
+ ui = UIDriver(ipc)
+ display = wait_for(lambda: next((p.name for p in tmp.glob('wayland-*')
+ if not p.name.endswith('.lock')), None), 'display')
+ left, right = 272, 273
+
+ def names():
+ return [w['name'] for w in ui.widgets('dock') if w['name']]
+
+ def pins():
+ return tomllib.loads(cfg.read_text())['compositor'].get('dock_pinned_apps', [])
+
+ def box(name):
+ return next(w for w in ui.widgets('dock') if w['name'] == name)['global_box']
+
+ def centre(b):
+ return round(b['x'] + b['width'] / 2), round(b['y'] + b['height'] / 2)
+
+ def open_menu():
+ if not ipc.get_shell_state()['start_menu']:
+ ipc.open_start_menu()
+ ipc.wait_for_panel_settled('start_menu')
+
+ def row(label):
+ tree = ui.widgets('start_menu')
+ text = next(w for w in tree if w['role'] == 'text' and w['label'] == label)
+ x, y = centre(text['global_box'])
+ found = next(w for w in tree if w['role'] == 'row' and
+ w['global_box']['y'] <= y < w['global_box']['y'] + w['global_box']['height'])
+ return centre(found['global_box'])
+
+ def shot(name):
+ path = tmp / (name + '.png')
+ ipc.screenshot(str(path))
+ root = ui.widgets('dock')[0]['global_box']
+ with Image.open(path) as image:
+ return image.convert('RGB').crop(tuple(round(v * scale) for v in
+ (root['x'], root['y'], root['x'] + root['width'], root['y'] + root['height'])))
+
+ def drag_to(label, x, y, release=True):
+ open_menu()
+ start = row(label)
+ 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 launch(app):
+ previous = {w['id'] for w in ipc.get_windows()}
+ client = subprocess.Popen([str(tmp / 'client'), '--app-id', app],
+ env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ clients.append(client)
+ win = wait_for(lambda: next((w for w in ipc.get_windows() if w['id'] not in previous), None), 'client')
+ ipc.wait_for_frame()
+ return client, win['id']
+
+ wait_for(lambda: 'terminal' in names(), 'dock')
+ dock = ui.widgets('dock')[0]['global_box']
+ dock_point = centre(dock)
+ idle = shot('idle')
+
+ # Released away from the dock: nothing is pinned, nothing launches.
+ drag_to('pin-one', 600, 100)
+ assert pins() == [] and not ipc.get_windows(), 'a drop off the dock pinned or launched'
+ assert ipc.get_shell_state()['start_menu'], 'a drag closed the menu'
+
+ # Hovering the dock marks where the app would go; Escape abandons the drag.
+ drag_to('pin-one', *dock_point, release=False)
+ assert ImageChops.difference(idle, shot('marker')).getbbox(), 'no drop marker over the dock'
+ ipc.key(1, True)
+ ipc.key(1, False)
+ ipc.wait_for_frame()
+ assert ImageChops.difference(idle, shot('cancelled')).getbbox() is None, 'Escape left the marker'
+ ipc.pointer_button(left, False)
+ ipc.wait_for_frame()
+ assert pins() == [] and not ipc.get_windows(), 'a cancelled drag pinned or launched'
+ assert ipc.get_shell_state()['start_menu'], 'Escape closed the menu'
+
+ # A drop pins it, saved without disturbing the config.
+ drag_to('pin-one', *dock_point)
+ wait_for(lambda: 'pin_pin-one.desktop' in names(), 'pinned button')
+ assert pins() == ['pin-one.desktop'] and '# keep this comment' in cfg.read_text()
+ assert not ipc.get_windows(), 'pinning launched the app'
+ assert ImageChops.difference(idle, shot('pinned')).getbbox()
+ assert names().index('pin_pin-one.desktop') == names().index('terminal') + 1
+ assert ipc.get_shell_state()['start_menu']
+
+ # Dropping on the left of a pin goes before it; pins already there are ignored.
+ one = box('pin_pin-one.desktop')
+ drag_to('pin-two', one['x'] + 4, centre(one)[1])
+ wait_for(lambda: pins() == ['pin-two.desktop', 'pin-one.desktop'], 'drop before the pin')
+ drag_to('pin-two', *dock_point)
+ ipc.wait_for_frame()
+ assert pins() == ['pin-two.desktop', 'pin-one.desktop']
+ assert [n for n in names() if n.startswith('pin_')] == ['pin_pin-two.desktop', 'pin_pin-one.desktop']
+ ipc.action('close_panel', {'panel': 'start_menu'})
+
+ # 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']
+ 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'
+ second, second_id = launch('dock.pin.one')
+ assert not any(n.startswith('window_') for n in names())
+ other, other_id = launch('dock.pin.free')
+ wait_for(lambda: f'window_{other_id}' in names(), 'unpinned app window')
+
+ # A click on a row still launches, and the menu closes.
+ open_menu()
+ ipc.click_at(*row('pin-two'))
+ wait_for(lambda: len(ipc.get_windows()) == 4, 'row click launched')
+ wait_for(lambda: not ipc.get_shell_state()['start_menu'], 'row click closed the menu')
+
+ # Unpinning keeps the windows, now as their own buttons. A running
+ # pin offers Close, Force Close and Unpin.
+ x, y = centre(box('pin_pin-one.desktop'))
+ ipc.move_cursor(x, y)
+ ipc.pointer_button(right, True)
+ ipc.pointer_button(right, False)
+ ipc.wait_for_frame()
+ menu_top = ui.widgets('dock')[0]['global_box']['y'] - 122 - 4
+ ipc.click_at(x + 20, menu_top + 6 + 2 * 39 + 16)
+ wait_for(lambda: pins() == ['pin-two.desktop'], 'unpinned')
+ wait_for(lambda: 'pin_pin-one.desktop' not in names(), 'pin button removed')
+ assert len([n for n in names() if n.startswith('window_')]) == 3, names()
+ print(f'PASS: dock pins by dragging from the start menu, marker, cancel, order, launch, merge and unpin ({scale}x)')
+ except Exception:
+ print((tmp / 'compositor.log').read_text()[-4000:])
+ raise
+ finally:
+ for client in clients:
+ stop_process(client)
+ stop_process(process)
+ log.close()
+
+
def positions():
"""Every edge, with either taskbar edge, using real pointer input."""
scale = float(os.environ.get('REDIWM_TEST_SCALE', '1'))
@@ -928,4 +1126,5 @@ if __name__ == '__main__':
run()
context_menu()
pill_animation()
+ pinning()
positions()
diff --git a/tests/glass_reblur.py b/tests/glass_reblur.py
index 750d23f..e2cdb6c 100644
--- a/tests/glass_reblur.py
+++ b/tests/glass_reblur.py
@@ -31,11 +31,13 @@ def reblurs_over(ipc, seconds):
return perf["glass_reblurs"], perf["output_commits"]
-def run(scale):
+def run(scale, sidebar=False):
with tempfile.TemporaryDirectory(prefix="rediwm-glass-reblur-") as directory:
tmp = Path(directory)
build_client(tmp)
config = '[compositor]\nxwayland = false\n[desktop]\nenabled = false\n[animations]\nreduced_motion = "on"\n'
+ if sidebar:
+ config += '[theme]\napp_sidebar = "rgba(27,33,40,0.72)"\napp_sidebar_blur = true\n'
process, log = spawn_compositor(tmp, scale=str(scale), config_content=config,
env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "REDIWM_TEST_DECORATION": "server"})
clients = []
@@ -48,7 +50,7 @@ def run(scale):
live = tmp / f"{name}.live"
live.write_text(f"{color} 400 260 {name}")
clients.append(subprocess.Popen(
- [str(tmp / "client")], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ [str(tmp / "client"), "--app-id", "rediwm-files" if sidebar and name == "A" else "rediwm.zoom-fixture"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
env=dict(os.environ, XDG_RUNTIME_DIR=str(tmp), WAYLAND_DISPLAY=display,
REDIWM_TEST_LIVE_FILE=str(live))))
return wait_for(lambda: next((w for w in ipc.get_windows() if w["title"] == name), None),
@@ -56,7 +58,7 @@ def run(scale):
# B first, so A (mapped later) is above it.
b = start("B", "ff40a060")
- a = start("A", "ff203040")
+ a = start("A", "b8203040" if sidebar else "ff203040")
ipc.action("move_window_to", {"id": a["id"], "x": 200, "y": 150})
ipc.action("move_window_to", {"id": b["id"], "x": 150, "y": 100})
ipc.move_cursor(5, 5)
@@ -67,6 +69,9 @@ def run(scale):
assert commits > 20, ("clients did not keep repainting", commits)
assert reblurs >= commits // 2, ("a window below did not re-blur the titlebar above it", scale, reblurs, commits)
+ if sidebar:
+ assert reblurs >= commits, ("sidebar and titlebar should both refresh", scale, reblurs, commits)
+
# B out of the region A's titlebar blur reads: A's own client keeps
# repainting under the titlebar, but it is above the effect.
ipc.action("move_window_to", {"id": b["id"], "x": 760, "y": 60})
@@ -80,7 +85,7 @@ def run(scale):
ipc.action("move_window_to", {"id": a["id"], "x": 210, "y": 150})
time.sleep(.3)
assert ipc.get_perf()["glass_reblurs"] >= 1, ("a moved titlebar kept its old blur", scale)
- print(f"PASS scale {scale}: glass re-blurs for changes below it, never for its own client")
+ print(f"PASS scale {scale}, sidebar={sidebar}: glass re-blurs for changes below it, never for its own client")
finally:
for client in clients:
stop_process(client)
@@ -91,3 +96,4 @@ def run(scale):
if __name__ == "__main__":
for scale in (1, 1.5):
run(scale)
+ run(scale, sidebar=True)
diff --git a/tests/hardware_keys.py b/tests/hardware_keys.py
index 8130581..8cf4025 100644
--- a/tests/hardware_keys.py
+++ b/tests/hardware_keys.py
@@ -115,6 +115,26 @@ print('fixture,backlight,700,70%,1000')
assert client.get_input_state() == focus, 'OSD changed input focus/state'
client.key_press('XF86AudioMute')
wait(lambda: not audio()['master_muted'], 'speaker unmute')
+ # Raising the volume of a muted sink unmutes it; lowering it
+ # does not. Keys and set_master_volume share the path.
+ client.key_press('XF86AudioMute')
+ wait(lambda: audio()['master_muted'], 'mute before lowering')
+ client.key_press('XF86AudioLowerVolume')
+ wait(lambda: abs(audio()['master_volume'] - .5) < .002, 'volume down while muted')
+ time.sleep(.1)
+ assert audio()['master_muted'], 'lowering the volume must not unmute'
+ client.action('set_master_volume', {'volume': .4})
+ wait(lambda: abs(audio()['master_volume'] - .4) < .002, 'set lower while muted')
+ time.sleep(.1)
+ assert audio()['master_muted'], 'setting a lower volume must not unmute'
+ client.key_press('XF86AudioRaiseVolume')
+ wait(lambda: not audio()['master_muted'] and abs(audio()['master_volume'] - .45) < .002, 'volume up unmutes')
+ client.key_press('XF86AudioMute')
+ wait(lambda: audio()['master_muted'], 'mute before set')
+ client.action('set_master_volume', {'volume': .5})
+ wait(lambda: not audio()['master_muted'] and abs(audio()['master_volume'] - .5) < .002, 'set higher unmutes')
+ client.action('set_master_volume', {'volume': .55})
+ wait(lambda: abs(audio()['master_volume'] - .55) < .002, 'volume restored')
client.key_press('XF86AudioMicMute')
wait(lambda: pactl('get-source-mute', 'osd_mic') == 'Mute: yes', 'mic mute')
time.sleep(.08)
diff --git a/tests/taskbar_sections.py b/tests/taskbar_sections.py
index a481a05..3cc5ec4 100644
--- a/tests/taskbar_sections.py
+++ b/tests/taskbar_sections.py
@@ -54,12 +54,12 @@ def run():
assert a['x'] + a['width'] <= b['x'] + 1, (a, b)
root = bar()[0]['global_box']
row = chips()
- assert abs((row[0]['x'] + row[-1]['x'] + row[-1]['width']) / 2 - (root['x'] + root['width'] / 2)) <= 1, row
+ assert 0 <= row[0]['x'] - (box('start')['x'] + box('start')['width']) <= 32, row
assert box('start')['x'] < row[0]['x'] < box('clock')['x']
check_bounds()
ipc.action('open_appearance')
ipc.wait_for_panel_settled('control_center')
- for name, expected in (('start', 0), ('windows', 1), ('tray', 2), ('clock', 2)):
+ 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'):
@@ -119,7 +119,7 @@ def run():
wait_for(lambda: not any(w['name'] == 'tray/1' for w in bar()), 'legacy hidden network')
assert box('clock')['x'] < box('tray/0')['x']
row = chips()
- assert abs((row[0]['x'] + row[-1]['x'] + row[-1]['width']) / 2 - (root['x'] + root['width'] / 2)) <= 1
+ assert 0 <= row[0]['x'] - (box('start')['x'] + box('start')['width']) <= 32, row
cfg.write_text(saved)
for client in clients:
stop_process(client)
@@ -134,7 +134,7 @@ def run():
assert ui.scroll_into_view('taskbar_start_section')['selected_index'] == 2
assert ui.scroll_into_view('taskbar_windows_section')['selected_index'] == 2
assert ui.scroll_into_view('taskbar_clock_section')['selected_index'] == 2
- print(f'PASS: taskbar sections, center default, section moves, bounds/input, visibility, Start menu, legacy config and restart ({scale}x)')
+ 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:
stop_process(client)
diff --git a/tests/taskbar_shape.py b/tests/taskbar_shape.py
index a294135..dd9a81c 100644
--- a/tests/taskbar_shape.py
+++ b/tests/taskbar_shape.py
@@ -136,6 +136,39 @@ def run():
print("PASS: floating taskbar gap, length, radius, strip and edges")
+def fractional_edges():
+ """Fractional scale floors the logical size (720 rows at 1.37 are 719.7): the
+ flush bar still reaches the last device row and column of the panel."""
+ with tempfile.TemporaryDirectory(prefix="rediwm-taskbar-edges-") as directory:
+ tmp = Path(directory)
+ for scale, position in (("1.37", "bottom"), ("1.37", "top"), ("1.33", "bottom")):
+ config = (f'[compositor]\nxwayland = false\ntaskbar_position = "{position}"\n[desktop]\nenabled = false\n'
+ '[animations]\nenabled = false\n')
+ process, log = spawn_compositor(tmp, scale=scale, config_content=config,
+ env_extra={"DBUS_SESSION_BUS_ADDRESS": "", "XDG_DATA_HOME": str(tmp / "data")})
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ info = ipc.get_outputs()[0]
+ path = tmp / "edges.png"
+ path.unlink(missing_ok=True)
+ ipc.move_cursor(5, 5)
+ ipc.wait_for_frame()
+ ipc.screenshot(str(path))
+ image = Image.open(path).convert("RGB")
+ assert image.size[0] > info["logical_width"] * float(scale) - 1, (image.size, info)
+ middle = BAR // 2 if position == "top" else image.height - BAR // 2
+ points = [(image.width - 1, middle)]
+ if position == "bottom":
+ points.append((image.width // 2, image.height - 1))
+ for point in points:
+ assert image.getpixel(point) != (0, 0, 0), (scale, position, "bar stops short of the panel", point, image.size)
+ finally:
+ stop_process(process)
+ log.close()
+ print("PASS: flush taskbar reaches the panel edge at fractional scales")
+
+
if __name__ == "__main__":
os.environ.pop("REDIWM_THEME", None)
run()
+ fractional_edges()
diff --git a/tests/theme_packs.py b/tests/theme_packs.py
index ea3b335..f21e6e8 100644
--- a/tests/theme_packs.py
+++ b/tests/theme_packs.py
@@ -127,7 +127,8 @@ def run():
gold = ipc.action("get_theme")
assert gold["tokens"]["notification_blur"] is True
assert gold["tokens"]["app_fg"] != gold["tokens"]["window_fg"]
- assert gold["tokens"]["app_sidebar"][3] == 1
+ 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",
"surface_hover", "start_menu_selected_bg"):
assert abs(gold["tokens"][key][3] - 0.96) < .001, key
@@ -174,7 +175,7 @@ def run():
return next(i for i in items if i["name"] == "clock")["box"]["x"]
wait_for(lambda: clock_x() < 300, "pack did not move the clock to the left section")
config_file = tmp / "rediwm-config.toml"
- default_items = '["left:start", "center:windows", "right:tray", "right:battery", "right:network", "right:volume", "right:clock"]'
+ default_items = '["left:start", "left:windows", "right:tray", "right:battery", "right:network", "right:volume", "right:clock"]'
config_file.write_text(config_file.read_text().replace("[compositor]", f"[compositor]\ntaskbar_items = {default_items}", 1))
ipc.reload_config()
wait_for(lambda: clock_x() > 900, "explicit taskbar_items did not win over the pack")
@@ -230,10 +231,19 @@ def run():
def files_has_gold_palette():
files_shot.unlink(missing_ok=True)
ipc.screenshot(str(files_shot))
+ win = next(w for w in ipc.get_windows() if w["app_id"] == "rediwm-files")
+ box = ipc.get_window_debug(win["id"])["client_box"]
with Image.open(files_shot) as image:
- colors = dict((color, count) for count, color in image.convert("RGB").getcolors(image.width * image.height))
+ rgb = image.convert("RGB")
+ colors = dict((color, count) for count, color in rgb.getcolors(image.width * image.height))
+ # Below the toolbar, the sidebar's empty leading margin
+ # now shows the blurred backdrop through its 50% tint.
+ sidebar = rgb.crop((box["x"] + 4, box["y"] + 130,
+ box["x"] + 12, box["y"] + box["height"] - 24))
+ tinted = sum(n for n, color in sidebar.getcolors(sidebar.width * sidebar.height)
+ if color != (68, 61, 58) and color != (238, 230, 219))
return (colors.get((238, 230, 219), 0) > 5000
- and colors.get((68, 61, 58), 0) > 5000
+ and tinted > sidebar.width * sidebar.height * .9
and colors.get((57, 51, 46), 0) > 100
and colors.get((241, 231, 219), 0) > 100)
wait_for(files_has_gold_palette, "Gold app, sidebar and chrome foregrounds were not separated")
diff --git a/tests/ui_driver.py b/tests/ui_driver.py
index 14681b1..bf2b026 100644
--- a/tests/ui_driver.py
+++ b/tests/ui_driver.py
@@ -20,7 +20,7 @@ class UIDriver:
except Exception:
return []
- def scroll_into_view(self, name: str, panel: str = "control_center", attempts: int = 30) -> Dict[str, Any]:
+ def scroll_into_view(self, name: str, panel: str = "control_center", attempts: int = 60) -> Dict[str, Any]:
"""Scroll the panel's content until the widget named `name` is fully
visible, and return it with its new box."""
# The wheel direction depends on scroll settings, so learn it: flip