RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Polygon outlines for windows and the taskbar, set from the theme
oxydizerd72e34526c66
diff --git a/assets/themes/chamfer-blue.toml b/assets/themes/chamfer-blue.tomlnew file mode 100644index 0000000..8e77220--- /dev/null+++ b/assets/themes/chamfer-blue.toml@@ -0,0 +1,136 @@+[meta]+format = 1+id = "chamfer-blue"+name = "Chamfer Blue"+description = "Test pack for polygon window outlines: cut corners, a stepped top edge and a dark top band."++[theme]+# Shared lock screen and login screen.+lock_bg = "#070F1F"+lock_fg = "#E6F1FF"+lock_dim = "#A0B4D8"+lock_divider = "#2A4B6F"+lock_session_fg = "#8FB7E8"+lock_wallpaper_opacity = 0.24++# Window outline: a polygon instead of a rounded rectangle (ui/window_shape.zig).+# Points are "x y" in logical px from the left/top, negative from the right/bottom;+# a "%" is a fraction of the window. Cut corners, and a top edge that steps down+# 3 px for the last 160 px.+window_shape = "0 14, 14 0, -160 0, -148 3, -14 3, -0 17, -0 -14, -14 -0, 14 -0, 0 -14"+# The taskbar the same way, against the bar's own box: a raised section on the+# left, a 6 px step down, and a slanted tip on the right. Items keep clear of the+# slanted ends; the notch is the window or desktop below.+taskbar_shape = "0 -0, 14 0, 300 0, 312 6, -14 6, -0 -0"+# A strip along the top of the titlebar, clipped by the outline.+window_top_band = "#0A2A5E"+window_top_band_height = 5++# Window chrome+window_bg = "rgba(14,19,28,0.46)"+window_fg = "#E6F1FF"+window_dim = "#A0B4D8"+window_border = "#2A4B6F"+window_border_hover = "rgba(59,130,246,0.70)"+window_divider = "#1E3A5F"+window_close_hover = "#EF4444"++# App windows (Files, Images, PDF)+text_secondary = "#A0B4D8"+app_bg = "#0D192B"+app_toolbar = "#0F1B2E"+app_sidebar = "#0F2036"+app_bar = "#12263F"+app_item = "#132B46"+app_item_hover = "#1A3658"+app_item_border = "#1E3A5F"+app_item_selected = "#1E40AF"+app_nav_selected = "#164E91"+app_divider = "#1E3A5F"+app_icon = "#8FB7E8"+scrollbar_thumb = "#2A4B6F"+scrollbar_thumb_active = "#3B82F6"++# Shell palette+bg = "#070F1F"+fg = "#E6F1FF"+dim = "#A0B4D8"+faint = "#6B84A5"+accent = "#00D1FF"+accent_2 = "#A855F7"+accent_3 = "#2563EB"+danger = "#EF4444"+on_accent = "#04111A"+# Shell controls use these overrides when constructing their palette.+shell_accent = "#00D1FF"+shell_on_accent = "#04111A"+surface = "rgba(255,255,255,0.05)"+surface_hover = "rgba(0,209,255,0.08)"+border = "#2A4B6F"+border_soft = "#1E3A5F"+border_hover = "#3B82F6"+border_focus = "rgba(0,209,255,0.45)"+glass = "rgba(8,20,38,0.62)"+glass_strong = "rgba(8,18,32,0.82)"+shadow = "rgba(0,0,0,0.55)"+border_glow = "rgba(0,209,255,0.50)"++# Taskbar+taskbar_bg = "rgba(10,20,38,0.96)"+taskbar_surface = "rgba(255,255,255,0.03)"+taskbar_hover = "rgba(0,209,255,0.08)"+taskbar_border = "#2A4B6F"++# Start menu and fields+start_menu_bg = "rgba(15,27,46,0.98)"+start_menu_border = "#2A4B6F"+start_menu_search_bg = "#0B1526"+start_menu_selected_bg = "rgba(37,99,235,0.18)"+start_menu_selected_border = "rgba(0,209,255,0.40)"+start_menu_selected_marker = "#00D1FF"+field_bg = "#0E182B"+field_border = "#315E9E"++# Caret, selection, selection_fg and field_border_focus follow the accent.+selection_alpha = 0.30++# Line thicknesses and sizes (logical px)+caret_width = 1.5+scrollbar_width = 8+chrome_height = 32+chrome_control_gap = 4+taskbar_size = 44+start_button_icon_size = 36+chip_gap = 4+shadow_size = 24+shadow_offset_y = 8++# Sharp corners+radius = 4+radius_md = 4+radius_lg = 4+field_radius = 4+start_menu_radius = 4+settings_radius = 4+settings_sidebar_radius = 4+settings_card_radius = 4+toggle_radius = 4+swatch_radius = 4+dialog_badge_radius = 4+dialog_inset_radius = 4+switcher_radius = 4+switcher_item_radius = 4+switcher_icon_radius = 4+switcher_selection_radius = 4+calendar_radius = 4+osd_radius = 4+start_button_radius = 4++[layout]+taskbar_position = "bottom"+taskbar_items = ["left:start", "left:windows", "right:capture", "right:tray", "right:battery", "~right:wifi", "~right:wired", "right:volume", "right:clock", "-right:power"]+dock_enabled = false++[assets]+color_scheme = "dark"+wallpaper = "wallpaper-blue.png"diff --git a/build.zig b/build.zigindex 57494fd..4c04073 100644--- a/build.zig+++ b/build.zig@@ -72,6 +72,7 @@ pub fn build(b: *std.Build) void {ui_mod.addAnonymousImport("theme-rediwm-light", .{ .root_source_file = b.path("assets/themes/rediwm-light.toml") });ui_mod.addAnonymousImport("theme-redi-blue", .{ .root_source_file = b.path("assets/themes/redi-blue.toml") });ui_mod.addAnonymousImport("theme-redi-mocha", .{ .root_source_file = b.path("assets/themes/redi-mocha.toml") });+ ui_mod.addAnonymousImport("theme-chamfer-blue", .{ .root_source_file = b.path("assets/themes/chamfer-blue.toml") });ui_mod.addAnonymousImport("theme-gold", .{ .root_source_file = b.path("assets/themes/gold.toml") });b.getInstallStep().dependOn(&b.addInstallDirectory(.{.source_dir = b.path("assets/themes/gold"),diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdindex 29bb58c..37088cc 100644--- a/docs/agent-notes/rendering.md+++ b/docs/agent-notes/rendering.md@@ -19,7 +19,21 @@ chrome, capture, or retained panel painting. General rules remain in`shadow_tree`, the CPU formula's smoothstep); its leaf `shadow_node` has nobuffer and carries footprint, opacity and input only, so the projectiondamages that footprint itself. CSD windows have no shape and keep the- `border_rects` outline. A changed clip damages its rim itself+ `border_rects` outline. A theme's `window_shape` makes the clip a polygon+ (`ui/window_shape.zig`, anchored points resolved against the live frame in+ `Toplevel.shapePolygon`): `radii` is then unused, `rediwm_clip.inset` is how+ far in the largest rectangle wholly inside it lies (the opaque cover, the+ plain core and the damage rim all use it), and the shader's `sdpoly` walks+ the same edges as `rediwm_sd_polygon`; keep the two, and `window_shape.sdPolygon`,+ in step. Anything that mirrors `rediwm_pass_shape` in Zig must mirror it whole.+ The polygon distance is compiled only into two extra programs (`POLY`,+ `shaped_poly[_external]`, `rediwm_scene_renderer_enable_polygons`), built on the+ first `chrome.polygonsReady()` from layout code (never inside a pass); a polygon+ draw before that fails the pass, so draw and capture code reads `chrome.polygons`.+ The taskbar uses the same clip on its tree (`Taskbar.applyClip`) with its raster+ outer edge left hard (`taskbar/shape.zig` `paintPolygon`: row spans, a distance+ only near an edge).+ A changed clip damages its rim itself(`projection_resolve.c`); a point the shape cuts away is declined by the pick(`pick_world`), so the pick falls to what is below. Window capture draws the client alone and ishanded the shape explicitly. The ring is one `max(1, round(border * scale))`.diff --git a/docs/wiki/Theme.md b/docs/wiki/Theme.mdindex f4dd85c..209f863 100644--- a/docs/wiki/Theme.md+++ b/docs/wiki/Theme.md@@ -127,6 +127,33 @@ same setting. It defaults to `false`, preserving the existing corner radii,and reloads live from the main config or the `REDIWM_THEME` file. Button sizesand hit targets stay the same; `radius_lg` still controls the window frame.+`[theme].window_shape` replaces the rounded rectangle of server-decorated+windows with a polygon: up to 16 points, `"x y"` pairs separated by commas.+A coordinate is logical px from the left or top edge, a negative one (`-0`+included) px from the right or bottom edge, and `N%` a fraction of the window,+so one outline fits any size. For example+`window_shape = "0 14, 14 0, -160 0, -148 3, -14 3, -0 17, -0 -14, -14 -0, 14 -0, 0 -14"`+cuts the corners and steps the top edge down for its last 160 px. The ring,+shadow, glass and pointer picking follow the outline. An outline that does not+parse is refused when the theme loads; one that crosses itself at a window's+size (a window narrower than its notches) falls back to the rounded rectangle,+as do maximized and fullscreen windows. `window_top_band` (colour) and+`window_top_band_height` (logical px, 0 = none) paint a strip along the top of+the titlebar, clipped by the shape. The titlebar's icon, title and controls+(and the tab strip's right end) keep in from the outline's slanted or cut ends+over the rows they occupy; a notch they do not reach into is left to the clip.+The outline's GL programs are built the first time a theme asks for one, so a+theme without `window_shape` or `taskbar_shape` never pays for them. The+bundled `chamfer-blue` pack is an example.++`[theme].taskbar_shape` does the same for the taskbar, against the bar's own+box (so `-0` is the bar's right or bottom edge): for example+`"0 -0, 14 0, 300 0, 312 6, -14 6, -0 -0"` is a raised left section, a 6 px step+down and a slanted right tip. It replaces `taskbar_radius`. Items keep clear of+the slanted ends but not of a notch in the middle, the notch is transparent and+clicks in it reach what is below, and glass follows the outline. The bar is+painted once per layout change, not per frame.+The lock's background always paints opaque, even if `lock_bg` supplies alpha;`lock_wallpaper_opacity` controls its wallpaper overlay. Actual image pixels,PDF paper/content, application-provided icons and fixed layout/hit-test@@ -290,6 +317,10 @@ Numeric tokens accept 0–4096 unless constrained below. Fractions ending in| `title_size` | `13.5` || `chrome_height` | `46.0` || `chrome_control_gap` | `4.0` |+| `window_shape` | `""` (the rounded rectangle) |+| `window_top_band` | `rgba(0,0,0,0)` |+| `window_top_band_height` | `0.0` |+| `taskbar_shape` | `""` (the rounded rectangle) || `taskbar_title_size` | `12.5` || `clock_bold`, `clock_italic` | `false` || `taskbar_size` | `44.0` |diff --git a/src/Server.zig b/src/Server.zigindex e87862a..b914293 100644--- a/src/Server.zig+++ b/src/Server.zig@@ -493,6 +493,8 @@ pub fn init(server: *Server, scale: ?f32, icon_theme_cfg: icon_theme.Config, io:// window exists. Without them windows are square, with no ring or shadow.if (server.output_renderer.enableShapes()) {@import("chrome.zig").shapes = true;+ @import("chrome.zig").polygon_context = server;+ @import("chrome.zig").polygon_enabler = &enablePolygons;// Glass (stage 5c of docs/plans/scene-graph.md); without the blur program// each glass surface shows its own tint.if (server.glass_engine != null and !server.output_renderer.enableBackdrops())@@ -1109,3 +1111,8 @@ pub fn parseGreeterFile(path: []const u8, a: std.mem.Allocator, io: std.Io) !condefer a.free(bytes);return config_loader.parse(a, bytes, path);}++fn enablePolygons(context: *anyopaque) bool {+ const server: *Server = @ptrCast(@alignCast(context));+ return server.output_renderer.enablePolygons();+}diff --git a/src/Taskbar.zig b/src/Taskbar.zigindex 352d97f..e718980 100644--- a/src/Taskbar.zig+++ b/src/Taskbar.zig@@ -68,6 +68,7 @@ pub const buttonSize = taskbar_metrics.buttonSize;pub const startButtonGap = taskbar_metrics.startButtonGap;pub const startButtonLeft = taskbar_metrics.startButtonLeft;pub const endInset = taskbar_metrics.endInset;+pub const hasPolygon = taskbar_metrics.hasPolygon;pub const rightPad = taskbar_metrics.rightPad;pub const startButtonBox = taskbar_metrics.startButtonBox;pub const startIconSize = taskbar_metrics.startIconSize;@@ -445,6 +446,7 @@ pub const bleedFor = taskbar_layout.bleedFor;pub const boxesOverlap = taskbar_layout.boxesOverlap;pub const isPlaced = taskbar_layout.isPlaced;pub const relayout = taskbar_layout.relayout;+pub const applyClip = taskbar_layout.applyClip;pub const notifyToplevelsChanged = taskbar_layout.notifyToplevelsChanged;/// Logical px the bar's background reaches past the far edges of its output.diff --git a/src/Toplevel.zig b/src/Toplevel.zigindex 49190dd..4b60ae7 100644--- a/src/Toplevel.zig+++ b/src/Toplevel.zig@@ -404,6 +404,9 @@ pub const x11Class = toplevel_configure.x11Class;pub const x11Instance = toplevel_configure.x11Instance;pub const owner = toplevel_configure.owner;pub const cornerRadius = toplevel_configure.cornerRadius;+pub const shapePolygon = toplevel_configure.shapePolygon;+pub const shapeKey = toplevel_configure.shapeKey;+pub const controlInsets = toplevel_configure.controlInsets;pub const ownsSurface = toplevel_configure.ownsSurface;pub const attachSceneData = toplevel_configure.attachSceneData;diff --git a/src/capture/window_source.zig b/src/capture/window_source.zigindex f896f74..528e1ac 100644--- a/src/capture/window_source.zig+++ b/src/capture/window_source.zig@@ -42,11 +42,18 @@ const DRM_FORMAT_ARGB8888: u32 = 0x34325241;/// and scene_pass.h). The capture is of the client alone, so the shape only/// matters where it cuts the client: its two bottom corners, which stay/// transparent here as they are on screen.+/// Mirrors `struct rediwm_pass_shape` field for field: the C side reads all of it.const PassShape = extern struct {box: wlr.Box,radii: [4]f32,+ poly_count: c_int = 0,+ poly: [16][2]f32 = @splat(.{ 0, 0 }),border: f32 = 0,border_color: [4]f32 = @splat(0),+ glow_center: [2]f32 = .{ 0, 0 },+ glow_radius: f32 = 0,+ glow_depth: f32 = 0,+ glow_color: [4]f32 = @splat(0),};extern fn rediwm_scene_pass_add_texture_shaped(pass: *wlr.RenderPass, options: *const wlr.RenderPass.TextureOptions, shape: *const PassShape) void;@@ -175,8 +182,9 @@ pub const WindowCaptureSource = struct {if (!chrome.shapes) return null;const toplevel = self.manager.server.findToplevelById(self.window_id) orelse return null;const radius = toplevel.cornerRadius();- if (!toplevel.hasServerDecorations() or radius <= 0 or toplevel.chrome_width <= 0 or toplevel.chrome_height <= 0) return null;- return .{+ const polygon = toplevel.shapePolygon(toplevel.chrome_width, toplevel.chrome_height);+ if (!toplevel.hasServerDecorations() or (radius <= 0 and polygon == null) or toplevel.chrome_width <= 0 or toplevel.chrome_height <= 0) return null;+ var shape: PassShape = .{.box = .{.x = -self.content_node.x - off_x,.y = -self.content_node.y - off_y,@@ -185,6 +193,12 @@ pub const WindowCaptureSource = struct {},.radii = @splat(radius),};+ if (polygon) |p| {+ shape.radii = @splat(0);+ shape.poly_count = @intCast(p.count);+ for (p.points[0..p.count], 0..) |point, i| shape.poly[i] = .{ @floatCast(point[0]), @floatCast(point[1]) };+ }+ return shape;}const RenderCtx = struct {diff --git a/src/chrome.zig b/src/chrome.zigindex f1a3b6d..e20f942 100644--- a/src/chrome.zig+++ b/src/chrome.zig@@ -42,6 +42,25 @@ const title_icon_gap = window_chrome.title_icon_gap;/// that cannot link the programs) windows are square, with no ring or shadow.pub var shapes: bool = false;+/// Polygon outlines (`window_shape`, `taskbar_shape`) need two more GL programs,+/// built the first time a theme asks for one (`polygonsReady`), never for a theme+/// that keeps the rounded rectangle. `polygons` is true once they exist; code that+/// draws or captures reads it, and only layout code, never a render pass, calls+/// `polygonsReady`.+pub var polygons: bool = false;+var polygons_tried: bool = false;+pub var polygon_enabler: ?*const fn (*anyopaque) bool = null;+pub var polygon_context: ?*anyopaque = null;++pub fn polygonsReady() bool {+ if (polygons or polygons_tried or !shapes) return polygons;+ polygons_tried = true;+ const enable = polygon_enabler orelse return false;+ polygons = enable(polygon_context orelse return false);+ if (!polygons) std.log.scoped(.chrome).warn("polygon outlines are unavailable: the programs did not build", .{});+ return polygons;+}+pub const ControlKind = window_chrome.ControlKind;const drm_format_argb8888: u32 = 0x34325241;@@ -68,6 +87,15 @@ pub const ChromeState = struct {// drawn at the titlebar's top-left in place of nothing at all. Absent// clients just get the title text starting further left, same as today.icon: ?icon_service.Entry = null,+ // Logical px the icon and title keep in from the left, and the controls from the+ // right, so a polygon outline's slanted ends do not cut them (`Toplevel.controlInsets`).+ inset_left: i32 = 0,+ inset_right: i32 = 0,++ /// The frame's width as the controls see it: less the right inset.+ pub fn controlsWidth(self: ChromeState, logical_width: i32) i32 {+ return logical_width - self.inset_right;+ }fn titleFont(self: ChromeState) text.Font {return if (self.active) .manrope_bold else .manrope;@@ -108,6 +136,10 @@ pub const TitlebarMemo = struct {chrome_height: f32 = 46,chrome_control_gap: f32 = 4,chrome_round_buttons: bool = false,+ top_band: [4]f32 = @splat(0),+ top_band_height: f32 = 0,+ inset_left: i32 = 0,+ inset_right: i32 = 0,pub fn capture(width: i32, height: i32, title_ptr: ?[*:0]const u8, state: ChromeState) TitlebarMemo {const t = theme.global;@@ -141,6 +173,10 @@ pub const TitlebarMemo = struct {.chrome_height = t.chrome_height,.chrome_control_gap = t.chrome_control_gap,.chrome_round_buttons = t.chrome_round_buttons,+ .top_band = t.window_top_band,+ .top_band_height = t.window_top_band_height,+ .inset_left = state.inset_left,+ .inset_right = state.inset_right,};}@@ -179,7 +215,8 @@ pub const TitlebarMemo = struct {inline for (.{ "glass", "border", "border_soft", "fg", "dim", "border_hover", "surface_hover", "danger", "close_fg", "workspace_active_border" }) |field| {if (!rgbaEql(@field(a, field), @field(b, field))) return false;}- return a.close_hover_alpha == b.close_hover_alpha and a.title_size == b.title_size and a.chrome_height == b.chrome_height and a.chrome_control_gap == b.chrome_control_gap and a.chrome_round_buttons == b.chrome_round_buttons;+ return a.close_hover_alpha == b.close_hover_alpha and a.title_size == b.title_size and a.chrome_height == b.chrome_height and a.chrome_control_gap == b.chrome_control_gap and a.chrome_round_buttons == b.chrome_round_buttons and+ rgbaEql(a.top_band, b.top_band) and a.top_band_height == b.top_band_height and a.inset_left == b.inset_left and a.inset_right == b.inset_right;}};@@ -291,7 +328,7 @@ pub const ChromeBuffer = struct {if (previous.tabs_layout_hash == tabs.layoutHash(state.tabs) andprevious.state.hover == state.hover and previous.state.chip_pos == state.chip_pos and previous.state.chip_alpha == state.chip_alpha and previous.state.maximized == state.maximized){- const geom = tabs.geometry(frame.logical_width, state.density, state.tabs);+ const geom = tabs.geometry(state.controlsWidth(frame.logical_width), state.density, state.tabs);for (state.tabs.tabs[geom.first..][0..geom.count], 0..) |tab, i| {if (previous.tabs_titles[geom.first + i] == std.hash.Wyhash.hash(0, tab.title)) continue;const rect = geom.tab(i);@@ -319,7 +356,7 @@ pub const ChromeBuffer = struct {}}var right = frame.logical_width;- if (controls_changed) right = @min(right, @max(0, controlRectScaled(frame.logical_width, .minimize, frame.state.density).x - 1));+ if (controls_changed) right = @min(right, @max(0, controlRectScaled(frame.state.controlsWidth(frame.logical_width), .minimize, frame.state.density).x - 1));if (right < frame.logical_width) {spans[count] = .{ .x0 = right, .x1 = frame.logical_width };count += 1;@@ -347,8 +384,8 @@ pub const ChromeBuffer = struct {/// The span the title can occupy: after the app icon, before the controls.fn titleRect(logical_width: i32, state: ChromeState) text.Rect {const m: Metrics = .{ .density = state.density };- const title_left: i32 = if (state.icon != null) m.length(title_inset) + m.iconSize() + m.length(title_icon_gap) else m.length(title_inset);- const controls_left = controlRectScaled(logical_width, .minimize, state.density).x;+ const title_left: i32 = state.inset_left + if (state.icon != null) m.length(title_inset) + m.iconSize() + m.length(title_icon_gap) else m.length(title_inset);+ const controls_left = controlRectScaled(state.controlsWidth(logical_width), .minimize, state.density).x;return .{ .x = title_left, .y = 0, .w = @max(0, controls_left - title_left), .h = m.titlebarHeight() - frame_border };}@@ -388,9 +425,10 @@ pub const ChromeBuffer = struct {fn rasterize(frame: *ChromeBuffer, clip: ?Rect) !void {const scale = frame.state.scale;const m: Metrics = .{ .density = frame.state.density };- const min_btn = controlRectScaled(frame.logical_width, .minimize, frame.state.density);- const max_btn = controlRectScaled(frame.logical_width, .maximize, frame.state.density);- const close_btn = controlRectScaled(frame.logical_width, .close, frame.state.density);+ const controls_width = frame.state.controlsWidth(frame.logical_width);+ const min_btn = controlRectScaled(controls_width, .minimize, frame.state.density);+ const max_btn = controlRectScaled(controls_width, .maximize, frame.state.density);+ const close_btn = controlRectScaled(controls_width, .close, frame.state.density);// All glyphs fit inside their buttons. Include a full device pixel// around the group for antialiasing, including fractional scales.const control_left = @as(f32, @floatFromInt(min_btn.x)) - 1 / scale;@@ -398,7 +436,7 @@ pub const ChromeBuffer = struct {const control_top = @as(f32, @floatFromInt(min_btn.y)) - 1 / scale;const control_bottom = @as(f32, @floatFromInt(min_btn.y + min_btn.h)) + 1 / scale;const diag = std.math.sqrt1_2;- const icon_left: f32 = @floatFromInt(m.length(title_inset));+ const icon_left: f32 = @floatFromInt(frame.state.inset_left + m.length(title_inset));const icon_top: f32 = @floatFromInt(@divTrunc(m.titlebarHeight() - m.iconSize(), 2));const base = Color.chrome();// Away from the controls and the icon every pixel in a row has the same@@ -424,6 +462,9 @@ pub const ChromeBuffer = struct {const yi: i32 = @intFromFloat(@floor(py));const row = frame.pixels[device_y * stride ..][0..stride];var row_color = base;+ // The strip along the top edge; the row it ends in is covered in part.+ const band = bandCoverage(py, scale, m.density);+ if (band > 0) row_color = Color.fromRgba(theme.global.window_top_band).scaled(band).over(row_color);if (yi == m.titlebarHeight() - 1) row_color = Color.divider().over(row_color);const flat_color = row_color.argb();const control_row = py >= control_top and py <= control_bottom;@@ -481,7 +522,7 @@ pub const ChromeBuffer = struct {}if (frame.state.tabs.tabs.len > 0) {- @import("chrome_tabs.zig").paint(Color, frame.pixels, frame.width, frame.height, frame.logical_width, frame.state.density, scale, frame.state.tabs, frame.state.icon, clip);+ @import("chrome_tabs.zig").paint(Color, frame.pixels, frame.width, frame.height, frame.state.controlsWidth(frame.logical_width), frame.state.density, scale, frame.state.tabs, frame.state.icon, clip);return;}const text_rect = titleRect(frame.logical_width, frame.state);@@ -507,6 +548,13 @@ pub const ChromeBuffer = struct {}};+/// How much of the pixel row centred at logical `py` the theme's top band covers.+fn bandCoverage(py: f32, scale: f32, density: f32) f32 {+ const height = @min(theme.global.window_top_band_height * density, theme.global.chrome_height * density);+ if (height <= 0 or theme.global.window_top_band[3] <= 0) return 0;+ return std.math.clamp((height - (py - 0.5 / scale)) * scale, 0, 1);+}+// What the window's analytic shadow was last set from (Toplevel.syncShadow).pub const ShadowMemo = struct {width: i32,@@ -517,8 +565,10 @@ pub const ShadowMemo = struct {offset_y: f32,scale: f32,disabled: bool,+ /// Which polygon outline the shadow follows (`Toplevel.shapeKey`).+ shape: u64,- pub fn capture(width: i32, height: i32, radius: f32, scale: f32, disabled: bool) ShadowMemo {+ pub fn capture(width: i32, height: i32, radius: f32, scale: f32, disabled: bool, shape: u64) ShadowMemo {const t = theme.global;return .{.width = width,@@ -529,6 +579,7 @@ pub const ShadowMemo = struct {.offset_y = t.shadow_offset_y,.scale = scale,.disabled = disabled,+ .shape = shape,};}@@ -541,7 +592,8 @@ pub const ShadowMemo = struct {rgbaEql(a.color, b.color) anda.softness == b.softness anda.offset_y == b.offset_y and- a.scale == b.scale;+ a.scale == b.scale and+ a.shape == b.shape;}};diff --git a/src/chrome_tests.zig b/src/chrome_tests.zigindex 59c047c..bd89f7f 100644--- a/src/chrome_tests.zig+++ b/src/chrome_tests.zig@@ -165,6 +165,7 @@ test "ShadowMemo.eql ignores geometry while the shadow is disabled" {.offset_y = 0,.scale = 1,.disabled = true,+ .shape = 0,};var b = a;b.width = 999;@@ -183,6 +184,7 @@ test "ShadowMemo.eql is false when softness changes" {.offset_y = 8,.scale = 1,.disabled = false,+ .shape = 0,};var b = a;try std.testing.expect(a.eql(b));diff --git a/src/ipc/handlers_widgets.zig b/src/ipc/handlers_widgets.zigindex 2cc46a9..33766f7 100644--- a/src/ipc/handlers_widgets.zig+++ b/src/ipc/handlers_widgets.zig@@ -515,7 +515,7 @@ pub fn buildWindowWidgetTree(};for (controls) |c| {- const crect = chrome.controlRectScaled(toplevel.chrome_width, c.kind, toplevel.chromeDensity());+ const crect = chrome.controlRectScaled(toplevel.chrome_width - toplevel.controlInsets().right, c.kind, toplevel.chromeDensity());const cpt = toplevel.frameWorld(@floatFromInt(crect.x), @floatFromInt(crect.y));const cw = @as(i32, @intFromFloat(@round(@as(f64, @floatFromInt(crect.w)) * toplevel.worldScale())));const ch = @as(i32, @intFromFloat(@round(@as(f64, @floatFromInt(crect.h)) * toplevel.worldScale())));diff --git a/src/projection.zig b/src/projection.zigindex f9d41bd..95f3d45 100644--- a/src/projection.zig+++ b/src/projection.zig@@ -59,9 +59,16 @@ pub const setTreeScale = rediwm_projection_set_tree_scale;/// One rounded-rectangle shape for every leaf under a tree (see scene_graph.h):/// source units, anchored at the tree's origin. `border_color` is premultiplied,/// with the window's opacity applied.+pub const poly_max = 16;+pub const ClipSpec = extern struct {width: c_int,height: c_int,+ /// 0 for the rounded rectangle; otherwise the first `poly_count` of `poly`+ /// are the shape, from the tree's origin, inside the box (`radii` is then+ /// unused). Three to `poly_max`, none the same as the next.+ poly_count: c_int = 0,+ reserved: c_int = 0,/// Top-left, top-right, bottom-right, bottom-left.radii: [4]f64,border: f64,@@ -73,6 +80,7 @@ pub const ClipSpec = extern struct {glow_radius: f64 = 0,glow_depth: f64 = 0,glow_color: [4]f32 = .{ 0, 0, 0, 0 },+ poly: [poly_max][2]f64 = @splat(.{ 0, 0 }),};extern fn rediwm_projection_set_tree_clip(target: *node.Node, spec: ?*const ClipSpec) bool;/// A null spec removes the clip. False for a size that is not positive or a@@ -88,11 +96,14 @@ pub fn setTreeClip(target: *node.Node, spec: ?ClipSpec) bool {pub const ShadowSpec = extern struct {width: c_int,height: c_int,+ poly_count: c_int = 0,+ reserved: c_int = 0,radii: [4]f64,offset_x: f64,offset_y: f64,softness: f64,color: [4]f32,+ poly: [poly_max][2]f64 = @splat(.{ 0, 0 }),};extern fn rediwm_projection_set_tree_shadow(target: *node.Node, spec: ?*const ShadowSpec) bool;/// A null spec removes the shadow. False for a size that is not positive or adiff --git a/src/projection_props.c b/src/projection_props.cindex e14b1df..2424ebf 100644--- a/src/projection_props.c+++ b/src/projection_props.c@@ -41,6 +41,18 @@ static bool set_tree_scale(struct wlr_addon_set *set, void **slot, double factorreturn true;}static bool finite_at_least_zero(double value) { return isfinite(value) && value >= 0; }+// 0 is no polygon. Otherwise 3 to REDIWM_POLY_MAX finite vertices inside the box,+// none the same as the next (a zero-length edge has no direction).+static bool valid_polygon(const double v[][2], int count, int width, int height) {+ if (count == 0) return true;+ if (count < 3 || count > REDIWM_POLY_MAX) return false;+ for (int i = 0; i < count; i++) {+ const double *a = v[i], *b = v[i + 1 < count ? i + 1 : 0];+ if (!isfinite(a[0]) || !isfinite(a[1]) || a[0] < 0 || a[1] < 0 || a[0] > width || a[1] > height) return false;+ if (a[0] == b[0] && a[1] == b[1]) return false;+ }+ return true;+}static bool set_tree_clip(struct wlr_addon_set *set, void **slot,const struct rediwm_clip_spec *spec) {if (!spec) {@@ -50,6 +62,7 @@ static bool set_tree_clip(struct wlr_addon_set *set, void **slot,return true;}if (spec->width <= 0 || spec->height <= 0 || !finite_at_least_zero(spec->border)) return false;+ if (!valid_polygon(spec->poly, spec->poly_count, spec->width, spec->height)) return false;for (int i = 0; i < 4; i++)if (!finite_at_least_zero(spec->radii[i]) || !isfinite(spec->border_color[i]) ||!isfinite(spec->glow_color[i]))@@ -75,6 +88,7 @@ static bool set_tree_shadow(struct wlr_addon_set *set, void **slot,if (spec->width <= 0 || spec->height <= 0 || !finite_at_least_zero(spec->softness) ||!isfinite(spec->offset_x) || !isfinite(spec->offset_y))return false;+ if (!valid_polygon(spec->poly, spec->poly_count, spec->width, spec->height)) return false;for (int i = 0; i < 4; i++)if (!finite_at_least_zero(spec->radii[i]) || !isfinite(spec->color[i])) return false;struct tree_props *props = tree_props_get(set, slot);diff --git a/src/projection_resolve.c b/src/projection_resolve.cindex 0d12347..ec48d8f 100644--- a/src/projection_resolve.c+++ b/src/projection_resolve.c@@ -22,8 +22,8 @@ static bool clip_same_shape(const struct rediwm_clip *a, const struct rediwm_clia->edges.y2 - a->edges.y1 != b->edges.y2 - b->edges.y1 || a->border != b->border)return false;for (int i = 0; i < 4; i++)- if (a->radii[i] != b->radii[i] || a->border_color[i] != b->border_color[i]) return false;- return true;+ if (a->border_color[i] != b->border_color[i]) return false;+ return rediwm_clip_outline_equal(a, b);}// Where the highlight is, as far as it can be seen: a square around its point.static bool clip_glow_box(const struct rediwm_clip *c, pixman_box32_t *out) {@@ -45,10 +45,7 @@ static bool clip_same_glow(const struct rediwm_clip *a, const struct rediwm_clipstatic void clip_rim(pixman_region32_t *out, const struct rediwm_clip *c, const pixman_box32_t *only) {const struct rediwm_snap f = rediwm_edges_snap(c->edges);if (f.width <= 0 || f.height <= 0) return;- double radius = 0;- for (int i = 0; i < 4; i++)- if (c->radii[i] > radius) radius = c->radii[i];- const int inset = (int)ceil(radius) + (int)ceil(c->border) + (int)ceil(c->glow_depth) + 2;+ const int inset = (int)ceil(c->inset) + (int)ceil(c->border) + (int)ceil(c->glow_depth) + 2;pixman_region32_t rim;pixman_region32_init_rect(&rim, f.x, f.y, f.width, f.height);if (f.width > 2 * inset && f.height > 2 * inset) {diff --git a/src/projection_test.c b/src/projection_test.cindex b86e45a..bffa03a 100644--- a/src/projection_test.c+++ b/src/projection_test.c@@ -313,6 +313,7 @@ int main(void) {test_graph(scene);test_clean_sync(scene);test_clip_geometry();+ test_polygon_geometry();test_clip_opaque();test_clip_projection(scene);test_clip_output(scene, out);diff --git a/src/projection_test_graph.c b/src/projection_test_graph.cindex d58b29d..87ccea5 100644--- a/src/projection_test_graph.c+++ b/src/projection_test_graph.c@@ -258,6 +258,58 @@ static void test_clip_geometry(void) {assert(rediwm_coverage(-.5) == 1 && rediwm_coverage(-3) == 1 && rediwm_coverage(.5) == 0 &&rediwm_coverage(9) == 0 && near(rediwm_coverage(0), .5) && near(rediwm_coverage(.25), .25));}+// A polygon outline: the distance, the part of the box that is surely inside, and+// the cover built from it. A 100x60 frame with its top-left corner cut and a 10 px+// step in the top edge from x = 60.+static void test_polygon_geometry(void) {+ const struct rediwm_xform id = {1, 0, 0};+ struct rediwm_clip_spec spec = {.width = 100, .height = 60, .poly_count = 7, .border = 1};+ const double v[7][2] = {{0, 20}, {20, 0}, {60, 0}, {70, 10}, {100, 10}, {100, 60}, {0, 60}};+ memcpy(spec.poly, v, sizeof(v));+ struct rediwm_clip clip = rediwm_clip_resolve(id, 10, 5, &spec);+ assert(clip.poly_count == 7 && near(clip.poly[1][0], 30) && near(clip.poly[1][1], 5));+ // The distance: inside is negative, a straight edge is exact, the cut is outside.+ assert(rediwm_clip_distance(&clip, 60, 35) < 0);+ assert(near(rediwm_clip_distance(&clip, 40, 5), 0)); // On the top edge.+ assert(near(rediwm_clip_distance(&clip, 40, 2), 3)); // 3 above it.+ assert(near(rediwm_clip_distance(&clip, 90, 15), 0)); // On the step.+ assert(near(rediwm_clip_distance(&clip, 90, 12), 3)); // Above the lower edge.+ assert(near(rediwm_clip_distance(&clip, 10, 65), 0)); // On the bottom edge.+ assert(near(rediwm_clip_distance(&clip, 11, 6), 18 * sqrt(.5))); // Beside the cut.+ assert(rediwm_clip_distance(&clip, 10, 5) > 0); // The cut-away corner.+ // Either winding.+ struct rediwm_clip_spec rev = spec;+ for (int i = 0; i < 7; i++) memcpy(rev.poly[i], v[6 - i], sizeof(v[0]));+ const struct rediwm_clip back = rediwm_clip_resolve(id, 10, 5, &rev);+ for (double px = 8; px < 112; px += 7.3)+ for (double py = 3; py < 68; py += 6.1)+ assert(near(rediwm_clip_distance(&clip, px, py), rediwm_clip_distance(&back, px, py)));+ // What is surely inside leaves out the cut and the step, nothing more than needed.+ assert(clip.inset >= 10 && clip.inset <= 21);+ struct rediwm_snap cover[3];+ const int n = rediwm_clip_opaque(&clip, cover);+ assert(n == 1);+ for (int y = cover[0].y; y < cover[0].y + cover[0].height; y++)+ for (int x = cover[0].x; x < cover[0].x + cover[0].width; x++)+ assert(rediwm_clip_distance(&clip, x + .5, y + .5) < -.5);+ // The rounded rectangle is unchanged: no polygon, inset = the largest radius.+ const struct rediwm_clip_spec round = {.width = 100, .height = 60, .radii = {4, 9, 6, 2}};+ const struct rediwm_clip rc = rediwm_clip_resolve(id, 0, 0, &round);+ assert(rc.poly_count == 0 && near(rc.inset, 9));+ // Same outline wherever it sits; a different point is a different outline.+ const struct rediwm_clip moved = rediwm_clip_resolve(id, 50, 80, &spec);+ assert(rediwm_clip_outline_equal(&clip, &moved));+ spec.poly[3][0] = 66;+ const struct rediwm_clip edited = rediwm_clip_resolve(id, 10, 5, &spec);+ assert(!rediwm_clip_outline_equal(&clip, &edited));+ // A triangle has a rectangle in it only well inside, and claims just that.+ const struct rediwm_clip_spec thin = {.width = 40, .height = 40, .poly_count = 3, .poly = {{0, 0}, {40, 20}, {0, 40}}};+ const struct rediwm_clip tc = rediwm_clip_resolve(id, 0, 0, &thin);+ assert(rediwm_clip_opaque(&tc, cover) == 1);+ for (int y = cover[0].y; y < cover[0].y + cover[0].height; y++)+ for (int x = cover[0].x; x < cover[0].x + cover[0].width; x++)+ assert(rediwm_clip_distance(&tc, x + .5, y + .5) < -.5);+}// Every pixel the opaque cover claims must be fully covered by the shape, and it// may leave out only the corner squares. Checked in the clip's own pixel grid,// for fractional origins and for clips authored at fractional scales.@@ -330,8 +382,8 @@ static void test_clip_opaque(void) {// pill keeps the full-height column between its two semicircles.struct rediwm_snap one[3];const struct rediwm_xform identity = {1, 0, 0};- assert(rediwm_clip_opaque(&(struct rediwm_clip){rediwm_xform_rect(identity, 0, 0, 8, 8), {4, 4, 4, 4}, 0, {0}, 0, 0, 0, 0, {0}}, one) == 0);- assert(rediwm_clip_opaque(&(struct rediwm_clip){rediwm_xform_rect(identity, 5, 7, 120, 80), {40, 40, 40, 40}, 0, {0}, 0, 0, 0, 0, {0}}, one) == 1);+ assert(rediwm_clip_opaque(&(struct rediwm_clip){.edges = rediwm_xform_rect(identity, 0, 0, 8, 8), .radii = {4, 4, 4, 4}}, one) == 0);+ assert(rediwm_clip_opaque(&(struct rediwm_clip){.edges = rediwm_xform_rect(identity, 5, 7, 120, 80), .radii = {40, 40, 40, 40}}, one) == 1);assert(one[0].x == 5 + 42 && one[0].y == 7 && one[0].width == 120 - 84 && one[0].height == 80);}static void test_clip_projection(struct rediwm_scene_outputs *scene) {diff --git a/src/scene_graph.h b/src/scene_graph.hindex 9e57ce3..cad96f5 100644--- a/src/scene_graph.h+++ b/src/scene_graph.h@@ -11,6 +11,7 @@#include <math.h>#include <stdbool.h>#include <stdint.h>+#include <string.h>#include <wayland-server-protocol.h>#include <wlr/render/color.h>#include <wlr/render/pass.h>@@ -73,8 +74,16 @@ static inline struct rediwm_snap rediwm_edges_snap(struct rediwm_edges e) {// `rediwm_clip` is the same shape in layout space as resolve hands it on. A// presenter snaps `edges` like any item's, so the shape and the quads that tile// it agree on pixel columns, and evaluates the distance in device pixels.+// A window shape can be a polygon instead of a rounded rectangle: up to this+// many vertices, in the order they are walked, either winding.+enum { REDIWM_POLY_MAX = 16 };struct rediwm_clip_spec {int width, height;+ // 0 for the rounded rectangle; otherwise 3 to REDIWM_POLY_MAX vertices of+ // `poly` (source units, from the tree's origin, inside the box) are the shape+ // and `radii` is ignored. `reserved` keeps the struct free of padding, which+ // it is compared byte for byte.+ int poly_count, reserved;// Top-left, top-right, bottom-right, bottom-left.double radii[4];double border;@@ -87,16 +96,80 @@ struct rediwm_clip_spec {// ring. A radius of 0 draws none.double glow_x, glow_y, glow_radius, glow_depth;float glow_color[4];+ double poly[REDIWM_POLY_MAX][2];};struct rediwm_clip {struct rediwm_edges edges;+ // Zero for a polygon, whose vertices are in layout space like the edges.double radii[4];+ int poly_count;+ double poly[REDIWM_POLY_MAX][2];+ // How deep the frame's rim reaches: the largest radius, or for a polygon how+ // far the largest axis-aligned rectangle inside it is inset from the box.+ double inset;double border;float border_color[4];// In layout space, like the edges.double glow_x, glow_y, glow_radius, glow_depth;float glow_color[4];};+// Signed distance, negative inside, to a simple polygon of `n` vertices: the+// nearest edge, signed by an even-odd crossing count, so either winding works.+// The fragment shader (scene_pass.c) walks the same edges in the same order.+static inline double rediwm_sd_polygon(double px, double py, const double v[][2], int n) {+ double d = (px - v[0][0]) * (px - v[0][0]) + (py - v[0][1]) * (py - v[0][1]);+ double s = 1;+ for (int i = 0; i < n; i++) {+ const double *a = v[i], *b = v[i + 1 < n ? i + 1 : 0];+ const double ex = b[0] - a[0], ey = b[1] - a[1], wx = px - a[0], wy = py - a[1];+ const double len2 = ex * ex + ey * ey;+ double h = (wx * ex + wy * ey) / (len2 > 1e-4 ? len2 : 1e-4);+ h = h < 0 ? 0 : h > 1 ? 1 : h;+ const double bx = wx - ex * h, by = wy - ey * h;+ if (bx * bx + by * by < d) d = bx * bx + by * by;+ const bool c0 = py >= a[1], c1 = py < b[1], c2 = ex * wy > ey * wx;+ if ((c0 && c1 && c2) || (!c0 && !c1 && !c2)) s = -s;+ }+ return s * sqrt(d);+}+// Whether the segment a-b passes through the inside of the rectangle (Liang-Barsky+// against it shrunk by a hair, so one lying along a side does not count).+static inline bool rediwm_seg_hits_rect(const double *a, const double *b, double x1, double y1,+ double x2, double y2) {+ x1 += 1e-6; y1 += 1e-6; x2 -= 1e-6; y2 -= 1e-6;+ const double d[2] = {b[0] - a[0], b[1] - a[1]};+ const double lo[2] = {x1 - a[0], y1 - a[1]}, hi[2] = {x2 - a[0], y2 - a[1]};+ double t0 = 0, t1 = 1;+ for (int k = 0; k < 2; k++) {+ if (d[k] == 0) {+ if (lo[k] > 0 || hi[k] < 0) return false;+ continue;+ }+ double ta = lo[k] / d[k], tb = hi[k] / d[k];+ if (ta > tb) { const double t = ta; ta = tb; tb = t; }+ if (ta > t0) t0 = ta;+ if (tb < t1) t1 = tb;+ if (t0 > t1) return false;+ }+ return true;+}+// How far in from the box's sides the largest rectangle that lies wholly inside+// the polygon is: the one that culling, the opaque core and the damage rim may+// trust. Walks inward one unit at a time; a rectangle is inside when its centre+// is and no edge crosses it. Box-sized when nothing fits (the whole shape is rim).+static inline double rediwm_poly_inset(const double v[][2], int n, const struct rediwm_edges *box) {+ const double w = box->x2 - box->x1, h = box->y2 - box->y1;+ const double limit = (w < h ? w : h) / 2;+ for (double inset = 0; inset < limit; inset += 1) {+ const double x1 = box->x1 + inset, y1 = box->y1 + inset, x2 = box->x2 - inset, y2 = box->y2 - inset;+ if (rediwm_sd_polygon((x1 + x2) / 2, (y1 + y2) / 2, v, n) >= 0) continue;+ bool crossed = false;+ for (int i = 0; i < n && !crossed; i++)+ crossed = rediwm_seg_hits_rect(v[i], v[i + 1 < n ? i + 1 : 0], x1, y1, x2, y2);+ if (!crossed) return inset;+ }+ return limit;+}// Radii are capped at half the short side before scaling, as the CPU chrome// does, so a small window never asks for an impossible arc.static inline struct rediwm_clip rediwm_clip_resolve(struct rediwm_xform t, double x,@@ -106,8 +179,19 @@ static inline struct rediwm_clip rediwm_clip_resolve(struct rediwm_xform t, doubstruct rediwm_clip clip = {.edges = rediwm_xform_rect(t, x, y, spec->width, spec->height),.border = spec->border * t.scale};- for (int i = 0; i < 4; i++)- clip.radii[i] = (spec->radii[i] < cap ? spec->radii[i] : cap) * t.scale;+ if (spec->poly_count >= 3 && spec->poly_count <= REDIWM_POLY_MAX) {+ clip.poly_count = spec->poly_count;+ for (int i = 0; i < clip.poly_count; i++) {+ clip.poly[i][0] = clip.edges.x1 + spec->poly[i][0] * t.scale;+ clip.poly[i][1] = clip.edges.y1 + spec->poly[i][1] * t.scale;+ }+ clip.inset = rediwm_poly_inset(clip.poly, clip.poly_count, &clip.edges);+ } else {+ for (int i = 0; i < 4; i++) {+ clip.radii[i] = (spec->radii[i] < cap ? spec->radii[i] : cap) * t.scale;+ if (clip.radii[i] > clip.inset) clip.inset = clip.radii[i];+ }+ }for (int i = 0; i < 4; i++) clip.border_color[i] = spec->border_color[i];if (spec->glow_radius > 0) {clip.glow_x = clip.edges.x1 + spec->glow_x * t.scale;@@ -136,6 +220,7 @@ static inline double rediwm_coverage(double d) {}static inline double rediwm_clip_distance(const struct rediwm_clip *clip, double px,double py) {+ if (clip->poly_count) return rediwm_sd_polygon(px, py, clip->poly, clip->poly_count);return rediwm_sd_rounded_box(px, py, clip->edges.x1, clip->edges.y1,clip->edges.x2 - clip->edges.x1,clip->edges.y2 - clip->edges.y1, clip->radii);@@ -155,6 +240,14 @@ static inline int rediwm_clip_opaque(const struct rediwm_clip *clip,struct rediwm_snap out[3]) {const struct rediwm_snap f = rediwm_edges_snap(clip->edges);if (f.width <= 0 || f.height <= 0) return 0;+ if (clip->poly_count) {+ // One rectangle: what lies inside the polygon whatever its outline does at the+ // rim, with the margin the arcs get.+ const int in = (int)ceil(clip->inset) + REDIWM_CLIP_OPAQUE_MARGIN;+ if (f.width - 2 * in <= 0 || f.height - 2 * in <= 0) return 0;+ out[0] = (struct rediwm_snap){f.x + in, f.y + in, f.width - 2 * in, f.height - 2 * in};+ return 1;+ }int inset[4];for (int i = 0; i < 4; i++)inset[i] = clip->radii[i] > 0 ? (int)ceil(clip->radii[i]) + REDIWM_CLIP_OPAQUE_MARGIN : 0;@@ -178,6 +271,19 @@ static inline int rediwm_clip_opaque(const struct rediwm_clip *clip,return n;}+// Whether two clips are the same outline: size apart, which callers compare+// with their own tolerance in mind.+static inline bool rediwm_clip_outline_equal(const struct rediwm_clip *a, const struct rediwm_clip *b) {+ if (a->poly_count != b->poly_count) return false;+ for (int i = 0; i < 4; i++)+ if (a->radii[i] != b->radii[i]) return false;+ for (int i = 0; i < a->poly_count; i++)+ if (a->poly[i][0] - a->edges.x1 != b->poly[i][0] - b->edges.x1 ||+ a->poly[i][1] - a->edges.y1 != b->poly[i][1] - b->edges.y1)+ return false;+ return true;+}+// Stage 4d: the analytic drop shadow of a window's shape, set on the tree that// holds the shadow's transport leaf. `width`, `height` and `radii` are the shape// the shadow is kept out of (the window's, at the tree's origin, in source@@ -186,9 +292,11 @@ static inline int rediwm_clip_opaque(const struct rediwm_clip *clip,// CPU chrome (`chrome.shadowCoverage`). Colour premultiplied.struct rediwm_shadow_spec {int width, height;+ int poly_count, reserved; // as in rediwm_clip_specdouble radii[4];double offset_x, offset_y, softness;float color[4];+ double poly[REDIWM_POLY_MAX][2];};struct rediwm_shadow {struct rediwm_clip shape; // in layout space; no border@@ -200,6 +308,8 @@ static inline struct rediwm_shadow rediwm_shadow_resolve(struct rediwm_xform t,const struct rediwm_shadow_spec *spec) {struct rediwm_clip_spec shape = {.width = spec->width, .height = spec->height};for (int i = 0; i < 4; i++) shape.radii[i] = spec->radii[i];+ shape.poly_count = spec->poly_count;+ memcpy(shape.poly, spec->poly, sizeof(shape.poly));struct rediwm_shadow shadow = {.shape = rediwm_clip_resolve(t, x, y, &shape),.offset_x = spec->offset_x * t.scale,.offset_y = spec->offset_y * t.scale,@@ -214,8 +324,8 @@ static inline bool rediwm_shadow_equal(const struct rediwm_shadow *a,a->offset_x != b->offset_x || a->offset_y != b->offset_y || a->softness != b->softness)return false;for (int i = 0; i < 4; i++)- if (a->shape.radii[i] != b->shape.radii[i] || a->color[i] != b->color[i]) return false;- return true;+ if (a->color[i] != b->color[i]) return false;+ return rediwm_clip_outline_equal(&a->shape, &b->shape);}enum rediwm_item_kind {diff --git a/src/scene_output.c b/src/scene_output.cindex 20a0616..98d89f9 100644--- a/src/scene_output.c+++ b/src/scene_output.c@@ -19,6 +19,9 @@ struct rediwm_output_renderer *rediwm_output_renderer_create(struct wlr_rendererbool rediwm_output_renderer_enable_shapes(struct rediwm_output_renderer *r) {return rediwm_scene_renderer_enable_shapes(r->pass);}+bool rediwm_output_renderer_enable_polygons(struct rediwm_output_renderer *r) {+ return rediwm_scene_renderer_enable_polygons(r->pass);+}bool rediwm_output_renderer_enable_backdrops(struct rediwm_output_renderer *r) {r->has_backdrops = rediwm_scene_renderer_enable_backdrops(r->pass);return r->has_backdrops;diff --git a/src/scene_output.h b/src/scene_output.hindex dd923af..5976e30 100644--- a/src/scene_output.h+++ b/src/scene_output.h@@ -12,6 +12,8 @@ struct rediwm_output_renderer *rediwm_output_renderer_create(struct wlr_renderer// Builds the programs that draw rounded shapes (see scene_pass.h); false if they// did not build, in which case no window may be given a shape.bool rediwm_output_renderer_enable_shapes(struct rediwm_output_renderer *);+// The programs for polygon outlines (see scene_pass.h), built on first request.+bool rediwm_output_renderer_enable_polygons(struct rediwm_output_renderer *);// Glass in the pass (stage 5c); requires shapes. False: glass is the surface's own tint.bool rediwm_output_renderer_enable_backdrops(struct rediwm_output_renderer *);void rediwm_output_renderer_destroy(struct rediwm_output_renderer *);diff --git a/src/scene_output.zig b/src/scene_output.zigindex 14b8cc8..397124f 100644--- a/src/scene_output.zig+++ b/src/scene_output.zig@@ -11,6 +11,8 @@ pub const Renderer = opaque {pub const create = rediwm_output_renderer_create;extern fn rediwm_output_renderer_enable_shapes(renderer: *Renderer) bool;pub const enableShapes = rediwm_output_renderer_enable_shapes;+ extern fn rediwm_output_renderer_enable_polygons(renderer: *Renderer) bool;+ pub const enablePolygons = rediwm_output_renderer_enable_polygons;extern fn rediwm_output_renderer_enable_backdrops(renderer: *Renderer) bool;pub const enableBackdrops = rediwm_output_renderer_enable_backdrops;extern fn rediwm_output_renderer_destroy(renderer: ?*Renderer) void;diff --git a/src/scene_output_collect.c b/src/scene_output_collect.cindex a1dbd87..355f302 100644--- a/src/scene_output_collect.c+++ b/src/scene_output_collect.c@@ -23,8 +23,7 @@ static void clip_cover(pixman_region32_t *out, const struct rediwm_clip *c, doubstatic bool same_clip(const struct rediwm_clip *a, const struct rediwm_clip *b) {if (a->edges.x1 != b->edges.x1 || a->edges.y1 != b->edges.y1 || a->edges.x2 != b->edges.x2 ||a->edges.y2 != b->edges.y2 || a->border != b->border) return false;- for (int i = 0; i < 4; i++) if (a->radii[i] != b->radii[i]) return false;- return true;+ return rediwm_clip_outline_equal(a, b);}bool scene_output_collect(const struct rediwm_item *item, struct rediwm_node *transport, void *data) {struct collector *collector = data;diff --git a/src/scene_output_draw.c b/src/scene_output_draw.cindex 33869cf..542e5d9 100644--- a/src/scene_output_draw.c+++ b/src/scene_output_draw.c@@ -15,6 +15,25 @@ static void device_radii(float out[4], const float in[4], enum wl_output_transfoout[b.x < w / 2 ? (b.y < h / 2 ? 0 : 3) : (b.y < h / 2 ? 1 : 2)] = in[i];}}+// A polygon's vertices (layout space) in the shape's device box: the snapped layout+// box `f` is stretched over the device box so the corners of the two coincide, then+// taken through the output's transform with the same probing as device_radii (the+// box's own size matters for a flip, which is why this is not a pixel box).+static void device_points(float out[][2], const double in[][2], int n, struct rediwm_snap f,+ const struct wlr_box *box, enum wl_output_transform transform) {+ enum { W = 3, H = 5 };+ struct wlr_box px[3], at[3] = {{0, 0, 1, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}};+ for (int i = 0; i < 3; i++) wlr_box_transform(&px[i], &at[i], wlr_output_transform_invert(transform), W, H);+ const int ex[2] = {px[1].x - px[0].x, px[1].y - px[0].y}, ey[2] = {px[2].x - px[0].x, px[2].y - px[0].y};+ const double pre_w = (transform & 1) ? box->height : box->width, pre_h = (transform & 1) ? box->width : box->height;+ const double shift[2] = {(ex[0] < 0 ? pre_w : 0) + (ey[0] < 0 ? pre_h : 0),+ (ex[1] < 0 ? pre_w : 0) + (ey[1] < 0 ? pre_h : 0)};+ for (int i = 0; i < n; i++) {+ const double lx = (in[i][0] - f.x) * pre_w / f.width, ly = (in[i][1] - f.y) * pre_h / f.height;+ out[i][0] = (float)(ex[0] * lx + ey[0] * ly + shift[0]);+ out[i][1] = (float)(ex[1] * lx + ey[1] * ly + shift[1]);+ }+}// The pass's shape for a clip: the clip's box snapped in layout space like any// item's, then taken to device pixels by the same function as the pieces that// tile it, so the shape and the quads agree on every pixel column. A ring is@@ -25,6 +44,8 @@ static void shape_for(struct rediwm_pass_shape *s, const struct rediwm_clip *c,float radii[4];for (int i = 0; i < 4; i++) radii[i] = (float)(c->radii[i] * v->scale);device_radii(s->radii, radii, v->transform);+ s->poly_count = c->poly_count;+ if (c->poly_count) device_points(s->poly, c->poly, c->poly_count, f, &s->box, v->transform);s->border = c->border > 0 ? fmaxf(1.f, roundf((float)(c->border * v->scale))) : 0.f;for (int i = 0; i < 4; i++) s->border_color[i] = c->border_color[i];s->glow_radius = s->glow_depth = 0;@@ -191,6 +212,7 @@ bool scene_output_render_entry(struct rediwm_output_renderer *r, struct entry *e// window for what a rim of a few shaded pixels costs far less than: draws// dominated the output build in a drag.float depth = fmaxf(fmaxf(shape.radii[0], shape.radii[1]), fmaxf(shape.radii[2], shape.radii[3]));+ if (shape.poly_count) depth = (float)(e->item.clip->inset * v->scale);const int inset = (int)ceilf(fmaxf(depth, shape.border + shape.glow_depth)) + REDIWM_CLIP_OPAQUE_MARGIN;if (shape.box.width > 2 * inset && shape.box.height > 2 * inset)pixman_region32_intersect_rect(&core, &core, shape.box.x + inset, shape.box.y + inset,diff --git a/src/scene_pass.c b/src/scene_pass.cindex fee1b71..b22b3e2 100644--- a/src/scene_pass.c+++ b/src/scene_pass.c@@ -90,7 +90,24 @@ static const char shaped_vertex[] ="#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n" \"varying vec2 uv; varying vec2 local; uniform vec2 size; uniform vec4 radii, bcolor, color;" \"uniform float border; uniform vec4 glow, gcolor;" \- "float sdf(vec2 p, vec4 r){ vec2 q=p-size*.5;" \+ /* A polygon's distance: the nearest edge, signed by an even-odd crossing count; */ \+ /* the loop of rediwm_sd_polygon (scene_graph.h). poly[npoly] repeats poly[0]. */ \+ /* Only the polygon programs (POLY, built on demand) carry it: the others */ \+ /* compile to what they did before polygons existed. */ \+ "\n#ifdef POLY\n" \+ "uniform float npoly; uniform vec2 poly[17];" \+ "float sdpoly(vec2 p){ float d=dot(p-poly[0],p-poly[0]); float s=1.;" \+ "for(int i=0;i<16;i++){ if(float(i)>=npoly) break; vec2 a=poly[i], b=poly[i+1];" \+ "vec2 e=b-a, w=p-a; float h=clamp(dot(w,e)/max(dot(e,e),1e-4),0.,1.); vec2 q=w-e*h; d=min(d,dot(q,q));" \+ "bool c0=p.y>=a.y, c1=p.y<b.y, c2=e.x*w.y>e.y*w.x;" \+ "if((c0&&c1&&c2)||(!c0&&!c1&&!c2)) s=-s; }" \+ "return s*sqrt(d); }" \+ "\n#endif\n" \+ "float sdf(vec2 p, vec4 r){" \+ "\n#ifdef POLY\n" \+ "if(npoly>.5) return sdpoly(p);" \+ "\n#endif\n" \+ "vec2 q=p-size*.5;" \"float rad=q.x<0.?(q.y<0.?r.x:r.w):(q.y<0.?r.y:r.z);" \"rad=clamp(rad,0.,min(size.x,size.y)*.5);" \"vec2 d=abs(q)-(size*.5-vec2(rad));" \@@ -212,6 +229,8 @@ static bool program_init(struct program *p, unsigned bit, const char *vertex_soup->origin = glGetUniformLocation(p->id, "origin");p->size = glGetUniformLocation(p->id, "size");p->radii = glGetUniformLocation(p->id, "radii");+ p->npoly = glGetUniformLocation(p->id, "npoly");+ p->poly = glGetUniformLocation(p->id, "poly[0]");p->border = glGetUniformLocation(p->id, "border");p->bcolor = glGetUniformLocation(p->id, "bcolor");p->glow = glGetUniformLocation(p->id, "glow");@@ -295,6 +314,8 @@ void rediwm_scene_renderer_destroy(struct rediwm_scene_renderer *r) {glDeleteBuffers(1, &r->vertices);glDeleteProgram(r->shaped.id);glDeleteProgram(r->shaped_external.id);+ glDeleteProgram(r->shaped_poly.id);+ glDeleteProgram(r->shaped_poly_external.id);glDeleteProgram(r->blur.id);glDeleteTextures(1, &r->prefix_tex);glDeleteFramebuffers(1, &r->prefix_fbo);@@ -312,6 +333,27 @@ bool rediwm_scene_renderer_enable_shapes(struct rediwm_scene_renderer *r) {return r->has_shapes;}+// The polygon programs: the shaped ones again with POLY defined (scene_pass.h).+bool rediwm_scene_renderer_enable_polygons(struct rediwm_scene_renderer *r) {+ assert(!r->active);+ if (r->polys_tried) return r->has_polys;+ r->polys_tried = true;+ if (!r->has_shapes) return false;+ struct gl_state state;+ if (!scene_pass_enter(r, &state)) return false;+ r->has_polys = program_init(&r->shaped_poly, 64, shaped_vertex, "#define POLY 1\nuniform sampler2D tex;\n", shaped_fragment) &&+ (!r->has_external || program_init(&r->shaped_poly_external, 128, shaped_vertex,+ "#extension GL_OES_EGL_image_external : require\n#define POLY 1\nuniform samplerExternalOES tex;\n", shaped_fragment));+ if (!r->has_polys) {+ wlr_log(WLR_ERROR, "scene pass: polygon programs failed to build, outlines are not drawn");+ glDeleteProgram(r->shaped_poly.id);+ glDeleteProgram(r->shaped_poly_external.id);+ r->shaped_poly.id = r->shaped_poly_external.id = 0;+ }+ scene_pass_leave(r, &state);+ return r->has_polys;+}+bool rediwm_scene_renderer_enable_backdrops(struct rediwm_scene_renderer *r) {assert(!r->active);if (r->backdrops_tried) return r->has_backdrops;diff --git a/src/scene_pass.h b/src/scene_pass.hindex 619c988..c4105aa 100644--- a/src/scene_pass.h+++ b/src/scene_pass.h@@ -27,11 +27,17 @@ struct wlr_render_pass *rediwm_scene_pass_begin(struct rediwm_scene_renderer *,// `box` of the draws (y down, row 0 first). The caller snaps the box (see// rediwm_edges_snap in scene_graph.h) and scales the radii and border; nothing// is rounded here, so a fractional radius or border is drawn as given.+enum { REDIWM_PASS_POLY_MAX = 16 };struct rediwm_pass_shape {struct wlr_box box;// Top-left, top-right, bottom-right, bottom-left. A radius larger than half// the short side is capped to it.float radii[4];+ // A polygon instead of the rounded rectangle when `poly_count` is 3 or more:+ // its vertices in device pixels from the box's corner, and `radii` is not used.+ // Simple, no two neighbouring vertices the same, either winding.+ int poly_count;+ float poly[REDIWM_PASS_POLY_MAX][2];// Width of the ring just inside the edge. The same fragment that draws the body// composites the ring over it, then applies the shape's coverage, so a// translucent border tints the fill beneath it, as the legacy border rects do,@@ -62,6 +68,11 @@ struct rediwm_pass_shadow {// first shaped draw; later calls return the first result. False when they did not// build: shaped draws then fail the pass at submit, plain drawing is unaffected.bool rediwm_scene_renderer_enable_shapes(struct rediwm_scene_renderer *);+// Builds the programs that draw a polygon shape (`poly_count` > 0), which are the+// shaped ones with the polygon distance compiled in: another 280 KiB or so, so only+// on request, outside a pass, before the first such draw. False when they did not+// build; a polygon draw then fails the pass, so callers must not make one.+bool rediwm_scene_renderer_enable_polygons(struct rediwm_scene_renderer *);// These take a pass from rediwm_scene_pass_begin only (a wlroots pass is a// programming error). `box` of the options is the piece to draw; the shape isdiff --git a/src/scene_pass_backdrop.c b/src/scene_pass_backdrop.cindex 69aa7fe..aa86cbb 100644--- a/src/scene_pass_backdrop.c+++ b/src/scene_pass_backdrop.c@@ -135,7 +135,7 @@ void rediwm_scene_pass_end_backdrop(struct wlr_render_pass *base, struct rediwm_void rediwm_scene_pass_add_backdrop(struct wlr_render_pass *base, const struct rediwm_pass_shape *shape,struct wlr_box box, const struct rediwm_pass_backdrop *o) {struct pass *p = owned_pass(base);- struct program *g = &p->renderer->shaped;+ struct program *g = shaped_for(p->renderer, shape, false);if (p->failed || (o->clip && !pixman_region32_not_empty(o->clip))) return;const struct rediwm_backdrop *b = o->backdrop;if (!g->id || !shape_usable(shape) || !b || !b->width || !isfinite(o->saturation) ||diff --git a/src/scene_pass_draw.c b/src/scene_pass_draw.cindex 5c854e0..64ea6a6 100644--- a/src/scene_pass_draw.c+++ b/src/scene_pass_draw.c@@ -52,6 +52,15 @@ void scene_pass_set_shape(const struct pass *p, const struct program *g, const selse glUniform2f(g->origin, s->box.x, s->box.y);glUniform2f(g->size, s->box.width, s->box.height);glUniform4f(g->radii, s->radii[0], s->radii[1], s->radii[2], s->radii[3]);+ if (g->npoly >= 0) glUniform1f(g->npoly, (float)s->poly_count);+ if (s->poly_count && g->poly >= 0) {+ // The walk closes the outline on a copy of the first vertex.+ float v[REDIWM_PASS_POLY_MAX + 1][2];+ memcpy(v, s->poly, sizeof(float) * 2 * s->poly_count);+ v[s->poly_count][0] = v[0][0];+ v[s->poly_count][1] = v[0][1];+ glUniform2fv(g->poly, s->poly_count + 1, &v[0][0]);+ }glUniform1f(g->border, s->border);glUniform4f(g->bcolor, s->border_color[0], s->border_color[1], s->border_color[2],s->border_color[3]);@@ -73,7 +82,7 @@ static void add_rect(struct wlr_render_pass *base, const struct wlr_render_rect_}static void rect_shaped(struct pass *p, const struct wlr_render_rect_options *o,const struct rediwm_pass_shape *shape) {- struct program *g = &p->renderer->shaped;+ struct program *g = shaped_for(p->renderer, shape, false);if (p->failed || (o->clip && !pixman_region32_not_empty(o->clip))) return;if (!g->id || !shape_usable(shape)) { p->failed = true; return; }struct wlr_box box;@@ -102,8 +111,8 @@ static bool wait_point(struct pass *p, struct wlr_drm_syncobj_timeline *timelinestatic void texture_draw(struct pass *p, const struct wlr_render_texture_options *o,struct wlr_gles2_texture_attribs a, const struct rediwm_pass_shape *shape) {struct rediwm_scene_renderer *r = p->renderer;- struct program *program = a.target == GL_TEXTURE_2D ? &r->shaped :- a.target == GL_TEXTURE_EXTERNAL_OES ? &r->shaped_external : NULL;+ struct program *program = a.target == GL_TEXTURE_2D ? shaped_for(r, shape, false) :+ a.target == GL_TEXTURE_EXTERNAL_OES ? shaped_for(r, shape, true) : NULL;if (!program || !program->id || (shape && !shape_usable(shape))) { p->failed = true; return; }struct wlr_box dst;struct wlr_fbox src;@@ -237,7 +246,7 @@ void rediwm_scene_pass_add_texture_shaped(struct wlr_render_pass *base,void rediwm_scene_pass_add_shadow(struct wlr_render_pass *base,const struct rediwm_pass_shape *shape, const struct rediwm_pass_shadow *shadow) {struct pass *p = owned_pass(base);- struct program *g = &p->renderer->shaped;+ struct program *g = shaped_for(p->renderer, shape, false);if (p->failed || (shadow->clip && !pixman_region32_not_empty(shadow->clip))) return;if (!g->id || !shape_usable(shape) || !isfinite(shadow->offset_x) ||!isfinite(shadow->offset_y) || !isfinite(shadow->softness) || shadow->softness > 4096 ||diff --git a/src/scene_pass_internal.h b/src/scene_pass_internal.hindex b06edca..6cd308c 100644--- a/src/scene_pass_internal.h+++ b/src/scene_pass_internal.h@@ -27,7 +27,7 @@ struct program {unsigned bit; // which bit of pass.targets_set tracks this program's target sizeGLint target, dst, color, alpha, opaque, sampler, coords;// Shaped programs only (-1 elsewhere): the shape, and the shadow's own terms.- GLint mode, origin, size, radii, border, bcolor, glow, gcolor, offset, softness, hide, use_shape, dim;+ GLint mode, origin, size, radii, npoly, poly, border, bcolor, glow, gcolor, offset, softness, hide, use_shape, dim;// What `dim` holds now (a uniform keeps its value between draws and passes).float dim_brightness, dim_saturation;// The backdrop composite (shaped mode 3) and the blur program.@@ -60,6 +60,12 @@ struct rediwm_scene_renderer {// a 2D texture, a solid colour and the shape's shadow (they differ in a mode// uniform, which every fragment of a draw reads the same), one for external.struct program shaped, shaped_external;+ // The same, with the polygon distance compiled in (POLY), built on demand by+ // enable_polygons the first time a theme gives a window or the bar an outline.+ // Draws of a polygon shape use these; every other draw the programs above,+ // which are what they were before polygons.+ struct program shaped_poly, shaped_poly_external;+ bool polys_tried, has_polys;// Backdrops (stage 5b), built by enable_backdrops: the blur, and scratch the// size of the largest region so far: the copy, and the horizontal pass.struct program blur;@@ -99,11 +105,23 @@ struct pass {// The unit quad every draw is made of.static const GLfloat positions[] = {0, 0, 1, 0, 0, 1, 1, 1};+// The program a draw of `shape` (NULL: none) uses: the polygon variant for an outline.+static inline struct program *shaped_for(struct rediwm_scene_renderer *r,+ const struct rediwm_pass_shape *shape, bool external) {+ const bool poly = shape && shape->poly_count > 0;+ if (external) return poly ? &r->shaped_poly_external : &r->shaped_external;+ return poly ? &r->shaped_poly : &r->shaped;+}// The shape's uniforms. A degenerate or non-finite shape is the caller's bug;// it fails the pass at submit like any other bad draw.static inline bool shape_usable(const struct rediwm_pass_shape *s) {if (!isfinite(s->border) || s->border < 0) return false;for (int i = 0; i < 4; i++) if (!isfinite(s->radii[i]) || s->radii[i] < 0) return false;+ if (s->poly_count < 0 || s->poly_count == 1 || s->poly_count == 2 || s->poly_count > REDIWM_PASS_POLY_MAX) return false;+ for (int i = 0; i < s->poly_count; i++) {+ const float *a = s->poly[i], *b = s->poly[i + 1 < s->poly_count ? i + 1 : 0];+ if (!isfinite(a[0]) || !isfinite(a[1]) || (a[0] == b[0] && a[1] == b[1])) return false;+ }for (int i = 0; i < 4; i++) if (!isfinite(s->border_color[i]) || !isfinite(s->glow_color[i])) return false;return isfinite(s->glow_radius) && isfinite(s->glow_depth) && s->glow_radius >= 0 && s->glow_depth >= 0 &&isfinite(s->glow_center[0]) && isfinite(s->glow_center[1]);diff --git a/src/scene_pass_test_shading.c b/src/scene_pass_test_shading.cindex 3c9adaa..c64bfdc 100644--- a/src/scene_pass_test_shading.c+++ b/src/scene_pass_test_shading.c@@ -265,6 +265,7 @@ static void shaped_gates(struct rediwm_scene_renderer *r, struct wlr_allocator *gate_no_seams(r, buf, &img);gate_border_partition(r, buf, &img, &ref);gate_premultiplied(r, buf, &img);+ gate_polygon(r, buf, &img, &ref);gate_dim(r, buf, &img);gate_opaque_cover(r, buf, &img, &ref);gate_shadow(r, buf, &img);diff --git a/src/scene_pass_test_shapes.c b/src/scene_pass_test_shapes.cindex d129e62..549ded8 100644--- a/src/scene_pass_test_shapes.c+++ b/src/scene_pass_test_shapes.c@@ -269,3 +269,101 @@ static void gate_premultiplied(struct rediwm_scene_renderer *r, struct wlr_buffewlr_texture_destroy(t_white);puts("PASS: premultiplied edges, opacity and XRGB textures blend correctly through the clip");}++// ---- Gate 5: a polygon outline (windows with cut corners and stepped edges) --------------+// A frame 200x120 whose top-left and bottom-right corners are cut, whose top edge+// steps down 10 px from x = 120 to its end, and whose top-right tip is slanted: the+// outline of a themed window. Device pixels from the shape box's corner.+static void polygon_shape(struct rediwm_pass_shape *s, bool reversed) {+ static const float v[][2] = {{0, 24}, {24, 0}, {118, 0}, {128, 10}, {176, 10}, {200, 34}, {200, 96}, {176, 120}, {0, 120}};+ const int n = (int)COUNT(v);+ *s = (struct rediwm_pass_shape){.box = {40, 40, 200, 120}, .poly_count = n};+ for (int i = 0; i < n; i++) {+ const int j = reversed ? n - 1 - i : i;+ s->poly[i][0] = v[j][0];+ s->poly[i][1] = v[j][1];+ }+}+static bool inside_polygon(double px, double py, const struct rediwm_pass_shape *s) {+ double v[REDIWM_POLY_MAX][2];+ for (int i = 0; i < s->poly_count; i++) { v[i][0] = s->poly[i][0]; v[i][1] = s->poly[i][1]; }+ return rediwm_sd_polygon(px - s->box.x, py - s->box.y, v, s->poly_count) < 0;+}+static void gate_polygon(struct rediwm_scene_renderer *r, struct wlr_buffer *buf, struct image *img,+ struct image *ref) {+ _Static_assert(REDIWM_PASS_POLY_MAX == REDIWM_POLY_MAX, "the pass and the graph size the outline alike");+ struct rediwm_pass_shape s;+ polygon_shape(&s, false);+ // The polygon programs are built on request: before it a polygon draw fails the+ // pass (the caller must not make one), and the next pass is unharmed.+ struct wlr_render_pass *pass = begin_fill(r, buf, BG, NULL);+ piece(pass, &s, s.box, BODY, NULL);+ check(!wlr_render_pass_submit(pass), "polygon: a draw without its programs did not fail the pass");+ check(rediwm_scene_renderer_enable_polygons(r), "polygon: the programs did not build");+ check(rediwm_scene_renderer_enable_polygons(r), "polygon: a second request lost the programs");+ pass = begin_fill(r, buf, BG, NULL);+ piece(pass, &s, s.box, BODY, NULL);+ finish(pass);+ read_image(r, buf, img);+ // The coverage of the outline, against sixty-four samples a pixel. The ramp is on+ // the distance, which on a diagonal is not area coverage: allow what the arc gets.+ int worst = 0, fringe = 0;+ const uint8_t bg[3] = {224, 225, 232}, body[3] = {16, 18, 21};+ for (int y = s.box.y - 2; y < s.box.y + s.box.height + 2; y++)+ for (int x = s.box.x - 2; x < s.box.x + s.box.width + 2; x++) {+ int hits = 0;+ for (int j = 0; j < 8; j++) for (int i = 0; i < 8; i++) hits += inside_polygon(x + (i + .5) / 8, y + (j + .5) / 8, &s);+ const double c = hits / 64.;+ for (int ch = 0; ch < 3; ch++) {+ const int got = at(img, x, y)[ch], want = (int)lround(bg[ch] * (1 - c) + body[ch] * c);+ if (diff(got, want) > worst) worst = diff(got, want);+ const int lo = body[ch] < bg[ch] ? body[ch] : bg[ch], hi = body[ch] < bg[ch] ? bg[ch] : body[ch];+ if (got < lo - 1 || got > hi + 1) fringe++;+ }+ }+ check(fringe == 0, "polygon: %d channel values fall outside the bg/body range", fringe);+ check(worst <= 30, "polygon: differs from supersampled coverage by %d levels", worst);+ // The corner the outline cuts is the backdrop, the notch too, the middle the body.+ check(diff(at(img, s.box.x + 2, s.box.y + 2)[0], 224) <= 1, "polygon: the cut top-left corner is drawn");+ check(diff(at(img, s.box.x + 150, s.box.y + 3)[0], 224) <= 1, "polygon: the step in the top edge is drawn");+ check(diff(at(img, s.box.x + 150, s.box.y + 14)[0], 16) <= 1, "polygon: the body below the step is missing");+ check(diff(at(img, s.box.x + 100, s.box.y + 60)[0], 16) <= 1, "polygon: the middle is not the body");+ // Walked the other way round it is the same outline.+ struct rediwm_pass_shape back;+ polygon_shape(&back, true);+ pass = begin_fill(r, buf, BG, NULL);+ piece(pass, &back, back.box, BODY, NULL);+ finish(pass);+ read_image(r, buf, ref);+ int moved = 0;+ for (int i = 0; i < img->w * img->h * 4; i++) if (diff(img->p[i], ref->p[i]) > 1) moved++;+ check(moved == 0, "polygon: the reversed outline differs in %d values", moved);+ // A ring follows the outline: its colour on a straight edge, the body just inside.+ struct rediwm_pass_shape ringed = s;+ const float red[4] = {1, 0, 0, 1};+ ringed.border = 2;+ memcpy(ringed.border_color, red, sizeof(red));+ pass = begin_fill(r, buf, BG, NULL);+ piece(pass, &ringed, ringed.box, BODY, NULL);+ finish(pass);+ read_image(r, buf, img);+ check(at(img, s.box.x + 60, s.box.y)[0] >= 254 && at(img, s.box.x + 60, s.box.y)[1] <= 1, "polygon: the top ring row is not the border colour");+ check(at(img, s.box.x + 150, s.box.y + 10)[0] >= 254, "polygon: the ring does not follow the step");+ check(diff(at(img, s.box.x + 60, s.box.y + 3)[0], 16) <= 1, "polygon: the row inside the ring is not the body");+ // Pieces tile it: a titlebar and a client in different colours meet with no seam+ // where the outline does not reach.+ const float green[4] = {0, 1, 0, 1};+ const struct wlr_box title = {s.box.x, s.box.y, s.box.width, 40}, client = {s.box.x, s.box.y + 40, s.box.width, 80};+ pass = begin_fill(r, buf, BG, NULL);+ piece(pass, &s, title, red, NULL);+ piece(pass, &s, client, green, NULL);+ finish(pass);+ read_image(r, buf, img);+ for (int y = 14; y < 118; y++) for (int x = 30; x < 170; x++) {+ const bool top = y < 40;+ const uint8_t *px = at(img, s.box.x + x, s.box.y + y);+ check(diff(px[0], top ? 255 : 0) <= 1 && diff(px[1], top ? 0 : 255) <= 1,+ "polygon: seam at (%d,%d): (%d,%d,%d)", x, y, px[0], px[1], px[2]);+ }+ printf("PASS: a polygon outline is within %d levels of area coverage, either winding, with its ring and without seams\n", worst);+}diff --git a/src/taskbar/layout.zig b/src/taskbar/layout.zigindex 74dcc5d..071e677 100644--- a/src/taskbar/layout.zig+++ b/src/taskbar/layout.zig@@ -9,6 +9,8 @@ const taskbar_items = @import("config").taskbar_items;const shape = @import("../taskbar/shape.zig");const text = @import("ui").text;const ui_theme = @import("ui").theme;+const projection = @import("../projection.zig");+const log = std.log.scoped(.taskbar);const Output = @import("../Output.zig");const nowMs = Taskbar.nowMs;const tray_gap = Taskbar.tray_gap;@@ -24,6 +26,7 @@ const battery_width = Taskbar.battery_width;const barHeight = Taskbar.barHeight;const edgeGap = Taskbar.edgeGap;const barRadius = Taskbar.barRadius;+const hasPolygon = Taskbar.hasPolygon;const chipGap = Taskbar.chipGap;const chipSize = Taskbar.chipSize;const trayHit = Taskbar.trayHit;@@ -48,7 +51,7 @@ pub fn placement(bar: *Taskbar, output_box: wlr.Box) shape.Placement {/// 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.pub fn bleedFor(bar: *Taskbar, output_box: wlr.Box, placed: wlr.Box) Bleed {- if (!shape.flush(output_box, placed, barRadius())) return .{};+ if (!shape.flush(output_box, placed, barRadius(), hasPolygon())) return .{};const out = bar.wlr_output;const turned = @intFromEnum(out.transform) & 1 != 0;const scale: f64 = out.scale;@@ -76,6 +79,29 @@ pub 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;}+/// The polygon outline of the bar as the clip of its tree: every item, and the+/// glass behind them, is cut to it on the GPU (the projection declines a pointer+/// pick outside it too, so a notch is the window below). No clip, and no cost,+/// for the rounded or the flush bar.+pub fn applyClip(bar: *Taskbar) void {+ const text_value = ui_theme.global.taskbar_shape;+ const poly = if (hasPolygon()) shape.polygon(text_value, @floatFromInt(bar.box.width), @floatFromInt(bar.box.height)) else null;+ const found = poly orelse {+ _ = projection.setTreeClip(&bar.tree.node, null);+ return;+ };+ var spec: projection.ClipSpec = .{+ .width = bar.box.width,+ .height = bar.box.height,+ .poly_count = @intCast(found.count),+ .radii = @splat(0),+ .border = 0,+ .border_color = @splat(0),+ };+ spec.poly = found.points;+ if (!projection.setTreeClip(&bar.tree.node, spec)) log.warn("could not set the taskbar shape ({d}x{d})", .{ bar.box.width, bar.box.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);@@ -91,9 +117,10 @@ pub fn relayout(bar: *Taskbar, output_box: wlr.Box) void {const placed = bar.placement(output_box);bar.box = placed.box;bar.reserved = placed.reserved;- bar.flush = shape.flush(output_box, bar.box, barRadius());+ bar.flush = shape.flush(output_box, bar.box, barRadius(), hasPolygon());bar.bleed = bar.bleedFor(output_box, bar.box);glass.Effect.configure(bar.glass_effect, barRadius(), 1);+ bar.applyClip();bar.tree.node.setPosition(bar.box.x, bar.box.y);const now_ms = nowMs();bar.pointerLeave();diff --git a/src/taskbar/metrics.zig b/src/taskbar/metrics.zigindex f1107c8..9a0bf7e 100644--- a/src/taskbar/metrics.zig+++ b/src/taskbar/metrics.zig@@ -5,6 +5,7 @@ const Taskbar = @import("../Taskbar.zig");const wlr = @import("wlroots");const shape = @import("../taskbar/shape.zig");const ui_theme = @import("ui").theme;+const chrome = @import("../chrome.zig");const max_edge_gap = Taskbar.max_edge_gap;const edge_pad = Taskbar.edge_pad;const base_chip_size = Taskbar.base_chip_size;@@ -29,7 +30,37 @@ pub fn reservedHeight() i32 {return barHeight() + edgeGap();}+/// What the theme's `taskbar_shape` means for items and pixels, worked out once+/// per change of the text, bar height or item margin: whether the bar is a+/// polygon and how far in its ends push the items. Reading it costs a hash of the+/// text, so it can sit in hit testing.+const PolygonInfo = struct { key: u64 = 0, active: bool = false, insets: shape.Insets = .{} };+var polygon_info: PolygonInfo = .{};++fn polygonInfo() PolygonInfo {+ const text = ui_theme.global.taskbar_shape;+ if (text.len == 0 or !chrome.shapes) return .{};+ const margin = chipVerticalMargin();+ const height = barHeight();+ const key = std.hash.Wyhash.hash(@as(u64, @bitCast(@as(i64, height))) ^ (@as(u64, @as(u32, @bitCast(margin))) << 32), text) | 1;+ if (polygon_info.key == key) return polygon_info;+ const h: f64 = @floatFromInt(height);+ const active = shape.polygon(text, 1600, h) != null and chrome.polygonsReady();+ polygon_info = .{+ .key = key,+ .active = active,+ .insets = if (active) shape.polygonInsets(text, h, margin, h - margin) else .{},+ };+ return polygon_info;+}++/// Whether the bar is drawn as the theme's polygon outline.+pub fn hasPolygon() bool {+ return polygonInfo().active;+}+pub fn barRadius() f32 {+ if (hasPolygon()) return 0;return shape.effectiveRadius(ui_theme.global.taskbar_radius, barHeight());}@@ -71,16 +102,19 @@ pub fn startButtonGap() i32 {}pub fn startButtonLeft() i32 {- return startButtonGap() + endInset();+ return startButtonGap() + endInset(.left);}-// Items keep clear of the curve at either end of a rounded bar.-pub fn endInset() i32 {+// Items keep clear of the curve at either end of a rounded bar, or of the slant+// of a polygon one.+pub fn endInset(end: enum { left, right }) i32 {+ const info = polygonInfo();+ if (info.active) return if (end == .left) info.insets.left else info.insets.right;return shape.cornerInset(barRadius(), chipVerticalMargin());}pub fn rightPad() i32 {- return @max(edge_pad, endInset() + startButtonGap());+ return @max(edge_pad, endInset(.right) + startButtonGap());}pub fn startButtonBox(bar: *Taskbar) wlr.Box {diff --git a/src/taskbar/paint.zig b/src/taskbar/paint.zigindex fa7e019..0bc23e2 100644--- a/src/taskbar/paint.zig+++ b/src/taskbar/paint.zig@@ -9,6 +9,7 @@ const battery = @import("../taskbar/battery.zig");const battery_badge = @import("ui").widgets.battery;const start_button = @import("../taskbar/start_button.zig");const shape = @import("../taskbar/shape.zig");+const window_shape = @import("ui").window_shape;const ui_theme = @import("ui").theme;const stats = @import("../ipc/stats.zig");const log = std.log.scoped(.taskbar);@@ -157,7 +158,16 @@ pub fn renderPart(bar: *Taskbar, now_ms: i64, part: Part, origin_x: i32, origin_};const battery_progress = if (part == .battery) bar.battery_shimmer.sweep.value(now_ms) else 1;const part_width: f32 = if (part == .capture) @floatFromInt(bar.captureWidth()) else @floatFromInt(trayHit());- if (chip_paint) |*paint| fillChipColumns(paint, buf.pixels, buf.width, buf.height, origin_x, origin_y, 0, stride, scale) else for (0..@intCast(buf.height)) |dy| {+ // A polygon bar: the rows are filled in runs, and only the pixels near an edge+ // pay for a distance (`shape.paintPolygon`).+ const polygon: ?window_shape.Resolved = if (part == .background and Taskbar.hasPolygon())+ shape.polygon(ui_theme.global.taskbar_shape, @floatFromInt(bar.box.width), @floatFromInt(bar.box.height))+ else+ null;+ if (polygon) |poly| {+ // The raster reaches no further than the bar's own box.+ shape.paintPolygon(Color, .{ .pixels = buf.pixels, .stride = stride, .width = @intCast(buf.width), .height = @intCast(buf.height), .scale = scale }, poly, ui_theme.global.taskbar_outline_width, Color.bar_fill(), Color.outline());+ } else if (chip_paint) |*paint| fillChipColumns(paint, buf.pixels, buf.width, buf.height, origin_x, origin_y, 0, stride, scale) else for (0..@intCast(buf.height)) |dy| {const py = @as(f32, @floatFromInt(origin_y)) + (@as(f32, @floatFromInt(dy)) + 0.5) / scale;for (0..stride) |dx| {const px = @as(f32, @floatFromInt(origin_x)) + (@as(f32, @floatFromInt(dx)) + 0.5) / scale;diff --git a/src/taskbar/shape.zig b/src/taskbar/shape.zigindex 4be46fd..dd4ce8d 100644--- a/src/taskbar/shape.zig+++ b/src/taskbar/shape.zig@@ -4,6 +4,7 @@const std = @import("std");const wlr = @import("wlroots");const sdf = @import("ui").sdf;+const window_shape = @import("ui").window_shape;/// The narrowest a bar is drawn however short it is asked to be: the start/// button, a few icons and the clock still have to fit.@@ -48,8 +49,8 @@ pub fn place(output: wlr.Box, spec: Spec) Placement {/// Flush means the original bar: edge to edge, on the output's edge, square./// It keeps its single hairline on the side facing the windows.-pub fn flush(output: wlr.Box, placed: wlr.Box, radius: f32) bool {- return radius <= 0 and placed.width >= output.width and placed.x == output.x and+pub fn flush(output: wlr.Box, placed: wlr.Box, radius: f32, outlined: bool) bool {+ return !outlined and radius <= 0 and placed.width >= output.width and placed.x == output.x and(placed.y == output.y or placed.y + placed.height == output.y + output.height);}@@ -98,3 +99,177 @@ fn coverage(distance: f32, scale: f32) f32 {test {_ = @import("shape_tests.zig");}++/// The bar's polygon outline in a bar of `width` x `height` logical px, from the+/// theme's `taskbar_shape` text, or null for the rounded rectangle (no text, a+/// text that does not parse, or an outline the size folds over itself).+pub fn polygon(text: []const u8, width: f64, height: f64) ?window_shape.Resolved {+ const outline = (window_shape.parse(text) catch return null) orelse return null;+ const resolved = window_shape.resolve(outline, width, height, 1);+ return if (window_shape.usable(resolved)) resolved else null;+}++pub const Insets = struct { left: i32 = 0, right: i32 = 0 };++/// How far from either end of a bar with this outline the items have to start+/// to stay inside it, over the band `top` to `bottom` (logical px from the bar's+/// top): the first column from that end where every row of the band is inside.+/// A row with no inside near the end (a notch the band reaches into) is left to+/// the clip rather than pushing the items off the bar. The outline is resolved at+/// a width past any slanted end, so the answer does not depend on the bar's+/// length for the usual px-anchored ends.+pub fn polygonInsets(text: []const u8, height: f64, top: f64, bottom: f64) Insets {+ const reference: f64 = 1600;+ const reach: i32 = 160;+ const poly = polygon(text, reference, height) orelse return .{};+ var out: Insets = .{};+ const rows = 8;+ for (0..rows + 1) |i| {+ const y = top + (bottom - top) * @as(f64, @floatFromInt(i)) / rows;+ var x: i32 = 0;+ while (x < reach and window_shape.sdPolygon(poly, @floatFromInt(x), y) > 0) x += 1;+ if (x < reach) out.left = @max(out.left, x);+ x = 0;+ while (x < reach and window_shape.sdPolygon(poly, reference - @as(f64, @floatFromInt(x)), y) > 0) x += 1;+ if (x < reach) out.right = @max(out.right, x);+ }+ return out;+}++/// A raster of device pixels the bar paints itself into.+pub const Raster = struct {+ pixels: []u32,+ stride: usize,+ width: usize,+ height: usize,+ scale: f32,+};++const max_edges = window_shape.max_points;++/// The bar's background for a polygon outline: `fill` inside it, with `outline`+/// (`outline_width` logical px, composited over the fill) along its edge, and+/// transparent outside, the way `background` paints the rounded bar, except that+/// the outer edge is not anti-aliased: the tree's clip (`Taskbar.applyClip`)+/// shapes and smooths it on the GPU, and a second ramp would thin it.+///+/// Only the pixels within reach of an edge cost a distance. For each row the+/// stretches that are near an edge (its extent in the row, widened by the+/// outline and a pixel) are worked out exactly; the rest of the row is flat,+/// filled in runs by the even-odd crossings of the row. A long flat top or+/// bottom edge is the whole of its rows, but the rows in between hold a few+/// short stretches, so a bar costs a fraction of one distance per pixel.+pub fn paintPolygon(comptime C: type, raster: Raster, poly: window_shape.Resolved, outline_width: f32, fill: C, outline: C) void {+ const scale: f64 = raster.scale;+ const reach: f64 = @max(outline_width, 0) + 1.0 / scale;+ const fill_px: u32 = fill.argb();+ const width: i32 = @intCast(raster.width);+ for (0..raster.height) |row_index| {+ const py = (@as(f64, @floatFromInt(row_index)) + 0.5) / scale;+ const row = raster.pixels[row_index * raster.stride ..][0..raster.width];+ var active: [max_edges]u8 = undefined;+ var active_count: usize = 0;+ var near: [max_edges][2]i32 = undefined;+ var crossings: [max_edges]f64 = undefined;+ var crossing_count: usize = 0;+ for (0..poly.count) |i| {+ const a = poly.points[i];+ const b = poly.points[(i + 1) % poly.count];+ if ((a[1] <= py) != (b[1] <= py)) {+ crossings[crossing_count] = a[0] + (py - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);+ crossing_count += 1;+ }+ if (@max(a[1], b[1]) < py - reach or @min(a[1], b[1]) > py + reach) continue;+ // The part of the edge within reach of this row, and the columns it spans.+ var t0: f64 = 0;+ var t1: f64 = 1;+ const dy = b[1] - a[1];+ if (dy != 0) {+ const u = (py - reach - a[1]) / dy;+ const v = (py + reach - a[1]) / dy;+ t0 = std.math.clamp(@min(u, v), 0, 1);+ t1 = std.math.clamp(@max(u, v), 0, 1);+ }+ const x0 = a[0] + t0 * (b[0] - a[0]);+ const x1 = a[0] + t1 * (b[0] - a[0]);+ active[active_count] = @intCast(i);+ near[active_count] = .{+ std.math.clamp(@as(i32, @intFromFloat(@floor((@min(x0, x1) - reach) * scale))), 0, width),+ std.math.clamp(@as(i32, @intFromFloat(@ceil((@max(x0, x1) + reach) * scale))) + 1, 0, width),+ };+ active_count += 1;+ }+ std.mem.sort(f64, crossings[0..crossing_count], {}, std.sort.asc(f64));+ // Where each crossing falls among the pixel centres: the first column right of it.+ var bounds: [max_edges]i32 = undefined;+ for (crossings[0..crossing_count], 0..) |x, i| {+ bounds[i] = std.math.clamp(@as(i32, @intFromFloat(@floor(x * scale - 0.5))) + 1, 0, width);+ }+ // The near stretches, merged left to right.+ std.mem.sort([2]i32, near[0..active_count], {}, struct {+ fn less(_: void, a: [2]i32, b: [2]i32) bool {+ return a[0] < b[0];+ }+ }.less);+ var cursor: i32 = 0;+ var i: usize = 0;+ while (i < active_count) {+ var start = near[i][0];+ var end = near[i][1];+ i += 1;+ while (i < active_count and near[i][0] <= end) : (i += 1) end = @max(end, near[i][1]);+ start = @max(start, cursor);+ if (end <= start) continue;+ flatRun(row, cursor, start, bounds[0..crossing_count], fill_px);+ for (@as(usize, @intCast(start))..@as(usize, @intCast(end))) |x| {+ const px = (@as(f64, @floatFromInt(x)) + 0.5) / scale;+ var d2: f64 = std.math.inf(f64);+ for (active[0..active_count]) |edge| d2 = @min(d2, segmentDistanceSquared(poly.points[edge], poly.points[(edge + 1) % poly.count], px, py));+ const distance: f64 = if (insideAt(bounds[0..crossing_count], @intCast(x))) -@sqrt(d2) else @sqrt(d2);+ row[x] = edgePixel(C, distance, scale, outline_width, fill, outline);+ }+ cursor = end;+ }+ flatRun(row, cursor, width, bounds[0..crossing_count], fill_px);+ }+}++/// Whether column `x` is inside: an odd number of the row's crossings lie left of it.+fn insideAt(bounds: []const i32, x: i32) bool {+ var count: usize = 0;+ for (bounds) |b| count += @intFromBool(b <= x);+ return count % 2 == 1;+}++/// Columns `from` to `to` of a row away from every edge: the fill inside, nothing outside.+fn flatRun(row: []u32, from: i32, to: i32, bounds: []const i32, fill_px: u32) void {+ if (to <= from) return;+ var k: usize = 0;+ while (k < bounds.len and bounds[k] <= from) k += 1;+ var x = from;+ while (x < to) {+ const next = if (k < bounds.len) @min(to, bounds[k]) else to;+ @memset(row[@intCast(x)..@intCast(next)], if (k % 2 == 1) fill_px else 0);+ x = next;+ k += 1;+ }+}++fn segmentDistanceSquared(a: [2]f64, b: [2]f64, px: f64, py: f64) f64 {+ const ex = b[0] - a[0];+ const ey = b[1] - a[1];+ const wx = px - a[0];+ const wy = py - a[1];+ const h = std.math.clamp((wx * ex + wy * ey) / @max(ex * ex + ey * ey, 1e-4), 0, 1);+ const bx = wx - ex * h;+ const by = wy - ey * h;+ return bx * bx + by * by;+}++/// One pixel at signed distance `distance` (logical px, negative inside).+pub fn edgePixel(comptime C: type, distance: f64, scale: f64, outline_width: f32, fill: C, outline: C) u32 {+ if (distance * scale >= 0.5) return 0;+ if (outline_width <= 0) return fill.argb();+ const inside = coverage(@floatCast(distance + outline_width), @floatCast(scale));+ return outline.scaled(1 - inside).over(fill).argb();+}diff --git a/src/taskbar/shape_tests.zig b/src/taskbar/shape_tests.zigindex 5ca6cf8..223d13e 100644--- a/src/taskbar/shape_tests.zig+++ b/src/taskbar/shape_tests.zig@@ -8,6 +8,7 @@ const cornerInset = shape.cornerInset;const effectiveRadius = shape.effectiveRadius;const Look = shape.Look;const background = shape.background;+const window_shape = @import("ui").window_shape;const TestColor = struct {r: f32 = 0,@@ -25,6 +26,14 @@ const TestColor = struct {.a = alpha,};}+ pub fn argb(color: TestColor) u32 {+ const q = struct {+ fn channel(v: f32) u32 {+ return @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255));+ }+ };+ return q.channel(color.a) << 24 | q.channel(color.r) << 16 | q.channel(color.g) << 8 | q.channel(color.b);+ }pub fn scaled(color: TestColor, alpha: f32) TestColor {return .{ .r = color.r, .g = color.g, .b = color.b, .a = std.math.clamp(color.a * alpha, 0, 1) };}@@ -67,11 +76,11 @@ test "the bar is centred, keeps its gap on the edge it sits on and never gets totest "only the original bar is flush" {const output: wlr.Box = .{ .x = 0, .y = 0, .width = 1920, .height = 1080 };const bottom = place(output, .{ .height = 44 }).box;- try std.testing.expect(flush(output, bottom, 0));- try std.testing.expect(flush(output, place(output, .{ .height = 44, .top = true }).box, 0));- try std.testing.expect(!flush(output, bottom, 8));- try std.testing.expect(!flush(output, place(output, .{ .height = 44, .edge_gap = 6 }).box, 0));- try std.testing.expect(!flush(output, place(output, .{ .height = 44, .length = 80 }).box, 0));+ try std.testing.expect(flush(output, bottom, 0, false));+ try std.testing.expect(flush(output, place(output, .{ .height = 44, .top = true }).box, 0, false));+ try std.testing.expect(!flush(output, bottom, 8, false));+ try std.testing.expect(!flush(output, place(output, .{ .height = 44, .edge_gap = 6 }).box, 0, false));+ try std.testing.expect(!flush(output, place(output, .{ .height = 44, .length = 80 }).box, 0, false));}test "items clear a rounded end by exactly what the curve takes" {@@ -125,3 +134,115 @@ test "a floating background rounds its corners and wears its outline all round"const edge = background(TestColor, look, 6.4, 6.4, 1, fill, line).a;try std.testing.expect(edge > 0 and edge < 1);}++// A raised left section, a step down and a slanted right end, as a 44 px bar.+const stepped = "0 -0, 14 0, 300 0, 312 6, -14 6, -0 -0";++test "a polygon outline resolves against the bar and is refused when it does not fit" {+ const poly = shape.polygon(stepped, 1000, 44).?;+ try std.testing.expectEqual(@as(usize, 6), poly.count);+ try std.testing.expectEqual([2]f64{ 986, 6 }, poly.points[4]);+ try std.testing.expectEqual([2]f64{ 1000, 44 }, poly.points[5]);+ try std.testing.expectEqual(@as(?window_shape.Resolved, null), shape.polygon("", 1000, 44));+ try std.testing.expectEqual(@as(?window_shape.Resolved, null), shape.polygon("0 0, 5 5", 1000, 44));+ // Edges that cross fold the outline over itself.+ try std.testing.expectEqual(@as(?window_shape.Resolved, null), shape.polygon("0 0, 30 30, 30 0, 0 30", 1000, 44));+ // A polygon bar is never the flush one, whatever its radius.+ const output: wlr.Box = .{ .x = 0, .y = 0, .width = 1920, .height = 1080 };+ try std.testing.expect(!flush(output, place(output, .{ .height = 44 }).box, 0, true));+}++test "items clear the slanted ends of a polygon bar" {+ // Band 4 to 40 of 44: the left slant (0,44)-(14,0) is 12.7 px in at row 4. The+ // right one, (w-14,6)-(w,44), is 14 px in at row 6; rows above the step belong+ // to the notch and are not the ends' business.+ const insets = shape.polygonInsets(stepped, 44, 4, 40);+ try std.testing.expect(insets.left >= 12 and insets.left <= 14);+ try std.testing.expect(insets.right >= 12 and insets.right <= 15);+ // A rectangle needs none; text that is no outline needs none.+ try std.testing.expectEqual(shape.Insets{}, shape.polygonInsets("0 0, -0 0, -0 -0, 0 -0", 44, 4, 40));+ try std.testing.expectEqual(shape.Insets{}, shape.polygonInsets("", 44, 4, 40));+}++fn expectRasterMatchesReference(text: []const u8, width: usize, height_px: f64, scale: f32, outline_width: f32) !void {+ const fill: TestColor = .{ .r = 0.1, .g = 0.2, .b = 0.3, .a = 0.9 };+ const line: TestColor = .{ .r = 1, .g = 0, .b = 0, .a = 0.5 };+ const device_height: usize = @intFromFloat(@round(height_px * scale));+ const poly = shape.polygon(text, @as(f64, @floatFromInt(width)) / scale, height_px).?;+ const pixels = try std.testing.allocator.alloc(u32, width * device_height);+ defer std.testing.allocator.free(pixels);+ @memset(pixels, 0xdeadbeef);+ shape.paintPolygon(TestColor, .{ .pixels = pixels, .stride = width, .width = width, .height = device_height, .scale = scale }, poly, outline_width, fill, line);+ var wrong: usize = 0;+ for (0..device_height) |y| for (0..width) |x| {+ const px = (@as(f64, @floatFromInt(x)) + 0.5) / scale;+ const py = (@as(f64, @floatFromInt(y)) + 0.5) / scale;+ const want = shape.edgePixel(TestColor, window_shape.sdPolygon(poly, px, py), scale, outline_width, fill, line);+ if (pixels[y * width + x] != want) wrong += 1;+ };+ // Only a pixel centre on an edge itself may land on either side of it.+ try std.testing.expect(wrong * 2000 < width * device_height);+}++test "the row-span raster paints exactly what a distance per pixel would" {+ for ([_]f32{ 1, 1.25, 1.5, 2 }) |scale| {+ try expectRasterMatchesReference(stepped, @intFromFloat(@round(1000 * scale)), 44, scale, 1);+ try expectRasterMatchesReference(stepped, @intFromFloat(@round(700 * scale)), 44, scale, 2.5);+ try expectRasterMatchesReference(stepped, @intFromFloat(@round(700 * scale)), 44, scale, 0);+ // Diagonals through the middle and a vertical edge.+ try expectRasterMatchesReference("0 -0, 30 0, 60% 22, -30 0, -0 -0, 50% -0, 20 -8", @intFromFloat(@round(500 * scale)), 44, scale, 1);+ }+}++test "a polygon raster is filled in runs: nothing near an edge but the edges" {+ const fill: TestColor = .{ .r = 0.1, .g = 0.2, .b = 0.3, .a = 0.9 };+ const line: TestColor = .{ .r = 1, .g = 0, .b = 0, .a = 0.5 };+ const width = 1000;+ const pixels = try std.testing.allocator.alloc(u32, width * 44);+ defer std.testing.allocator.free(pixels);+ shape.paintPolygon(TestColor, .{ .pixels = pixels, .stride = width, .width = width, .height = 44, .scale = 1 }, shape.polygon(stepped, 1000, 44).?, 1, fill, line);+ // The middle of the raised section is fill, the cut-away top right is clear.+ try std.testing.expectEqual(fill.argb(), pixels[22 * width + 100]);+ try std.testing.expectEqual(@as(u32, 0), pixels[2 * width + 600]);+ try std.testing.expectEqual(fill.argb(), pixels[20 * width + 600]);+ try std.testing.expectEqual(line.over(fill).argb(), pixels[43 * width + 500]);+}++fn nowNs() u64 {+ var ts: std.posix.timespec = undefined;+ _ = std.posix.system.clock_gettime(std.posix.CLOCK.MONOTONIC, &ts);+ return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec));+}++fn lap(mark: *u64) u64 {+ const now = nowNs();+ defer mark.* = now;+ return now - mark.*;+}++test "bench: polygon raster against a distance per pixel (printed, never asserted)" {+ const fill: TestColor = .{ .r = 0.1, .g = 0.2, .b = 0.3, .a = 0.9 };+ const line: TestColor = .{ .r = 1, .g = 0, .b = 0, .a = 0.5 };+ const scale: f32 = 2;+ const width = 3840;+ const height = 88;+ const pixels = try std.testing.allocator.alloc(u32, width * height);+ defer std.testing.allocator.free(pixels);+ const poly = shape.polygon(stepped, 1920, 44).?;+ var mark = nowNs();+ for (0..20) |_| shape.paintPolygon(TestColor, .{ .pixels = pixels, .stride = width, .width = width, .height = height, .scale = scale }, poly, 1, fill, line);+ const spans = lap(&mark) / 20;+ const look: Look = .{ .width = 1920, .height = 44, .radius = 12, .outline = 1, .flush = false, .top = false };+ for (0..20) |_| for (0..height) |y| for (0..width) |x| {+ pixels[y * width + x] = background(TestColor, look, (@as(f32, @floatFromInt(x)) + 0.5) / scale, (@as(f32, @floatFromInt(y)) + 0.5) / scale, scale, fill, line).argb();+ };+ const rounded = lap(&mark) / 20;+ var every: u64 = 0;+ for (0..20) |_| for (0..height) |y| for (0..width) |x| {+ const d = window_shape.sdPolygon(poly, (@as(f64, @floatFromInt(x)) + 0.5) / scale, (@as(f64, @floatFromInt(y)) + 0.5) / scale);+ pixels[y * width + x] = shape.edgePixel(TestColor, d, scale, 1, fill, line);+ every += pixels[y * width + x] & 1;+ };+ const naive = lap(&mark) / 20;+ std.debug.print("\nbench 1920x44 @2x: polygon spans {d} us, rounded bar {d} us, polygon per pixel {d} us ({d})\n", .{ spans / 1000, rounded / 1000, naive / 1000, every });+}diff --git a/src/toplevel/appearance.zig b/src/toplevel/appearance.zigindex 6df0964..db04fe6 100644--- a/src/toplevel/appearance.zig+++ b/src/toplevel/appearance.zig@@ -11,6 +11,7 @@ const theme = @import("ui").theme;const actions = @import("../config_runtime/actions.zig");const anim = @import("ui").anim;const border_glow = @import("../border_glow.zig");+const window_shape = @import("ui").window_shape;const log = std.log.scoped(.toplevel);const chip_slot_px = Toplevel.chip_slot_px;@@ -144,14 +145,22 @@ pub fn glowProbe(toplevel: *const Toplevel, lx: f64, ly: f64) ?border_glow.Probeif (!toplevel.hasServerDecorations() or toplevel.isMaximized() or toplevel.isFullscreen()) return null;const density = toplevel.chromeDensity();const local = toplevel.frameLocal(lx, ly);- return border_glow.probe(+ const found = border_glow.probe(@floatFromInt(toplevel.chrome_width),@floatFromInt(toplevel.chrome_height),toplevel.cornerRadius(),@floatCast(local.x),@floatCast(local.y),theme.global.border_glow_reach * density,- );+ ) orelse return null;+ // A polygon outline: the highlight sits on the frame's bounding box, so it shows+ // only where the outline runs along it (within a few px: a shallow step still+ // lights). Where the nearest point of the box is cut away (a deep notch, a+ // slanted corner) there is no edge there to light.+ if (toplevel.shapePolygon(toplevel.chrome_width, toplevel.chrome_height)) |polygon| {+ if (@abs(window_shape.sdPolygon(polygon, found.x, found.y)) > 4 * density) return null;+ }+ return found;}/// Shows the highlight of the frame's edge at `probe` (null: fades it out). Onlydiff --git a/src/toplevel/chrome_actions.zig b/src/toplevel/chrome_actions.zigindex ca41a92..cba4389 100644--- a/src/toplevel/chrome_actions.zig+++ b/src/toplevel/chrome_actions.zig@@ -10,8 +10,9 @@ const fromSurface = Toplevel.fromSurface;pub fn controlAt(toplevel: *Toplevel, sx: f64, sy: f64) ?chrome.ControlKind {if (!toplevel.hasServerDecorations() or sy >= @as(f64, @floatFromInt(toplevel.titlebarHeight()))) return null;+ const width = toplevel.chrome_width - toplevel.controlInsets().right;inline for (.{ chrome.ControlKind.close, .maximize, .minimize }) |kind| {- if (chrome.controlRectScaled(toplevel.chrome_width, kind, toplevel.chromeDensity()).contains(sx, sy)) return kind;+ if (chrome.controlRectScaled(width, kind, toplevel.chromeDensity()).contains(sx, sy)) return kind;}return null;}diff --git a/src/toplevel/chrome_sync.zig b/src/toplevel/chrome_sync.zigindex dad816e..538bbb7 100644--- a/src/toplevel/chrome_sync.zig+++ b/src/toplevel/chrome_sync.zig@@ -152,7 +152,7 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !void// ReleaseSafe would fill on every client commit.const tab_storage = if (toplevel.tab_group != 0) try gpa.create([@import("../window_tabs.zig").max_tabs]@import("../chrome_tabs.zig").Tab) else null;defer if (tab_storage) |storage| gpa.destroy(storage);- const state: chrome.ChromeState = .{+ var state: chrome.ChromeState = .{.tabs = toplevel.tabStrip(tab_storage),.active = toplevel.activated,.workspace_focus = toplevel.hasWorkspaceFocusBorder(),@@ -169,6 +169,9 @@ pub fn syncChrome(toplevel: *Toplevel, rebuild_shadow: bool, now_ms: i64) !voidtoplevel.last_painted_hover = hover;toplevel.chrome_width = width;toplevel.chrome_height = height;+ const insets = toplevel.controlInsets();+ state.inset_left = insets.left;+ state.inset_right = insets.right;const title_memo = chrome.TitlebarMemo.capture(width, height, toplevel.titlePtr(), state);const skip_titlebar = if (toplevel.last_titlebar) |prev| prev.eql(title_memo) or toplevel.stretchesTitlebar(prev, title_memo, now_ms) else false;@@ -271,8 +274,9 @@ pub fn visualChromeSize(toplevel: *Toplevel, now_ms: i64, natural_w: i32, natura// where geometry or theme may have changed, never on a hover repaint.pub fn syncShadow(toplevel: *Toplevel, width: i32, height: i32, radius: f32) !void {const t = theme.global;+ if (t.window_shape.len > 0) _ = chrome.polygonsReady();const disabled = !chrome.shapes or toplevel.isMaximized() or t.shadow[3] <= 0 or t.shadow_size <= 0;- const memo = chrome.ShadowMemo.capture(width, height, radius, toplevel.render_scale, disabled);+ const memo = chrome.ShadowMemo.capture(width, height, radius, toplevel.render_scale, disabled, toplevel.shapeKey());if (disabled) {toplevel.shadow_tree.node.setEnabled(false);@@ -291,7 +295,7 @@ pub fn syncShadow(toplevel: *Toplevel, width: i32, height: i32, radius: f32) !votoplevel.shadow_node.node.setPosition(-margin, -margin + offset_y);toplevel.shadow_node.setDestSize(width + 2 * margin, height + 2 * margin);const r: f64 = radius;- if (!projection.setTreeShadow(&toplevel.shadow_tree.node, .{+ var spec: projection.ShadowSpec = .{.width = width,.height = height,.radii = .{ r, r, r, r },@@ -299,7 +303,13 @@ pub fn syncShadow(toplevel: *Toplevel, width: i32, height: i32, radius: f32) !vo.offset_y = @floatFromInt(offset_y),.softness = t.shadow_size,.color = col.Straight.fromRgba(t.shadow).premultiply().rgba,- })) log.warn("could not set the window shadow ({d}x{d})", .{ width, height });+ };+ if (toplevel.shapePolygon(width, height)) |polygon| {+ spec.poly_count = @intCast(polygon.count);+ spec.poly = polygon.points;+ spec.radii = @splat(0);+ }+ if (!projection.setTreeShadow(&toplevel.shadow_tree.node, spec)) log.warn("could not set the window shadow ({d}x{d})", .{ width, height });toplevel.last_shadow = memo;}@@ -323,6 +333,8 @@ pub fn applyShape(toplevel: *Toplevel) void {_ = projection.setTreeClip(node, null);return;}+ // The polygon programs are built the first time a theme asks for an outline.+ if (theme.global.window_shape.len > 0) _ = chrome.polygonsReady();const radius: f64 = toplevel.cornerRadius();const ring = toplevel.borderColor().scale(toplevel.shape_opacity);var spec: projection.ClipSpec = .{@@ -332,6 +344,11 @@ pub fn applyShape(toplevel: *Toplevel) void {.border = @floatFromInt(chrome.frame_border),.border_color = ring.rgba,};+ if (toplevel.shapePolygon(toplevel.chrome_width, toplevel.chrome_height)) |polygon| {+ spec.poly_count = @intCast(polygon.count);+ spec.poly = polygon.points;+ spec.radii = @splat(0);+ }const t = theme.global;const glow = toplevel.glow_anim.value(nowMs()) * toplevel.shape_opacity;if (t.border_glow_enabled and glow * t.border_glow[3] >= 0.004) {diff --git a/src/toplevel/configure.zig b/src/toplevel/configure.zigindex c1c88b3..b0e5149 100644--- a/src/toplevel/configure.zig+++ b/src/toplevel/configure.zig@@ -5,6 +5,8 @@ const Toplevel = @import("../Toplevel.zig");const xscale = @import("../xwayland_scale.zig");const wlr = @import("wlroots");const chrome = @import("../chrome.zig");+const window_shape = @import("ui").window_shape;+const theme = @import("ui").theme;const resize = @import("../resize.zig");const scene_data = @import("../scene_data.zig");const xdg = @import("../xdg.zig");@@ -107,6 +109,37 @@ pub fn cornerRadius(toplevel: *const Toplevel) f32 {return if (toplevel.isMaximized() or toplevel.isFullscreen()) 0 else chrome.frameRadius() * toplevel.chromeDensity();}+/// The window's polygon outline for a frame of `width` x `height` (the theme's+/// `window_shape`), or null for the rounded rectangle: maximized and fullscreen+/// windows are square, and an outline that does not parse or cannot be drawn is+/// ignored (the theme loader refuses one that does not parse).+pub fn shapePolygon(toplevel: *const Toplevel, width: i32, height: i32) ?window_shape.Resolved {+ if (!chrome.polygons or toplevel.isMaximized() or toplevel.isFullscreen() or width <= 0 or height <= 0) return null;+ const outline = (window_shape.parse(theme.global.window_shape) catch return null) orelse return null;+ const resolved = window_shape.resolve(outline, @floatFromInt(width), @floatFromInt(height), toplevel.chromeDensity());+ return if (window_shape.usable(resolved)) resolved else null;+}++/// What the window's polygon depends on beyond its size, for memos: the outline's+/// text and the density its px coordinates scale with. 0 without a polygon.+pub fn shapeKey(toplevel: *const Toplevel) u64 {+ if (theme.global.window_shape.len == 0) return 0;+ const density: u32 = @bitCast(toplevel.chromeDensity());+ return std.hash.Wyhash.hash(density, theme.global.window_shape) | 1;+}++/// How far the titlebar's icon and controls keep in from the left and right of a+/// polygon outline's slanted or cut ends (zero for the rounded rectangle), over the+/// rows they occupy. The titlebar raster, the control hit tests and the tab strip+/// all lay out against the frame less these.+pub fn controlInsets(toplevel: *const Toplevel) window_shape.Insets {+ const polygon = toplevel.shapePolygon(toplevel.chrome_width, toplevel.chrome_height) orelse return .{};+ const density = toplevel.chromeDensity();+ const bar: f64 = @floatFromInt(toplevel.titlebarHeight());+ const band: f64 = @floatFromInt((chrome.Metrics{ .density = density }).length(34));+ return window_shape.rowInsets(polygon, @floatFromInt(toplevel.chrome_width), @max(0, (bar - band) / 2), @min(bar, (bar + band) / 2));+}+pub fn ownsSurface(toplevel: *const Toplevel, candidate: *wlr.Surface) bool {const owned = surface(toplevel) orelse return false;if (owned == candidate) return true;diff --git a/src/toplevel/info.zig b/src/toplevel/info.zigindex ac5d38d..ede4fff 100644--- a/src/toplevel/info.zig+++ b/src/toplevel/info.zig@@ -9,6 +9,7 @@ const sn = @import("../node.zig");const Server = @import("../Server.zig");const ControlCenter = @import("../control_center/panel.zig").ControlCenter;const chrome = @import("../chrome.zig");+const window_shape = @import("ui").window_shape;const geometry = @import("../geometry.zig");const resize = @import("../resize.zig");const scene_data = @import("../scene_data.zig");@@ -332,6 +333,9 @@ pub fn insideFrame(toplevel: *Toplevel, px: f32, py: f32) bool {const height = toplevel.chrome_height;if (width <= 0 or height <= 0) return false;+ if (toplevel.shapePolygon(width, height)) |polygon| {+ return chrome.coverage(@floatCast(window_shape.sdPolygon(polygon, px, py))) != 0;+ }const radius: f32 = toplevel.cornerRadius();return chrome.coverage(chrome.sdRoundedBox(px,diff --git a/src/toplevel/tabs.zig b/src/toplevel/tabs.zigindex fc1a424..c3a1dc5 100644--- a/src/toplevel/tabs.zig+++ b/src/toplevel/tabs.zig@@ -32,7 +32,7 @@ fn fillTabs(toplevel: *Toplevel, storage: *[@import("../window_tabs.zig").max_tapub fn tabAt(toplevel: *Toplevel, x: f64, y: f64) @import("../chrome_tabs.zig").Hit {if (!toplevel.hasServerDecorations() or toplevel.tab_group == 0) return .none;var storage: [@import("../window_tabs.zig").max_tabs]@import("../chrome_tabs.zig").Tab = undefined;- return @import("../chrome_tabs.zig").hit(toplevel.chrome_width, toplevel.chromeDensity(), toplevel.tabStrip(&storage), x, y);+ return @import("../chrome_tabs.zig").hit(toplevel.chrome_width - toplevel.controlInsets().right, toplevel.chromeDensity(), toplevel.tabStrip(&storage), x, y);}pub fn hoverTab(toplevel: *Toplevel, x: f64, y: f64) void {diff --git a/src/ui/mod.zig b/src/ui/mod.zigindex 11ef9fc..f10103b 100644--- a/src/ui/mod.zig+++ b/src/ui/mod.zig@@ -42,6 +42,7 @@ pub const shell_icons = @import("shell_icons.zig");pub const text = @import("text.zig");pub const theme_presets = @import("theme_presets.zig");pub const wheel = @import("wheel.zig");+pub const window_shape = @import("window_shape.zig");test {@import("std").testing.refAllDecls(@This());diff --git a/src/ui/theme.zig b/src/ui/theme.zigindex 16d6a35..d666a73 100644--- a/src/ui/theme.zig+++ b/src/ui/theme.zig@@ -35,6 +35,13 @@ pub const Theme = struct {chrome_control_gap: f32 = 4.0,/// Circular window controls and pill-shaped tabs, including tab controls.chrome_round_buttons: bool = false,+ /// A polygon outline for server-decorated windows instead of the rounded+ /// rectangle (syntax in `window_shape.zig`); empty keeps `radius_lg`.+ window_shape: []const u8 = "",+ /// A strip of this colour along the top of the titlebar, `window_top_band_height`+ /// logical px tall (0 draws none), clipped by the window's shape.+ window_top_band: [4]f32 = .{ 0, 0, 0, 0 },+ window_top_band_height: f32 = 0,// Window decorations use neutral charcoal independently of shell glass.window_bg: [4]f32 = .{ @as(f32, 7.6) / 255.0, 9.0 / 255.0, 11.0 / 255.0, 0.80 }, // 80% darkness and opacity// Neutral foregrounds keep text and monochrome icons free of a blue tint.@@ -123,6 +130,10 @@ pub const Theme = struct {taskbar_edge_gap: f32 = 0,taskbar_length: f32 = 100,taskbar_radius: f32 = 0,+ // A polygon outline for the bar instead of the rounded rectangle, in the+ // syntax of `window_shape` but against the bar's own box; empty keeps+ // `taskbar_radius`. Items keep clear of its slanted ends, nothing else.+ taskbar_shape: []const u8 = "",// Thickness of the bar's own outline (colour: `taskbar_outline`). With a// flush, full-width, square bar only the edge facing the windows is drawn.taskbar_outline_width: f32 = 1,diff --git a/src/ui/theme_file.zig b/src/ui/theme_file.zigindex bf5f004..eff0da5 100644--- a/src/ui/theme_file.zig+++ b/src/ui/theme_file.zig@@ -5,6 +5,7 @@ const Allocator = std.mem.Allocator;const Io = std.Io;const log = std.log.scoped(.theme);const theme = @import("theme.zig");+const window_shape = @import("window_shape.zig");const Theme = theme.Theme;const TaskbarToken = theme.TaskbarToken;@@ -122,6 +123,9 @@ pub fn applyKey(allocator: Allocator, t: *Theme, name_in: []const u8, value: []cif (comptime std.mem.eql(u8, name, "start_button_icon")) {if (text.len > 0 and !std.fs.path.isAbsolute(text)) return error.InvalidIconPath;}+ if (comptime std.mem.eql(u8, name, "window_shape") or std.mem.eql(u8, name, "taskbar_shape")) {+ _ = try window_shape.parse(text);+ }@field(t, name) = try allocator.dupe(u8, text);return;}diff --git a/src/ui/theme_presets.zig b/src/ui/theme_presets.zigindex a75f3d7..320bd28 100644--- a/src/ui/theme_presets.zig+++ b/src/ui/theme_presets.zig@@ -12,5 +12,6 @@ pub const bundled = [_]Preset{.{ .id = "rediwm-light", .name = "RediWM Light", .bytes = @embedFile("theme-rediwm-light") },.{ .id = "redi-blue", .name = "Redi Blue", .bytes = @embedFile("theme-redi-blue") },.{ .id = "redi-mocha", .name = "Redi-Mocha", .bytes = @embedFile("theme-redi-mocha") },+ .{ .id = "chamfer-blue", .name = "Chamfer Blue", .bytes = @embedFile("theme-chamfer-blue") },.{ .id = "gold", .name = "Gold", .bytes = @embedFile("theme-gold") },};diff --git a/src/ui/window_shape.zig b/src/ui/window_shape.zignew file mode 100644index 0000000..9a79f21--- /dev/null+++ b/src/ui/window_shape.zig@@ -0,0 +1,233 @@+//! A window's outline as a polygon, written in a theme as+//! `window_shape = "0 12, 18 0, -40 0, ..."`: up to sixteen points, each an+//! `x y` pair, separated by commas. A coordinate is+//!+//! * `12` logical px from the left (x) or top (y) edge,+//! * `-12` logical px from the right or bottom edge (`-0` is the edge itself),+//! * `40%` a fraction of the width or height (`-40%` from the far side).+//!+//! so one outline fits a window of any size, and a notch keeps its depth. Pure+//! arithmetic, no compositor: the points are resolved against the live frame by+//! `resolve` and handed to the projection (`projection.ClipSpec.poly`), whose+//! shader and C code use the same distance function as `sdPolygon`.+const std = @import("std");++pub const max_points = 16;++pub const Error = error{InvalidShape};++const Anchor = struct {+ value: f32,+ percent: bool,+ far: bool,++ fn resolve(a: Anchor, length: f64, density: f64) f64 {+ const along: f64 = if (a.percent) @as(f64, a.value) / 100.0 * length else @as(f64, a.value) * density;+ return std.math.clamp(if (a.far) length - along else along, 0, length);+ }+};++pub const Outline = struct {+ count: usize = 0,+ points: [max_points][2]Anchor = undefined,+};++pub const Resolved = struct {+ count: usize = 0,+ points: [max_points][2]f64 = @splat(.{ 0, 0 }),+};++/// Null for an empty text (no polygon: the rounded rectangle). An outline of+/// fewer than three or more than `max_points` points, a malformed coordinate, or+/// one whose edges cross is `InvalidShape`.+pub fn parse(text: []const u8) Error!?Outline {+ const trimmed = std.mem.trim(u8, text, " \t");+ if (trimmed.len == 0) return null;+ var outline: Outline = .{};+ var it = std.mem.splitScalar(u8, trimmed, ',');+ while (it.next()) |part| {+ if (outline.count == max_points) return error.InvalidShape;+ var words = std.mem.tokenizeAny(u8, part, " \t");+ const x = words.next() orelse return error.InvalidShape;+ const y = words.next() orelse return error.InvalidShape;+ if (words.next() != null) return error.InvalidShape;+ outline.points[outline.count] = .{ try parseAnchor(x), try parseAnchor(y) };+ outline.count += 1;+ }+ if (outline.count < 3) return error.InvalidShape;+ // Checked at a nominal size: the points keep their order and sides, so a+ // sensible outline does not start crossing itself at another one.+ const nominal = resolve(outline, 800, 600, 1);+ if (!simple(nominal)) return error.InvalidShape;+ return outline;+}++fn parseAnchor(word: []const u8) Error!Anchor {+ var text = word;+ const percent = text.len > 0 and text[text.len - 1] == '%';+ if (percent) text = text[0 .. text.len - 1];+ const value = std.fmt.parseFloat(f32, text) catch return error.InvalidShape;+ if (!std.math.isFinite(value) or (percent and @abs(value) > 100)) return error.InvalidShape;+ return .{ .value = @abs(value), .percent = percent, .far = std.math.signbit(value) };+}++/// The points in a frame of `width` x `height` logical px, `density` scaling the+/// px coordinates (a percent keeps its fraction). Inside the frame, clamped.+pub fn resolve(outline: Outline, width: f64, height: f64, density: f64) Resolved {+ var out: Resolved = .{ .count = outline.count };+ for (outline.points[0..outline.count], 0..) |p, i| {+ out.points[i] = .{ p[0].resolve(width, density), p[1].resolve(height, density) };+ }+ return out;+}++/// What the projection takes: at least three points, none the same as the next+/// (an edge needs a direction), no edges crossing (a window too narrow for its+/// outline folds it over itself). False falls back to the rounded rectangle.+pub fn usable(r: Resolved) bool {+ if (r.count < 3) return false;+ for (0..r.count) |i| {+ const a = r.points[i];+ const b = r.points[(i + 1) % r.count];+ if (a[0] == b[0] and a[1] == b[1]) return false;+ }+ return simple(r);+}++/// Signed distance, negative inside, to the polygon: the nearest edge, signed+/// by an even-odd crossing count. The same walk as `rediwm_sd_polygon`.+pub fn sdPolygon(r: Resolved, px: f64, py: f64) f64 {+ var d = (px - r.points[0][0]) * (px - r.points[0][0]) + (py - r.points[0][1]) * (py - r.points[0][1]);+ var s: f64 = 1;+ for (0..r.count) |i| {+ const a = r.points[i];+ const b = r.points[(i + 1) % r.count];+ const ex = b[0] - a[0];+ const ey = b[1] - a[1];+ const wx = px - a[0];+ const wy = py - a[1];+ const len2 = ex * ex + ey * ey;+ const h = std.math.clamp((wx * ex + wy * ey) / @max(len2, 1e-4), 0, 1);+ const bx = wx - ex * h;+ const by = wy - ey * h;+ d = @min(d, bx * bx + by * by);+ const c0 = py >= a[1];+ const c1 = py < b[1];+ const c2 = ex * wy > ey * wx;+ if ((c0 and c1 and c2) or (!c0 and !c1 and !c2)) s = -s;+ }+ return s * @sqrt(d);+}++pub const Insets = struct { left: i32 = 0, right: i32 = 0 };++/// How far in from the left and right edges of a frame `width` wide the outline+/// is over the rows `top` to `bottom`: for each of nine rows the first and last+/// point inside, the greatest of them. Content laid out over those rows (a+/// titlebar's icon and controls) that starts this far in stays inside the+/// outline. A row the outline does not reach near an end (a notch) is left out+/// rather than pushing the content off, as is one that is entirely outside.+pub fn rowInsets(r: Resolved, width: f64, top: f64, bottom: f64) Insets {+ const reach: f64 = 160;+ var out: Insets = .{};+ const rows = 8;+ for (0..rows + 1) |row| {+ const y = top + (bottom - top) * @as(f64, @floatFromInt(row)) / rows;+ var xs: [max_points]f64 = undefined;+ var count: usize = 0;+ for (0..r.count) |i| {+ const a = r.points[i];+ const b = r.points[(i + 1) % r.count];+ if ((a[1] <= y) != (b[1] <= y)) {+ xs[count] = a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]);+ count += 1;+ }+ }+ if (count < 2) continue;+ std.mem.sort(f64, xs[0..count], {}, std.sort.asc(f64));+ if (xs[0] < reach) out.left = @max(out.left, @as(i32, @intFromFloat(@ceil(xs[0]))));+ const from_right = width - xs[count - 1];+ if (from_right < reach) out.right = @max(out.right, @as(i32, @intFromFloat(@ceil(from_right))));+ }+ return out;+}++/// No two edges that do not share a vertex cross.+fn simple(r: Resolved) bool {+ for (0..r.count) |i| {+ var j = i + 2;+ while (j < r.count) : (j += 1) {+ if (i == 0 and j == r.count - 1) continue;+ if (cross(r.points[i], r.points[(i + 1) % r.count], r.points[j], r.points[(j + 1) % r.count])) return false;+ }+ }+ return true;+}++fn orient(a: [2]f64, b: [2]f64, c: [2]f64) f64 {+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);+}++fn cross(a: [2]f64, b: [2]f64, c: [2]f64, d: [2]f64) bool {+ const o1 = orient(a, b, c);+ const o2 = orient(a, b, d);+ const o3 = orient(c, d, a);+ const o4 = orient(c, d, b);+ return ((o1 > 0) != (o2 > 0) and o1 != 0 and o2 != 0) and ((o3 > 0) != (o4 > 0) and o3 != 0 and o4 != 0);+}++test "parse reads px, far-side and percent coordinates" {+ const outline = (try parse("0 12, 18 0, -40 0%, -0 -12")).?;+ try std.testing.expectEqual(@as(usize, 4), outline.count);+ const r = resolve(outline, 200, 100, 1);+ try std.testing.expectEqual([2]f64{ 0, 12 }, r.points[0]);+ try std.testing.expectEqual([2]f64{ 18, 0 }, r.points[1]);+ try std.testing.expectEqual([2]f64{ 160, 0 }, r.points[2]);+ try std.testing.expectEqual([2]f64{ 200, 88 }, r.points[3]);+}++test "percent keeps its fraction and px scale with density" {+ const outline = (try parse("0 0, 50% 0, 50% 10, 0 10")).?;+ const r = resolve(outline, 200, 100, 0.5);+ try std.testing.expectEqual([2]f64{ 100, 0 }, r.points[1]);+ try std.testing.expectEqual([2]f64{ 100, 5 }, r.points[2]);+}++test "an empty text is no polygon, a malformed or crossing one is refused" {+ try std.testing.expectEqual(@as(?Outline, null), try parse(" "));+ try std.testing.expectError(error.InvalidShape, parse("0 0, 10 10"));+ try std.testing.expectError(error.InvalidShape, parse("0 0, 10 x, 20 20"));+ try std.testing.expectError(error.InvalidShape, parse("0 0, 10 10 5, 20 20"));+ try std.testing.expectError(error.InvalidShape, parse("0 0, 100% 100%, 100% 0, 0 100%"));+}++test "too many points are refused" {+ const text = "0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6 0, 7 0, 8 0, 9 0, 10 0, 11 0, 12 0, 13 0, 14 0, 15 0, 16 0, 16 5";+ try std.testing.expectError(error.InvalidShape, parse(text));+}++test "the distance is negative inside, positive outside, either winding" {+ const outline = (try parse("10 0, -10 0, -0 10, -0 -10, 10 -0, 0 -10")).?;+ const r = resolve(outline, 100, 60, 1);+ try std.testing.expect(sdPolygon(r, 50, 30) < 0);+ try std.testing.expect(sdPolygon(r, 1, 1) > 0); // The cut corner.+ try std.testing.expectApproxEqAbs(@as(f64, 0), sdPolygon(r, 50, 0), 1e-9);+ var reversed = r;+ for (0..r.count) |i| reversed.points[i] = r.points[r.count - 1 - i];+ try std.testing.expectApproxEqAbs(sdPolygon(r, 5, 5), sdPolygon(reversed, 5, 5), 1e-9);+ try std.testing.expect(sdPolygon(reversed, 50, 30) < 0);+}++test "row insets follow the slants and skip a notch" {+ const outline = (try parse("0 -0, 14 0, 300 0, 312 6, -14 6, -0 -0")).?;+ const r = resolve(outline, 1000, 44, 1);+ // Rows 4 to 40: the left slant is 12.7 px in at row 4; the right end is slanted+ // from (986, 6) to (1000, 44), so 14 in at its top, and row 4 above the step is+ // the notch, which has no end to clear.+ const insets = rowInsets(r, 1000, 4, 40);+ try std.testing.expect(insets.left >= 12 and insets.left <= 14);+ try std.testing.expect(insets.right >= 12 and insets.right <= 15);+ // Rows wholly inside a rectangle need nothing.+ const box = resolve((try parse("0 0, -0 0, -0 -0, 0 -0")).?, 1000, 44, 1);+ try std.testing.expectEqual(Insets{}, rowInsets(box, 1000, 4, 40));+}