RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
theme fixes and wip
oxydizerd33d58e192a9
diff --git a/assets/themes/blackout.toml b/assets/themes/blackout.tomlindex 489f5a8..25928d2 100644--- a/assets/themes/blackout.toml+++ b/assets/themes/blackout.toml@@ -17,8 +17,9 @@ chrome_control_offset_y = 5chrome_round_buttons = falsechrome_button_bevel = 7# Raised title tab, a 45-degree step down, and four clipped corners. The step-# is the title plate's slant moved out by the plate inset: 310 wide, 36 slant-# (48 - 2 * 6) and inset 6 give x - y = 268 + 6 * sqrt(2). Change them together.+# is the title plate's slant moved out by the plate inset: 307.60 wide, 34 slant+# (48 - 2 * 7) and inset 7 give x - y = 266.60 + 7 * sqrt(2) = 276.5. Change+# them together. The inset leaves 2 px beyond the outer and inner borders (2 + 3 px).# Below ~298 px wide the outline cannot fit and the window uses rounded corners;# maximized windows stay rectangular.window_shape = "0 14, 14 0, 276.5 0, 283.5 7, -14 7, -0 21, -0 -12, -12 -0, 12 -0, 0 -12"@@ -28,31 +29,38 @@ window_dim = "#A2A8A6"window_border = "#3B4242"window_border_hover = "#737C68"window_border_width = 2+# Yellow corners occupy this continuous inner band, flush against the outer ring.+# Both borders reserve space outside the client content.+window_inner_border = "#2B3233"+window_inner_border_width = 3window_divider = "#2A3030"-window_title_plate = "#FAEB01"-window_title_plate_width = 310+window_title_plate = "#FBE301"+window_title_plate_width = 307.60window_title_plate_fg = "#111400"-# Plate geometry; slant is a fraction of chrome_height (36 of 48: 45 degrees).+# Plate geometry; slant is a fraction of chrome_height (34 of 48: 45 degrees).# With an outline the plate follows its cut corners at the inset; the bevel# applies to rectangular (maximized) frames.-window_title_plate_inset = 6+window_title_plate_inset = 7window_title_plate_bevel = 7-window_title_plate_slant = 0.75+window_title_plate_bottom_bevel = 7+window_title_plate_slant = 0.7083333333window_title_plate_control_gap = 8window_title_plate_text_padding = 8-window_corner_accent = "#FAEB01"-window_corner_extent = 34+window_corner_accent = "#FBE301"+window_corner_extent = 40window_corner_resize_extra = 18window_corner_width = 3# Extra inset beyond the frame ring; resize/restore durations in milliseconds.window_corner_inset = 0window_corner_end_padding = 2+# The yellow fills the inner band; its ends keep their 45-degree cuts.+window_corner_cut_ends = truewindow_corner_resize_ms = 140window_corner_restore_ms = 180window_corner_resize_ease = "out_cubic"-window_close_hover = "#FAEB01"+window_close_hover = "#FBE301"window_close_fg = "#111400"-workspace_active_border = "#FAEB01"+workspace_active_border = "#FBE301"app_bg = "#101314"app_fg = "#E3E5E3"@@ -69,21 +77,21 @@ app_nav_selected = "#454719"# icons carry the accent without requiring per-app selection text overrides.app_sidebar_selected = "#454719"app_sidebar_hover = "#252B2B"-app_sidebar_selected_marker = "#FAEB01"+app_sidebar_selected_marker = "#FBE301"app_sidebar_item_radius = 5app_highlight_bevel = 7app_divider = "#303737"-app_icon = "#FAEB01"+app_icon = "#FBE301"app_menu_bg = "#171B1C"app_field_bg = "#0D1011"app_field_border = "#343C3C"text_secondary = "#A2A8A6"-file_folder_back = "#A89D00"-file_folder_front = "#FAEB01"+file_folder_back = "#A99800"+file_folder_front = "#FBE301"file_document = "#D7DBD9"file_document_lines = "#515A58"-scrollbar_thumb = "#E4D500"-scrollbar_thumb_active = "#FFF233"+scrollbar_thumb = "#E5CE00"+scrollbar_thumb_active = "#FFEA33"scrollbar_track = "#1A2021"scrollbar_track_stripe = "#343D3E"# Distances along the scrollbar; slope 1 makes 45-degree diagonal bands.@@ -98,11 +106,11 @@ bg = "#101314"fg = "#E3E5E3"dim = "#A2A8A6"faint = "#747E7B"-accent = "#FAEB01"-accent_2 = "#D3C600"-accent_3 = "#A89D00"+accent = "#FBE301"+accent_2 = "#D4BF00"+accent_3 = "#A99800"on_accent = "#111400"-shell_accent = "#FAEB01"+shell_accent = "#FBE301"shell_on_accent = "#111400"danger = "#F06A51"surface = "#202627"@@ -110,8 +118,8 @@ surface_hover = "#303737"border = "#3B4242"border_soft = "#2A3030"border_hover = "#737C68"-border_focus = "#FAEB01"-border_glow = "rgba(250,235,1,0.55)"+border_focus = "#FBE301"+border_glow = "rgba(251,227,1,0.55)"glass = "#15191A"glass_strong = "#171B1C"shadow = "rgba(0,0,0,0.65)"@@ -120,10 +128,10 @@ shadow_offset_y = 6field_bg = "#0D1011"field_border = "#343C3C"selection_alpha = 0.28-toggle_on = "#FAEB01"+toggle_on = "#FBE301"toggle_thumb = "#E3E5E3"slider_track = "#343C3C"-control_thumb = "#FAEB01"+control_thumb = "#FBE301"radius = 5radius_md = 6@@ -145,21 +153,21 @@ dock_border = "#3B4242"dock_bevel = 14dock_item_bg = "#171B1C"dock_item_border = "#2A3030"-dock_item_hover_border = "#FAEB01"+dock_item_hover_border = "#FBE301"dock_item_bevel = 7dock_icon_grey = 1# A short status bar in the top-right corner, its one exposed corner cut.taskbar_length = 20taskbar_shape = "0 0, -0 0, -0 -0, 16 -0, 0 -16"-start_button_logo_color = "#FAEB01"-start_button_indicator = "#FAEB01"+start_button_logo_color = "#FBE301"+start_button_indicator = "#FBE301"start_menu_bg = "#15191A"start_menu_bevel = 16start_menu_border = "#3B4242"start_menu_search_bg = "#0D1011"start_menu_selected_bg = "#454719"-start_menu_selected_border = "#8F8700"-start_menu_selected_marker = "#FAEB01"+start_menu_selected_border = "#908200"+start_menu_selected_marker = "#FBE301"popup_bg = "#171B1C"popup_border = "#3B4242"popup_card_bg = "#202627"@@ -174,7 +182,7 @@ switcher_bg = "#111516"switcher_border = "#3B4242"switcher_item_bg = "#202627"switcher_item_border = "#343C3C"-switcher_selected_border = "#FAEB01"+switcher_selected_border = "#FBE301"switcher_fg = "#E3E5E3"switcher_dim = "#A2A8A6"switcher_icon_bg = "#303737"@@ -182,14 +190,14 @@ lock_bg = "#101314"lock_fg = "#E3E5E3"lock_dim = "#A2A8A6"lock_divider = "#3B4242"-lock_session_fg = "#FAEB01"+lock_session_fg = "#FBE301"lock_wallpaper_opacity = 0.15power_menu_bevel = 16terminal_bg = "#101314"terminal_fg = "#E3E5E3"-terminal_cursor = "#FAEB01"-terminal_yellow = "#D3C600"-terminal_bright_yellow = "#FAEB01"+terminal_cursor = "#FBE301"+terminal_yellow = "#D4BF00"+terminal_bright_yellow = "#FBE301"[layout]# Status items only: the start menu stays on Super, windows on Alt+Tab.diff --git a/assets/themes/blackout/icons/folder-documents.svg b/assets/themes/blackout/icons/folder-documents.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-documents.svg+++ b/assets/themes/blackout/icons/folder-documents.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder-download.svg b/assets/themes/blackout/icons/folder-download.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-download.svg+++ b/assets/themes/blackout/icons/folder-download.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder-music.svg b/assets/themes/blackout/icons/folder-music.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-music.svg+++ b/assets/themes/blackout/icons/folder-music.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder-pictures.svg b/assets/themes/blackout/icons/folder-pictures.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-pictures.svg+++ b/assets/themes/blackout/icons/folder-pictures.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder-publicshare.svg b/assets/themes/blackout/icons/folder-publicshare.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-publicshare.svg+++ b/assets/themes/blackout/icons/folder-publicshare.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder-templates.svg b/assets/themes/blackout/icons/folder-templates.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-templates.svg+++ b/assets/themes/blackout/icons/folder-templates.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder-videos.svg b/assets/themes/blackout/icons/folder-videos.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder-videos.svg+++ b/assets/themes/blackout/icons/folder-videos.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/folder.svg b/assets/themes/blackout/icons/folder.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/folder.svg+++ b/assets/themes/blackout/icons/folder.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/rediwm-files.svg b/assets/themes/blackout/icons/rediwm-files.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/rediwm-files.svg+++ b/assets/themes/blackout/icons/rediwm-files.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/system-file-manager.svg b/assets/themes/blackout/icons/system-file-manager.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/system-file-manager.svg+++ b/assets/themes/blackout/icons/system-file-manager.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/user-desktop.svg b/assets/themes/blackout/icons/user-desktop.svgindex 057dee7..0332fc2 100644--- a/assets/themes/blackout/icons/user-desktop.svg+++ b/assets/themes/blackout/icons/user-desktop.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/></svg>diff --git a/assets/themes/blackout/icons/user-home.svg b/assets/themes/blackout/icons/user-home.svgindex f555b8b..ebeb260 100644--- a/assets/themes/blackout/icons/user-home.svg+++ b/assets/themes/blackout/icons/user-home.svg@@ -1,6 +1,6 @@<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">- <path d="M6 12h18l6 7h28v34H6z" fill="#A89D00"/>- <path d="M6 21h52v32H6z" fill="#FAEB01"/>+ <path d="M6 12h18l6 7h28v34H6z" fill="#A99800"/>+ <path d="M6 21h52v32H6z" fill="#FBE301"/><path d="M8 23h48" fill="none" stroke="#FFF566" stroke-width="2"/><path d="m22 37 10-8 10 8v11h-7v-8h-6v8h-7z" fill="#111400"/></svg>diff --git a/build.zig b/build.zigindex ed3b93f..05a6f0f 100644--- a/build.zig+++ b/build.zig@@ -77,6 +77,14 @@ pub fn build(b: *std.Build) void {const memory_mod = b.createModule(.{ .root_source_file = b.path("src/memory/allocator.zig"), .target = target, .optimize = optimize });// The OS-specific parts (children, file watching, own path): std only.const platform_mod = b.createModule(.{ .root_source_file = b.path("src/platform/mod.zig"), .target = target, .optimize = optimize });+ // Exact copies of Redinit's exported client/wire modules; no compositor protocol implementation.+ const redi_options = b.addOptions();+ redi_options.addOption([]const u8, "name", "redinit");+ const redi_proto = b.createModule(.{ .root_source_file = b.path("src/platform/redinit_client/ctl_proto.zig"), .target = target, .optimize = optimize });+ redi_proto.addOptions("config", redi_options);+ const redi_client = b.createModule(.{ .root_source_file = b.path("src/platform/redinit_client/ctl_client.zig"), .target = target, .optimize = optimize });+ redi_client.addImport("ctl_proto", redi_proto);+ platform_mod.addImport("redi_ctl", redi_client);const i18n_tool = b.addExecutable(.{ .name = "i18n-tool", .root_module = b.createModule(.{ .root_source_file = b.path("tools/i18n.zig"), .target = b.graph.host, .optimize = .safe }) });const catalog_compile = b.addRunArtifact(i18n_tool);catalog_compile.setCwd(b.path("."));diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdindex 01fcadc..b722ff3 100644--- a/docs/agent-notes/rendering.md+++ b/docs/agent-notes/rendering.md@@ -13,8 +13,12 @@ chrome, capture, or retained panel painting. General rules remain incolour (× window opacity); the pass composites the ring over the body, sosomething must be drawn under every ring pixel: the titlebar `ChromeBuffer`(a plain band) on top and the three `frame_fills` rects beside and below the- client. `chrome.frameBorder()` resolves `window_border_width` for the ring,- client offsets, side fills, footer and resize/layout geometry. Corner rasters+ client. `chrome.outerBorder()` resolves `window_border_width` for the outer ring.+ `chrome.frameBorder()` adds `window_inner_border_width` for client offsets,+ side fills, footer and resize/layout geometry. The optional inner ring+ (`toplevel/inner_border.zig`) paints `window_inner_border` in four disjoint,+ memoized perimeter strips, below corner accents and above the clipped client+ corners. Its width is reserved even when its color is transparent. Corner rastersand titlebar memos include it for live reloads. `shadow_tree`, the resize-grab tree andevery xdg popup carry `setTreeUnclipped` (a new node that hangs outside thewindow needs it too). The shadow is analytic (`setTreeShadow` on@@ -69,6 +73,10 @@ chrome, capture, or retained panel painting. General rules remain in`window_corner_restore_ms`, and `window_corner_resize_ease`; live timing editscontinue from the displayed length. `window_corner_inset` adds space beyondthe frame ring, and `window_corner_end_padding` shortens the stroke endpoints.+ `window_corner_casing(_width)` wraps the stroke in a band of its own (the+ stroke moves in by its width, `reach` covers it); `window_corner_cut_ends`+ cuts both at 45 degrees with the outer edge longest, the casing's sharp tip+ capped at its end.`window_title_plate*` paints an angled title label, limits text before itsslant and leaves grouped tabs to their existing painter. Its tokens belongin `TitlebarMemo` so reload and partial title repaint agree.diff --git a/src/Toplevel.zig b/src/Toplevel.zigindex a820feb..f8e37ac 100644--- a/src/Toplevel.zig+++ b/src/Toplevel.zig@@ -152,6 +152,7 @@ titlebar_buffer: *sn.Buffer,// Body under the border ring beside and below the client (left, right, bottom).frame_fills: [3]*sn.Rect,corner_accents: @import("toplevel/corner_accents.zig").State = .{},+inner_border: @import("toplevel/inner_border.zig").State = .{},// The outline of a window that draws its own decorations.border_rects: [4]*sn.Rect,content_tree: *sn.Tree,@@ -517,6 +518,7 @@ pub const syncShadow = toplevel_chrome_sync.syncShadow;pub const syncResizeGrab = toplevel_chrome_sync.syncResizeGrab;pub const applyShape = toplevel_chrome_sync.applyShape;pub const syncCornerAccents = @import("toplevel/corner_accents.zig").syncCornerAccents;+pub const syncInnerBorder = @import("toplevel/inner_border.zig").syncInnerBorder;pub const tickCornerAccents = @import("toplevel/corner_accents.zig").tickCornerAccents;pub const wakeCornerAccents = @import("toplevel/corner_accents.zig").wakeCornerAccents;pub const syncBorders = toplevel_chrome_sync.syncBorders;diff --git a/src/calendar.zig b/src/calendar.zigindex 7f9df40..89cc256 100644--- a/src/calendar.zig+++ b/src/calendar.zig@@ -166,7 +166,7 @@ pub const Calendar = struct {const today = current and self.year == tm.tm_year + 1900 and self.month == tm.tm_mon + 1 and day == tm.tm_mday;if (today) r.fillRect(20 + x * 47 + 5, y, 37, 37, .{ .color = t.accent, .radius = 6 });var number: [4]u8 = undefined;- centered(&r, x, y, std.fmt.bufPrint(&number, "{d}", .{day}) catch "", 14, if (today) .{ 1, 1, 1, 1 } else if (current) t.text_secondary else t.faint);+ centered(&r, x, y, std.fmt.bufPrint(&number, "{d}", .{day}) catch "", 14, if (today) t.on_accent else if (current) t.text_secondary else t.faint);}self.buffer_node.setBuffer(&buf.base);self.buffer_node.setDestSize(@max(1, width), @max(1, height));diff --git a/src/chrome.zig b/src/chrome.zigindex 7904d59..bbd464f 100644--- a/src/chrome.zig+++ b/src/chrome.zig@@ -17,6 +17,8 @@ const plate = @import("chrome_plate.zig");// App dialogs use these same decoration metrics and control hit targets.const window_chrome = @import("ui").window_chrome;pub const frameBorder = window_chrome.frameBorder;+pub const outerBorder = window_chrome.outerBorder;+pub const innerBorder = window_chrome.innerBorder;pub const Metrics = window_chrome.Metrics;pub const frameRadius = window_chrome.frameRadius;@@ -150,7 +152,7 @@ pub const TitlebarMemo = struct {title_plate: [4]f32 = @splat(0),title_plate_width: f32 = 0,title_plate_fg: ?[4]f32 = null,- title_plate_geometry: [5]f32 = @splat(0),+ title_plate_geometry: [6]f32 = @splat(0),title_plate_outline: u64 = 0,inset_left: i32 = 0,inset_right: i32 = 0,diff --git a/src/chrome_plate.zig b/src/chrome_plate.zigindex 63931db..cc198bb 100644--- a/src/chrome_plate.zig+++ b/src/chrome_plate.zig@@ -6,8 +6,8 @@ const theme = @import("ui").theme;const shape = @import("ui").window_shape;/// Retained chrome must include every plate geometry input in its cache key.-pub fn geometry(t: theme.Theme) [5]f32 {- return .{ t.window_title_plate_inset, t.window_title_plate_bevel, t.window_title_plate_slant, t.window_title_plate_control_gap, t.window_title_plate_text_padding };+pub fn geometry(t: theme.Theme) [6]f32 {+ return .{ t.window_title_plate_inset, t.window_title_plate_bevel, t.window_title_plate_slant, t.window_title_plate_control_gap, t.window_title_plate_text_padding, t.window_title_plate_bottom_bevel };}pub fn width(frame_width: i32, state: chrome.ChromeState) f32 {@@ -37,10 +37,13 @@ pub fn polygon(frame_width: i32, state: chrome.ChromeState) ?shape.Resolved {// configured bevels cannot produce crossing edges.const bevel = @min(t.window_title_plate_bevel * d, @min((w - left) / 2, h - 2 * inset));const slant = @min(t.window_title_plate_slant * h, w - left - bevel);- var result: shape.Resolved = .{ .count = 5 };- result.points[0..5].* = .{- .{ left, h - inset }, .{ left, inset + bevel }, .{ left + bevel, inset },- .{ w - slant, inset }, .{ w, h - inset },+ const bottom = @max(0, @min(t.window_title_plate_bottom_bevel * d, @min((w - left) / 2, h - 2 * inset - bevel)));+ // Points 3 and 4 are the top and bottom of the slant (`titleRight`,+ // `right`); a bottom bevel adds its far end last, never a zero-length edge.+ var result: shape.Resolved = .{ .count = if (bottom > 0) 6 else 5 };+ result.points[0..6].* = .{+ .{ left, h - inset - bottom }, .{ left, inset + bevel }, .{ left + bevel, inset },+ .{ w - slant, inset }, .{ w, h - inset }, .{ left + bottom, h - inset },};return result;}diff --git a/src/chrome_tests.zig b/src/chrome_tests.zigindex c7abc0b..a6daca5 100644--- a/src/chrome_tests.zig+++ b/src/chrome_tests.zig@@ -119,6 +119,10 @@ test "chrome geometry changes invalidate retained titlebar pixels" {theme.global.window_border_width = 2;try std.testing.expectEqual(@as(i32, 2), chrome_mod.frameBorder());try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, null, .{})));+ theme.global.window_inner_border_width = 3;+ try std.testing.expectEqual(@as(i32, 5), chrome_mod.frameBorder());+ try std.testing.expectEqual(@as(i32, 2), chrome_mod.outerBorder());+ try std.testing.expect(!before.reusableFor(TitlebarMemo.capture(400, null, .{})));theme.global = saved;theme.global.chrome_control_gap += 1;const spaced = TitlebarMemo.capture(400, null, .{});diff --git a/src/config_runtime/apply.zig b/src/config_runtime/apply.zigindex 9f43bc2..a63bfae 100644--- a/src/config_runtime/apply.zig+++ b/src/config_runtime/apply.zig@@ -206,7 +206,7 @@ pub fn applyDiff(server: *Server, old: Config, new: Config) void {if (theme_changed) {server.saveLoginTheme();if (server.notifications) |manager| manager.themeChanged();- if (server.desktop) |desktop| desktop.app.themeChanged();+ if (server.desktop) |desktop| desktop.themeChanged();if (server.locker) |lock| lock.themeChanged();server.refreshTaskbarsGeometry();var top_it = server.world.toplevels.iterator(.forward);diff --git a/src/control_center/sections/appearance_themes.zig b/src/control_center/sections/appearance_themes.zigindex 62e9825..37eaa90 100644--- a/src/control_center/sections/appearance_themes.zig+++ b/src/control_center/sections/appearance_themes.zig@@ -99,7 +99,7 @@ pub fn onResetStartLogo(owner: ?*anyopaque, _: usize) void {pub fn refreshTheme(server: *@import("../../Server.zig"), taskbar_geometry: bool) void {@import("../../config_runtime/app_colors.zig").sync(server);server.saveLoginTheme();- if (server.desktop) |desktop| desktop.app.themeChanged();+ if (server.desktop) |desktop| desktop.themeChanged();@import("ui").text.setPreferredFamilies(theme.global.font, theme.global.mono_font);if (taskbar_geometry) server.refreshTaskbarsGeometry() else server.refreshTaskbars();var it = server.world.toplevels.iterator(.forward);diff --git a/src/desktop/AGENTS.md b/src/desktop/AGENTS.mdindex 2faf70c..b9ed0e6 100644--- a/src/desktop/AGENTS.md+++ b/src/desktop/AGENTS.md@@ -10,6 +10,11 @@ Desktop keyboard focus and compositor drop targets are in the rootdamaged tiles get new buffers. Rasterize the selection band once per paint;repair clips snap outward to device pixels. Labels/icons are rasterized atexact scale.+ Selection colours come from `Theme.desktopSelectionColor`,+ `desktopSelectionBorder` and `desktopSelectedColor`: explicit desktop tokens+ win, otherwise they follow the shell accent, including on live reload.+ Call `Desktop.themeChanged` so cache invalidation also schedules its paint;+ an unrelated output frame alone does not pass the desktop's pending gate.* **The grid fills the output.** Columns count from the right (saved cellskeep their meaning) and share the whole width: cells are at least 96px andstretch by a few pixels so the first and last column sit the same distancediff --git a/src/desktop/app_draw.zig b/src/desktop/app_draw.zigindex cad1149..b1a9643 100644--- a/src/desktop/app_draw.zig+++ b/src/desktop/app_draw.zig@@ -35,9 +35,10 @@ pub fn iconPattern(cr: *c.cairo_t, ic: *Icon, key: IconRaster.Key, name: []constif (ic.selection_amount > 0 or ic.hover_amount > 0) {rounded(cr, r.x, r.y, r.w, if (key.renaming) 68 else r.h, 8);const t = appearance_theme.global;+ const selected = t.desktopSelectedColor();var fill: [4]f32 = undefined;- for (0..3) |i| fill[i] = @floatCast(t.desktop_hover[i] + (t.desktop_selected[i] - t.desktop_hover[i]) * ic.selection_amount);- fill[3] = @floatCast(t.desktop_selected[3] * ic.selection_amount + t.desktop_hover[3] * ic.hover_amount * (1 - ic.selection_amount));+ for (0..3) |i| fill[i] = @floatCast(t.desktop_hover[i] + (selected[i] - t.desktop_hover[i]) * ic.selection_amount);+ fill[3] = @floatCast(selected[3] * ic.selection_amount + t.desktop_hover[3] * ic.hover_amount * (1 - ic.selection_amount));shell_cairo.setSource(cr, fill);c.cairo_fill(cr);}@@ -78,7 +79,7 @@ pub fn iconPattern(cr: *c.cairo_t, ic: *Icon, key: IconRaster.Key, name: []constc.cairo_restore(cr);if (ic.selection_amount > 0 and !key.renaming) {rounded(cr, ox + 4, r.y + 71, 88, 34, 3);- var fill = appearance_theme.global.desktop_selection;+ var fill = appearance_theme.global.desktopSelectionColor();fill[3] *= @floatCast(ic.selection_amount);shell_cairo.setSource(cr, fill);c.cairo_fill(cr);diff --git a/src/desktop/app_paint.zig b/src/desktop/app_paint.zigindex 752d54e..9b224d4 100644--- a/src/desktop/app_paint.zig+++ b/src/desktop/app_paint.zig@@ -45,9 +45,9 @@ pub fn drawBand(self: *App, cr: *c.cairo_t) void {const r = self.selectionRect();const rad: f64 = @min(@as(f64, damage_mod.rubberband_radius), @as(f64, @floatFromInt(@min(r.w, r.h))) / 2.0);rounded(cr, r.x, r.y, r.w, r.h, rad);- shell_cairo.setSource(cr, appearance_theme.global.desktop_selection);+ shell_cairo.setSource(cr, appearance_theme.global.desktopSelectionColor());c.cairo_fill_preserve(cr);- shell_cairo.setSource(cr, appearance_theme.global.desktop_selection_border);+ shell_cairo.setSource(cr, appearance_theme.global.desktopSelectionBorder());c.cairo_set_line_width(cr, 1);c.cairo_stroke(cr);}@@ -265,7 +265,7 @@ pub fn paintOverlay(self: *App, cr: *c.cairo_t, now: i64) void {const y = py + 64 + @as(i32, @intCast(row)) * 32;if (index == self.choice) {rounded(cr, px + 8, y, 464, 32, 4);- shell_cairo.setSource(cr, appearance_theme.global.desktop_selection);+ shell_cairo.setSource(cr, appearance_theme.global.desktopSelectionColor());c.cairo_fill(cr);}label(cr, entry.name, px + 12, y, 456, 32, false);diff --git a/src/desktop/embedded.zig b/src/desktop/embedded.zigindex f88fd58..22f0b42 100644--- a/src/desktop/embedded.zig+++ b/src/desktop/embedded.zig@@ -344,6 +344,11 @@ pub const Desktop = struct {if (self.output) |output| output.wlr_output.scheduleFrame();}+ pub fn themeChanged(self: *Desktop) void {+ self.app.themeChanged();+ self.schedule();+ }+/// Runs from the output's frame handler, before projection is synced./// Returns whether the desktop is still animating.pub fn frame(self: *Desktop, output: *Output) bool {diff --git a/src/platform/mod.zig b/src/platform/mod.zigindex 5450494..d0db6d9 100644--- a/src/platform/mod.zig+++ b/src/platform/mod.zig@@ -22,6 +22,7 @@ pub const watch = @import("watch.zig");pub const seccomp = @import("seccomp.zig");pub const system = @import("system.zig");pub const tool = @import("tool.zig");+pub const redinit = @import("redinit.zig");pub const key_scan = @import("key_scan.zig");test {diff --git a/src/platform/redinit.zig b/src/platform/redinit.zignew file mode 100644index 0000000..17957ae--- /dev/null+++ b/src/platform/redinit.zig@@ -0,0 +1,44 @@+//! Native user-manager transport. The Linux implementation uses Redinit's+//! exported client module verbatim; other platforms retain their usual backend.+const std = @import("std");+const builtin = @import("builtin");+const client = if (builtin.os.tag == .linux) @import("redi_ctl") else struct {};++pub fn path(allocator: std.mem.Allocator, runtime: []const u8) !?[:0]u8 {+ if (builtin.os.tag != .linux) return null;+ if (!std.fs.path.isAbsolute(runtime)) return null;+ const result = try std.fmt.allocPrintSentinel(allocator, "{s}/redinit/ctl", .{runtime}, 0);+ if (std.c.access(result, std.posix.F_OK) != 0) {+ allocator.free(result);+ return null;+ }+ return result;+}+pub fn fromBusAddress(allocator: std.mem.Allocator, address: []const u8) !?[:0]u8 {+ const prefix = "unix:path=";+ if (!std.mem.startsWith(u8, address, prefix) or !std.mem.endsWith(u8, address, "/bus")) return null;+ return path(allocator, address[prefix.len .. address.len - 4]);+}+pub fn adopt(socket: []const u8, name: []const u8, pid: i32) !void {+ if (builtin.os.tag != .linux) return error.Unsupported;+ var conn = try client.Connection.connectTimeout(socket, 1000);+ defer conn.close();+ const a = std.heap.c_allocator;+ const reply = try client.adopt(&conn, a, name, pid);+ defer a.free(reply.message);+ if (!reply.ok) return error.AdoptionRefused;+}+pub fn environment(socket: []const u8, allocator: std.mem.Allocator) ![][]u8 {+ if (builtin.os.tag != .linux) return error.Unsupported;+ var conn = try client.Connection.connectTimeout(socket, 1000);+ defer conn.close();+ return client.environment(&conn, allocator);+}+pub fn changeEnvironment(socket: []const u8, allocator: std.mem.Allocator, set: bool, entries: []const []const u8) !void {+ if (builtin.os.tag != .linux) return error.Unsupported;+ var conn = try client.Connection.connectTimeout(socket, 1000);+ defer conn.close();+ const reply = try client.changeEnvironment(&conn, allocator, set, entries);+ defer allocator.free(reply.message);+ if (!reply.ok) return error.EnvironmentRefused;+}diff --git a/src/platform/redinit_client/SOURCE.json b/src/platform/redinit_client/SOURCE.jsonnew file mode 100644index 0000000..3ffd53f--- /dev/null+++ b/src/platform/redinit_client/SOURCE.json@@ -0,0 +1,7 @@+{+ "source": "redi-iso/redinit/src",+ "sha256": {+ "ctl_client.zig": "c26ed5bd3dab0d42956c374dc0a481db83a7846ca3aecfd1da9b74a7f4a62433",+ "ctl_proto.zig": "96afa58566b9bebc2913dccc617772257a52ed566bc85ec6b55821e2c1c7d541"+ }+}diff --git a/src/platform/redinit_client/ctl_client.zig b/src/platform/redinit_client/ctl_client.zignew file mode 100644index 0000000..d77d0cd--- /dev/null+++ b/src/platform/redinit_client/ctl_client.zig@@ -0,0 +1,225 @@+//! Exported client module. Reuses the wire schema; applications need neither a+//! shell nor their own framing/parser. Blocking I/O belongs in the client only.+const std = @import("std");+const linux = std.os.linux;+pub const protocol = @import("ctl_proto");+pub const Request = protocol.Request;+pub const Error = error{ ConnectFailed, Disconnected, IoFailure, FrameTooLarge, InvalidRequest };++pub const Connection = struct {+ fd: linux.fd_t,+ buffer: [protocol.max_line]u8 = undefined,+ begin: usize = 0,+ end: usize = 0,++ pub fn connect(path: []const u8) Error!Connection {+ return connectTimeout(path, 0);+ }+ /// A nonzero timeout bounds connect/send/read for short desktop requests.+ /// Streaming clients keep the default (no socket timeout).+ pub fn connectTimeout(path: []const u8, timeout_ms: u32) Error!Connection {+ var address: linux.sockaddr.un = .{ .path = @splat(0) };+ if (path.len >= address.path.len or std.mem.indexOfScalar(u8, path, 0) != null) return error.ConnectFailed;+ @memcpy(address.path[0..path.len], path);+ const result = linux.socket(linux.AF.UNIX, linux.SOCK.STREAM | linux.SOCK.CLOEXEC, 0);+ if (linux.errno(result) != .SUCCESS) return error.ConnectFailed;+ const fd: linux.fd_t = @intCast(result);+ if (timeout_ms != 0) {+ const timeout: linux.timeval = .{ .sec = timeout_ms / 1000, .usec = (timeout_ms % 1000) * 1000 };+ inline for (.{ linux.SO.RCVTIMEO, linux.SO.SNDTIMEO }) |opt| {+ if (linux.errno(linux.setsockopt(fd, linux.SOL.SOCKET, opt, @ptrCast(&timeout), @sizeOf(linux.timeval))) != .SUCCESS) {+ _ = linux.close(fd);+ return error.IoFailure;+ }+ }+ }+ if (linux.errno(linux.connect(fd, &address, @sizeOf(@TypeOf(address)))) != .SUCCESS) {+ _ = linux.close(fd);+ return error.ConnectFailed;+ }+ return .{ .fd = fd };+ }+ pub fn close(self: *Connection) void {+ _ = linux.close(self.fd);+ }++ pub fn send(self: *Connection, req: Request) Error!void {+ switch (req.verb) {+ .start, .stop, .restart, .status, .enable, .disable, .why, .logs, .reload_unit, .run, .adopt => {},+ else => if (req.unit.len != 0) return error.InvalidRequest,+ }+ if (req.follow and req.verb != .logs) return error.InvalidRequest;+ var buffer: [protocol.max_request + 1]u8 = undefined;+ var w = std.Io.Writer.fixed(&buffer);+ const verb = switch (req.verb) {+ inline else => |v| protocol.name(v),+ };+ w.writeAll(verb) catch return error.InvalidRequest;+ switch (req.verb) {+ .start, .stop, .restart, .status, .enable, .disable, .why, .reload_unit => w.print(" {s}", .{req.unit}) catch return error.InvalidRequest,+ .logs => w.print(" {s} {d} {d}", .{ req.unit, req.lines, @intFromBool(req.follow) }) catch return error.InvalidRequest,+ .run, .adopt => w.print(" {s} {s}", .{ req.unit, req.rest }) catch return error.InvalidRequest,+ .scope, .environment => if (req.rest.len != 0) {+ w.print(" {s}", .{req.rest}) catch return error.InvalidRequest;+ },+ .subscribe => {+ if (req.since) |seq| w.print(" {d}", .{seq}) catch return error.InvalidRequest else w.writeAll(" now") catch return error.InvalidRequest;+ w.print(" {d} {s} {d}", .{ req.epoch, req.glob, req.kinds }) catch return error.InvalidRequest;+ },+ else => {},+ }+ _ = protocol.parse(w.buffered()) catch return error.InvalidRequest;+ w.writeByte('\n') catch return error.InvalidRequest;+ var at: usize = 0;+ while (at < w.buffered().len) {+ const n = linux.sendto(self.fd, w.buffered()[at..].ptr, w.buffered().len - at, linux.MSG.NOSIGNAL, null, 0);+ if (linux.errno(n) == .INTR) continue;+ if (linux.errno(n) != .SUCCESS or n == 0) return error.IoFailure;+ at += n;+ }+ }++ /// Borrowed until the next call. A whole frame is always returned, even+ /// when the stream split it across several reads or coalesced many frames.+ pub fn next(self: *Connection) Error![]const u8 {+ while (true) {+ if (std.mem.indexOfScalarPos(u8, self.buffer[0..self.end], self.begin, '\n')) |eol| {+ const line = self.buffer[self.begin..eol];+ self.begin = eol + 1;+ return line;+ }+ if (self.begin > 0) {+ std.mem.copyForwards(u8, &self.buffer, self.buffer[self.begin..self.end]);+ self.end -= self.begin;+ self.begin = 0;+ }+ if (self.end == self.buffer.len) return error.FrameTooLarge;+ const n = linux.read(self.fd, self.buffer[self.end..].ptr, self.buffer.len - self.end);+ if (linux.errno(n) == .INTR) continue;+ if (linux.errno(n) != .SUCCESS) return error.IoFailure;+ if (n == 0) return error.Disconnected;+ self.end += n;+ }+ }++ pub fn nextFrame(self: *Connection, allocator: std.mem.Allocator) !std.json.Parsed(std.json.Value) {+ return std.json.parseFromSlice(std.json.Value, allocator, try self.next(), .{ .allocate = .alloc_always });+ }+};++/// What to run in a transient unit of its own (`redictl run`, or a launcher+/// such as a compositor starting an application).+pub const RunSpec = struct {+ /// `null` lets the manager pick `run-<n>`.+ name: ?[]const u8 = null,+ workdir: ?[]const u8 = null,+ /// `NAME=value` entries, at most 16.+ env: []const []const u8 = &.{},+ /// argv, the first an absolute path, at most 16 words.+ argv: []const []const u8,+};++/// Encode a `RunSpec` as the `rest` of a `run` request (put the name in `unit`).+pub fn encodeRun(buf: []u8, spec: RunSpec) ?[]const u8 {+ var w = std.Io.Writer.fixed(buf);+ protocol.encodeToken(&w, spec.workdir orelse "") catch return null;+ w.print(" {d}", .{spec.env.len}) catch return null;+ for (spec.env) |entry| {+ w.writeByte(' ') catch return null;+ protocol.encodeToken(&w, entry) catch return null;+ }+ for (spec.argv) |arg| {+ w.writeByte(' ') catch return null;+ protocol.encodeToken(&w, arg) catch return null;+ }+ return w.buffered();+}++pub const RunReply = struct {+ ok: bool,+ /// The unit's name when `ok`, otherwise why not. Allocated.+ message: []u8,+};++/// Run `spec` in a unit of its own.+pub fn run(conn: *Connection, allocator: std.mem.Allocator, spec: RunSpec) !RunReply {+ var buf: [protocol.max_request]u8 = undefined;+ const rest = encodeRun(&buf, spec) orelse return error.InvalidRequest;+ return request(conn, allocator, .{ .verb = .run, .unit = spec.name orelse "-", .rest = rest });+}++pub fn adopt(conn: *Connection, allocator: std.mem.Allocator, name: []const u8, pid: i32) !RunReply {+ var buf: [24]u8 = undefined;+ const text = try std.fmt.bufPrint(&buf, "{d}", .{pid});+ return request(conn, allocator, .{ .verb = .adopt, .unit = name, .rest = text });+}++pub fn request(conn: *Connection, allocator: std.mem.Allocator, req: Request) !RunReply {+ try conn.send(req);+ while (true) {+ const parsed = try conn.nextFrame(allocator);+ defer parsed.deinit();+ const v = parsed.value;+ if (v != .object) continue;+ const kind = v.object.get("type") orelse continue;+ if (kind != .string or !std.mem.eql(u8, kind.string, "done")) continue;+ const ok = v.object.get("ok") orelse return error.IoFailure;+ const message = v.object.get("message");+ if (ok != .bool or message == null or message.? != .string) return error.IoFailure;+ return .{ .ok = ok.bool, .message = try allocator.dupe(u8, message.?.string) };+ }+}++/// Allocated NAME=value strings; callers own both the strings and the slice.+pub fn environment(conn: *Connection, allocator: std.mem.Allocator) ![][]u8 {+ var entries: std.ArrayList([]u8) = .empty;+ errdefer {+ for (entries.items) |entry| allocator.free(entry);+ entries.deinit(allocator);+ }+ try conn.send(.{ .verb = .environment, .rest = "get" });+ while (true) {+ const parsed = try conn.nextFrame(allocator);+ defer parsed.deinit();+ if (parsed.value != .object) return error.InvalidRequest;+ const kind = parsed.value.object.get("type") orelse return error.InvalidRequest;+ if (kind != .string) return error.InvalidRequest;+ if (std.mem.eql(u8, kind.string, "done")) {+ const ok = parsed.value.object.get("ok") orelse return error.InvalidRequest;+ if (ok != .bool or !ok.bool) return error.IoFailure;+ return entries.toOwnedSlice(allocator);+ }+ if (std.mem.eql(u8, kind.string, "environment")) {+ const value = parsed.value.object.get("assignment") orelse return error.InvalidRequest;+ if (value != .string or entries.items.len == 32) return error.InvalidRequest;+ var decoded: [protocol.max_line]u8 = undefined;+ const entry = try allocator.dupe(u8, try decodeBytes(value.string, &decoded));+ errdefer allocator.free(entry);+ try entries.append(allocator, entry);+ }+ }+}++pub fn changeEnvironment(conn: *Connection, allocator: std.mem.Allocator, set: bool, entries: []const []const u8) !RunReply {+ var buf: [protocol.max_request]u8 = undefined;+ var w = std.Io.Writer.fixed(&buf);+ try w.writeAll(if (set) "set" else "unset");+ for (entries) |entry| {+ try w.writeByte(' ');+ try protocol.encodeToken(&w, entry);+ }+ return request(conn, allocator, .{ .verb = .environment, .rest = w.buffered() });+}++/// JSON carries arbitrary log bytes as U+0000..U+00FF, avoiding invalid UTF-8.+/// Decode after the JSON parser has converted those escapes to UTF-8.+pub fn decodeBytes(text: []const u8, out: []u8) error{InvalidData}![]u8 {+ var view = (std.unicode.Utf8View.init(text) catch return error.InvalidData).iterator();+ var n: usize = 0;+ while (view.nextCodepoint()) |cp| {+ if (cp > 255 or n == out.len) return error.InvalidData;+ out[n] = @intCast(cp);+ n += 1;+ }+ return out[0..n];+}diff --git a/src/platform/redinit_client/ctl_proto.zig b/src/platform/redinit_client/ctl_proto.zignew file mode 100644index 0000000..8f8a3ea--- /dev/null+++ b/src/platform/redinit_client/ctl_proto.zig@@ -0,0 +1,274 @@+//! v1: bounded ASCII request lines; newline-delimited JSON replies. Every+//! finite response ends with `done`. Streaming replies use explicit overflow.+const std = @import("std");+pub const max_request = 8192;+pub const max_line = 8192;+/// Where the control socket is. A per-user instance moves it under $XDG_RUNTIME_DIR.+pub var socket_path: [:0]const u8 = "/run/" ++ @import("config").name ++ "/ctl";+pub const Verb = enum { start, stop, restart, status, list, enable, disable, reload, why, logs, subscribe, clients, trace_dump, poweroff, reboot, log_attach, reload_unit, run, scope, adopt, environment };+pub const verb_count = std.meta.tags(Verb).len;+pub const Request = struct {+ verb: Verb,+ unit: []const u8 = "",+ lines: u32 = 10,+ follow: bool = false,+ since: ?u64 = null,+ epoch: u64 = 0,+ glob: []const u8 = "*",+ kinds: u8 = 15,+ /// `run`: encoded arguments; `scope`: validated scope operation tokens.+ rest: []const u8 = "",+};+pub const Error = error{ InvalidRequest, TooLarge };++pub fn parse(line: []const u8) Error!Request {+ if (line.len > max_request) return error.TooLarge;+ for (line) |c| if (c < 0x20 or c > 0x7e) return error.InvalidRequest;+ var tokens = std.mem.tokenizeScalar(u8, line, ' ');+ const command = tokens.next() orelse return error.InvalidRequest;+ var verb: ?Verb = null;+ inline for (std.meta.tags(Verb)) |v| if (std.mem.eql(u8, command, name(v))) {+ verb = v;+ };+ var req: Request = .{ .verb = verb orelse return error.InvalidRequest };+ switch (req.verb) {+ .adopt => {+ req.unit = tokens.next() orelse return error.InvalidRequest;+ if (!validName(req.unit)) return error.InvalidRequest;+ req.rest = tokens.next() orelse return error.InvalidRequest;+ const pid = try number(u32, req.rest);+ if (pid <= 1 or pid > std.math.maxInt(i32)) return error.InvalidRequest;+ },+ .environment => {+ req.rest = tokens.rest();+ for (req.rest) |c| if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "._-/=:+,@%~ ", c) != null)) return error.InvalidRequest;+ return req;+ },+ .start, .stop, .restart, .status, .enable, .disable, .why, .logs, .reload_unit => {+ req.unit = tokens.next() orelse return error.InvalidRequest;+ if (!validName(req.unit)) return error.InvalidRequest;+ if (req.verb == .logs) {+ req.lines = number(u32, tokens.next() orelse return error.InvalidRequest) catch return error.InvalidRequest;+ if (req.lines > 10000) return error.InvalidRequest;+ const follow = tokens.next() orelse return error.InvalidRequest;+ if (!std.mem.eql(u8, follow, "0") and !std.mem.eql(u8, follow, "1")) return error.InvalidRequest;+ req.follow = follow[0] == '1';+ }+ },+ .run => {+ // run NAME|- WORKDIR|~ NENV ENV... ARG... (tokens are percent-encoded)+ req.unit = tokens.next() orelse return error.InvalidRequest;+ if (!std.mem.eql(u8, req.unit, "-") and !validName(req.unit)) return error.InvalidRequest;+ req.rest = tokens.rest();+ if (req.rest.len == 0) return error.InvalidRequest;+ for (req.rest) |c| if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "._-/=:+,@%~ ", c) != null)) return error.InvalidRequest;+ return req;+ },+ .scope => {+ req.rest = tokens.rest();+ _ = try parseScope(req.rest);+ return req;+ },+ .subscribe => {+ const since = tokens.next() orelse return error.InvalidRequest;+ if (!std.mem.eql(u8, since, "now")) req.since = try number(u64, since);+ req.epoch = try number(u64, tokens.next() orelse return error.InvalidRequest);+ req.glob = tokens.next() orelse return error.InvalidRequest;+ if (req.glob.len > 63) return error.InvalidRequest;+ for (req.glob) |c| if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "._-@*?", c) != null)) return error.InvalidRequest;+ req.kinds = try number(u8, tokens.next() orelse return error.InvalidRequest);+ if (req.kinds == 0 or req.kinds > 15) return error.InvalidRequest;+ },+ else => {},+ }+ if (tokens.next() != null) return error.InvalidRequest;+ return req;+}++pub const ScopeAction = enum { list, create, status, stop, kill, abandon };+pub const max_scope_pids = 16;+pub const ScopeRequest = struct {+ action: ScopeAction = .list,+ name: []const u8 = "",+ uid: u32 = 0,+ pids: [max_scope_pids]i32 = @splat(0),+ pid_count: usize = 0,+ signal: u8 = 0,+ main_only: bool = false,+};++/// Session names are also directory components and D-Bus unit names. Only+/// logind's session-ID.scope shape is accepted; arbitrary paths are never used.+pub fn validScopeName(unit: []const u8) bool {+ const prefix = "session-";+ const suffix = ".scope";+ if (unit.len > 47 or unit.len <= prefix.len + suffix.len or !std.mem.startsWith(u8, unit, prefix) or !std.mem.endsWith(u8, unit, suffix)) return false;+ for (unit[prefix.len .. unit.len - suffix.len]) |c| if (!(std.ascii.isAlphanumeric(c) or c == '_' or c == '-')) return false;+ return true;+}++pub fn scopeSliceUid(unit: []const u8) ?u32 {+ if (!std.mem.startsWith(u8, unit, "user-") or !std.mem.endsWith(u8, unit, ".slice") or unit.len <= 11) return null;+ const value = unit[5 .. unit.len - 6];+ if (value.len > 1 and value[0] == '0') return null;+ const uid = number(u32, value) catch return null;+ return if (uid == std.math.maxInt(u32)) null else uid;+}++/// `scope` alone enumerates the session registry. All other operations have+/// strict arity and bounded input, before PID 1 touches a process or cgroup.+pub fn parseScope(rest: []const u8) Error!ScopeRequest {+ var tokens = std.mem.tokenizeScalar(u8, rest, ' ');+ const action = tokens.next() orelse return .{};+ var req: ScopeRequest = .{};+ req.action = std.meta.stringToEnum(ScopeAction, action) orelse return error.InvalidRequest;+ if (req.action == .list) {+ if (tokens.next() != null) return error.InvalidRequest;+ return req;+ }+ req.name = tokens.next() orelse return error.InvalidRequest;+ if (!validScopeName(req.name) and !(req.action == .kill and scopeSliceUid(req.name) != null)) return error.InvalidRequest;+ switch (req.action) {+ .create => {+ req.uid = try number(u32, tokens.next() orelse return error.InvalidRequest);+ if (req.uid == std.math.maxInt(u32)) return error.InvalidRequest;+ while (tokens.next()) |pid| {+ if (req.pid_count == req.pids.len) return error.InvalidRequest;+ const value = try number(u32, pid);+ if (value <= 1 or value > std.math.maxInt(i32)) return error.InvalidRequest;+ for (req.pids[0..req.pid_count]) |existing| if (existing == value) return error.InvalidRequest;+ req.pids[req.pid_count] = @intCast(value);+ req.pid_count += 1;+ }+ if (req.pid_count == 0) return error.InvalidRequest;+ return req;+ },+ .kill => {+ req.signal = try number(u8, tokens.next() orelse return error.InvalidRequest);+ if (req.signal == 0 or req.signal > 64) return error.InvalidRequest;+ if (tokens.next()) |who| {+ if (std.mem.eql(u8, who, "main")) req.main_only = true else if (!std.mem.eql(u8, who, "all")) return error.InvalidRequest;+ }+ if (req.main_only and scopeSliceUid(req.name) != null) return error.InvalidRequest;+ },+ else => {},+ }+ if (tokens.next() != null) return error.InvalidRequest;+ return req;+}++/// A token that is safe on a request line: letters, digits and `._-/=:+,@` pass,+/// every other byte is `%XX`, and an empty value is `~` (a real `~` is `%7E`).+pub fn encodeToken(w: *std.Io.Writer, bytes: []const u8) std.Io.Writer.Error!void {+ if (bytes.len == 0) return w.writeByte('~');+ for (bytes) |c| {+ if (std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "._-/=:+,@", c) != null) {+ try w.writeByte(c);+ } else try w.print("%{X:0>2}", .{c});+ }+}++pub const DecodeError = error{ InvalidToken, NoSpace };++/// The inverse of `encodeToken`. Never produces a NUL: a command line cannot carry one.+pub fn decodeToken(out: []u8, token: []const u8) DecodeError![]u8 {+ if (std.mem.eql(u8, token, "~")) return out[0..0];+ var n: usize = 0;+ var i: usize = 0;+ while (i < token.len) {+ if (n == out.len) return error.NoSpace;+ if (token[i] == '%') {+ if (i + 3 > token.len) return error.InvalidToken;+ const value = std.fmt.parseInt(u8, token[i + 1 .. i + 3], 16) catch return error.InvalidToken;+ if (value == 0) return error.InvalidToken;+ out[n] = value;+ i += 3;+ } else {+ out[n] = token[i];+ i += 1;+ }+ n += 1;+ }+ return out[0..n];+}++pub fn validName(unit: []const u8) bool {+ if (unit.len == 0 or unit.len > 47 or std.mem.eql(u8, unit, ".") or std.mem.eql(u8, unit, "..")) return false;+ for (unit) |c| if (!(std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "._-@", c) != null)) return false;+ return true;+}++fn number(comptime T: type, text: []const u8) Error!T {+ if (text.len == 0) return error.InvalidRequest;+ for (text) |c| if (!std.ascii.isDigit(c)) return error.InvalidRequest;+ return std.fmt.parseInt(T, text, 10) catch error.InvalidRequest;+}++pub fn name(verb: Verb) []const u8 {+ return switch (verb) {+ .trace_dump => "trace-dump",+ .log_attach => "log-attach",+ .reload_unit => "reload-unit",+ else => @tagName(verb),+ };+}++pub fn privileged(verb: Verb) bool {+ return switch (verb) {+ .list, .status, .why, .subscribe, .clients, .trace_dump => false,+ else => true,+ };+}++/// Iterative wildcard match, bounded by input length. No recursive backtracking.+pub fn matches(pattern: []const u8, value: []const u8) bool {+ var p: usize = 0;+ var v: usize = 0;+ var star: ?usize = null;+ var retry: usize = 0;+ while (v < value.len) {+ if (p < pattern.len and (pattern[p] == '?' or pattern[p] == value[v])) {+ p += 1;+ v += 1;+ } else if (p < pattern.len and pattern[p] == '*') {+ star = p;+ p += 1;+ retry = v;+ } else if (star) |s| {+ retry += 1;+ v = retry;+ p = s + 1;+ } else return false;+ }+ while (p < pattern.len and pattern[p] == '*') p += 1;+ return p == pattern.len;+}++/// Escape bytes, including non-ASCII log bytes, without trusting UTF-8 input.+pub fn string(w: *std.Io.Writer, text: []const u8) std.Io.Writer.Error!void {+ try w.writeByte('"');+ for (text) |c| switch (c) {+ '"', '\\' => {+ try w.writeByte('\\');+ try w.writeByte(c);+ },+ '\n' => try w.writeAll("\\n"),+ '\r' => try w.writeAll("\\r"),+ '\t' => try w.writeAll("\\t"),+ else => if (c < 0x20 or c >= 0x7f) try w.print("\\u00{x:0>2}", .{c}) else try w.writeByte(c),+ };+ try w.writeByte('"');+}++pub const Bucket = struct {+ credit: u64 = 20 * std.time.ns_per_s,+ at: u64 = 0,+ pub fn allow(self: *Bucket, now: u64) bool {+ if (self.at == 0) self.at = now;+ self.credit = @min(20 * std.time.ns_per_s, self.credit +| ((now -| self.at) *| 20));+ self.at = now;+ if (self.credit < std.time.ns_per_s) return false;+ self.credit -= std.time.ns_per_s;+ return true;+ }+};diff --git a/src/session/app_scope.zig b/src/session/app_scope.zigindex 660863a..94edd4f 100644--- a/src/session/app_scope.zig+++ b/src/session/app_scope.zig@@ -17,6 +17,7 @@ const wire = dbus.wire;const wl = @import("wayland").server.wl;const Server = @import("../Server.zig");const activation = @import("activation.zig");+const Native = @import("redinit_scopes.zig").Worker;const log = std.log.scoped(.app_scope);@@ -118,6 +119,8 @@ pub const Scopes = struct {unavailable: bool = false,closing: bool = false,queued: std.ArrayList(Unit) = .empty,+ native: ?*Native = null,+ native_checked: bool = false,pub fn create(allocator: std.mem.Allocator, loop: *wl.EventLoop, environ: std.process.Environ) !*Scopes {const self = try allocator.create(Scopes);@@ -128,6 +131,7 @@ pub const Scopes = struct {/// Before the event loop is destroyed.pub fn destroy(self: *Scopes) void {self.closing = true;+ if (self.native) |native| native.destroy();if (self.conn) |conn| conn.destroy();self.queued.deinit(self.allocator);self.allocator.destroy(self);@@ -135,6 +139,11 @@ pub const Scopes = struct {pub fn place(self: *Scopes, pid: i32, app_id: []const u8) void {if (self.unavailable or pid <= 0) return;+ if (!self.native_checked) {+ self.native = Native.create(self.environ) catch null;+ self.native_checked = true;+ }+ if (self.native) |native| return native.place(pid, app_id);const unit = unitName(pid, app_id);if (self.ready) return self.start(unit);if (self.conn == null or self.conn.?.closed) self.connect() catch |err| {diff --git a/src/session/login_bus.zig b/src/session/login_bus.zigindex 908b82e..f17225a 100644--- a/src/session/login_bus.zig+++ b/src/session/login_bus.zig@@ -6,6 +6,7 @@ const wl = @import("wayland").server.wl;const dbus = @import("dbus");const sys = @import("login_sys.zig");const publication = @import("publication.zig");+const native = @import("platform").redinit;const wire = dbus.wire;const Connection = dbus.Connection;@@ -31,13 +32,17 @@ pub fn Client(comptime Login: type) type {user_address: []const u8,system: ?*Connection = null,user: ?*Connection = null,+ redinit_socket: ?[:0]u8 = null,pub fn init(allocator: std.mem.Allocator, system_address: []const u8, user_address: []const u8) !Self {+ const loop = try wl.EventLoop.create();+ errdefer loop.destroy();return .{.allocator = allocator,- .loop = try wl.EventLoop.create(),+ .loop = loop,.system_address = system_address,.user_address = user_address,+ .redinit_socket = try native.fromBusAddress(allocator, user_address),};}@@ -46,6 +51,7 @@ pub fn Client(comptime Login: type) type {if (self.login_owner) |owner| self.allocator.free(owner);if (self.system) |conn| conn.destroy();if (self.user) |conn| conn.destroy();+ if (self.redinit_socket) |socket| self.allocator.free(socket);self.loop.destroy();}@@ -138,6 +144,17 @@ pub fn Client(comptime Login: type) type {/// The systemd user manager's environment.pub fn environment(self: *Self, arena: std.mem.Allocator) !Env {+ if (self.redinit_socket) |socket| {+ const assignments = try native.environment(socket, arena);+ defer arena.free(assignments);+ var result: Env = .empty;+ for (assignments) |entry| {+ defer arena.free(entry);+ const eq = std.mem.indexOfScalar(u8, entry, '=') orelse continue;+ try result.put(arena, try arena.dupe(u8, entry[0..eq]), try arena.dupe(u8, entry[eq + 1 ..]));+ }+ return result;+ }var reply = try self.getProperty(.user, systemd1, "/org/freedesktop/systemd1", systemd1 ++ ".Manager", "Environment");defer reply.deinit(self.allocator);var r = reply.reader();@@ -153,6 +170,15 @@ pub fn Client(comptime Login: type) type {}pub fn systemd(self: *Self, values: []const Pair, absent: []const []const u8) !void {+ if (self.redinit_socket) |socket| {+ var arena: std.heap.ArenaAllocator = .init(self.allocator);+ defer arena.deinit();+ var assignments: std.ArrayList([]const u8) = .empty;+ for (values) |pair| try assignments.append(arena.allocator(), try std.fmt.allocPrint(arena.allocator(), "{s}={s}", .{ pair.key, pair.value }));+ if (assignments.items.len != 0) try native.changeEnvironment(socket, arena.allocator(), true, assignments.items);+ if (absent.len != 0) try native.changeEnvironment(socket, arena.allocator(), false, absent);+ return;+ }if (values.len > 0) {var body: wire.Writer = .{ .allocator = self.allocator };defer body.deinit();diff --git a/src/session/redinit_scopes.zig b/src/session/redinit_scopes.zignew file mode 100644index 0000000..6904b5d--- /dev/null+++ b/src/session/redinit_scopes.zig@@ -0,0 +1,68 @@+//! Bounded off-thread adoption. No compositor frame waits on the user manager.+const std = @import("std");+const c = @import("c");+const platform = @import("platform");+const a = std.heap.c_allocator;+const Job = struct { pid: i32, name: [48]u8 = @splat(0) };++pub const Worker = struct {+ socket: [:0]u8,+ mutex: c.pthread_mutex_t = undefined,+ condition: c.pthread_cond_t = undefined,+ jobs: [32]Job = undefined,+ count: usize = 0,+ stop: bool = false,+ thread: ?std.Thread = null,++ pub fn create(environ: std.process.Environ) !?*Worker {+ const runtime = environ.getPosix("XDG_RUNTIME_DIR") orelse return null;+ const socket = (try platform.redinit.path(a, runtime)) orelse return null;+ errdefer a.free(socket);+ const self = try a.create(Worker);+ errdefer a.destroy(self);+ self.* = .{ .socket = socket };+ if (c.pthread_mutex_init(&self.mutex, null) != 0) return error.MutexFailed;+ errdefer _ = c.pthread_mutex_destroy(&self.mutex);+ if (c.pthread_cond_init(&self.condition, null) != 0) return error.ConditionFailed;+ errdefer _ = c.pthread_cond_destroy(&self.condition);+ self.thread = try std.Thread.spawn(.{}, run, .{self});+ return self;+ }+ pub fn destroy(self: *Worker) void {+ _ = c.pthread_mutex_lock(&self.mutex);+ self.stop = true;+ _ = c.pthread_cond_signal(&self.condition);+ _ = c.pthread_mutex_unlock(&self.mutex);+ if (self.thread) |thread| thread.join();+ _ = c.pthread_cond_destroy(&self.condition);+ _ = c.pthread_mutex_destroy(&self.mutex);+ a.free(self.socket);+ a.destroy(self);+ }+ pub fn place(self: *Worker, pid: i32, id: []const u8) void {+ var job: Job = .{ .pid = pid };+ var app: [20]u8 = undefined;+ const n = @min(id.len, app.len);+ for (id[0..n], 0..) |ch, i| app[i] = if (std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '.') ch else '-';+ _ = std.fmt.bufPrintSentinel(&job.name, "app-{s}-{d}", .{ app[0..n], pid }, 0) catch return;+ _ = c.pthread_mutex_lock(&self.mutex);+ defer _ = c.pthread_mutex_unlock(&self.mutex);+ if (self.stop or self.count == self.jobs.len) return;+ self.jobs[self.count] = job;+ self.count += 1;+ _ = c.pthread_cond_signal(&self.condition);+ }+ fn run(self: *Worker) void {+ while (true) {+ _ = c.pthread_mutex_lock(&self.mutex);+ while (self.count == 0 and !self.stop) _ = c.pthread_cond_wait(&self.condition, &self.mutex);+ if (self.stop) { _ = c.pthread_mutex_unlock(&self.mutex); return; }+ const job = self.jobs[0];+ self.count -= 1;+ std.mem.copyForwards(Job, &self.jobs, self.jobs[1 .. self.count + 1]);+ _ = c.pthread_mutex_unlock(&self.mutex);+ platform.redinit.adopt(self.socket, std.mem.sliceTo(&job.name, 0), job.pid) catch |err|+ std.log.scoped(.app_scope).debug("Redinit adoption for pid {d}: {t}", .{ job.pid, err });+ }+ }+};diff --git a/src/toplevel/chrome_sync.zig b/src/toplevel/chrome_sync.zigindex fbffcac..2278576 100644--- a/src/toplevel/chrome_sync.zig+++ b/src/toplevel/chrome_sync.zig@@ -132,6 +132,7 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !voidtoplevel.last_painted_hover = 0;toplevel.syncBorders(animated.w, animated.h);toplevel.applyShape();+ try toplevel.syncInnerBorder();try toplevel.syncCornerAccents();return;}@@ -197,6 +198,7 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !voidtoplevel.syncBorders(width, height);toplevel.applyShape();+ try toplevel.syncInnerBorder();try toplevel.syncCornerAccents();toplevel.syncResizeGrab(width, height);if (rebuild_shadow) try toplevel.syncShadow(width, height, radius);@@ -346,7 +348,7 @@ pub fn applyShape(toplevel: *Toplevel) void {.width = toplevel.chrome_width,.height = toplevel.chrome_height,.radii = .{ radius, radius, radius, radius },- .border = @floatFromInt(chrome.frameBorder()),+ .border = @floatFromInt(chrome.outerBorder()),.border_color = ring.rgba,};if (toplevel.shapePolygon(toplevel.chrome_width, toplevel.chrome_height)) |polygon| {@@ -375,7 +377,7 @@ pub fn syncBorders(toplevel: *Toplevel, width: i32, height: i32) void {// coordinates stay unchanged, and the content remains above the stroke.const color = toplevel.borderColor();for (toplevel.border_rects) |rect| col.setRect(rect, color);- const edge = chrome.frameBorder();+ const edge = chrome.outerBorder();toplevel.border_rects[0].node.setPosition(-edge, -edge);toplevel.border_rects[0].setSize(width + 2 * edge, edge);toplevel.border_rects[1].node.setPosition(-edge, 0);diff --git a/src/toplevel/corner_accents.zig b/src/toplevel/corner_accents.zigindex 6edadda..8dd1e9e 100644--- a/src/toplevel/corner_accents.zig+++ b/src/toplevel/corner_accents.zig@@ -18,6 +18,9 @@ const Memo = struct {stroke: f32,inset: f32,end_padding: f32,+ casing: [4]f32,+ casing_width: f32,+ cut_ends: bool,};/// What the last sync saw: an unchanged client commit stops at comparing it.@@ -106,10 +109,16 @@ pub fn syncCornerAccents(t: *Toplevel) !void {.density = density,.color = palette.window_corner_accent,.extent = extent,- .border = chrome.frameBorder(),- .stroke = palette.window_corner_width,+ .border = chrome.outerBorder(),+ // Reserved frame bands keep their logical width on X11 too;+ // density still scales the length and free-standing accents.+ .stroke = palette.window_corner_width / (if (chrome.innerBorder() > 0) density else 1),.inset = palette.window_corner_inset,.end_padding = palette.window_corner_end_padding,+ .casing = palette.window_corner_casing,+ // A transparent casing is none, but it still keeps its room.+ .casing_width = palette.window_corner_casing_width,+ .cut_ends = palette.window_corner_cut_ends,},.width = width,.height = height,@@ -155,7 +164,7 @@ pub fn syncCornerAccents(t: *Toplevel) !void {/// How far from the outline the stroke's ink can lie, in logical px.fn reach(memo: Memo) f32 {- return @as(f32, @floatFromInt(memo.border)) + (memo.inset + memo.stroke) * memo.density + 1;+ return @as(f32, @floatFromInt(memo.border)) + (memo.inset + memo.stroke + 2 * memo.casing_width) * memo.density + 1;}/// What the corner whose square starts at (`x`, `y`) shows of the outline. A@@ -168,13 +177,28 @@ fn cornerKey(memo: Memo, polygon: ?ui.window_shape.Resolved, radius: f32, x: i32fn paint(buffer: *PanelBuffer, memo: Memo, polygon: ?ui.window_shape.Resolved, radius: f32, x: i32, y: i32, width: i32, height: i32) void {const color: ui.text.Color = .{ .r = memo.color[0], .g = memo.color[1], .b = memo.color[2], .a = memo.color[3] };+ const casing_color: ui.text.Color = .{ .r = memo.casing[0], .g = memo.casing[1], .b = memo.casing[2], .a = memo.casing[3] };const extent: f32 = @floatFromInt(memo.extent);+ // The ink is the band `inset` to `inset + band` inside the outline: the+ // casing, the stroke `case` further in, and the casing again.const inset = @as(f32, @floatFromInt(memo.border)) + memo.inset * memo.density;const stroke = memo.stroke * memo.density;- // The stroke is the band `inset` to `inset + stroke` inside the outline.+ const case = memo.casing_width * memo.density;+ const band = stroke + 2 * case;+ const cased = case > 0 and memo.casing[3] > 0;+ // Ends: the casing reaches `end_padding` short of the square and the+ // stroke the casing width short of that. A cut end runs at 45 degrees,+ // from the outer edge to the inner edge `stroke` shorter. The casing's+ // cut is the stroke's moved out by the casing width, square to it, and+ // its sharp tip is capped at the casing's end rather than growing a barb.+ const cut: f32 = if (memo.cut_ends) 1 else 0;+ const casing_end = extent - memo.end_padding * memo.density;+ const stroke_end = casing_end - case;+ const casing_cut = stroke_end + case * (1 + cut * std.math.sqrt2);+ const end_scale = memo.scale / @sqrt(1 + cut * cut);// Its ink ends half a device pixel beyond either side.- const centre = -(inset + stroke / 2);- const half = stroke / 2 + 0.5 / memo.scale;+ const centre = -(inset + band / 2);+ const half = band / 2 + 0.5 / memo.scale;const stride: usize = @intCast(buffer.width);// A raster outlives a resize, so it must not depend on where the frame's far// edges were when it was painted: the polygon is measured in f64, and a@@ -198,11 +222,21 @@ fn paint(buffer: *PanelBuffer, memo: Memo, polygon: ?ui.window_shape.Resolved, rdx += @intFromFloat(clear);continue;}- // Leave the output pass's frame ring untouched. This stroke is- // just inside it; all pixels still inherit frame opacity and clipping.- const coverage = ui.sdf.coverage((distance + inset) * memo.scale) *- ui.sdf.coverage((-distance - inset - stroke) * memo.scale);- const end = ui.sdf.coverage((@max(along_x, along_y) - extent + memo.end_padding * memo.density) * memo.scale);+ // Leave the output pass's frame ring untouched. This band is just+ // inside it; all pixels still inherit frame opacity and clipping.+ // Near an end one coordinate runs along the arm and the other is+ // small, so the larger one is how far along the stroke a pixel is.+ const along = @max(along_x, along_y);+ // How far in from the band's outer edge.+ const depth = -distance - inset;+ if (cased) {+ const coverage = ui.sdf.coverage(-depth * memo.scale) * ui.sdf.coverage((depth - band) * memo.scale);+ const end = @min(ui.sdf.coverage((along - casing_cut + cut * depth) * end_scale), ui.sdf.coverage((along - casing_end) * memo.scale));+ if (coverage * end > 0) ui.text.blendPixel(&buffer.pixels[dy * stride + dx], casing_color, coverage * end);+ }+ const inner = depth - case;+ const coverage = ui.sdf.coverage(-inner * memo.scale) * ui.sdf.coverage((inner - stroke) * memo.scale);+ const end = ui.sdf.coverage((along - stroke_end + cut * inner) * end_scale);if (coverage * end > 0) ui.text.blendPixel(&buffer.pixels[dy * stride + dx], color, coverage * end);}}diff --git a/src/toplevel/inner_border.zig b/src/toplevel/inner_border.zignew file mode 100644index 0000000..d4f540b--- /dev/null+++ b/src/toplevel/inner_border.zig@@ -0,0 +1,130 @@+//! Continuous inner frame ring. Four disjoint strips keep its raster storage+//! proportional to the perimeter; no full-window buffer or idle repainting.+const std = @import("std");+const Toplevel = @import("../Toplevel.zig");+const sn = @import("../node.zig");+const chrome = @import("../chrome.zig");+const PanelBuffer = @import("../panel_buffer.zig").PanelBuffer;+const ui = @import("ui");+const Rect = ui.window_chrome.Rect;++const Memo = struct {+ width: i32,+ height: i32,+ scale: f32,+ radius: f32,+ shape: u64,+ maximized: bool,+ outer: i32,+ inner: i32,+ color: [4]f32,+};++pub const State = struct {+ nodes: [4]?*sn.Buffer = @splat(null),+ memo: ?Memo = null,+};++pub fn syncInnerBorder(t: *Toplevel) !void {+ const state = &t.inner_border;+ const color = ui.theme.global.window_inner_border;+ if (!chrome.shapes or !t.hasServerDecorations() or chrome.innerBorder() == 0 or color[3] <= 0) {+ for (state.nodes) |node| if (node) |n| n.node.setEnabled(false);+ state.memo = null;+ return;+ }+ const memo: Memo = .{+ .width = t.chrome_width,+ .height = t.chrome_height,+ .scale = t.render_scale,+ .radius = t.cornerRadius(),+ .shape = t.shapeKey(),+ .maximized = t.isMaximized(),+ .outer = chrome.outerBorder(),+ .inner = chrome.innerBorder(),+ .color = color,+ };+ const repaint = if (state.memo) |previous| !std.meta.eql(previous, memo) else true;+ if (repaint) {+ const polygon = t.shapePolygon(memo.width, memo.height);+ const boxes = strips(memo, polygon);+ for (&state.nodes, boxes) |*slot, box| {+ if (box.w <= 0 or box.h <= 0) {+ if (slot.*) |node| node.node.setEnabled(false);+ continue;+ }+ if (slot.* == null) {+ const node = try t.frame_tree.createSceneBuffer(null);+ node.point_accepts_input = struct {+ fn accepts(_: *sn.Buffer, _: *f64, _: *f64) callconv(.c) bool {+ return false;+ }+ }.accepts;+ node.setFilterMode(.bilinear);+ // Even when enabled after the accents, the continuous band+ // belongs below their yellow ink and above the client's edge.+ node.node.placeAbove(&t.content_tree.node);+ slot.* = node;+ }+ const node = slot.*.?;+ const buffer = try PanelBuffer.createUnpooled(box.w, box.h, memo.scale);+ defer buffer.base.drop();+ paint(buffer, memo, polygon, box);+ node.setBuffer(&buffer.base);+ node.setDestSize(box.w, box.h);+ node.node.setPosition(box.x, box.y);+ node.node.setEnabled(true);+ }+ state.memo = memo;+ }+ for (state.nodes) |node| if (node) |n| n.setOpacity(t.shape_opacity);+}++fn strips(memo: Memo, polygon: ?ui.window_shape.Resolved) [4]Rect {+ const w: f64 = @floatFromInt(memo.width);+ const h: f64 = @floatFromInt(memo.height);+ var reach: f64 = @min(memo.radius, @min(w, h) / 2);+ if (polygon) |p| {+ reach = 0;+ for (p.points[0..p.count], 0..) |a, i| {+ const b = p.points[(i + 1) % p.count];+ // Every edge is wholly in at least one strip, even a concave+ // title step. Grow that strip by the ring width and AA fringe.+ const edge_reach = @min(@max(a[0], b[0]), @max(w - a[0], w - b[0]), @max(a[1], b[1]), @max(h - a[1], h - b[1]));+ reach = @max(reach, edge_reach);+ }+ }+ const band: i32 = @intFromFloat(@ceil(reach + @as(f64, @floatFromInt(memo.outer + memo.inner)) + 1));+ const sx = @min(band, @divTrunc(memo.width + 1, 2));+ const sy = @min(band, @divTrunc(memo.height + 1, 2));+ const right = @min(band, memo.width - sx);+ const bottom = @min(band, memo.height - sy);+ return .{+ .{ .x = 0, .y = 0, .w = memo.width, .h = sy },+ .{ .x = 0, .y = memo.height - bottom, .w = memo.width, .h = bottom },+ .{ .x = 0, .y = sy, .w = sx, .h = memo.height - sy - bottom },+ .{ .x = memo.width - right, .y = sy, .w = right, .h = memo.height - sy - bottom },+ };+}++fn paint(buffer: *PanelBuffer, memo: Memo, polygon: ?ui.window_shape.Resolved, box: Rect) void {+ const color: ui.text.Color = .{ .r = memo.color[0], .g = memo.color[1], .b = memo.color[2], .a = memo.color[3] };+ const outer: f32 = @floatFromInt(memo.outer);+ const inner: f32 = @floatFromInt(memo.inner);+ const stride: usize = @intCast(buffer.width);+ for (0..@intCast(buffer.height)) |dy| {+ const py = (@as(f32, @floatFromInt(dy)) + 0.5) / memo.scale + @as(f32, @floatFromInt(box.y));+ var dx: usize = 0;+ while (dx < stride) : (dx += 1) {+ const px = (@as(f32, @floatFromInt(dx)) + 0.5) / memo.scale + @as(f32, @floatFromInt(box.x));+ const distance: f32 = if (polygon) |p| @floatCast(ui.window_shape.sdPolygon(p, px, py)) else ui.sdf.sdRoundedBox(px, py, 0, 0, @floatFromInt(memo.width), @floatFromInt(memo.height), memo.radius);+ const band_distance = (@abs(distance + outer + inner / 2) - inner / 2) * memo.scale;+ const run = @min(ui.window_shape.saturatedRun(band_distance), stride - dx - 1);+ const coverage = ui.sdf.coverage(band_distance);+ if (coverage > 0) {+ for (dx..dx + run + 1) |x| ui.text.blendPixel(&buffer.pixels[dy * stride + x], color, coverage);+ }+ dx += run;+ }+ }+}diff --git a/src/ui/theme.zig b/src/ui/theme.zigindex 06867e6..84462cd 100644--- a/src/ui/theme.zig+++ b/src/ui/theme.zig@@ -55,6 +55,8 @@ pub const Theme = struct {window_title_plate_fg: ?[4]f32 = null,window_title_plate_inset: f32 = 5,window_title_plate_bevel: f32 = 7,+ /// Cut at the plate's bottom-left corner (the bevel above is its top-left).+ window_title_plate_bottom_bevel: f32 = 0,/// Right slant as a fraction of chrome_height; gaps/padding are logical px.window_title_plate_slant: f32 = 0.65,window_title_plate_control_gap: f32 = 8,@@ -68,6 +70,12 @@ pub const Theme = struct {/// Inset beyond the frame's own border ring, and padding at stroke endpoints.window_corner_inset: f32 = 0,window_corner_end_padding: f32 = 2,+ /// Band of its own around the stroke on every side, ends included (zero+ /// width: none). The stroke moves in by the casing width.+ window_corner_casing: [4]f32 = .{ 0, 0, 0, 0 },+ window_corner_casing_width: f32 = 0,+ /// Cut the stroke's (and casing's) ends at 45 degrees, the outer edge longest.+ window_corner_cut_ends: bool = false,window_corner_resize_ms: f32 = 140,window_corner_restore_ms: f32 = 180,/// out_cubic, in_out_sine or flip_bezier; global animation preferences still apply.@@ -81,6 +89,9 @@ pub const Theme = struct {window_border_hover: [4]f32 = .{ 1, 1, 1, 0.13 },/// Outer window frame, logical px (1–16, rounded to whole pixels).window_border_width: f32 = 1,+ /// Continuous inner frame band, reserved outside the client (zero: none).+ window_inner_border: [4]f32 = .{ 0, 0, 0, 0 },+ window_inner_border_width: f32 = 0,/// Active window outline in opt-in workspace mode (#ed1b2e).workspace_active_border: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 1 },window_divider: [4]f32 = .{ 1, 1, 1, 0.045 },@@ -400,9 +411,10 @@ pub const Theme = struct {desktop_fg: [4]f32 = .{ 238.0 / 255.0, 241.0 / 255.0, 251.0 / 255.0, 1 },desktop_text_shadow: [4]f32 = .{ 0, 0, 0, 0.22 },desktop_hover: [4]f32 = .{ 1, 1, 1, 0.06 },- desktop_selected: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 0.12 },- desktop_selection: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 0.15 },- desktop_selection_border: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 1 },+ /// Unset desktop selection colours follow the shell accent.+ desktop_selected: ?[4]f32 = null,+ desktop_selection: ?[4]f32 = null,+ desktop_selection_border: ?[4]f32 = null,desktop_drop_border: [4]f32 = .{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 0.8 },desktop_dialog_bg: [4]f32 = .{ 0.035, 0.043, 0.094, 0.98 },desktop_notice_bg: [4]f32 = .{ 0.12, 0.035, 0.06, 0.95 },@@ -550,6 +562,23 @@ pub const Theme = struct {if (t.selection) |color| return color;return .{ t.accent[0], t.accent[1], t.accent[2], t.accent[3] * t.selection_alpha };}++ pub fn desktopSelectedColor(t: Theme) [4]f32 {+ return t.desktop_selected orelse t.desktopAccent(0.12);+ }++ pub fn desktopSelectionColor(t: Theme) [4]f32 {+ return t.desktop_selection orelse t.desktopAccent(0.15);+ }++ pub fn desktopSelectionBorder(t: Theme) [4]f32 {+ return t.desktop_selection_border orelse t.desktopAccent(1);+ }++ fn desktopAccent(t: Theme, alpha: f32) [4]f32 {+ const color = t.shell_accent orelse t.start_menu_selected_marker;+ return .{ color[0], color[1], color[2], color[3] * alpha };+ }};/// Neutral window greys with the start menu's marker as accent: the palettediff --git a/src/ui/theme_file.zig b/src/ui/theme_file.zigindex 3e6acb9..4ba3c87 100644--- a/src/ui/theme_file.zig+++ b/src/ui/theme_file.zig@@ -168,6 +168,9 @@ pub fn applyKey(allocator: Allocator, t: *Theme, name_in: []const u8, value: []cif (comptime std.mem.eql(u8, name, "window_border_width")) {if (number < 1 or number > 16) return error.InvalidSize;}+ if (comptime std.mem.eql(u8, name, "window_inner_border_width")) {+ if (number > 16) return error.InvalidSize;+ }if (comptime std.mem.eql(u8, name, "chrome_control_gap")) {if (number > 24) return error.InvalidSize;}diff --git a/src/ui/theme_tests.zig b/src/ui/theme_tests.zigindex b5a9531..1cbfd8b 100644--- a/src/ui/theme_tests.zig+++ b/src/ui/theme_tests.zig@@ -58,6 +58,23 @@ test "parse reads the spec's example theme file" {try std.testing.expectApproxEqAbs(@as(f32, 0.40), t.border_focus[3], 1e-6);}+test "desktop selection inherits the shell accent and preserves explicit colours" {+ var t: Theme = .{};+ try std.testing.expectEqual([4]f32{ 237.0 / 255.0, 27.0 / 255.0, 46.0 / 255.0, 1 }, t.desktopSelectionBorder());+ t.start_menu_selected_marker = .{ 0, 1, 0, 1 };+ try std.testing.expectEqual([4]f32{ 0, 1, 0, 0.15 }, t.desktopSelectionColor());+ t.shell_accent = .{ 1, 0.8, 0, 0.5 };+ try std.testing.expectEqual([4]f32{ 1, 0.8, 0, 0.06 }, t.desktopSelectedColor());+ try std.testing.expectEqual([4]f32{ 1, 0.8, 0, 0.075 }, t.desktopSelectionColor());+ try std.testing.expectEqual(t.shell_accent.?, t.desktopSelectionBorder());+ t.desktop_selection = .{ 0, 0, 0, 0 };+ t.desktop_selection_border = .{ 0, 0, 1, 1 };+ t.desktop_selected = .{ 0, 1, 0, 0.2 };+ try std.testing.expectEqual(t.desktop_selection.?, t.desktopSelectionColor());+ try std.testing.expectEqual(t.desktop_selection_border.?, t.desktopSelectionBorder());+ try std.testing.expectEqual(t.desktop_selected.?, t.desktopSelectedColor());+}+test "writeInto then parse round-trips every field" {var t: Theme = .{};t.clock_bold = true;@@ -74,6 +91,7 @@ test "writeInto then parse round-trips every field" {t.radius_md = 9;t.radius_lg = 12;t.window_border_width = 2;+ t.window_inner_border_width = 3;t.glass = .{ 0.2, 0.4, 0.6, 0.56 };t.taskbar_bg = .{ 0.1, 0.2, 0.3, 0.62 };t.start_button_icon = "/tmp/custom logo.svg";@@ -268,6 +286,10 @@ test "chrome geometry validates and survives theme serialization" {var t: Theme = .{};try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "window_border_width", value));}+ for ([_][]const u8{ "-1", "17", "nan", "inf" }) |value| {+ var t: Theme = .{};+ try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "window_inner_border_width", value));+ }for ([_][]const u8{ "0", "27", "85", "nan", "inf" }) |value| {var t: Theme = .{};try std.testing.expectError(error.InvalidSize, applyKey(a, &t, "chrome_height", value));@@ -281,12 +303,13 @@ test "chrome geometry validates and survives theme serialization" {try std.testing.expectError(error.InvalidBoolean, applyKey(a, &t, "chrome_round_buttons", value));}try std.testing.expect(!(try parse(a, "[theme]\nchrome_round_buttons = false\n")).chrome_round_buttons);- const t = try parse(a, "[theme]\nchrome_height = 28\nchrome_control_gap = 0\nchrome_round_buttons = true\nwindow_border_width = 2\n");+ const t = try parse(a, "[theme]\nchrome_height = 28\nchrome_control_gap = 0\nchrome_round_buttons = true\nwindow_border_width = 2\nwindow_inner_border_width = 3\n");var buf: std.ArrayList(u8) = .empty;try writeInto(a, &buf, t);const restored = try parse(a, buf.items);try std.testing.expectEqual(@as(f32, 28), restored.chrome_height);try std.testing.expectEqual(@as(f32, 2), restored.window_border_width);+ try std.testing.expectEqual(@as(f32, 3), restored.window_inner_border_width);try std.testing.expectEqual(@as(f32, 0), restored.chrome_control_gap);try std.testing.expect(restored.chrome_round_buttons);}diff --git a/src/ui/window_chrome.zig b/src/ui/window_chrome.zigindex 4a56d5f..907d5d8 100644--- a/src/ui/window_chrome.zig+++ b/src/ui/window_chrome.zig@@ -19,8 +19,16 @@ pub const ControlKind = enum { minimize, maximize, close };// Charcoal header with evenly spaced, unboxed window controls.pub fn frameBorder() i32 {+ return outerBorder() + innerBorder();+}++pub fn outerBorder() i32 {return @intFromFloat(@round(std.math.clamp(theme.global.window_border_width, 1, 16)));}++pub fn innerBorder() i32 {+ return @intFromFloat(@round(std.math.clamp(theme.global.window_inner_border_width, 0, 16)));+}const btn_size: i32 = 34;const close_size: i32 = 34;// Preserve the original icon/control proportions when changing bar height.diff --git a/tests/blackout.py b/tests/blackout.pyindex d214799..4d7f608 100644--- a/tests/blackout.py+++ b/tests/blackout.py@@ -93,10 +93,10 @@ def run(scale):assert colors.get((52, 61, 62), 0) > 30, colorsdebug = ipc.get_window_debug(wid)assert debug["titlebar_height"] == 48, debug- assert debug["frame_border"] == debug["footer_height"] == 2, debug+ assert debug["frame_border"] == debug["footer_height"] == 5, debugcontrols = {w["name"]: w for w in ipc.get_widget_tree(f"window/{wid}")["widgets"]}close = controls["close"]["box"]- assert close["x"] + close["width"] > debug["chrome_box"]["width"] - 14, close+ assert close["x"] + close["width"] > debug["chrome_box"]["width"] - 17, closeassert close["y"] + close["height"] / 2 > debug["titlebar_height"] / 2 + 3, close# Keep a real rendered preview for review (never the reference image).shot.save(f"/tmp/blackout-preview-{scale}.png")diff --git a/tests/blackout_config.py b/tests/blackout_config.pyindex 2c08417..aa346e9 100644--- a/tests/blackout_config.py+++ b/tests/blackout_config.py@@ -22,14 +22,14 @@ def check_config(ipc, wid, scale, tmp, capture, crop, yellow):check_border(ipc, wid, scale, tmp, capture)before = capture()box = ipc.get_window_debug(wid)["chrome_box"]- sample = (round((box["x"] + 80) * scale), round((box["y"] + 8) * scale))+ sample = (round((box["x"] + 80) * scale), round((box["y"] + 14) * scale))assert yellow(before.getpixel(sample)), "title plate depends on pack name"check_power_menu(ipc, scale, capture, crop, yellow)body = ipc.get_window_debug(wid)["client_box"]track_box = (body["width"] - 18, 120, 18, 160)old_track = crop(before, body, track_box).tobytes()values = {- "window_title_plate_inset": 10,+ "window_title_plate_inset": 16,"window_title_plate_bevel": 2,"window_title_plate_slant": 0.25,"window_title_plate_control_gap": 20,@@ -57,7 +57,8 @@ def check_config(ipc, wid, scale, tmp, capture, crop, yellow):after = wait_for(changed, "live plate/stripe geometry overrides")def endpoint(image):- strip = crop(image, box, (0, box["height"] - 4, 80, 3))+ # Inside the outer ring, 1 px further in with the inset.+ strip = crop(image, box, (0, box["height"] - 6, 80, 4))return max((x for x in range(strip.width)if any(yellow(strip.getpixel((x, y))) for y in range(strip.height))), default=0)assert 5 * scale <= endpoint(before) - endpoint(after) <= 7 * scale, "corner padding ignored"@@ -73,17 +74,17 @@ def check_border(ipc, wid, scale, tmp, capture):original = config_path.read_text()client = ipc.get_window_debug(wid)["client_box"]try:- for border in (2, 1, 2):- config_path.write_text(original + f"\nwindow_border_width = {border}\n")+ for border, inner in ((2, 3), (1, 3), (2, 5), (2, 0), (2, 3)):+ config_path.write_text(original + f"\nwindow_border_width = {border}\nwindow_inner_border_width = {inner}\n")ipc.reload_config()ipc.wait_for("window_geometry_settled", window_id=wid)debug = ipc.get_window_debug(wid)body, frame = debug["client_box"], debug["chrome_box"]- assert debug["frame_border"] == debug["footer_height"] == border, debug+ assert debug["frame_border"] == debug["footer_height"] == border + inner, debugassert (body["width"], body["height"]) == (client["width"], client["height"]), debug- assert body["x"] == frame["x"] + border, debug- assert frame["width"] == body["width"] + 2 * border, debug- assert frame["height"] == body["height"] + debug["titlebar_height"] + border, debug+ assert body["x"] == frame["x"] + border + inner, debug+ assert frame["width"] == body["width"] + 2 * (border + inner), debug+ assert frame["height"] == body["height"] + debug["titlebar_height"] + border + inner, debugipc.move_cursor(body["x"] + body["width"] // 2, body["y"] + body["height"] // 2)image = capture()x = round((frame["x"] + frame["width"] / 2) * scale)@@ -92,6 +93,46 @@ def check_border(ipc, wid, scale, tmp, capture):for offset in range(int(border * scale + .5)):pixel = image.getpixel((x, bottom - 1 - offset))assert max(abs(a - b) for a, b in zip(pixel, (115, 124, 104))) <= 3, (border, offset, pixel)+ if inner:+ # Follow all four sides, including the lowered top edge. The+ # band touches the ring and occupies reserved client margins.+ mid = border + inner / 2+ points = ((mid, frame["height"] / 2),+ (frame["width"] - mid, frame["height"] / 2),+ (frame["width"] / 2, frame["height"] - mid),+ (frame["width"] - 100, 7 + mid))+ for px, py in points:+ pixel = image.getpixel((int((frame["x"] + px) * scale),+ int((frame["y"] + py) * scale)))+ assert max(abs(a - b) for a, b in zip(pixel, (43, 50, 51))) <= 3, (border, inner, px, py, pixel)+ if inner == 3:+ # Yellow starts immediately after the outer ring, replacing+ # the dark band for the entire stroke width, with no casing gap.+ y = int((frame["y"] + frame["height"] - 25) * scale)+ for depth in (border + .75, border + inner - .75):+ pixel = image.getpixel((int((frame["x"] + depth) * scale), y))+ assert pixel[0] > 180 and pixel[1] > 170 and pixel[2] < 60, (depth, pixel)+ # Every beveled end has its longest edge toward the outside.+ for right in (False, True):+ for bottom_edge in (False, True):+ for vertical in (False, True):+ ends = []+ for depth in (border + .75, border + inner - .75):+ end = 0+ for along in range(round(45 * scale)):+ px, py = (depth, along / scale) if vertical else (along / scale, depth)+ if right:+ px = frame["width"] - px+ if bottom_edge:+ py = frame["height"] - py+ elif right and not vertical:+ py += 7 # The lowered top-right edge.+ pixel = image.getpixel((int((frame["x"] + px) * scale),+ int((frame["y"] + py) * scale)))+ if pixel[0] > 180 and pixel[1] > 170 and pixel[2] < 60:+ end = along+ ends.append(end)+ assert ends[0] > ends[1], (right, bottom_edge, vertical, ends)image.save(f"/tmp/blackout-border-{scale}.png")finally:config_path.write_text(original)diff --git a/tests/blackout_resize.py b/tests/blackout_resize.pyindex 9c4c52b..043dfb6 100644--- a/tests/blackout_resize.py+++ b/tests/blackout_resize.py@@ -46,7 +46,7 @@ def check_narrow(ipc, scale, tmp, capture, crop):fallback = capture()same = crop(actual, box, rect).tobytes() == crop(fallback, box, rect).tobytes()# The raised step and the right chamfer need 297.5 logical px,- # including the two 2 px borders around the client.+ # including both reserved frame bands around the client.assert same == (box["width"] < 297.5), (grouped, width, box, same)config_path.write_text(config)ipc.reload_config()@@ -72,7 +72,8 @@ def check_resize(ipc, wid, scale, tmp, capture, crop, yellow):def length():image = capture()box = ipc.get_window_debug(wid)["chrome_box"]- strip = crop(image, box, (0, box["height"] - 4, 80, 3))+ # The stroke fills the inner band, 2 to 5 px inside the outline.+ strip = crop(image, box, (0, box["height"] - 5, 80, 3))return max((x for x in range(strip.width)if any(yellow(strip.getpixel((x, y))) for y in range(strip.height))), default=0)diff --git a/tests/desktop_selection.py b/tests/desktop_selection.pynew file mode 100644index 0000000..78cfad8--- /dev/null+++ b/tests/desktop_selection.py@@ -0,0 +1,89 @@+#!/usr/bin/env python3+"""Desktop selection follows theme accents, overrides and reloads during a drag."""+import math+import os+from pathlib import Path+import tempfile++from PIL import Image++from ipc_client import IPCClient, spawn_compositor, stop_process+++def run(scale):+ with tempfile.TemporaryDirectory(prefix="rediwm-desktop-selection-") as directory:+ tmp = Path(directory)+ home = tmp / "home"+ desktop = home / "Desktop"+ desktop.mkdir(parents=True)+ wallpaper = tmp / "black.png"+ Image.new("RGB", (8, 8)).save(wallpaper)+ env = dict(HOME=str(home), XDG_CONFIG_HOME=str(tmp / "config"),+ XDG_DATA_HOME=str(tmp / "data"), XDG_CACHE_HOME=str(tmp / "cache"),+ XDG_STATE_HOME=str(tmp / "state"), DBUS_SESSION_BUS_ADDRESS="",+ DBUS_SYSTEM_BUS_ADDRESS="unix:path=/nonexistent",+ REDIWM_DESKTOP_DIR=str(desktop), REDIWM_DESKTOP_BUILTINS="0")++ def config(pack, overrides=""):+ return (f'[compositor]\nxwayland = false\nwallpaper = "{wallpaper}"\n'+ '[desktop]\nenabled = true\n[animations]\nenabled = false\n'+ f'[theme]\nbase = "{pack}"\n{overrides}')++ process, log = spawn_compositor(tmp, scale=str(scale),+ config_content=config("blackout"), env_extra=env)+ try:+ with IPCClient(tmp, timeout=20) as ipc:+ ipc.wait_for("wallpaper_presented")+ ipc.move_cursor(300, 200)+ ipc.pointer_button(272, True)+ ipc.move_cursor(600, 400)+ cases = (+ ("blackout", (251, 227, 1), .15, (251, 227, 1), ""),+ ("redi-blue", (0, 209, 255), .15, (0, 209, 255), ""),+ # Existing explicit desktop colours still take precedence.+ ("rediwm-light", (14, 165, 160), .15, (14, 165, 160), ""),+ ("gold", (218, 169, 110), .18, (220, 172, 115), ""),+ ("blackout", (20, 180, 80), .25, (20, 180, 80),+ 'desktop_selection = "rgba(20,180,80,0.25)"\n'+ 'desktop_selection_border = "#14B450"\n'),+ ("blackout", (0, 0, 0), 0, (20, 180, 80),+ 'desktop_selection = "#00000000"\n'+ 'desktop_selection_border = "#14B450"\n'),+ ("blackout", (251, 227, 1), .15, (251, 227, 1), ""),+ )+ for index, (pack, fill, alpha, border, overrides) in enumerate(cases):+ # Keep the button down: a reload must repaint the unchanged+ # interior as well as its edges, without another motion.+ (tmp / "rediwm-config.toml").write_text(config(pack, overrides))+ ipc.reload_config()+ ipc.wait_for_frame()+ path = tmp / f"selection-{index}.png"+ ipc.screenshot(str(path))+ image = Image.open(path).convert("RGB")+ assert image.getpixel((round(250 * scale), round(300 * scale))) == (0, 0, 0)+ pixel = image.getpixel((round(450 * scale), round(300 * scale)))+ expected = tuple(round(channel * alpha) for channel in fill)+ assert max(abs(a - b) for a, b in zip(pixel, expected)) <= 2, (pack, pixel, expected)+ # Cairo's 1px outline straddles pixels at these scales.+ # Its brightest sample must be the border hue at >=40%+ # coverage; red inherited from another theme cannot pass.+ edge = max((image.getpixel((round(450 * scale), y))+ for y in range(math.floor(200 * scale) - 2,+ math.ceil(200 * scale) + 3)), key=sum)+ coverage = sum(a * b for a, b in zip(edge, border)) / sum(b * b for b in border)+ assert .4 <= coverage <= 1.01, (pack, edge, border, coverage)+ assert max(abs(a - b * coverage) for a, b in zip(edge, border)) <= 3, (pack, edge, border)+ image.save(f"/tmp/desktop-selection-{pack}-{scale}.png")+ ipc.pointer_button(272, False)+ print(f"PASS: desktop selection accents, explicit colours and live drag reload (scale={scale})")+ except Exception:+ print((tmp / "compositor.log").read_text()[-4000:])+ raise+ finally:+ stop_process(process)+ log.close()+++if __name__ == "__main__":+ run(1)+ run(1.5)