From 71c273b7777ed17bc72c11df1a9221a9e645c714 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 16 Sep 2026 11:53:11 -0300 Subject: Restore the macOS shell build after the compact tagline drift The body-layer context rules landed on a private TaglineMetrics.scale, which never compiled: no macOS host built this shell when they were written. Expose the physical-pixel thickness the way borderThickness/borderTop already expose theirs, and paint the rule over the row's last pixel the way the SDL shell does, so the two shells agree on the pixel rather than sitting one apart. Co-Authored-By: Claude Opus 5 (1M context) --- src/macos/Sources/PardesView.swift | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'src/macos/Sources') diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index f64678ee..cd3ec980 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -531,6 +531,12 @@ private struct TaglineMetrics { let px = pardes_topbar_pane_border_px(cellPixels, bandPixels) return (CGFloat(cellPixels * UInt32(PARDES_TOPBAR_H)) - CGFloat(px / 2)) / scale } + + /// One physical pixel, in points. The rules separating discontinuous + /// context rows inside a body layer are a single pixel in the SDL shell, + /// so they are stated there and converted here rather than handing `scale` + /// out and letting the caller reinvent the conversion. + var contextBorderThickness: CGFloat { 1 / scale } } private func modifiers(_ flags: NSEvent.ModifierFlags) -> UInt32 { @@ -1362,8 +1368,11 @@ final class PardesView: NSView { if border != UInt32(PARDES_COLOR_DEFAULT) { for row in 0.. Date: Wed, 16 Sep 2026 12:00:52 -0300 Subject: Let WindowOpacity through on macOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The builtin was gated on the SDL platform, so the macOS shell never registered it and the setting had nowhere to land. macOS already had transparency, but only the binary kind a theme decides — a theme with no background of its own drops the ground and the blur shows through. WindowOpacity is the graded, theme-independent version, and the window had no way to hear about it. pardes_window_opacity reports the percentage and acknowledges the request in one read, beside pardes_theme_bg: an SDL surface can arrive without an alpha channel and has to be able to refuse, while an AppKit window always composites per pixel, so there is nothing here to refuse and no rollback to perform. The view then paints the rule shaders/ui.frag.glsl states for the SDL shell: backgrounds — ground, cell and band fills, and the chrome rules over them — take the alpha, glyph ink never does, and the block cursor is exempt because it is foreground chrome that happens to be carried in a cell background. That exemption is why the cursor joins the colour in the background run key; it can no longer share a fill with the cells beside it. Two things the harness was missing fall out of testing it: it never adopted the theme background or the opacity, so a Theme or WindowOpacity in a script moved the core and never reached a pixel. draw-opacity records both ends of the alpha range, which is what makes the two-sided contract assertable — 60% reads 153..255, and 0% reads 0..255 with the ink still standing. Co-Authored-By: Claude Opus 5 (1M context) --- src/builtins.zig | 2 +- src/macos.zig | 19 +++++++++ src/macos/Sources/AppDelegate.swift | 18 ++++++-- src/macos/Sources/PardesView.swift | 82 ++++++++++++++++++++++++++++--------- src/macos/pardes.h | 9 ++++ test/macos-snapshots/opacity.golden | 29 +++++++++++++ test/macos-snapshots/opacity.snap | 34 +++++++++++++++ test/macos_e2e.swift | 62 ++++++++++++++++++++++++++++ 8 files changed, 231 insertions(+), 24 deletions(-) create mode 100644 test/macos-snapshots/opacity.golden create mode 100644 test/macos-snapshots/opacity.snap (limited to 'src/macos/Sources') diff --git a/src/builtins.zig b/src/builtins.zig index a21a20c4..1cd10a99 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -17,7 +17,7 @@ pub const capabilities: config.Runtime.Capabilities = .{ // The tty's font belongs to its emulator, and the P4 firmware's belongs to // whatever terminal is on the other end of the serial line. .tagline_font_size = pardes.platform != .tty and pardes.platform != .esp32p4, - .window_opacity = pardes.platform == .gui, + .window_opacity = pardes.platform == .gui or pardes.platform == .macos, }; pub const Ctx = struct { diff --git a/src/macos.zig b/src/macos.zig index 3003fd46..67a5ec5b 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -875,6 +875,24 @@ export fn pardes_theme_bg() u32 { return @as(u32, bg[0]) << 16 | @as(u32, bg[1]) << 8 | bg[2]; } +/// The percentage the shell must paint window backgrounds at, read once per +/// pump beside pardes_theme_bg(). +/// +/// Reading it also ACKNOWLEDGES whatever `WindowOpacity` asked for. The SDL +/// shell has to answer that request because an SDL surface can arrive without +/// an alpha channel and the core must not claim a value the compositor +/// refused; an AppKit window always composites per pixel, so there is nothing +/// here to refuse and no rollback for the core to perform. +/// +/// The theme's own decision stays separate: a theme with no background of its +/// own (pardes_theme_bg == PARDES_COLOR_DEFAULT) drops the ground entirely, +/// whatever percentage is set here. +export fn pardes_window_opacity() u8 { + const st = &(state orelse return 100); + st.core.settings.window_opacity_pending = false; + return st.core.settings.window_opacity; +} + fn taglineFontPercent(core: ?*const pardes.Pardes) u8 { return if (core) |p| p.settings.font.tagline_percent else pardes.config.gui_tagline_font_percent; } @@ -2437,6 +2455,7 @@ test "pardes.h declares every export the way it is defined" { try expectSameAbi(@TypeOf(c.pardes_active_path), @TypeOf(pardes_active_path)); try expectSameAbi(@TypeOf(c.pardes_active_dirty), @TypeOf(pardes_active_dirty)); try expectSameAbi(@TypeOf(c.pardes_theme_bg), @TypeOf(pardes_theme_bg)); + try expectSameAbi(@TypeOf(c.pardes_window_opacity), @TypeOf(pardes_window_opacity)); } test "pardes.h matches the Zig boundary" { diff --git a/src/macos/Sources/AppDelegate.swift b/src/macos/Sources/AppDelegate.swift index 96f4a184..107c40fd 100644 --- a/src/macos/Sources/AppDelegate.swift +++ b/src/macos/Sources/AppDelegate.swift @@ -462,17 +462,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { private var dressed = false private func applyTheme() { - let changed = view.adoptThemeBG(pardes_theme_bg()) - guard changed || !dressed else { return } + // Both reads happen every pump, and neither may be short-circuited by + // the other: `changed` has to be the OR of two adoptions, not the first + // one that answered true, or a Theme and a WindowOpacity in the same + // tick would leave one of them unworn. + let themeChanged = view.adoptThemeBG(pardes_theme_bg()) + let opacityChanged = view.adoptWindowOpacity(pardes_window_opacity()) + guard themeChanged || opacityChanged || !dressed else { return } dressed = true + // A ground short of solid needs the same non-opaque window a + // background-less theme does — but not the blur behind it. The backdrop + // answers "this theme brings no background"; WindowOpacity says how + // much of the one it brings to paint, and what shows through the rest + // is the desktop, which is what asking for a translucent window means. if let rgb = view.themeBG { backdrop.isHidden = true - window.isOpaque = true + window.isOpaque = view.backgroundAlpha >= 1 window.backgroundColor = NSColor( srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, green: CGFloat((rgb >> 8) & 0xFF) / 255, blue: CGFloat(rgb & 0xFF) / 255, - alpha: 1) + alpha: view.backgroundAlpha) // ...and follow the theme into light mode, so the titlebar, the // traffic lights and the resize cursor stop belonging to a // different application than the grid under them. Luminance off diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index cd3ec980..5df1fd73 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -626,6 +626,32 @@ final class PardesView: NSView { return true } + /// What `WindowOpacity` asked for, as the alpha every BACKGROUND is painted + /// at: the ground, cell and band backgrounds, and the chrome rules over + /// them. Glyph ink is never scaled by it, and neither is the block cursor — + /// it is foreground chrome that merely happens to be carried in a cell's + /// background, and it has to stay visible at `WindowOpacity 0`. + /// + /// The rule is stated once for the SDL shell in shaders/ui.frag.glsl; this + /// is the same rule in CoreGraphics, where painting the ground at this + /// alpha and the glyph over it at its own coverage composites to what that + /// shader writes premultiplied in one pass. + /// + /// Orthogonal to `themeBG`: a theme with no background of its own drops the + /// ground whatever this says, and an opaque theme still honours it. + private(set) var backgroundAlpha: CGFloat = 1 + + /// Adopt the core's percentage. Returns whether anything moved, on the same + /// contract as adoptThemeBG: the host redresses the window only when it has. + @discardableResult + func adoptWindowOpacity(_ percent: UInt8) -> Bool { + let wanted = CGFloat(min(percent, 100)) / 100 + guard wanted != backgroundAlpha else { return false } + backgroundAlpha = wanted + needsDisplay = true + return true + } + // The button a left-stream click actually started with. mouseDown decides // it from the fingers on the trackpad, and mouseDragged/mouseUp must use // the same one: a press of right followed by a release of left leaves the @@ -792,10 +818,11 @@ final class PardesView: NSView { // Row 0 at the top, so the drawing arithmetic reads like the grid it is. override var isFlipped: Bool { true } - // Opaque only while the theme brings its own background. A transparent - // theme has none, and an opaque view over a visual-effect backdrop is a - // grey rectangle where the blur should be. - override var isOpaque: Bool { themeBG != nil } + // Opaque only while the theme brings its own background AND that background + // is painted solid. A transparent theme has none, and an opaque view over a + // visual-effect backdrop is a grey rectangle where the blur should be; + // a WindowOpacity below 100 has the same problem against the desktop. + override var isOpaque: Bool { themeBG != nil && backgroundAlpha >= 1 } override var acceptsFirstResponder: Bool { true } // A click that focuses the window should also land in the grid: this is a // text surface, and having to click twice after switching apps is the kind @@ -974,7 +1001,12 @@ final class PardesView: NSView { // otherwise pile up on themselves. let ground = themeBG ?? pardesDefaultBG let clearGround = themeBG == nil - if clearGround { ctx.clear(bounds) } else { fill(ctx, bounds, ground, 1) } + // AppKit does not blank a non-opaque view, so anything that leaves the + // ground short of solid has to clear first or last frame's pixels pile + // up on themselves — a translucent ground would darken toward opaque + // over a few frames otherwise. + if clearGround || backgroundAlpha < 1 { ctx.clear(bounds) } + if !clearGround { fill(ctx, bounds, ground, backgroundAlpha) } if frozenImages == nil { frameImages.removeAll(keepingCapacity: true) } guard cols > 0, rows > 0, Int(count) == cols * rows, let cells = suppliedCells ?? pardes_frame_cells() @@ -1004,30 +1036,38 @@ final class PardesView: NSView { // cell in the row, and it is a call across the ABI. let bandTop = taglines.top(row: row, canvasHeight: canvasHeight) var start = 0 - var color = resolve(cells[base], block: blockY == row && blockX == 0, + var block = blockY == row && blockX == 0 + var color = resolve(cells[base], block: block, ground: ground, clearGround: clearGround).bg var tagline = cells[base].flags & UInt8(PARDES_CELL_TAGLINE) != 0 for col in 1...cols { // A real color is 24 bits, so .max is a sentinel that cannot // compare equal and therefore always flushes the last run. + let nextBlock = col < cols && blockY == row && blockX == col let next: UInt32 = col == cols ? .max - : resolve(cells[base + col], block: blockY == row && blockX == col, + : resolve(cells[base + col], block: nextBlock, ground: ground, clearGround: clearGround).bg let nextTagline = col < cols && cells[base + col].flags & UInt8(PARDES_CELL_TAGLINE) != 0 - if next == color && nextTagline == tagline { continue } + // The cursor is in the run key as well as the colour: it is the + // one background that stays solid under WindowOpacity, so it + // cannot share a fill with the cells beside it even when the + // reverse happened to land on their colour. + if next == color && nextTagline == tagline && nextBlock == block { continue } // bgClear runs are the ground showing through, and the ground is // already clear — painting them would be painting the hole shut. if color != bgClear { let bandY = tagline ? y + bandTop : y let bandHeight = tagline ? taglines.height : cellHeight fill(ctx, CGRect(x: CGFloat(start) * cellWidth, y: bandY, - width: CGFloat(col - start) * cellWidth, height: bandHeight), color, 1) + width: CGFloat(col - start) * cellWidth, height: bandHeight), + color, block ? 1 : backgroundAlpha) } start = col color = next tagline = nextTagline + block = nextBlock } } @@ -1050,7 +1090,7 @@ final class PardesView: NSView { } if joins { fill(ctx, CGRect(x: 0, y: taglines.borderTop, width: bounds.width, - height: ruleThickness), ruleColor, 1) + height: ruleThickness), ruleColor, backgroundAlpha) } } @@ -1069,7 +1109,7 @@ final class PardesView: NSView { clearGround: clearGround).bg if bg != bgClear { fill(ctx, CGRect(x: 0, y: gridBottom, width: bounds.width, - height: canvasHeight - gridBottom), bg, 1) + height: canvasHeight - gridBottom), bg, backgroundAlpha) } break } @@ -1251,15 +1291,17 @@ final class PardesView: NSView { let viewport = CGRect(x: left, y: y, width: CGFloat(values[6]) * cellWidth, height: taglines.height) ctx.saveGState() ctx.clip(to: viewport) - fill(ctx, viewport, UInt32(values[10]), 1) + fill(ctx, viewport, UInt32(values[10]), backgroundAlpha) for pass in 0...1 { for col in 0..= viewport.maxY { break } let rowStyle = resolve(cells[row*cols], block: false, ground: themeBG ?? pardesDefaultBG, clearGround: false) - fill(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, 1) + fill(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, backgroundAlpha) for pass in 0...1 { for col in 0.. 0, rep.pixelsHigh > 0 else { + throw ScriptError(message: "draw-opacity \(label): cacheDisplay produced no pixels") + } + guard rep.hasAlpha, rep.bitsPerPixel == 32 else { + // An opaque view caches into a rep with no alpha at all, which is + // itself the answer at WindowOpacity 100 — say so rather than + // reporting a range read out of the wrong byte. + output += "== draw-opacity \(label) \(Int(bounds.width.rounded()))x\(Int(bounds.height.rounded())) opaque\n" + return + } + // Where alpha sits depends on the rep's format, and only the two + // AppKit actually hands back here are worth decoding. + let alphaFirst = rep.bitmapFormat.contains(.alphaFirst) + let offset = alphaFirst ? 0 : 3 + let rowBytes = rep.bytesPerRow + var lowest: UInt8 = 255 + var highest: UInt8 = 0 + for y in 0.. highest { highest = alpha } + } + } + let w = Int(bounds.width.rounded()) + let h = Int(bounds.height.rounded()) + output += "== draw-opacity \(label) \(w)x\(h) alpha \(lowest)..\(highest)\n" + } + // MARK: - the script func run(source: String) throws -> String { @@ -799,6 +853,14 @@ private final class Driver: PardesViewDelegate { guard !rest.isEmpty else { throw ScriptError(message: "draw needs a label") } try draw(rest) + // What WindowOpacity actually did to the pixels, which is the only + // place it can be checked: the core's cell buffer says nothing about + // alpha, and `draw` deliberately compares channels without knowing + // which one is which. + case "draw-opacity": + guard !rest.isEmpty else { throw ScriptError(message: "draw-opacity needs a label") } + try drawOpacity(rest) + case "draw-effect": let view = try live() guard !rest.isEmpty else { throw ScriptError(message: "draw-effect needs a label") } -- cgit v1.3 From 2109098400fa37d7b448f232c848a0411c318591 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 16 Sep 2026 12:18:01 -0300 Subject: Give macOS scrolling momentum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A swipe that was still moving when the fingers lifted stopped dead. The dial next to it has thrown properly since pardes_rotate_end, and this is that same curve on the scroll accumulator: velocity sampled between events off the monotonic clock, weighted toward the newest sample because a flick is decided by how the hand was moving when it left, and a fling that ramps up from zero at the floor rather than switching on at it. A coast stops at the end of a document rather than spinning its remaining velocity against the edge, which is why spendScroll now reports whether the pane moved and why paneAt is public. Only a step that delivered a press can report an edge — the many steps between two rows cross nothing. Nothing suppresses AppKit's own momentum, and nothing needs to: its momentum events are ordinary pardes_scroll calls, every one of which cancels the coast before spending its travel, so on a real trackpad the system takes the gesture over about a frame after the lift and the tail it ends on is below the floor. This is the path for devices AppKit does not fling for — and the only one a script can reach, since NSEvent phases have no public constructor. momentum.snap asserts both halves, which is why it needs the long scrollback: a flick with no document left proves nothing. A slow swipe is byte-identical after the release; a hard one coasts twenty-four rows further on its own, and a finger back on the pad stops it there. Co-Authored-By: Claude Opus 5 (1M context) --- src/macos.zig | 194 +++++++++++++++++++++++++++++++---- src/macos/Sources/PardesView.swift | 34 ++++++ src/macos/pardes.h | 18 ++++ src/pardes.zig | 2 +- test/macos-snapshots/momentum.golden | 186 +++++++++++++++++++++++++++++++++ test/macos-snapshots/momentum.snap | 73 +++++++++++++ test/macos_e2e.swift | 25 +++++ 7 files changed, 509 insertions(+), 23 deletions(-) create mode 100644 test/macos-snapshots/momentum.golden create mode 100644 test/macos-snapshots/momentum.snap (limited to 'src/macos/Sources') diff --git a/src/macos.zig b/src/macos.zig index 67a5ec5b..4b37255e 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -658,6 +658,15 @@ const State = struct { gens: [pardes.MAX_PANES]u32 = @splat(0), scroll_lag: f32 = 0, scroll_lag_x: f32 = 0, + scroll_velocity: f32 = 0, + scroll_velocity_x: f32 = 0, + scroll_last_ns: i128 = 0, + /// Where the gesture turned. A coast keeps delivering THERE rather than + /// wherever the pointer has drifted to since — the same rule the SDL + /// shell keeps in scroll_col/scroll_row. + scroll_col: u16 = 0, + scroll_row: u16 = 0, + scroll_coasting: bool = false, rotate_lag: f32 = 0, rotate_velocity: f32 = 0, rotate_last_ns: i128 = 0, @@ -866,7 +875,7 @@ test "the animation clock spends real time, not callbacks" { export fn pardes_animating() bool { const st = &(state orelse return false); - return st.core.animationActive() or st.rotate_coasting; + return st.core.animationActive() or st.rotate_coasting or st.scroll_coasting; } export fn pardes_theme_bg() u32 { @@ -1282,6 +1291,10 @@ fn restoreCore(st: *State) bool { st.cwd_stale = @splat(false); st.scroll_lag = 0; st.scroll_lag_x = 0; + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + st.scroll_last_ns = 0; + st.scroll_coasting = false; st.rotate_lag = 0; st.rotate_velocity = 0; st.rotate_last_ns = 0; @@ -1464,6 +1477,30 @@ export fn pardes_animation_tick() bool { st.core.update(.tick); changed = true; } + if (st.scroll_coasting) { + const spent_now = spendScroll( + st, + st.scroll_velocity * scroll_fling_step, + st.scroll_velocity_x * scroll_fling_step, + st.scroll_col, + st.scroll_row, + ); + st.scroll_velocity *= scroll_fling_decay; + st.scroll_velocity_x *= scroll_fling_decay; + const decayed = @abs(st.scroll_velocity) < scroll_fling_stop and + @abs(st.scroll_velocity_x) < scroll_fling_stop; + // Only a step that actually delivered a press can report an edge; + // the many steps between two rows cross nothing and say nothing. + const at_edge = spent_now.ticks != 0 and !spent_now.moved; + if (decayed or at_edge) { + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + st.scroll_coasting = false; + st.scroll_lag = 0; + st.scroll_lag_x = 0; + } + changed = true; + } if (st.rotate_coasting) { spendRotation(st, st.rotate_velocity * rotation_fling_step); st.rotate_velocity *= rotation_fling_decay; @@ -1563,28 +1600,48 @@ export fn pardes_pointer_leave() void { export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) void { const st = &(state orelse return); - var down_left = takeScrollTicks(&st.scroll_lag, delta_rows); - while (down_left != 0) { - const down = down_left > 0; - down_left += if (down) -1 else 1; - st.core.update(.{ .mouse = .{ - .button = if (down) .wheel_down else .wheel_up, - .kind = .press, - .col = col, - .row = row, - } }); - } - var right_left = takeScrollTicks(&st.scroll_lag_x, delta_cols); - while (right_left != 0) { - const right = right_left > 0; - right_left += if (right) -1 else 1; - st.core.update(.{ .mouse = .{ - .button = if (right) .wheel_right else .wheel_left, - .kind = .press, - .col = col, - .row = row, - } }); + st.scroll_col = col; + st.scroll_row = row; + noteScrollVelocity(st, delta_rows, delta_cols); + _ = spendScroll(st, delta_rows, delta_cols, col, row); +} + +/// A finger back on the pad, which catches a coast the way a hand catches a +/// spinning dial. Also drops whatever the last gesture left banked, so the +/// first millimetre of a new swipe cannot inherit a nearly-complete row. +export fn pardes_scroll_begin() void { + const st = &(state orelse return); + st.scroll_lag = 0; + st.scroll_lag_x = 0; + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + st.scroll_coasting = false; + st.scroll_last_ns = monotonicNs(); +} + +/// Fingers lifted. A swipe that was still moving when it ended becomes a +/// fling, measured from the speed of the last events rather than from any one +/// of them, exactly as pardes_rotate_end measures the dial. +/// +/// A host whose windowing system flings for it need do nothing to suppress +/// this: its first momentum event is an ordinary pardes_scroll, and every +/// pardes_scroll cancels the coast before spending its own travel. The system's +/// momentum simply takes the gesture over, and the tail of that momentum is +/// below the fling floor, so its end arms nothing. +export fn pardes_scroll_end() void { + const st = &(state orelse return); + const last = st.scroll_last_ns; + st.scroll_last_ns = 0; + st.scroll_coasting = false; + // A hand that came to rest before lifting is not throwing anything. + if (last == 0 or monotonicNs() - last > 90 * std.time.ns_per_ms) { + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + return; } + st.scroll_velocity = scrollFling(st.scroll_velocity); + st.scroll_velocity_x = scrollFling(st.scroll_velocity_x); + st.scroll_coasting = st.scroll_velocity != 0 or st.scroll_velocity_x != 0; } export fn pardes_rotate(degrees: f32) void { @@ -2351,6 +2408,97 @@ fn encodeCellFlags(default: bool, role: pardes.FontRole) u8 { @as(u8, @intFromBool(role == .tagline)) * cell_flag_tagline; } +fn noteScrollVelocity(st: *State, delta_rows: f32, delta_cols: f32) void { + const now = monotonicNs(); + const last = st.scroll_last_ns; + st.scroll_last_ns = now; + // Any real travel ends a coast: that is what lets a host with momentum of + // its own take the gesture over without either side knowing about it. + st.scroll_coasting = false; + if (last == 0 or now == 0) return; + const dt_ns = now - last; + // A gap this long is a new gesture, not a fast one. Without the guard the + // pause between two separate swipes would read as enormous speed. + if (dt_ns <= 0 or dt_ns > 200 * std.time.ns_per_ms) return; + const seconds: f32 = @floatCast(@as(f64, @floatFromInt(dt_ns)) / @as(f64, std.time.ns_per_s)); + const rows = delta_rows / seconds; + const cols = delta_cols / seconds; + if (!std.math.isFinite(rows) or !std.math.isFinite(cols)) return; + // Weighted toward the newest sample: a flick is decided by how the hand was + // moving when it left, not by how the swipe started. + st.scroll_velocity = st.scroll_velocity * 0.35 + rows * 0.65; + st.scroll_velocity_x = st.scroll_velocity_x * 0.35 + cols * 0.65; +} + +/// Spend accumulated travel as wheel presses, and report whether the pane under +/// the gesture actually moved. +/// +/// A coast has to stop at the end of a document instead of spinning the rest of +/// its velocity against the edge — the SDL shell stops for the same reason in +/// stepScroll. Only the vertical axis can be measured that way (a pane's +/// horizontal position is not Pane.scroll()), so sideways travel counts as +/// movement; a purely horizontal fling therefore rides its decay out, which is +/// what it would do anyway once the drift guard has swallowed it. +const Spent = struct { + /// Whole wheel presses delivered. Most coast steps cross no row at all, + /// which is why "did not move" cannot be read off `moved` alone. + ticks: u32 = 0, + moved: bool = false, +}; + +fn spendScroll(st: *State, delta_rows: f32, delta_cols: f32, col: u16, row: u16) Spent { + const pane = if (st.core.paneAt(col, row)) |id| st.core.panes[id] else null; + var out: Spent = .{}; + var down_left = takeScrollTicks(&st.scroll_lag, delta_rows); + while (down_left != 0) { + const down = down_left > 0; + down_left += if (down) -1 else 1; + out.ticks += 1; + const was = if (pane) |p| p.scroll() else 0; + st.core.update(.{ .mouse = .{ + .button = if (down) .wheel_down else .wheel_up, + .kind = .press, + .col = col, + .row = row, + } }); + if (pane) |p| { + if (p.scroll() != was) out.moved = true; + } else out.moved = true; + } + var right_left = takeScrollTicks(&st.scroll_lag_x, delta_cols); + while (right_left != 0) { + const right = right_left > 0; + right_left += if (right) -1 else 1; + st.core.update(.{ .mouse = .{ + .button = if (right) .wheel_right else .wheel_left, + .kind = .press, + .col = col, + .row = row, + } }); + out.ticks += 1; + out.moved = true; + } + return out; +} + +// Rows per second. The floor is what separates a flick from a swipe that +// merely ended while still in contact; the ceiling stops a jab from launching +// the page past anything the eye can follow. Step and decay are stated at +// 60 Hz and spent by the same measured display clock the rotation fling uses, +// so a 120 Hz screen coasts the same distance in the same time. +const scroll_fling_floor: f32 = 8; +const scroll_fling_max: f32 = 90; +const scroll_fling_step: f32 = 1.0 / 60.0; +const scroll_fling_decay: f32 = 0.94; +const scroll_fling_stop: f32 = 2; + +fn scrollFling(speed: f32) f32 { + if (!std.math.isFinite(speed)) return 0; + const excess = @min(@abs(speed) - scroll_fling_floor, scroll_fling_max); + if (excess < scroll_fling_stop) return 0; + return std.math.copysign(excess, speed); +} + fn takeScrollTicks(lag: *f32, delta_rows: f32) i32 { if (!std.math.isFinite(delta_rows)) return 0; const next = std.math.clamp(lag.* + delta_rows, -256, 256); @@ -2419,6 +2567,8 @@ test "pardes.h declares every export the way it is defined" { try expectSameAbi(@TypeOf(c.pardes_pointer_leave), @TypeOf(pardes_pointer_leave)); try expectSameAbi(@TypeOf(c.pardes_watch_changed), @TypeOf(pardes_watch_changed)); try expectSameAbi(@TypeOf(c.pardes_scroll), @TypeOf(pardes_scroll)); + try expectSameAbi(@TypeOf(c.pardes_scroll_begin), @TypeOf(pardes_scroll_begin)); + try expectSameAbi(@TypeOf(c.pardes_scroll_end), @TypeOf(pardes_scroll_end)); try expectSameAbi(@TypeOf(c.pardes_rotate), @TypeOf(pardes_rotate)); try expectSameAbi(@TypeOf(c.pardes_rotate_end), @TypeOf(pardes_rotate_end)); try expectSameAbi(@TypeOf(c.pardes_command), @TypeOf(pardes_command)); diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 5df1fd73..ba3677e7 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -1842,6 +1842,20 @@ final class PardesView: NSView { fed() } + /// Fingers down and fingers up on a precise scroll. Entry points of their + /// own for the same reason rotateEnd is one: NSEvent phases have no public + /// constructor, and a fling nothing can synthesize is a fling nothing can + /// assert. + func scrollBegin() { + pardes_scroll_begin() + fed() + } + + func scrollEnd() { + pardes_scroll_end() + fed() + } + func rotate(degrees: CGFloat) { guard degrees != 0 else { return } pardes_rotate(Float(degrees)) @@ -2086,12 +2100,32 @@ final class PardesView: NSView { return } if event.hasPreciseScrollingDeltas { + // Phases first: a finger back on the pad has to catch a coast before + // its own travel is spent, or the first millimetre of the new swipe + // would be added to the old fling instead of replacing it. + // + // Momentum events carry `phase == .none` and a momentumPhase + // instead, so neither branch here fires for them — they are just + // more travel, and libpardes lets them take the gesture over. That + // is deliberate: AppKit's fling is the one the rest of the system + // uses, and a second fling of our own underneath it would scroll + // everything at double speed. `pardes_scroll_end` exists for the + // devices AppKit does NOT fling for. + if event.phase == .began { scrollBegin() } // The core scrolls a cell at a time, so libpardes accumulates the // sub-cell travel and spends it as wheel presses — which is why the // cell has to travel with the delta. scroll(rows: -event.scrollingDeltaY / cellHeight, cols: -event.scrollingDeltaX / cellWidth, at: at) + switch event.phase { + case .ended: scrollEnd() + // A gesture the system took away should not be thrown. scrollBegin + // is the catching half of the pair — coast stopped, bank and + // velocity cleared — which is exactly what a cancellation means. + case .cancelled: scrollBegin() + default: break + } } else { // AppKit's sign is the opposite of the DOM's: positive deltaY means the // content moved down, which is a scroll back through history. diff --git a/src/macos/pardes.h b/src/macos/pardes.h index 5f1ccf77..a2d13b1f 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -377,6 +377,24 @@ void pardes_watch_changed(uint8_t pane, uint32_t generation); void pardes_scroll(float delta_rows, float delta_cols, uint16_t col, uint16_t row); +// The gesture boundaries around pardes_scroll, and the whole of scroll +// momentum. `begin` is fingers down: it catches a coast the way a hand catches +// a spinning dial, and drops whatever the last gesture left banked. `end` is +// fingers up: a swipe still moving when it ended becomes a fling, in +// proportion to how hard it was thrown, on the same curve pardes_rotate_end +// uses — momentum ramps up from zero rather than switching on at a threshold. +// +// A coast makes pardes_animating true and is spent by pardes_animation_tick, +// and it stops at the end of a document instead of spinning against the edge. +// +// A host whose windowing system already flings for it needs no suppression: +// the system's momentum arrives as ordinary pardes_scroll calls, every one of +// which cancels the coast before spending its own travel, so that momentum +// simply takes the gesture over. A host that calls neither — a discrete wheel +// has no phases — scrolls with no momentum at all. +void pardes_scroll_begin(void); +void pardes_scroll_end(void); + // A two-finger trackpad rotation, in degrees since the last call, positive // counterclockwise (AppKit's sign, unchanged). The core has no rotation: this // is spent as the search-step keys, clockwise `n` and counterclockwise `N`, a diff --git a/src/pardes.zig b/src/pardes.zig index 16343972..c1a6b038 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11047,7 +11047,7 @@ pub const Pardes = struct { return null; } - fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { + pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { for (p.panes, 0..) |slot, id| { if (slot == null) continue; const r = p.rects[id]; diff --git a/test/macos-snapshots/momentum.golden b/test/macos-snapshots/momentum.golden new file mode 100644 index 00000000..b4471061 --- /dev/null +++ b/test/macos-snapshots/momentum.golden @@ -0,0 +1,186 @@ +== snap home grid=100x30 cursor=4,29 +|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +| New Tty Find Grep Joincol +|$ /private/tmp/pardes-macos-e2e/momentum/cwd Tty Save Del Mode Filter Collapse +| LINE 175 +| LINE 176 +| LINE 177 +| LINE 178 +| LINE 179 +| LINE 180 +| LINE 181 +| LINE 182 +| LINE 183 +| LINE 184 +| LINE 185 +| LINE 186 +| LINE 187 +| LINE 188 +| LINE 189 +| LINE 190 +| LINE 191 +| LINE 192 +| LINE 193 +| LINE 194 +| LINE 195 +| LINE 196 +| LINE 197 +| LINE 198 +| LINE 199 +| LINE 200 +| $ +== snap placed grid=100x30 cursor=0,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +| New Tty Find Grep Joincol +|$ /private/tmp/pardes-macos-e2e/momentum/cwd Tty Save Del Mode Filter Collapse +| LINE 174 +| LINE 175 +| LINE 176 +| LINE 177 +| LINE 178 +| LINE 179 +| LINE 180 +| LINE 181 +| LINE 182 +| LINE 183 +| LINE 184 +| LINE 185 +| LINE 186 +| LINE 187 +| LINE 188 +| LINE 189 +| LINE 190 +| LINE 191 +| LINE 192 +| LINE 193 +| LINE 194 +| LINE 195 +| LINE 196 +| LINE 197 +| LINE 198 +| LINE 199 +| LINE 200 +== snap placed_released grid=100x30 cursor=0,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +| New Tty Find Grep Joincol +|$ /private/tmp/pardes-macos-e2e/momentum/cwd Tty Save Del Mode Filter Collapse +| LINE 174 +| LINE 175 +| LINE 176 +| LINE 177 +| LINE 178 +| LINE 179 +| LINE 180 +| LINE 181 +| LINE 182 +| LINE 183 +| LINE 184 +| LINE 185 +| LINE 186 +| LINE 187 +| LINE 188 +| LINE 189 +| LINE 190 +| LINE 191 +| LINE 192 +| LINE 193 +| LINE 194 +| LINE 195 +| LINE 196 +| LINE 197 +| LINE 198 +| LINE 199 +| LINE 200 +== snap thrown grid=100x30 cursor=0,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +| New Tty Find Grep Joincol +|$ /private/tmp/pardes-macos-e2e/momentum/cwd Tty Save Del Mode Filter Collapse +| LINE 165 +| LINE 166 +| LINE 167 +| LINE 168 +| LINE 169 +| LINE 170 +| LINE 171 +| LINE 172 +| LINE 173 +| LINE 174 +| LINE 175 +| LINE 176 +| LINE 177 +| LINE 178 +| LINE 179 +| LINE 180 +| LINE 181 +| LINE 182 +| LINE 183 +| LINE 184 +| LINE 185 +| LINE 186 +| LINE 187 +| LINE 188 +| LINE 189 +| LINE 190 +| LINE 191 +== snap coasted grid=100x30 cursor=0,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +| New Tty Find Grep Joincol +|$ /private/tmp/pardes-macos-e2e/momentum/cwd Tty Save Del Mode Filter Collapse +| LINE 141 +| LINE 142 +| LINE 143 +| LINE 144 +| LINE 145 +| LINE 146 +| LINE 147 +| LINE 148 +| LINE 149 +| LINE 150 +| LINE 151 +| LINE 152 +| LINE 153 +| LINE 154 +| LINE 155 +| LINE 156 +| LINE 157 +| LINE 158 +| LINE 159 +| LINE 160 +| LINE 161 +| LINE 162 +| LINE 163 +| LINE 164 +| LINE 165 +| LINE 166 +| LINE 167 +== snap caught grid=100x30 cursor=0,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +| New Tty Find Grep Joincol +|$ /private/tmp/pardes-macos-e2e/momentum/cwd Tty Save Del Mode Filter Collapse +| LINE 141 +| LINE 142 +| LINE 143 +| LINE 144 +| LINE 145 +| LINE 146 +| LINE 147 +| LINE 148 +| LINE 149 +| LINE 150 +| LINE 151 +| LINE 152 +| LINE 153 +| LINE 154 +| LINE 155 +| LINE 156 +| LINE 157 +| LINE 158 +| LINE 159 +| LINE 160 +| LINE 161 +| LINE 162 +| LINE 163 +| LINE 164 +| LINE 165 +| LINE 166 +| LINE 167 diff --git a/test/macos-snapshots/momentum.snap b/test/macos-snapshots/momentum.snap new file mode 100644 index 00000000..1c578e68 --- /dev/null +++ b/test/macos-snapshots/momentum.snap @@ -0,0 +1,73 @@ +# Scroll momentum: a swipe still moving when the fingers lift keeps scrolling, +# in proportion to how hard it was thrown. +# +# The same shape as the dial's fling in rotate.snap, and asserted the same way, +# because the contract is the same one: momentum ramps up from zero at the +# floor (scroll_fling_floor in src/macos.zig, 8 rows/second) rather than +# switching on at it. The `gap_ms` argument is what makes the two cases +# different — it is a real sleep before the event, so libpardes measures a real +# speed off its monotonic clock rather than reading back-to-back script lines +# as an impossibly fast hand. +# +# Momentum on a real Apple trackpad comes from AppKit, not from here: its +# momentum events are ordinary pardes_scroll calls and every one of them +# cancels the coast. This is the path for the devices AppKit does not fling +# for, and it is the only one a script can reach at all, since NSEvent phases +# have no public constructor. +start 30 100 +wait 8000 Newcol Joincol +wait 8000 $ +stable 700 20000 +# Something long enough to coast ALONG. A flick that runs out of document has +# nothing left to prove: at the top of a short scrollback the hardest possible +# throw and no throw at all leave the same screen. Brace expansion rather than +# seq, so the hermetic world needs nothing on PATH. +text printf 'LINE %s\n' {1..200} +key enter +wait 10000 LINE 200 +stable 700 10000 +snap home + +# ---- PLACED ---- +# +# Half a row every 100 ms is 5 rows/second, under the floor, so lifting the +# fingers changes nothing: the swipe itself has moved what it moved and that is +# where it stops. This is the case that has to hold — a slow deliberate scroll +# that kept sliding afterwards would be unusable. +scroll_begin +scroll -0.5 10 10 0 100 +scroll -0.5 10 10 0 100 +scroll -0.5 10 10 0 100 +stable 700 15000 +snap placed +scroll_end +stable 700 15000 +# Byte-identical to `placed`, which is the whole assertion. +snap placed_released + +# ---- THROWN ---- +# +# The same hand moving six times as far in a twentieth of the time is hundreds +# of rows a second, so the release keeps the view travelling after the fingers +# are gone. +# +# `snap` and then `scroll_end` with NO `stable` between them, which is not +# impatience: a release is only a throw if it arrives while the hand is still +# moving, and a 700 ms wait here would be a hand that stopped — which is +# exactly what PLACED above already proves. +scroll_begin +scroll -3 10 10 0 5 +scroll -3 10 10 0 5 +scroll -3 10 10 0 5 +snap thrown +scroll_end +stable 700 15000 +# Further back through the scrollback than `thrown`, and that distance is the +# coast: nothing but the fling moved the view between these two captures. +snap coasted + +# A finger back on the pad catches it. Begin re-zeros the velocity and the +# bank, so a second throw cannot inherit the first one's speed. +scroll_begin +stable 700 15000 +snap caught diff --git a/test/macos_e2e.swift b/test/macos_e2e.swift index fbfa0e3e..43627a7e 100644 --- a/test/macos_e2e.swift +++ b/test/macos_e2e.swift @@ -790,6 +790,12 @@ private final class Driver: PardesViewDelegate { view.drop([path], at: cell) pump() + // `scroll [cols] [gap_ms]`. The optional gap is a + // real sleep BEFORE the event and means what it does for `rotate`: + // libpardes measures the release speed off the monotonic clock between + // calls, so back-to-back script lines read as an impossibly fast swipe. + // Pacing them is the only way a script can say a swipe was SLOW, which + // is the half of the momentum contract a fling test cannot show. case "scroll": let view = try live() let rows = try double(args, 0, "scroll rows") @@ -799,9 +805,28 @@ private final class Driver: PardesViewDelegate { // other suites' scroll commands do. var cols = 0.0 if args.count > 3 { cols = try double(args, 3, "scroll cols") } + if args.count > 4 { + Thread.sleep(forTimeInterval: try double(args, 4, "scroll gap_ms") / 1000) + } view.scroll(rows: CGFloat(rows), cols: CGFloat(cols), at: cell) pump() + // Fingers down and fingers up. Their own commands for the reason + // rotate_end is one: the fling is decided by the RELEASE SPEED, and + // NSEvent phases have no public constructor, so these entry points are + // the only way the momentum path is reachable from a script at all. + // The coast is then spent by idle's display clock, one step per + // animation frame; ordinary pumps do not move it. + case "scroll_begin": + let view = try live() + view.scrollBegin() + pump() + + case "scroll_end": + let view = try live() + view.scrollEnd() + pump() + case "wheel": let view = try live() let button = try mouseButton(try token(args, 0, "wheel button")) -- cgit v1.3 From 7cbd44dd1cfe97126e7fc996214e458525d2980c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 16 Sep 2026 13:20:29 -0300 Subject: Align macOS rendering with Linux and establish parity regressions --- docs/macos.md | 64 ++++----- docs/rendering-parity-design.md | 132 +++++++++++++++++++ src/macos.zig | 21 ++- src/macos/Sources/AppDelegate.swift | 2 +- src/macos/Sources/PardesView.swift | 128 +++++++++++------- src/macos/pardes.h | 1 + test/macos-snapshots/context.zig | 109 ++++++++++++++++ test/macos-snapshots/rendering-parity.golden | 14 ++ test/macos-snapshots/rendering-parity.snap | 54 ++++++++ test/macos-snapshots/tag-ink.golden | 1 + test/macos-snapshots/tag-ink.snap | 8 ++ test/macos_e2e.swift | 185 ++++++++++++++++++++++++++- 12 files changed, 634 insertions(+), 85 deletions(-) create mode 100644 docs/rendering-parity-design.md create mode 100644 test/macos-snapshots/context.zig create mode 100644 test/macos-snapshots/rendering-parity.golden create mode 100644 test/macos-snapshots/rendering-parity.snap create mode 100644 test/macos-snapshots/tag-ink.golden create mode 100644 test/macos-snapshots/tag-ink.snap (limited to 'src/macos/Sources') diff --git a/docs/macos.md b/docs/macos.md index 3c02de8a..3fdf399f 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -14,6 +14,10 @@ plumbing actually requires, and which parts of it are distribution machinery rather than integration. Read that for the alternatives; this file is what was built and why. +Future layout/compositing ownership and the regression baseline are discussed in +[Shared rendering contract](rendering-parity-design.md). That proposal is design +groundwork; the native drawing implementation remains in place. + ## Why not ghostty's split Ghostty was read carefully before this was written, and this backend @@ -496,33 +500,22 @@ different kinds of assertion because a snapshot is the core's cell buffer and the core has no font: `font Menlo-Regular` asks the view what it is actually wearing, and the snapshots catch the grid moving when the cell changes size. -### The tagline band follows the core's rule, not this shell's - -A pane tag is drawn at `gui_tagline_font_percent` of the body face -(`TaglineSize ` changes it live) and the band it sits on shrinks with -it, while the grid row stays body-sized. Where that shorter band sits inside its -row is no longer this shell's arithmetic: `pardes_tagline_band_offset` and -`pardes_topbar_pane_border_px` answer out of `src/pardes.zig`, and that is the -same rule `src/gui/gui.zig` draws with. - -It is shared because it drifted. This shell centred every band in its own row, -and centring two reduced-height bands is precisely the case -`config.gui_topbar_pane_border_px` exists to prevent: the topbar's unused -half-band meets the first pane tag's unused half-band and the window background -shows through the seam. The strip is as wide as the bands are short — on a -20-pixel cell, 4 physical pixels at the default 82%, 10 at 50%, 14 at 30% — so it -read as "the tagline is wrong on the mac" rather than as one missing rule. Row -zero is bottom-aligned now, the first pane-tag row top-aligned, the two joined by -`gui_topbar_pane_border_px` in the theme's scrollbar-track colour -(`pardes_topbar_pane_border_rgb`, or a compiled override), every row between -centred, and a `Tagbottom` band on the final row bottom-aligned against the -window edge — with the sub-cell strip below it painted in that band's own colour, -because the core grid holds only whole cells and a window is any height it likes. - -The offsets cross as PHYSICAL PIXELS. The host multiplies its points by the -backing scale going in and divides coming out, which is the snapping `Metrics` -already does for the cell, and is what keeps a one-pixel rule one pixel instead -of a two-pixel smear. +### Compact tags and context rows + +`TaglineSize ` scales the tag face, pitch and glyph band. The tag's +background still fills a whole body-grid row, as in the SDL renderer. Painting +only the compact band leaves dark strips between tags. Glyph offsets come from +`pardes_tagline_band_offset`; all measurements cross the ABI in physical pixels. + +The chrome overlay runs after the compact layers. It draws the topbar rule, +the column rule and the pane's tag/body boundary using the theme's border +colour. The pane rule moves above a bottom-positioned tag. Tag-layer fields 11 +and 12 preserve that placement and colour in frozen transition frames. + +Tree-sitter context rows use the compact height and pitch, with full-width row +backgrounds. Their one-physical-pixel separators use the same border colour as +SDL, after discontinuous declarations and after the final context row. The +remaining body starts immediately after the compact rows. ### The cell is snapped to device pixels, not to points @@ -713,6 +706,20 @@ The blur is a **sibling** of the grid inside a plain container, never its parent. Hiding a superview hides its subviews, so a nested backdrop drew a blank window for every opaque theme the moment it was hidden. +`WindowOpacity <0..100>` sets one background coverage throughout the frame. +Background fills replace existing coverage, so overlapping ground, cell, tag +and context layers cannot increase the requested opacity. The window itself +stays clear below 100%; a second tinted window backdrop would compound it. +Text and cursor ink stay opaque. PDF and image pixels follow the SDL image +pipeline: remove the destination by source coverage, then add the image at the +requested opacity. This also preserves the background under transparent image +pixels. Theme colours and attachment rasters are interpreted as sRGB. + +`test/macos-snapshots/rendering-parity.snap` checks background colour and alpha, +regular and bottom tags, compact context separators, and PDF fit, tint and +scrolling. Its native-metrics mode uses backing pixels like the shipping app; +the older grid-only tests keep their display-independent point metrics. + ## Threading One core, touched only from the main thread, plus one pty reader task per pane @@ -955,8 +962,7 @@ select scripts or directories instead. The executable stays in the build cache. `test/macos_e2e.swift` links the same Swift sources the app does, minus `main.swift`, into a second binary — test scaffolding does not ship inside the -product. Scripts are `test/macos-snapshots/*.snap` (seven of them: boot, cwd, -drop, font, keys, rotate, trackpad) and speak the tty suite's +product. Scripts are `test/macos-snapshots/*.snap` and speak the tty suite's vocabulary (`start`, `wait`, `stable`, `text`, `key`, `snap`, `command`, `mouse`, `click`, `wheel`, `resize`, `draw`) plus what only exists here: `fingers `, `force `, diff --git a/docs/rendering-parity-design.md b/docs/rendering-parity-design.md new file mode 100644 index 00000000..b6036543 --- /dev/null +++ b/docs/rendering-parity-design.md @@ -0,0 +1,132 @@ +# Shared rendering contract: design groundwork + +Status: proposed direction, not an implemented renderer abstraction. The current +change fixes the native macOS backend and adds regression coverage. It does not +move layout or drawing into a new shared module. + +## Why the backends diverged + +The core shares editor state, cells, tag layers, body layers, and PDF placements. +It does not yet specify every visual operation needed to present them. SDL and +AppKit therefore independently reconstruct tag backgrounds, compact text bands, +context separators, overlay order, and opacity. A correct cell snapshot can +coexist with an incorrect rendered frame. + +The macOS/Linux comparison exposed concrete gaps in this contract: + +- Reduced tag glyph bands were also used as background bounds on macOS; SDL + fills the entire row. Column and pane rules were missing or painted before + an overlapping layer. +- Tree-sitter context rows had matching compact geometry, but the separator + used the scroll-track color instead of the border color. +- Repeated source-over background fills compounded window opacity. At 71%, + two overlapping fills yield about 92%, and three about 98%. The window's own + colored background added another layer behind the view. +- CoreText fallback runs did not inherit the selected foreground color. +- PDF/image composition ignored window opacity on macOS, while SDL applies it + to raster content. Theme colors also need an explicit sRGB interpretation. + +These are duplicated policy decisions, rather than a reason to replace CoreText +or require identical fonts on every host. + +## Proposed ownership boundary + +A shared scene builder should translate the existing surface and its layers +into an ordered list of positioned drawing operations. Platform code should +consume that list without deciding which rows are compact, which edge has a +separator, or which objects participate in window opacity. + +The builder would own: + +- Tag and context geometry, background extents, separator positions and colors, + clipping, and the order of backgrounds, text, images, cursors, and overlays. +- Coordinate conversion rules: logical layout units, supplied font metrics, + device scale, and the rounding policy for one-device-pixel rules. +- Color and compositing semantics, including clear backgrounds, replacement + background fills, image coverage, selection, and opaque native text/cursors. +- Stable image references and a defined frame lifetime, including snapshots + retained for transitions and postprocessing. + +Backends would continue to own native font selection, shaping/rasterization, +image upload/cache management, and presentation. Native event handling, window +management, and the text-only terminal frontend are outside this proposal. + +A small 2D operation vocabulary could include solid rectangles, positioned text +runs, images with source/destination rectangles, and explicit clips. Operations +must carry semantic blend behavior and a documented color space. Wrapping +`fillRect` and `drawText` while leaving each backend to build the scene would +preserve most of the duplication that caused these bugs. + +Do not freeze a new ABI before extracting one small path and checking its needs. +Font metrics must enter the shared layout explicitly; changing fonts can still +change line capacity and glyph appearance. Pixel equality across different +fonts, rasterizers, and display scales is not the acceptance criterion. + +## Compositing contract to preserve + +Let p be WindowOpacity in [0, 1]. An ordinary background region has alpha p, +regardless of how many logical layers cover it. Clear background regions remain +clear. Native text and cursors retain their own opacity. + +For an image sample with coverage a and straight RGB c, the existing SDL +background-layer behavior produces premultiplied output: + +``` +out.rgb = p * a * c + (1 - a) * dst.rgb +out.a = p * a + (1 - a) * dst.a +``` + +Thus PDF text is part of a raster page and fades with the page; native text does +not. Transparent image pixels preserve the destination. Ordinary source-over +with source alpha p*a is not equivalent. Any future operation API needs to +express this distinction directly and specify sampling and premultiplication. + +## Tests available before extraction + +`test/macos-snapshots/tag-ink.snap` checks actual rendered tag foreground pixels, +covering failures that a cell-grid golden cannot detect. + +`test/macos-snapshots/rendering-parity.snap` uses native backing-scale metrics +and checks rendered tag backgrounds and rules, top/bottom tags, opacity 100/71/0, +invalid opacity rejection, and nested multiline Tree-sitter context separators. +It also checks PDF placement and sampled page alpha at those opacity values, +height fit, tint modes, and scrolling. `context.zig` is the nested context fixture; +`docs/9p.pdf` is the existing PDF fixture. Optional PNG output is enabled with +`PARDES_TEST_CAPTURE_DIR`. + +The Zig test named `mac tag layer ABI preserves logical capacity and physical +grip` covers tag-bottom and border-color metadata as well as existing capacity +and grip behavior. The existing Linux `test/window_opacity.py` checks background +changes, native glyph preservation, zero opacity, invalid input, and restoration. + +Run on macOS: + +```sh +zig build unit-test -Dplatform=macos '-Dtest-filter=mac tag layer ABI' +zig build macos-e2e -Dplatform=macos +zig build -Dplatform=macos +``` + +These are baseline regressions, not a comprehensive cross-backend image oracle. +PDF alpha samples do not establish exact raster color or interpolation equality; +offscreen AppKit captures do not test the desktop compositor. Live comparison +still matters for window transparency and display color management. + +## Suggested later extraction and acceptance gates + +1. Add shared geometry/scene assertions for tags and context rows using supplied + metrics at several scales. Include clipping, partial rows, bottom tags, and + final separator order; expected values should come from the contract rather + than a copy of either backend's implementation. +2. Extract that scene construction once and adapt both native renderers. Keep + current backend pixel checks running without regenerating goldens merely to + accept differences. Compare matching fixtures and settings on both systems. +3. Add synthetic RGBA image coverage cases before extracting image composition: + opaque, transparent, and partial-alpha pixels over a known destination at + p=0, intermediate p, and p=1. Include fit, crop, and clip boundaries. +4. Extend the contract to the remaining overlays and retained transition frames. + Measure frame time and allocations before broadening the abstraction. + +The desired result is one definition of visual policy with small native drawing +adapters. A new GPU engine, shared font rasterizer, or wholesale backend rewrite +is not required to reach that boundary. diff --git a/src/macos.zig b/src/macos.zig index 4b37255e..bbfb8c08 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -931,7 +931,7 @@ export fn pardes_grid_col_at(x: f32, row: u16, body_w: f32, tagline_w: f32) u16 export fn pardes_topbar_pane_border_rgb() u32 { const rgb = pardes.config.gui_topbar_pane_border_rgb orelse fromTheme: { const st = state orelse return color_default; - break :fromTheme st.core.chromeTheme().scroll_track; + break :fromTheme st.core.chromeTheme().border; }; return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; } @@ -1979,6 +1979,11 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { 8 => if (layer.cursor) |c| c.col else 65535, 9 => if (layer.cursor) |c| @intFromBool(c.bar) else 0, 10 => @as(u32, layer.bg[0]) << 16 | @as(u32, layer.bg[1]) << 8 | layer.bg[2], + 11 => @intFromBool(layer.kind == .pane and st.core.settings.tag_bottom), + 12 => rgb: { + const border = st.core.chromeTheme().border; + break :rgb @as(u32, border[0]) << 16 | @as(u32, border[1]) << 8 | border[2]; + }, else => 0, }; } @@ -2914,6 +2919,20 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { defer core.surface.tag_layers[0] = .{}; try std.testing.expectEqual(@as(u32, 12), pardes_tag_layer_value(0, 0)); try std.testing.expectEqual(@as(u32, 0x123456), pardes_tag_layer_value(0, 10)); + try std.testing.expectEqual(@as(u32, 0), pardes_tag_layer_value(0, 11)); + core.settings.tag_bottom = true; + try std.testing.expectEqual(@as(u32, 1), pardes_tag_layer_value(0, 11)); + core.surface.tag_layers[0].kind = .column; + try std.testing.expectEqual(@as(u32, 0), pardes_tag_layer_value(0, 11)); + core.surface.tag_layers[0].kind = .pane; + const border = core.chromeTheme().border; + const border_rgb = @as(u32, border[0]) << 16 | @as(u32, border[1]) << 8 | border[2]; + try std.testing.expectEqual(border_rgb, pardes_tag_layer_value(0, 12)); + try std.testing.expectEqual(pardes.config.gui_topbar_pane_border_rgb orelse border, .{ + @as(u8, @intCast(pardes_topbar_pane_border_rgb() >> 16)), + @as(u8, @truncate(pardes_topbar_pane_border_rgb() >> 8)), + @as(u8, @truncate(pardes_topbar_pane_border_rgb())), + }); try std.testing.expectEqual(@as(u32, 11), pardes_tag_layer_value(0, 8)); try std.testing.expectEqual(@as(u8, 'Z'), pardes_tag_layer_cells(0).?[11].text[0]); var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{'G'} ++ .{0} ** 6, .len = 1, .default = false })); diff --git a/src/macos/Sources/AppDelegate.swift b/src/macos/Sources/AppDelegate.swift index 107c40fd..4e91e407 100644 --- a/src/macos/Sources/AppDelegate.swift +++ b/src/macos/Sources/AppDelegate.swift @@ -478,7 +478,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { if let rgb = view.themeBG { backdrop.isHidden = true window.isOpaque = view.backgroundAlpha >= 1 - window.backgroundColor = NSColor( + window.backgroundColor = view.backgroundAlpha < 1 ? .clear : NSColor( srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, green: CGFloat((rgb >> 8) & 0xFF) / 255, blue: CGFloat(rgb & 0xFF) / 255, diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index ba3677e7..7c537055 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -1006,7 +1006,7 @@ final class PardesView: NSView { // up on themselves — a translucent ground would darken toward opaque // over a few frames otherwise. if clearGround || backgroundAlpha < 1 { ctx.clear(bounds) } - if !clearGround { fill(ctx, bounds, ground, backgroundAlpha) } + if !clearGround { fillBackground(ctx, bounds, ground, backgroundAlpha) } if frozenImages == nil { frameImages.removeAll(keepingCapacity: true) } guard cols > 0, rows > 0, Int(count) == cols * rows, let cells = suppliedCells ?? pardes_frame_cells() @@ -1060,7 +1060,7 @@ final class PardesView: NSView { if color != bgClear { let bandY = tagline ? y + bandTop : y let bandHeight = tagline ? taglines.height : cellHeight - fill(ctx, CGRect(x: CGFloat(start) * cellWidth, y: bandY, + fillBackground(ctx, CGRect(x: CGFloat(start) * cellWidth, y: bandY, width: CGFloat(col - start) * cellWidth, height: bandHeight), color, block ? 1 : backgroundAlpha) } @@ -1071,29 +1071,6 @@ final class PardesView: NSView { } } - // The rule joining the topbar band to the first pane-tag band. Both were - // centred in their own rows until now, and centring two reduced-height - // bands is exactly what leaves their unused half-bands touching with a - // strip of window background showing between them — the case - // config.gui_topbar_pane_border_px exists to close. Drawn only when that - // first pane row really carries a band, so a session whose second row is - // pane BODY gets no stray line across it. - let ruleThickness = taglines.borderThickness - let ruleColor = pardes_topbar_pane_border_rgb() - if ruleThickness > 0, ruleColor != UInt32(PARDES_COLOR_DEFAULT), - rows > Int(PARDES_TOPBAR_H) { - let base = Int(PARDES_TOPBAR_H) * cols - let joins = (0.. [FrozenBodyLayer] { var result: [FrozenBodyLayer] = [] for index in 0.., cols: Int, rows: Int) { + var layers: [[Int]] = [] for index in 0.. 0 { + fillBackground(ctx, CGRect(x: 0, y: taglines.borderTop, width: bounds.width, + height: taglines.borderThickness), + pardes_topbar_pane_border_rgb(), backgroundAlpha) + } } private func gripGlyph(_ text: String, face: Face) -> GripGlyph? { @@ -1288,10 +1289,13 @@ final class PardesView: NSView { private func drawTagLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer, hideCursor: Bool) { let left = CGFloat(values[4]) * cellWidth let y = CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height) - let viewport = CGRect(x: left, y: y, width: CGFloat(values[6]) * cellWidth, height: taglines.height) + // SDL gives the tag a full body-row background; only its glyphs + // and per-cell highlights use the compact band. + let viewport = CGRect(x: left, y: CGFloat(values[5]) * cellHeight, + width: CGFloat(values[6]) * cellWidth, height: cellHeight) ctx.saveGState() ctx.clip(to: viewport) - fill(ctx, viewport, UInt32(values[10]), backgroundAlpha) + fillBackground(ctx, viewport, UInt32(values[10]), backgroundAlpha) for pass in 0...1 { for col in 0..= viewport.maxY { break } - let rowStyle = resolve(cells[row*cols], block: false, ground: themeBG ?? pardesDefaultBG, clearGround: false) - fill(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, backgroundAlpha) + let rowStyle = resolve(cells[row*cols], block: false, ground: themeBG ?? pardesDefaultBG, clearGround: themeBG == nil) + fillBackground(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, backgroundAlpha) for pass in 0...1 { for col in 0..> 16) & 0xFF) / 255, - green: CGFloat((rgb >> 8) & 0xFF) / 255, - blue: CGFloat(rgb & 0xFF) / 255, - alpha: alpha) + // Theme channels, like PDF raster bytes, are sRGB. Device RGB can + // brighten them when AppKit's backing bitmap uses another profile. + ctx.setFillColor(CGColor(srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, + green: CGFloat((rgb >> 8) & 0xFF) / 255, + blue: CGFloat(rgb & 0xFF) / 255, + alpha: alpha)) + } + + /// One surface pixel has one background opacity, even when a compact + /// layer covers a canonical cell. Source-over would turn 71% into 92%, + /// then 98%, as the ground, row and cell are painted over each other. + private func fillBackground(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { + ctx.saveGState() + ctx.setShouldAntialias(false) + if rgb == bgClear { + ctx.clear(rect) + } else { + ctx.setBlendMode(.copy) + fill(ctx, rect, rgb, alpha) + } + ctx.restoreGState() } private func fill(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { diff --git a/src/macos/pardes.h b/src/macos/pardes.h index a2d13b1f..a2e34f53 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -353,6 +353,7 @@ void pardes_row_metrics(uint16_t body_w, uint16_t body_h, uint16_t tagline_w, ui uint32_t pardes_tag_text_inset(void); uint32_t pardes_grip_columns(void); uint32_t pardes_tag_layer_limit(void); +// Tag layer fields 11 and 12 carry tag-bottom placement and chrome border RGB. uint32_t pardes_tag_layer_value(uint32_t index, uint32_t field); const pardes_cell_s *pardes_tag_layer_cells(uint32_t index); uint32_t pardes_body_layer_limit(void); diff --git a/test/macos-snapshots/context.zig b/test/macos-snapshots/context.zig new file mode 100644 index 00000000..ff8f8553 --- /dev/null +++ b/test/macos-snapshots/context.zig @@ -0,0 +1,109 @@ +const Workspace = struct { + const enabled = true; + + fn draw( + value: u32, + ) u32 { + var result = value; + result +%= 1; + result +%= 2; + result +%= 3; + result +%= 4; + result +%= 5; + result +%= 6; + result +%= 7; + result +%= 8; + result +%= 9; + result +%= 10; + result +%= 11; + result +%= 12; + result +%= 13; + result +%= 14; + result +%= 15; + result +%= 16; + result +%= 17; + result +%= 18; + result +%= 19; + result +%= 20; + result +%= 21; + result +%= 22; + result +%= 23; + result +%= 24; + result +%= 25; + result +%= 26; + result +%= 27; + result +%= 28; + result +%= 29; + result +%= 30; + result +%= 31; + result +%= 32; + result +%= 33; + result +%= 34; + result +%= 35; + result +%= 36; + result +%= 37; + result +%= 38; + result +%= 39; + result +%= 40; + result +%= 41; + result +%= 42; + result +%= 43; + result +%= 44; + result +%= 45; + result +%= 46; + result +%= 47; + result +%= 48; + result +%= 49; + result +%= 50; + result +%= 51; + result +%= 52; + result +%= 53; + result +%= 54; + result +%= 55; + result +%= 56; + result +%= 57; + result +%= 58; + result +%= 59; + result +%= 60; + result +%= 61; + result +%= 62; + result +%= 63; + result +%= 64; + result +%= 65; + result +%= 66; + result +%= 67; + result +%= 68; + result +%= 69; + result +%= 70; + result +%= 71; + result +%= 72; + result +%= 73; + result +%= 74; + result +%= 75; + result +%= 76; + result +%= 77; + result +%= 78; + result +%= 79; + result +%= 80; + result +%= 81; + result +%= 82; + result +%= 83; + result +%= 84; + result +%= 85; + result +%= 86; + result +%= 87; + result +%= 88; + result +%= 89; + result +%= 90; + result +%= 91; + result +%= 92; + result +%= 93; + result +%= 94; + result +%= 95; + result +%= 96; + result +%= 97; + result +%= 98; + result +%= 99; + return result; + } +}; diff --git a/test/macos-snapshots/rendering-parity.golden b/test/macos-snapshots/rendering-parity.golden new file mode 100644 index 00000000..536f6800 --- /dev/null +++ b/test/macos-snapshots/rendering-parity.golden @@ -0,0 +1,14 @@ +== backgrounds tags-100 uniform +== backgrounds tags-bottom uniform +== backgrounds tags-71 uniform +== backgrounds tags-0 uniform +== backgrounds invalid-stays-0 uniform +== context context-100 compact separators verified +== context context-71 compact separators verified +== pdf pdf-100 native page opacity verified +== pdf pdf-0 native page opacity verified +== pdf pdf-71 native page opacity verified +== pdf pdf-fit-height native page opacity verified +== pdf pdf-full-tint native page opacity verified +== pdf pdf-original-colors native page opacity verified +== pdf pdf-scrolled native page opacity verified diff --git a/test/macos-snapshots/rendering-parity.snap b/test/macos-snapshots/rendering-parity.snap new file mode 100644 index 00000000..cdd940c8 --- /dev/null +++ b/test/macos-snapshots/rendering-parity.snap @@ -0,0 +1,54 @@ +start 40 110 +native-metrics +wait 8000 $ +command Theme forge +command TaglineSize 70 +stable 700 20000 +check-backgrounds tags-100 +command Tagbottom +stable 700 20000 +check-backgrounds tags-bottom +command Tagbottom +stable 700 20000 +command WindowOpacity 71 +stable 700 20000 +check-backgrounds tags-71 +command WindowOpacity 0 +stable 700 20000 +check-backgrounds tags-0 +command WindowOpacity 101 +stable 700 20000 +check-backgrounds invalid-stays-0 +command WindowOpacity 100 +open-fixture context.zig:55 +command TreeContext on +stable 700 20000 +capture context-initial +check-context context-100 +command WindowOpacity 71 +stable 700 20000 +check-context context-71 +command WindowOpacity 100 +open-fixture ../../docs/9p.pdf +stable 1000 20000 +check-pdf pdf-100 +command WindowOpacity 0 +stable 700 20000 +check-pdf pdf-0 +command WindowOpacity 71 +stable 700 20000 +check-pdf pdf-71 +command WindowOpacity 100 +command PdfFit +stable 700 20000 +check-pdf pdf-fit-height +command PdfTint +stable 700 20000 +check-pdf pdf-full-tint +command PdfTint +stable 700 20000 +check-pdf pdf-original-colors +command PdfFit +scroll 6 10 30 +stable 700 20000 +check-pdf pdf-scrolled diff --git a/test/macos-snapshots/tag-ink.golden b/test/macos-snapshots/tag-ink.golden new file mode 100644 index 00000000..dfb0704d --- /dev/null +++ b/test/macos-snapshots/tag-ink.golden @@ -0,0 +1 @@ +== tag-ink forge-tags visible diff --git a/test/macos-snapshots/tag-ink.snap b/test/macos-snapshots/tag-ink.snap new file mode 100644 index 00000000..e9e4c8e2 --- /dev/null +++ b/test/macos-snapshots/tag-ink.snap @@ -0,0 +1,8 @@ +start 24 80 +wait 8000 Newcol Joincol +wait 8000 $ +stable 700 20000 +command Theme forge +command TaglineSize 70 +stable 700 20000 +draw-tag-ink forge-tags diff --git a/test/macos_e2e.swift b/test/macos_e2e.swift index 43627a7e..5427c3ad 100644 --- a/test/macos_e2e.swift +++ b/test/macos_e2e.swift @@ -92,6 +92,8 @@ private final class Driver: PardesViewDelegate { private var window: NSWindow? private var view: PardesView? private var booted = false + private var nativeMetrics = false + private let scriptDirectory: String private var observer: NSObjectProtocol? private var output = "" private var nextAnimationFrame: Date? @@ -101,7 +103,8 @@ private final class Driver: PardesViewDelegate { /// The script's own file name, for error messages. private let scriptName: String - init(scriptName: String) { + init(scriptName: String, scriptDirectory: String) { + self.scriptDirectory = scriptDirectory self.scriptName = scriptName // The app answers this notification with pump(); so does the harness, // and for the same reason — the view calls into the core and never @@ -232,11 +235,17 @@ private final class Driver: PardesViewDelegate { let grid = view.gridSize // Points, not backing-store pixels. The app passes physical pixels // because the native PDF placement path measures in them; a golden must - // not change when the same script runs on a Retina display, and nothing - // here places a PDF. - let cellW = UInt16(max(1, min(view.cellWidth.rounded(), CGFloat(UInt16.max)))) - let cellH = UInt16(max(1, min(view.cellHeight.rounded(), CGFloat(UInt16.max)))) + // not change when the same grid script runs on a Retina display. Pixel + // parity scripts opt into native metrics below, including PDF placement. + let scale: CGFloat = nativeMetrics ? (window?.backingScaleFactor ?? 1) : 1 + let cellW = UInt16(max(1, min((view.cellWidth * scale).rounded(), CGFloat(UInt16.max)))) + let cellH = UInt16(max(1, min((view.cellHeight * scale).rounded(), CGFloat(UInt16.max)))) pardes_resize(grid.cols, grid.rows, cellW, cellH) + if nativeMetrics { + pardes_row_metrics(cellW, cellH, + UInt16(max(1, (view.taglineCellWidth * scale).rounded())), + UInt16(max(1, (view.taglineBandHeight * scale).rounded()))) + } pump() } @@ -498,6 +507,34 @@ private final class Driver: PardesViewDelegate { output += "== draw \(label) \(w)x\(h) nonblank\n" } + /// Forge's topbar must contain light ink, not CoreText's default black. + /// Restrict the sample to text, excluding grips, pane bodies and cursors. + private func drawTagInk(_ label: String) throws { + let view = try live() + let bounds = view.bounds + guard let rep = view.bitmapImageRepForCachingDisplay(in: bounds) else { + throw ScriptError(message: "draw-tag-ink: no bitmap") + } + view.cacheDisplay(in: bounds, to: rep) + let scale = CGFloat(rep.pixelsWide) / bounds.width + var brightest: CGFloat = 0 + for y in 0.. 0.5 else { + throw ScriptError(message: "draw-tag-ink: Forge topbar has no light foreground ink") + } + if let directory = ProcessInfo.processInfo.environment["PARDES_TEST_CAPTURE_DIR"], + let png = rep.representation(using: .png, properties: [:]) { + try png.write(to: URL(fileURLWithPath: directory).appendingPathComponent(label + ".png")) + } + output += "== tag-ink \(label) visible\n" + } + /// The alpha range of a drawn frame, recorded into the golden. /// /// The contract WindowOpacity states (shaders/ui.frag.glsl, and @@ -543,6 +580,122 @@ private final class Driver: PardesViewDelegate { output += "== draw-opacity \(label) \(w)x\(h) alpha \(lowest)..\(highest)\n" } + private func renderedCapture(_ label: String) throws -> NSBitmapImageRep { + let view = try live() + guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { + throw ScriptError(message: "capture: no bitmap") + } + view.cacheDisplay(in: view.bounds, to: rep) + if let directory = ProcessInfo.processInfo.environment["PARDES_TEST_CAPTURE_DIR"], + let png = rep.representation(using: .png, properties: [:]) { + try png.write(to: URL(fileURLWithPath: directory).appendingPathComponent(label + ".png")) + } + return rep + } + + // colorAt labels components as calibrated RGB even for a Display P3 + // bitmap. Reattach the bitmap's actual profile before comparing sRGB. + private func sample(_ rep: NSBitmapImageRep, x: Int, y: Int) -> NSColor? { + guard let raw = rep.colorAt(x: x, y: y) else { return nil } + let components = [raw.redComponent, raw.greenComponent, raw.blueComponent, raw.alphaComponent] + return NSColor(colorSpace: rep.colorSpace, components: components, count: 4).usingColorSpace(.sRGB) + } + + private func checkBackgrounds(_ label: String) throws { + let view = try live(), rep = try renderedCapture(label) + let scale = CGFloat(rep.pixelsWide) / view.bounds.width + func check(x: CGFloat, y: CGFloat, rgb: UInt32, name: String) throws { + guard let c = sample(rep, x: Int(x * scale), y: Int(y * scale)) else { + throw ScriptError(message: "\(name): no pixel") + } + guard abs(c.alphaComponent - view.backgroundAlpha) < 2.0 / 255 else { + throw ScriptError(message: "\(name): background alpha \(c.alphaComponent), expected \(view.backgroundAlpha)") + } + if view.backgroundAlpha > 0 { + let actual = [c.redComponent, c.greenComponent, c.blueComponent] + let expected = [CGFloat((rgb >> 16) & 255), CGFloat((rgb >> 8) & 255), CGFloat(rgb & 255)] + guard zip(actual, expected).allSatisfy({ abs($0 * 255 - $1) < 4 }) else { + throw ScriptError(message: "\(name): tag background does not cover the full row: \(actual) vs \(expected)") + } + } + } + for i in 0.. 0 else { continue } + let x = CGFloat(pardes_tag_layer_value(i, 4) + pardes_tag_layer_value(i, 6)) * view.cellWidth - 2 / scale + let top = CGFloat(pardes_tag_layer_value(i, 5)) * view.cellHeight + let height = Int(view.cellHeight * scale) + let kind = pardes_tag_layer_value(i, 1) + let bottom = kind == 2 && pardes_tag_layer_value(i, 11) != 0 + for pixel in 0.. 0 else { continue } + headers += count + let x = CGFloat(pardes_body_layer_value(i, 3) + pardes_body_layer_value(i, 5)) * view.cellWidth - 2 / scale + let top = CGFloat(pardes_body_layer_value(i, 4)) * view.cellHeight + for row in 0..> 16) & 255)) < 4, + abs(c.greenComponent * 255 - CGFloat((rgb >> 8) & 255)) < 4, + abs(c.blueComponent * 255 - CGFloat(rgb & 255)) < 4, + abs(c.alphaComponent - view.backgroundAlpha) < 2.0 / 255 else { + throw ScriptError(message: "context: separator is misplaced or has accumulated opacity") + } + } + } + guard headers >= 2, separators > 0 else { + throw ScriptError(message: "context: expected nested compact declarations, got \(headers) rows") + } + output += "== context \(label) compact separators verified\n" + } + + private func checkPDF(_ label: String) throws { + let view = try live(), rep = try renderedCapture(label) + guard nativeMetrics, pardes_frame_images() > 0, let images = pardes_frame_image_list() else { + throw ScriptError(message: "PDF: no native image placements") + } + let scale = window?.backingScaleFactor ?? 1 + let image = images[0] + let x = CGFloat(image.cell_x) * view.cellWidth + CGFloat(image.dst_x) / scale + let y = CGFloat(image.cell_y) * view.cellHeight + (CGFloat(image.dst_y) + CGFloat(image.offset_y)) / scale + let width = CGFloat(image.dst_w) / scale, height = CGFloat(image.dst_h) / scale + guard width > view.cellWidth * 4, height > view.cellHeight * 2, + y >= CGFloat(image.cell_y) * view.cellHeight - 1, + x + width <= view.bounds.width + 1, y + height <= view.bounds.height + 1 else { + throw ScriptError(message: "PDF: placement is outside its physical-pixel viewport") + } + let backing = CGFloat(rep.pixelsWide) / view.bounds.width + var matched = 0 + for fraction in [CGFloat(0.2), 0.4, 0.6, 0.8] { + if let c = rep.colorAt(x: Int((x + width * fraction) * backing), + y: Int((y + height * fraction) * backing)), abs(c.alphaComponent - view.backgroundAlpha) < 2.0 / 255 { matched += 1 } + } + guard matched == 4 else { throw ScriptError(message: "PDF: raster opacity does not match WindowOpacity") } + output += "== pdf \(label) native page opacity verified\n" + } + // MARK: - the script func run(source: String) throws -> String { @@ -569,6 +722,23 @@ private final class Driver: PardesViewDelegate { let args = rest.split(separator: " ").map(String.init) switch cmd { + case "native-metrics": + nativeMetrics = true + pardesViewDidResize(try live()) + case "open-fixture": + _ = try live() + let path = URL(fileURLWithPath: scriptDirectory).appendingPathComponent(rest).standardized.path + let command = "Look " + path + pardes_command(command, command.utf8.count) + pump() + case "check-backgrounds": + try checkBackgrounds(rest) + case "check-context": + try checkContext(rest) + case "check-pdf": + try checkPDF(rest) + case "capture": + _ = try renderedCapture(rest) case "start": let rows = try int(args, 0, "start rows") let cols = try int(args, 1, "start cols") @@ -882,6 +1052,9 @@ private final class Driver: PardesViewDelegate { // place it can be checked: the core's cell buffer says nothing about // alpha, and `draw` deliberately compares channels without knowing // which one is which. + case "draw-tag-ink": + try drawTagInk(rest) + case "draw-opacity": guard !rest.isEmpty else { throw ScriptError(message: "draw-opacity needs a label") } try drawOpacity(rest) @@ -1125,7 +1298,7 @@ private func runOne(scriptPath: String, update: Bool) -> Bool { let goldenPath = String(scriptPath.dropLast(".snap".count)) + ".golden" let actualPath = String(scriptPath.dropLast(".snap".count)) + ".actual" - let driver = Driver(scriptName: name) + let driver = Driver(scriptName: name, scriptDirectory: (scriptPath as NSString).deletingLastPathComponent) // pardes_deinit is mandatory, not tidiness: the ABI is a singleton, so a // core left standing makes the NEXT script's pardes_init return 1. defer { driver.shutdown() } -- cgit v1.3 From 717afaf3177a2e0925b18ae3445119efe808b129 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 16 Sep 2026 14:46:16 -0300 Subject: Add macOS backdrop blur and preserve PDF ink opacity --- docs/macos.md | 42 +++++++++++++++++++++--- docs/rendering-parity-design.md | 6 ++-- src/builtins.zig | 1 + src/config.zig | 49 +++++++++++++++++++++++++--- src/macos.zig | 29 ++++++++++++++++ src/macos/Sources/AppDelegate.swift | 24 +++++++------- src/macos/Sources/PardesView.swift | 16 ++++++++- src/macos/pardes.h | 4 +++ src/panes.zig | 7 +++- src/pardes.zig | 2 ++ src/pdf.zig | 48 +++++++++++++++++++++++++++ src/pdf_bridge.c | 21 ++++++++++-- src/pdf_bridge.h | 6 ++-- test/macos-snapshots/rendering-parity.golden | 14 ++++---- test/macos_e2e.swift | 21 ++++++++---- 15 files changed, 249 insertions(+), 41 deletions(-) (limited to 'src/macos/Sources') diff --git a/docs/macos.md b/docs/macos.md index 3fdf399f..9190ca67 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -696,7 +696,7 @@ A theme with `bg = null` — the curated `dark`, and every vendored `pardes_theme_bg` answers `PARDES_COLOR_DEFAULT` and the host goes see-through: `window.isOpaque = false`, a clear background colour, and an `NSVisualEffectView` (`.underWindowBackground`, `.behindWindow`, `.active`) -behind the grid. `PardesView` stops painting the ground at all — it *clears*, +behind the grid when `WindowBlur` is enabled. `PardesView` stops painting the ground at all — it *clears*, because AppKit does not blank a non-opaque view — and any cell whose background is still the default resolves to `bgClear` and is skipped by the run loop. Reversed cells are not: a reverse puts the text colour in the background, and @@ -710,10 +710,42 @@ blank window for every opaque theme the moment it was hidden. Background fills replace existing coverage, so overlapping ground, cell, tag and context layers cannot increase the requested opacity. The window itself stays clear below 100%; a second tinted window backdrop would compound it. -Text and cursor ink stay opaque. PDF and image pixels follow the SDL image -pipeline: remove the destination by source coverage, then add the image at the -requested opacity. This also preserves the background under transparent image -pixels. Theme colours and attachment rasters are interpreted as sRGB. +Text and cursor ink stay opaque. PDFs render onto a transparent MuPDF pixmap, +which preserves the coverage of text, paths, photos, and highlights. The host +paints paper at `WindowOpacity`, then composites PDF content at its original +opacity. Blank paper therefore reveals the blurred backdrop while lettering +stays readable even at `WindowOpacity 0`. Paper is white with `PdfTint` disabled +and uses the theme background otherwise. Explicit PDF background rectangles +and scanned page images remain content: this does not guess paper from pixel +brightness or remove white objects from a document. Scrolling and transitions +retain both the content raster and its paper color. + +Ordinary image attachments still follow the SDL image pipeline: remove the +destination by source coverage, then add the image at the requested opacity. +Theme colours and attachment rasters are interpreted as sRGB. The PDF paper +separation is currently macOS-specific; other hosts keep the opaque raster path. + +`WindowBlur <0..100>` controls the strength of that native backdrop independently +of `WindowOpacity`. It is a macOS-only builtin, also accepted in the startup +config and reported by `Config`. It defaults to 0 (off); 100 shows the full +AppKit material and intermediate values blend the material with the unblurred +backdrop using the effect view's alpha. An opaque themed background hides the +effect; lowering `WindowOpacity` makes the remembered strength visible again. +For example: + +```text +WindowOpacity 71 +WindowBlur 60 +``` + +This is material strength, not a Gaussian radius in pixels. AppKit's public +`NSVisualEffectView` API chooses its own blur and tint for the material. It +samples behind the window; text and cursors are drawn in a separate sibling +above the effect and remain sharp. macOS accessibility settings such as Reduce +Transparency can override the material's appearance. `WindowBlur 0` also turns +off the formerly implicit blur for background-less themes; set it to 100 to +restore that appearance. The compositor must be checked in a live window: +offscreen grid captures cannot verify behind-window blur. `test/macos-snapshots/rendering-parity.snap` checks background colour and alpha, regular and bottom tags, compact context separators, and PDF fit, tint and diff --git a/docs/rendering-parity-design.md b/docs/rendering-parity-design.md index b6036543..14a5bc62 100644 --- a/docs/rendering-parity-design.md +++ b/docs/rendering-parity-design.md @@ -76,8 +76,10 @@ out.rgb = p * a * c + (1 - a) * dst.rgb out.a = p * a + (1 - a) * dst.a ``` -Thus PDF text is part of a raster page and fades with the page; native text does -not. Transparent image pixels preserve the destination. Ordinary source-over +This describes ordinary image attachments and the existing SDL PDF path. +macOS PDFs now separate unpainted paper from content: paper uses p and content +uses its own coverage, without multiplying that coverage by p. A future shared +scene must carry this paper/content distinction explicitly. Transparent image pixels preserve the destination. Ordinary source-over with source alpha p*a is not equivalent. Any future operation API needs to express this distinction directly and specify sampling and premultiplication. diff --git a/src/builtins.zig b/src/builtins.zig index 1cd10a99..39d70e5d 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -18,6 +18,7 @@ pub const capabilities: config.Runtime.Capabilities = .{ // whatever terminal is on the other end of the serial line. .tagline_font_size = pardes.platform != .tty and pardes.platform != .esp32p4, .window_opacity = pardes.platform == .gui or pardes.platform == .macos, + .window_blur = pardes.platform == .macos, }; pub const Ctx = struct { diff --git a/src/config.zig b/src/config.zig index f91d95c6..440549b3 100644 --- a/src/config.zig +++ b/src/config.zig @@ -102,6 +102,7 @@ pub const leader_path = paths: { } if (pardes.platform == .gui) table.set(.Pet, null); if (builtins.capabilities.window_opacity) table.set(.WindowOpacity, null); + if (builtins.capabilities.window_blur) table.set(.WindowBlur, null); if (builtins.capabilities.panel_transitions) { table.set(.PanelSlide, "as"); table.set(.PanelZoom, "az"); @@ -540,6 +541,7 @@ pub const Runtime = struct { column_tags: bool = true, syntax_bold: bool = false, window_opacity: u8 = 100, + window_blur: u8 = 0, window_opacity_pending: bool = true, pet: enum { off, cat, frog } = .off, @@ -630,6 +632,7 @@ pub const Runtime = struct { scene_shaders: bool, tagline_font_size: bool, window_opacity: bool = false, + window_blur: bool = false, }; pub const Capability = std.meta.FieldEnum(Capabilities); @@ -644,6 +647,7 @@ pub const Runtime = struct { font, tagline_size, window_opacity, + window_blur, transition: layout.Transition, scene: Scene, }; @@ -655,7 +659,7 @@ pub const Runtime = struct { pub fn takesArg(setting: Setting) bool { return switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur => true, else => false, }; } @@ -683,6 +687,7 @@ pub const Runtime = struct { .{ .word = "Font", .action = .font, .availability = .font_picker }, .{ .word = "TaglineSize", .action = .tagline_size, .availability = .font_picker }, .{ .word = "WindowOpacity", .action = .window_opacity, .availability = .window_opacity }, + .{ .word = "WindowBlur", .action = .window_blur, .availability = .window_blur }, .{ .word = "PanelSlide", .action = .{ .transition = .slide }, .availability = .panel_transitions }, .{ .word = "PanelZoom", .action = .{ .transition = .zoom }, .availability = .panel_transitions }, .{ .word = "PanelDissolve", .action = .{ .transition = .dissolve }, .availability = .panel_transitions }, @@ -726,6 +731,8 @@ pub const Runtime = struct { @compileError("native font settings must use the font-picker capability"), .window_opacity => if (setting.availability != .window_opacity) @compileError("window opacity must use the window-opacity capability"), + .window_blur => if (setting.availability != .window_blur) + @compileError("window blur must use the window-blur capability"), .transition => if (setting.availability != .panel_transitions) @compileError("panel effects must use the panel-transition capability"), .scene => if (setting.availability != .scene_shaders) @@ -737,8 +744,8 @@ pub const Runtime = struct { for (std.enums.values(Toggle)) |field| if (actionCount(.{ .toggle = field }) != 1) @compileError("runtime toggle must occur exactly once: " ++ @tagName(field)); if (actionCount(.shell) != 1 or actionCount(.theme) != 1 or actionCount(.font) != 1 or - actionCount(.tagline_size) != 1 or actionCount(.window_opacity) != 1) - @compileError("Shell, Theme, Font, TaglineSize, and WindowOpacity actions must each occur exactly once"); + actionCount(.tagline_size) != 1 or actionCount(.window_opacity) != 1 or actionCount(.window_blur) != 1) + @compileError("Shell, Theme, Font, TaglineSize, WindowOpacity, and WindowBlur actions must each occur exactly once"); for (std.enums.values(layout.Transition)) |effect| { const expected: comptime_int = @intFromBool(effect != .off); if (actionCount(.{ .transition = effect }) != expected) @@ -783,6 +790,13 @@ pub const Runtime = struct { state.window_opacity = percent; state.window_opacity_pending = true; }, + .window_blur => { + const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); + for (text) |byte| if (!std.ascii.isDigit(byte)) return false; + const percent = std.fmt.parseInt(u8, text, 10) catch return false; + if (percent > 100) return false; + state.window_blur = percent; + }, .transition => |effect| state.toggleTransition(effect), .scene => |effect| switch (effect) { inline else => |field| { @@ -849,6 +863,12 @@ pub const Runtime = struct { else try out.print("{s}: unsupported\n", .{setting.word}); }, + .window_blur => { + if (setting.enabled(context.capabilities)) + try out.print("{s}: {d}%\n", .{ setting.word, state.window_blur }) + else + try out.print("{s}: unsupported\n", .{setting.word}); + }, .shell => { const chosen = state.shell.requested.get(); try out.print( @@ -947,7 +967,7 @@ pub const Runtime = struct { for (settings[i + 1 ..]) |later| try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); try std.testing.expectEqual(switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur => true, else => false, }, setting.takesArg()); } @@ -1011,6 +1031,22 @@ pub const Runtime = struct { try std.testing.expect(state.window_opacity_pending); } + test "window blur defaults off and validates without changing opacity" { + const setting = find("WindowBlur").?; + var state: Runtime = .{}; + try std.testing.expectEqual(@as(u8, 0), state.window_blur); + try std.testing.expectEqual(Capability.window_blur, setting.availability.?); + for ([_][]const u8{ "0", " 40\n", "100" }, [_]u8{ 0, 40, 100 }) |argument, expected| { + try std.testing.expect(apply(&state, setting, argument)); + try std.testing.expectEqual(expected, state.window_blur); + try std.testing.expectEqual(@as(u8, 100), state.window_opacity); + } + for ([_]?[]const u8{ null, "", " \t\n", "101", "-1", "+40", "40%", "0.5", "40 20", "4_0", "0x28", "999999999999999" }) |argument| { + try std.testing.expect(!apply(&state, setting, argument)); + try std.testing.expectEqual(@as(u8, 100), state.window_blur); + } + } + test "font request tuple rejects atomically" { var state: Runtime = .{}; try std.testing.expect(requestFont(&state, "/fonts/old.ttf", "Old", 1200)); @@ -1052,6 +1088,7 @@ pub const Runtime = struct { .scene_shaders = true, .tagline_font_size = true, .window_opacity = true, + .window_blur = true, }, .state = &state, }; @@ -1065,6 +1102,7 @@ pub const Runtime = struct { .shell => "fish", .tagline_size => "73", .window_opacity => "85", + .window_blur => "40", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1086,6 +1124,7 @@ pub const Runtime = struct { .shell => "Shell requested (new panes): fish\n", .tagline_size => "TaglineSize: 73%\n", .window_opacity => "WindowOpacity: 85% (pending)\n", + .window_blur => "WindowBlur: 40%\n", .transition => |transition| switch (transition) { .off => unreachable, .slide => "Panel transition: PanelSlide\n", @@ -1160,6 +1199,8 @@ pub const Runtime = struct { const defaults_report = storage[0..out.end]; try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowOpacity: unsupported\n") != null); try std.testing.expect(!find("WindowOpacity").?.enabled(defaults_context.capabilities)); + try std.testing.expect(std.mem.indexOf(u8, defaults_report, "WindowBlur: unsupported\n") != null); + try std.testing.expect(!find("WindowBlur").?.enabled(defaults_context.capabilities)); try std.testing.expect(find("WindowOpacity").?.enabled(context.capabilities)); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell requested (new panes): /bin/sh (default)\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Shell effective (last spawn): (none)\n") != null); diff --git a/src/macos.zig b/src/macos.zig index bbfb8c08..d0d379de 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -92,6 +92,7 @@ pub const Image = extern struct { iw: u32, ih: u32, rgba: [*]const u8, + paper_bg: u32, }; pub const Runtime = extern struct { @@ -902,6 +903,11 @@ export fn pardes_window_opacity() u8 { return st.core.settings.window_opacity; } +/// Public AppKit backdrop strength, independent of background paint opacity. +export fn pardes_window_blur() u8 { + return if (state) |st| st.core.settings.window_blur else 0; +} + fn taglineFontPercent(core: ?*const pardes.Pardes) u8 { return if (core) |p| p.settings.font.tagline_percent else pardes.config.gui_tagline_font_percent; } @@ -1879,6 +1885,10 @@ fn collectImages(st: *State, surface: *const pardes.Surface) void { .iw = @intCast(place.iw), .ih = @intCast(place.ih), .rgba = place.rgba.ptr, + .paper_bg = if (place.native.paper_bg) |bg| + @as(u32, bg[0]) << 16 | @as(u32, bg[1]) << 8 | bg[2] + else + color_default, }; st.images_len += 1; } @@ -2611,6 +2621,7 @@ test "pardes.h declares every export the way it is defined" { try expectSameAbi(@TypeOf(c.pardes_active_dirty), @TypeOf(pardes_active_dirty)); try expectSameAbi(@TypeOf(c.pardes_theme_bg), @TypeOf(pardes_theme_bg)); try expectSameAbi(@TypeOf(c.pardes_window_opacity), @TypeOf(pardes_window_opacity)); + try expectSameAbi(@TypeOf(c.pardes_window_blur), @TypeOf(pardes_window_blur)); } test "pardes.h matches the Zig boundary" { @@ -2941,3 +2952,21 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { try std.testing.expectEqual(@as(u8, 'G'), canonical[18].text[0]); try std.testing.expectEqual(encodeCell(.{}).len, canonical[10].len); } + +test "mac window blur builtin reaches the ABI without changing opacity" { + try std.testing.expectEqual(@as(u8, 0), pardes_window_blur()); + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 8, .rows = 3 }); + defer core.deinit(); + state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} }; + defer { + state.?.config_arena.deinit(); + state = null; + } + try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 71")); + for ([_][]const u8{ "WindowBlur 0", "WindowBlur 40", "WindowBlur 100", "WindowBlur 101", "WindowBlur 0" }, [_]u8{ 0, 40, 100, 100, 0 }) |command, expected| { + try std.testing.expect(core.executeBuiltinLine(0, command)); + try std.testing.expectEqual(expected, pardes_window_blur()); + try std.testing.expectEqual(@as(u8, 71), pardes_window_opacity()); + } +} diff --git a/src/macos/Sources/AppDelegate.swift b/src/macos/Sources/AppDelegate.swift index 4e91e407..cbe9cdc9 100644 --- a/src/macos/Sources/AppDelegate.swift +++ b/src/macos/Sources/AppDelegate.swift @@ -81,8 +81,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { // The grid and the blur are SIBLINGS in a plain container, not parent // and child. A transparent theme has to show something through the // grid, and AppKit will not blur what is behind a window unless an - // NSVisualEffectView asks it to — but the backdrop is hidden for every - // theme that brings its own background, and hiding a superview hides + // NSVisualEffectView asks it to. The backdrop can be hidden independently + // when blur is disabled or the ground is opaque; hiding a superview hides // its subviews with it. Nested, an opaque theme drew a blank window. let container = NSView(frame: NSRect(origin: .zero, size: want)) container.autoresizesSubviews = true @@ -460,6 +460,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { /// theme whose background happened to equal the view's starting guess /// would otherwise leave the window in AppKit's default clothes forever. private var dressed = false + private var appliedBlur: UInt8 = 0 private func applyTheme() { // Both reads happen every pump, and neither may be short-circuited by @@ -468,15 +469,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { // tick would leave one of them unworn. let themeChanged = view.adoptThemeBG(pardes_theme_bg()) let opacityChanged = view.adoptWindowOpacity(pardes_window_opacity()) - guard themeChanged || opacityChanged || !dressed else { return } + let blur = pardes_window_blur() + let blurChanged = blur != appliedBlur + guard themeChanged || opacityChanged || blurChanged || !dressed else { return } + appliedBlur = blur + backdrop.alphaValue = CGFloat(blur) / 100 + backdrop.isHidden = blur == 0 || (view.themeBG != nil && view.backgroundAlpha >= 1) dressed = true - // A ground short of solid needs the same non-opaque window a - // background-less theme does — but not the blur behind it. The backdrop - // answers "this theme brings no background"; WindowOpacity says how - // much of the one it brings to paint, and what shows through the rest - // is the desktop, which is what asking for a translucent window means. + // Opacity paints the theme ground; blur controls the native material + // behind it. An opaque ground hides the backdrop without losing the + // requested strength, so lowering opacity restores the effect. if let rgb = view.themeBG { - backdrop.isHidden = true window.isOpaque = view.backgroundAlpha >= 1 window.backgroundColor = view.backgroundAlpha < 1 ? .clear : NSColor( srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, @@ -493,10 +496,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { window.appearance = NSAppearance(named: luma > 0.5 ? .aqua : .darkAqua) } else { // Transparent: the window stops painting anything of its own and - // the blur takes over. isOpaque false is what lets the desktop + // the optional blur sits behind it. isOpaque false lets the desktop // reach the backdrop at all — a titled window is opaque by default // and would composite over it. - backdrop.isHidden = false window.isOpaque = false window.backgroundColor = .clear window.appearance = NSAppearance(named: .darkAqua) diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 7c537055..7981cf46 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -1446,6 +1446,7 @@ final class PardesView: NSView { let source: CGRect let body: CGRect let destination: CGRect + let paperBG: UInt32 } /// Rasterized attachments, decoded once each. The bytes the core lends are @@ -1496,7 +1497,7 @@ final class PardesView: NSView { height: CGFloat(place.dst_h) / scale) let frozen = FrozenImage( key: key, image: crop, source: source, - body: body, destination: dst) + body: body, destination: dst, paperBG: place.paper_bg) frameImages.append(frozen) drawFrozenImage(ctx, frozen) } @@ -1545,11 +1546,24 @@ final class PardesView: NSView { ctx.clip(to: placed.body) // isFlipped gives us a y-down CTM and CGImage draws +y up, so flip // about this destination rather than changing the grid arithmetic. + let isPDF = placed.paperBG != UInt32(PARDES_COLOR_DEFAULT) + if isPDF { + fillBackground(ctx, placed.destination, placed.paperBG, backgroundAlpha) + } ctx.translateBy(x: placed.destination.minX, y: placed.destination.maxY) ctx.scaleBy(x: 1, y: -1) ctx.interpolationQuality = .high let rect = CGRect(x: 0, y: 0, width: placed.destination.width, height: placed.destination.height) + if isPDF { + // Paper was painted at WindowOpacity. Content keeps the PDF's own + // coverage, so glyphs, photos and paths stay legible at zero opacity. + ctx.setAlpha(1) + ctx.setBlendMode(.normal) + ctx.draw(placed.image, in: rect) + ctx.restoreGState() + return + } // Match image.frag.glsl/backgroundLayerBlend: source coverage removes // the destination independently of WindowOpacity, then the source is // added at that opacity. Ordinary source-over would compound alpha; diff --git a/src/macos/pardes.h b/src/macos/pardes.h index a2e34f53..df3ba04f 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -262,6 +262,8 @@ uint32_t pardes_theme_bg(void); // Read it once per pump beside pardes_theme_bg(): reading also acknowledges // whatever `WindowOpacity` asked for. 100 is opaque and is the default. uint8_t pardes_window_opacity(void); +// Backdrop material strength, 0..100; zero disables blur. Not a pixel radius. +uint8_t pardes_window_blur(void); // Pane taglines use this percentage of the current body font size. It is the // embedded default before init and the live core setting afterwards; the host @@ -475,6 +477,8 @@ typedef struct { uint32_t ih; // iw * ih * 4 bytes, RGBA8, borrowed until the next pardes_frame const uint8_t *rgba; + // PDF paper RGB; PARDES_COLOR_DEFAULT means an ordinary image. + uint32_t paper_bg; } pardes_image_s; // This frame's attachments, in paint order. Ask after pardes_frame; both are diff --git a/src/panes.zig b/src/panes.zig index 93abae30..49e5d624 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -4577,13 +4577,14 @@ pub const Pdf = struct { { const tz_render = tracy.zone(@src(), "pdf.render_into"); defer tz_render.end(); - state.document.renderIntoAt( + state.document.renderIntoAtWithPaper( page, request, shape, want, page_highlights, fresh, + pardes.platform == .macos, ) catch break :filled false; } const tz_tint = tracy.zone(@src(), "pdf.tint"); @@ -5852,6 +5853,10 @@ pub const Pdf = struct { .pan_x = placed.pan_x, .geometry = placed.geometry, .pixel_offset_y = placed.pixel_offset_y, + .paper_bg = if (pardes.platform == .macos) + (if (key.mode == .disabled) .{ 255, 255, 255 } else key.colors.background) + else + null, }, .x = text_x, .y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H, diff --git a/src/pardes.zig b/src/pardes.zig index 94f67ced..5c0ac263 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3593,6 +3593,8 @@ pub const NativePlacement = if (pdf_enabled) struct { geometry: ?image.NativeGeometry = null, /// Subpixel vertical displacement retained from proportional SDL wheel dy. pixel_offset_y: f32 = 0, + /// Separate paper behind straight-alpha PDF content; null for other images. + paper_bg: ?[3]u8 = null, } else struct {}; pub const ImagePlace = struct { diff --git a/src/pdf.zig b/src/pdf.zig index 052d34db..712750dc 100644 --- a/src/pdf.zig +++ b/src/pdf.zig @@ -975,6 +975,20 @@ pub const Document = struct { band: Raster.Band, highlights: []const Highlight, rgba: []u8, + ) !void { + return document.renderIntoAtWithPaper(page, request, raster, band, highlights, rgba, false); + } + + /// Preserve the PDF's content coverage when the host paints paper separately. + pub fn renderIntoAtWithPaper( + document: *Document, + page: usize, + request: RenderRequest, + raster: Raster, + band: Raster.Band, + highlights: []const Highlight, + rgba: []u8, + transparent_paper: bool, ) !void { if (rgba.len != band.len) return error.BadPixmap; if (band.height == 0 or band.y + band.height > raster.height) @@ -999,6 +1013,7 @@ pub const Document = struct { @intCast(raster.stride), @intCast(band.y), @intCast(band.height), + @intFromBool(transparent_paper), ) != c.PARDES_PDF_OK) return error.RenderFailed; } @@ -1832,6 +1847,7 @@ test "RGBA allocation and buffer-validation failures leave the document renderab raw_layout.stride, 0, raw_layout.height, + 0, )); for (scratch) |byte| try std.testing.expectEqual(@as(u8, 0xa5), byte); @@ -2074,3 +2090,35 @@ test "offset crop and rotation keep normalized highlights pixel-aligned" { marked.rgba[left + 1] < 10 and marked.rgba[left + 2] > 240); try std.testing.expectEqualSlices(u8, plain.rgba[right .. right + 4], marked.rgba[right .. right + 4]); } + +test "transparent PDF paper preserves ink and band coverage" { + var document = try Document.open("docs/9p.pdf"); + defer document.deinit(); + const request: RenderRequest = .{ .dpi = 96, .max_dimension = 1200 }; + const raster = try document.measureRenderAt(0, request); + const flattened = try std.testing.allocator.alloc(u8, raster.len); + defer std.testing.allocator.free(flattened); + const content = try std.testing.allocator.alloc(u8, raster.len); + defer std.testing.allocator.free(content); + try document.renderIntoAt(0, request, raster, raster.wholePage(), &.{}, flattened); + try document.renderIntoAtWithPaper(0, request, raster, raster.wholePage(), &.{}, content, true); + var paper: usize = 0; + var ink: usize = 0; + var edges: usize = 0; + for (std.mem.bytesAsSlice([4]u8, content), std.mem.bytesAsSlice([4]u8, flattened)) |pixel, reference| { + const a: u32 = pixel[3]; + paper += @intFromBool(a == 0); + ink += @intFromBool(a == 255); + edges += @intFromBool(a > 0 and a < 255); + for (0..3) |channel| { + const over_white = (a * pixel[channel] + (255 - a) * 255 + 127) / 255; + try std.testing.expect(@abs(@as(i32, @intCast(over_white)) - @as(i32, reference[channel])) <= 2); + } + } + try std.testing.expect(paper > 100 and ink > 100 and edges > 100); + const band = raster.band(raster.height / 3, raster.height / 4); + const rows = try std.testing.allocator.alloc(u8, band.len); + defer std.testing.allocator.free(rows); + try document.renderIntoAtWithPaper(0, request, raster, band, &.{}, rows, true); + try std.testing.expectEqualSlices(u8, content[band.y * raster.stride ..][0..band.len], rows); +} diff --git a/src/pdf_bridge.c b/src/pdf_bridge.c index bdc7b891..976ed838 100644 --- a/src/pdf_bridge.c +++ b/src/pdf_bridge.c @@ -588,7 +588,8 @@ pardes_pdf_render_into( int height, int stride, int band_y, - int band_height) + int band_height, + int transparent_paper) { fz_context *ctx; fz_pixmap *pixmap = NULL; @@ -654,7 +655,8 @@ pardes_pdf_render_into( * paid either way by the glyph spans and the tint pass that walk the * same buffer immediately afterwards. Leave it alone. */ - fz_clear_pixmap_with_value(ctx, pixmap, 0xFF); + if (transparent_paper) fz_clear_pixmap(ctx, pixmap); + else fz_clear_pixmap_with_value(ctx, pixmap, 0xFF); if (document->cached_display_list != NULL || document->display_list_candidate_page_number == page_number) { @@ -719,6 +721,21 @@ pardes_pdf_render_into( return PARDES_PDF_ERROR; } + /* MuPDF draws premultiplied samples. The public RGBA contract and tint + * pass use straight alpha; preserve coverage and undo premultiplication. */ + if (transparent_paper) { + size_t pixel; + for (pixel = 0; pixel < samples_len; pixel += 4) { + unsigned int a = samples[pixel + 3]; + int channel; + if (a == 0 || a == 255) continue; + for (channel = 0; channel < 3; ++channel) { + unsigned int straight = (samples[pixel + channel] * 255u + a / 2) / a; + samples[pixel + channel] = (unsigned char)(straight > 255 ? 255 : straight); + } + } + } + if (document->cached_display_list == NULL) document->display_list_candidate_page_number = page_number; diff --git a/src/pdf_bridge.h b/src/pdf_bridge.h index 8c73f688..cda426aa 100644 --- a/src/pdf_bridge.h +++ b/src/pdf_bridge.h @@ -220,7 +220,8 @@ int pardes_pdf_measure_render( * A full page is the band `(0, height)`. * * MuPDF wraps but never owns or frees samples. Every successful pixel is - * opaque, including the caller-supplied highlights composited onto the page. + * opaque unless transparent_paper is nonzero. That mode preserves content + * coverage and returns straight-alpha RGBA over an unpainted page. * The CTM does not depend on the band, so a band's rows are bit-identical to * the same rows of the whole page: it is a clip, not a different rendering. */ @@ -239,7 +240,8 @@ int pardes_pdf_render_into( int height, int stride, int band_y, - int band_height + int band_height, + int transparent_paper ); int pardes_pdf_page_text( diff --git a/test/macos-snapshots/rendering-parity.golden b/test/macos-snapshots/rendering-parity.golden index 536f6800..cbb56ab2 100644 --- a/test/macos-snapshots/rendering-parity.golden +++ b/test/macos-snapshots/rendering-parity.golden @@ -5,10 +5,10 @@ == backgrounds invalid-stays-0 uniform == context context-100 compact separators verified == context context-71 compact separators verified -== pdf pdf-100 native page opacity verified -== pdf pdf-0 native page opacity verified -== pdf pdf-71 native page opacity verified -== pdf pdf-fit-height native page opacity verified -== pdf pdf-full-tint native page opacity verified -== pdf pdf-original-colors native page opacity verified -== pdf pdf-scrolled native page opacity verified +== pdf pdf-100 paper opacity and opaque ink verified +== pdf pdf-0 paper opacity and opaque ink verified +== pdf pdf-71 paper opacity and opaque ink verified +== pdf pdf-fit-height paper opacity and opaque ink verified +== pdf pdf-full-tint paper opacity and opaque ink verified +== pdf pdf-original-colors paper opacity and opaque ink verified +== pdf pdf-scrolled paper opacity and opaque ink verified diff --git a/test/macos_e2e.swift b/test/macos_e2e.swift index 5427c3ad..5efc366c 100644 --- a/test/macos_e2e.swift +++ b/test/macos_e2e.swift @@ -687,13 +687,22 @@ private final class Driver: PardesViewDelegate { throw ScriptError(message: "PDF: placement is outside its physical-pixel viewport") } let backing = CGFloat(rep.pixelsWide) / view.bounds.width - var matched = 0 - for fraction in [CGFloat(0.2), 0.4, 0.6, 0.8] { - if let c = rep.colorAt(x: Int((x + width * fraction) * backing), - y: Int((y + height * fraction) * backing)), abs(c.alphaComponent - view.backgroundAlpha) < 2.0 / 255 { matched += 1 } + guard image.paper_bg != UInt32(PARDES_COLOR_DEFAULT) else { + throw ScriptError(message: "PDF: missing separate paper background") } - guard matched == 4 else { throw ScriptError(message: "PDF: raster opacity does not match WindowOpacity") } - output += "== pdf \(label) native page opacity verified\n" + var lowest: CGFloat = 1, highest: CGFloat = 0 + for py in stride(from: Int(y * backing) + 2, to: Int((y + height) * backing) - 2, by: 2) { + for px in stride(from: Int(x * backing) + 2, to: Int((x + width) * backing) - 2, by: 2) { + if let c = rep.colorAt(x: px, y: py) { + lowest = min(lowest, c.alphaComponent) + highest = max(highest, c.alphaComponent) + } + } + } + guard abs(lowest - view.backgroundAlpha) < 2.0 / 255, highest > 0.98 else { + throw ScriptError(message: "PDF: expected translucent paper and opaque ink, got alpha \(lowest)...\(highest)") + } + output += "== pdf \(label) paper opacity and opaque ink verified\n" } // MARK: - the script -- cgit v1.3 From 44ce573e15c773cf5bb0d42941a143b63e44d900 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 21 Sep 2026 14:55:53 -0300 Subject: Make the macOS shell a first-class host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pty children are exec'd with their own TERM/COLORTERM/TERM_PROGRAM instead of inheriting a .app launch's empty environment, and ttyTaken finally answers on darwin — libproc walks the tty's foreground process group — so Escape reaches the child and Exec stops believing every pane sits at its prompt. The occupancy suite runs on both platforms now. The workspace tag row moves into the native menu bar as a Builtins menu. -Dworkspace-tag (default off for -Dplatform=macos, on everywhere else) drives it, and Pardes.topBarHeight replaces the TOPBAR_H constant so the core stops reserving the row. The view pins every variable-font axis to the file's own default (Maple Mono came up Thin otherwise), shapes ligatures, carries per-shape pointer cursors, and draws the look-hover affordance as refracted glass. Tag rows fill edge to edge, with the anchor box painted back on top of that fill and its mode glyph centred on the same square. Theme accents re-saturated across the set. Co-Authored-By: Claude Opus 5 (1M context) --- build.zig | 8 + docs/config.md | 1 + docs/macos.md | 38 +++- src/CHANGELOG.md | 12 ++ src/config.zig | 15 ++ src/gui/gui.zig | 22 +- src/host_io.zig | 320 +++++++++++++++++++++++++--- src/layout.zig | 8 +- src/macos.zig | 58 ++++-- src/macos/Sources/AppDelegate.swift | 18 +- src/macos/Sources/PardesView.swift | 406 +++++++++++++++++++++++++++++++++--- src/macos/pardes.h | 12 +- src/pardes.zig | 149 ++++++++----- src/themes/acme.zig | 8 +- src/themes/atelier.zig | 32 +-- src/themes/clay.zig | 32 +-- src/themes/dark.zig | 12 +- src/themes/daybreak.zig | 28 +-- src/themes/dusk.zig | 32 +-- src/themes/forge.zig | 28 +-- src/themes/forge_black.zig | 28 +-- src/themes/forge_soft.zig | 28 +-- src/themes/harvest.zig | 32 +-- src/themes/helix.zig | 6 +- src/themes/ink.zig | 18 +- src/themes/lagoon.zig | 24 +-- src/themes/orchard.zig | 32 +-- src/themes/orchard_black.zig | 32 +-- src/themes/paper.zig | 32 +-- src/themes/solarium.zig | 32 +-- src/themes/spectrum.zig | 22 +- src/web.zig | 2 +- test/macos_e2e.swift | 10 +- 33 files changed, 1160 insertions(+), 377 deletions(-) (limited to 'src/macos/Sources') diff --git a/build.zig b/build.zig index 6734d9b0..0cd7f312 100644 --- a/build.zig +++ b/build.zig @@ -301,6 +301,9 @@ pub fn build(b: *std.Build) void { const esp32p4_cols = b.option(u16, "esp32p4-cols", "the board's grid width in cells (-Dplatform=esp32p4 only)") orelse 56; const esp32p4_rows = b.option(u16, "esp32p4-rows", "the board's grid height in cells (-Dplatform=esp32p4 only)") orelse 14; const theme_animation = b.option(bool, "theme-animation", "animate chrome colors across a theme change (default: off for esp32p4)"); + // The macOS shell carries the workspace tag row's commands in its native + // menu bar; the row itself goes away. `-Dworkspace-tag=true` puts it back. + const workspace_tag = b.option(bool, "workspace-tag", "draw the workspace tag row (default: on except on macOS, whose menu bar carries its commands)"); const shell_cfg: ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, .tracy = tracy != null, @@ -309,6 +312,7 @@ pub fn build(b: *std.Build) void { .esp32p4_cols = esp32p4_cols, .esp32p4_rows = esp32p4_rows, .theme_animation = theme_animation, + .workspace_tag = workspace_tag, .prebuilt_shaders = prebuilt_shaders, .embed_sources = embed_sources, .zig_lib_dir = b.graph.zig_lib_directory.path orelse "", @@ -1434,6 +1438,9 @@ const ShellConfig = struct { /// null = "the platform's own default", resolved per shell below, because /// the default is off for the board and on everywhere else. theme_animation: ?bool, + /// null = "the platform's own default": the macOS shell hands the row to + /// its native menu bar, every other shell keeps the acme topbar. + workspace_tag: ?bool, prebuilt_shaders: bool, embed_sources: bool, zig_lib_dir: []const u8, @@ -1452,6 +1459,7 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. o.addOption(bool, "mupdf", cfg.mupdf); o.addOption(u16, "esp32p4_cols", cfg.esp32p4_cols); o.addOption(u16, "esp32p4_rows", cfg.esp32p4_rows); + o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); o.addOption(bool, "theme_animation", cfg.theme_animation orelse (platform != .esp32p4)); // Meaningful only for the SDL shell. Keeping the platform condition here // prevents Config/EffectCode from describing tty/macOS/web as "prebuilt". diff --git a/docs/config.md b/docs/config.md index a55aef1c..a229830b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -538,6 +538,7 @@ including the standard `-Dtarget` and `-Doptimize` options. | `-Djpx` | bool | `true` — JPEG 2000, and with it scanned PDFs | | `-Dtree-sitter` | `disabled`, `zig`, `minimal`, `full` | `full` natively, `zig` for web, `disabled` for esp32p4 | | `-Dtheme-animation` | bool | on everywhere except `-Dplatform=esp32p4` | +| `-Dworkspace-tag` | bool; draw the workspace tag row — the macOS shell hands its commands to the native menu bar instead | on except on `-Dplatform=macos` | | `-Dprebuilt-shaders` | bool | on for a bare `zig build`, off when `-Dplatform` names a shell | | `-Dtracy` | path to a Tracy source checkout | off | | `-Dmacos-identity` | codesigning identity for `pardes.app` | `-` (ad-hoc) | diff --git a/docs/macos.md b/docs/macos.md index 9190ca67..e104d3a6 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -369,6 +369,14 @@ second spelling of builtins — `AppDelegate` calls `run("New")`, `run("Save")`, `run("Help")`, `run("Tutor")` — and the items with no builtin behind them are left out rather than stubbed. +The workspace tag row — the topmost tagline, the one carrying `Newcol Joincol +Find Grep …` — is not drawn on this shell. `-Dworkspace-tag` (default off for +`-Dplatform=macos`, on everywhere else) hands the row to the menu bar: the +core stops reserving the row (`Pardes.topBarHeight`), the grid starts at the +column tags, and the row's commands live in a **Builtins** menu instead. The +items are the tag's own words, spelled exactly as a tag Exec would type them, +and nothing in that menu is editable — it is the tag's buttons, not the tag: + | menu | item | chord | what it does | |---|---|---|---| | pardes | About pardes | — | AppKit's panel | @@ -378,6 +386,7 @@ left out rather than stubbed. | | New | ⌘N | the `New` builtin | | | Save | ⌘S | the `Save` builtin | | | Close Window | ⌘W | AppKit; the app terminates after the last one | +| Builtins | Newcol / Joincol / Find / Grep / Changelog / Dump / NextColor / Debug / Kill | — | the workspace tag's own builtins, `run(word)` | | Edit | Paste | ⌘V | the view's own paste path, not a second one | | View | Zoom In / Zoom Out / Actual Size | ⌘= / ⌘- / ⌘0 | point size, host-side | | Window | Minimize / Zoom | ⌘M / — | AppKit | @@ -455,6 +464,32 @@ Nested launches use the same inherited 9P address and pane serial as other native hosts. They do not inspect ancestor processes or executable names. See [the control filesystem](fs.md) for paths and transports. +Two more things this host cannot inherit from its launcher, because a `.app` +has none: + +- **The terminal's identity.** `host_io.ChildEnv` writes `TERM`, `COLORTERM` + and `TERM_PROGRAM` over whatever the environment carried and the child is + `execve`'d with that array — built before the fork, because a `setenv` + between fork and exec can deadlock on the heap a pty reader thread was + holding. Every pane is emulated by the bundled VT, so the value describes + pardes and never the terminal pardes was started from; `-Dplatform=gui` and + the tty shell take the same path, where the difference is only that their + launcher usually happened to set something. The names come from + `config.child_term` / `child_colorterm` / `child_term_program`, and `TERM` + is deliberately `xterm-256color` rather than a name with no installed + terminfo entry — `clear`, colour and cursor addressing all resolve through + that lookup. +- **Whether a program has the terminal.** `host_io.ttyTaken` is what + `Pardes.takesCommandLine` asks before deciding that Escape is the `Last` + builtin rather than a keystroke for the child, and what `Exec` asks before + believing a pane is at its prompt. Linux descends `/proc//task// + children`; darwin has neither that nor a children list, so it enumerates the + tty's foreground process group with `proc_listpids(PROC_PGRP_ONLY)` and + compares each member's `proc_pidpath` against the shell's own. A nested + interactive shell is therefore still a prompt, and `bash -c 'sleep 30'` is + still taken — the wrapper wears the shell's binary, but `sleep` shares its + group. The occupancy suite in `src/host_io.zig` runs on both platforms. + ## Fonts and zoom The face is the shell's business and the size is the window's, so the two are @@ -1109,9 +1144,6 @@ used for the table and is not folded into the direct-path claim. says nothing either. Wiring it up means a unix-socket frontend loop beside the AppKit one, which is `src/detached/client.zig`'s job in the tty and SDL shells; see `docs/detached.md`. -- **`tty_taken` on darwin.** The pull is wired (`ttyTaken`, `src/macos.zig:1838`) - but `look.ttyTaken` has no libproc implementation and answers `false`, so an - `Exec` here always believes the pane is still at the prompt it forked. - **IME and marked text.** Only finished characters reach `pardes_key`, so a dead key composes nothing and Option is Alt rather than a compose modifier. Real composition means implementing `NSTextInputClient` *and* giving the core diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 18bcceb9..e518f97a 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,18 @@ ## 0.0.3 +- Give pty children their own terminal identity. `TERM`, `COLORTERM` and + `TERM_PROGRAM` are now written by pardes rather than inherited from whatever + launched it, and the child is exec'd with that environment. A macOS `.app` + launch supplies no `TERM` at all, so until now `clear` failed, nothing + painted a colour, and every cursor-addressing program fell back to printing + lines. +- Answer tty occupancy on macOS. `ttyTaken` had no darwin implementation and + said `false` for every pane, which made `Pardes.takesCommandLine` permanently + true: a bare Escape in a raw terminal ran the `Last` builtin instead of + reaching the child, and `Exec` always believed the pane sat at its prompt. + libproc answers it from the tty's foreground process group, and the + occupancy suite now runs on both platforms instead of only Linux. - Flatten the 9P control tree: `self/` is gone, so `/index`, `/pane//`, `/screen` and `/os` sit at the root. `/new` is one clone file (reading it makes a pane and answers its serial), `/ctl` takes `look TEXT` and diff --git a/src/config.zig b/src/config.zig index 440549b3..da23f51f 100644 --- a/src/config.zig +++ b/src/config.zig @@ -222,6 +222,17 @@ pub const tty_blank: enum { prompt, prompt_and_input } = .prompt; // Projected colors below this contrast use the theme's more legible anchor. pub const tty_filter_min_contrast: f64 = 1.5; +// What a pty child is told it is talking to. Every pane is emulated by the +// bundled VT, so this describes pardes and never the terminal pardes itself +// was launched from — the child inherits the launcher's TERM otherwise, which +// under a macOS .app launch is no TERM at all, and `clear`, colour and every +// cursor-addressing program fail at the terminfo lookup. There is no installed +// `xterm-ghostty` entry to name, and a name with no entry is worse than a +// conservative one that every system ships. +pub const child_term = "xterm-256color"; +pub const child_colorterm = "truecolor"; +pub const child_term_program = "pardes"; + pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill"; pub const pane_builtins_str = "Tty Del Collapse"; @@ -538,6 +549,10 @@ pub const Runtime = struct { tree_context_tag_style: bool = true, debug: bool = false, focus_tint: bool = true, + /// The workspace tag row. Native shells with their own chrome (the macOS + /// menu bar) turn it off and carry its commands there instead; the core + /// keeps the row as the acme tradition everywhere else. + workspace_tag: bool = true, column_tags: bool = true, syntax_bold: bool = false, window_opacity: u8 = 100, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 27f3346c..d871e55e 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -5290,10 +5290,12 @@ test "tagline bands face the topbar rule and Tagbottom faces the window edge" { const canvas_h: f32 = 200; const border = topbarPaneBorderPixels(cell_h, tagline_h); try std.testing.expectEqual(@as(u32, 1), border); - try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(0, canvas_h, cell_h, tagline_h)); - try std.testing.expectEqual(@as(u32, 1), taglineBandOffset(1, canvas_h, cell_h, tagline_h)); - try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(5, canvas_h, cell_h, tagline_h)); - try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(9, canvas_h, cell_h, tagline_h)); + try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(0, canvas_h, cell_h, tagline_h, true)); + try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(0, canvas_h, cell_h, tagline_h, false)); + try std.testing.expectEqual(@as(u32, 1), taglineBandOffset(1, canvas_h, cell_h, tagline_h, true)); + try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(1, canvas_h, cell_h, tagline_h, false)); + try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(5, canvas_h, cell_h, tagline_h, true)); + try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(9, canvas_h, cell_h, tagline_h, true)); } fn resolveCell(g: *Gui, cell: *const pardes.Cell, role: pardes.FontRole, is_cursor: bool, page: Ground) ResolvedCell { @@ -5486,7 +5488,7 @@ fn emitBodyLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const if (left + @as(f32, @floatFromInt(col)) * width >= right) break; const cell = &layer.cells[index * layer.cols + col]; const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == row else false; - const glyph_top = top - (if (header) @as(f32, @floatFromInt(taglineBandOffset(0, win_h, g.cell_h, g.tagline_height))) else 0); + const glyph_top = top - (if (header) @as(f32, @floatFromInt(taglineBandOffset(0, win_h, g.cell_h, g.tagline_height, true))) else 0); emitInstance(g, instances, next.*, 0, 0, .{ .w = width, .h = height, .x_off = left + @as(f32, @floatFromInt(col)) * width, .y_off = glyph_top }, win_w, win_h, track, role, cell, old_layer, cursor, page); clipBodyInstance(&instances[next.*], bottom, win_h); clipInstanceRight(&instances[next.*], right, win_w); @@ -5638,7 +5640,7 @@ fn emitInstance( else layout.h; const band_offset: f32 = if (resolved.role == .tagline) - @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height)) + @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height, true)) else 0; const py0 = layout.y_off + @as(f32, @floatFromInt(row)) * layout.h + band_offset; @@ -6448,7 +6450,7 @@ fn addCursorBar( const x0 = layout.x_off + @as(f32, @floatFromInt(x)) * layout.w; const height = std.math.clamp(visual_height, 1.0, layout.h); const y0 = layout.y_off + @as(f32, @floatFromInt(y)) * layout.h + - @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, @intFromFloat(layout.h), @intFromFloat(height)))); + @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, @intFromFloat(layout.h), @intFromFloat(height), true))); builder.addRect( x0, y0, @@ -6548,7 +6550,7 @@ fn buildOverlay( const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; const x = left + @as(f32, @floatFromInt(cursor.col)) * width; if (x >= right) continue; - const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(layer.viewport.y, builder.win_h, g.cell_h, g.tagline_height))); + const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(layer.viewport.y, builder.win_h, g.cell_h, g.tagline_height, true))); builder.addRect(x, top, @min(right, x + @max(1, width / 8)), top + @as(f32, @floatFromInt(g.tagline_height)), overlayRgb(cursorColor(core, &layer.cells[cursor.col], .tagline))); }; if (transient_on) appendTouchOverlay(g, &builder, debug_on); @@ -6569,7 +6571,7 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard if (cellCodepoint(cell) != ' ') occupied = i + 1; } const editing = p.topbar_col != null and p.header_column == null; - const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); + const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height, true)); const region = if (occupied >= surface.cols) null else pet.lane( occupied, @floatFromInt(g.tagline_width), @@ -6741,7 +6743,7 @@ fn appendTagGrips(g: *const Gui, surface: *const pardes.Surface, layout: CellLay else => continue, }; const center_x = (@as(f32, @floatFromInt(x)) + @as(f32, @floatFromInt(config.GUTTER)) / 2) * layout.w; - const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; + const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, g.cell_h, g.tagline_height, true))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; const half_w = @max(1, @min(3, layout.w - 2)); builder.addRect(@floor(center_x - half_w), @floor(center_y - 2), @floor(center_x + half_w), @floor(center_y - 1), overlayRgb(rgb)); builder.addRect(@floor(center_x - half_w), @floor(center_y + 1), @floor(center_x + half_w), @floor(center_y + 2), overlayRgb(rgb)); diff --git a/src/host_io.zig b/src/host_io.zig index 212c23b4..55592957 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -837,6 +837,7 @@ pub const Shell = struct { extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; extern "c" fn chdir(path: [*:0]const u8) c_int; extern "c" fn _exit(status: c_int) noreturn; @@ -845,6 +846,100 @@ pub const Child = struct { pid: posix.pid_t, }; +/// The environment a pty child is handed: everything this process carries, +/// with the terminal's own identity written over whatever the launcher left +/// behind. The child is talking to the bundled VT, never to the terminal +/// pardes itself was started from, and a macOS `.app` launch supplies no +/// `TERM` at all — which is exactly why `clear` fails there, why nothing +/// paints a colour, and why every cursor-addressing program falls back to a +/// dumb line-at-a-time mode. +pub const ChildEnv = struct { + /// Entries pardes owns. The name of each is read back out of its own + /// spelling, so there is one place to edit and no second list to drift. + const own = [_][*:0]const u8{ + "TERM=" ++ pardes.config.child_term, + "COLORTERM=" ++ pardes.config.child_colorterm, + "TERM_PROGRAM=" ++ pardes.config.child_term_program, + }; + + /// Wide enough for any real environment; `build` answers null rather than + /// truncate, because a child missing half its variables is a worse bug + /// than one missing TERM, and the caller then execs with `environ` intact. + pub const Slots = [1024]?[*:0]const u8; + + fn name(entry: [*:0]const u8) []const u8 { + const line = std.mem.span(entry); + return line[0 .. std.mem.indexOfScalar(u8, line, '=') orelse line.len]; + } + + pub fn build(slots: *Slots) ?[*:null]const ?[*:0]const u8 { + var n: usize = 0; + var i: usize = 0; + while (libc.environ[i]) |entry| : (i += 1) { + const inherited = name(entry); + const shadowed = for (own) |mine| { + if (std.mem.eql(u8, inherited, name(mine))) break true; + } else false; + if (shadowed) continue; + if (n + own.len + 1 > slots.len) return null; + slots[n] = entry; + n += 1; + } + for (own) |mine| { + slots[n] = mine; + n += 1; + } + slots[n] = null; + return @ptrCast(slots); + } +}; + +test "the child environment replaces the launcher's terminal identity exactly once" { + const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + if (t.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..t.len], t); + saved_buf[t.len] = 0; + break :blk saved_buf[0..t.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = unsetenv("TERM"); + }; + + // A launcher TERM must be shadowed rather than duplicated, and the rest of + // the environment must arrive untouched. + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); + defer _ = unsetenv("PARDES_CHILD_ENV_PROBE"); + + var slots: ChildEnv.Slots = undefined; + const envp = ChildEnv.build(&slots) orelse return error.EnvironmentTooLarge; + var terms: usize = 0; + var colorterms: usize = 0; + var probes: usize = 0; + var dumb = false; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) { + const line = std.mem.span(entry); + if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; + if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; + if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; + if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; + } + try std.testing.expectEqual(@as(usize, 1), terms); + try std.testing.expectEqual(@as(usize, 1), colorterms); + try std.testing.expectEqual(@as(usize, 1), probes); + try std.testing.expect(!dumb); + // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it + // is a separate entry and never a second TERM. + try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); +} + +extern "c" fn unsetenv(name: [*:0]const u8) c_int; + pub fn forkShell( core: ?*pardes.Pardes, pane: usize, @@ -888,6 +983,11 @@ pub fn forkShell( try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); if (!try pardes.panes.Terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } + // Built here and not after the fork: between fork and exec the child may + // not call setenv, whose malloc can deadlock against a pty reader thread + // that held the heap when the fork took its snapshot. + var env_slots: ChildEnv.Slots = undefined; + const envp = ChildEnv.build(&env_slots); const ws = posix.winsize{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; const pid = forkpty(&master, null, null, &ws); if (pid < 0) return error.ForkFailed; @@ -896,6 +996,7 @@ pub fn forkShell( posix.sigaddset(&set, posix.SIG.WINCH); posix.sigprocmask(posix.SIG.UNBLOCK, &set, null); if (cwd_z) |path| if (chdir(path.ptr) != 0) _exit(126); + if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); _ = execv(spawn.path, &spawn.argv); _exit(127); } @@ -925,6 +1026,42 @@ test "shell spawn rejects invalid directories before creating a child" { try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80, null)); } +test "a forked shell is told which terminal it is talking to" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + // Whatever launched the test is the wrong answer, so make it a loud one. + const saved = libc.getenv("TERM"); + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + const span = std.mem.span(t); + if (span.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..span.len], span); + saved_buf[span.len] = 0; + break :blk saved_buf[0..span.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = unsetenv("TERM"); + }; + _ = Shell.setenv("TERM", "dumb", 1); + + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80, null); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + // The echoed command carries the unexpanded `$TERM`, so only the shell's + // own expansion can match this. + try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); + try std.testing.expect(sh.waitText( + "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, + 5_000, + )); +} + test "shell spawn uses an explicit OS directory longer than 256 bytes" { if (!haveFile("/bin/sh")) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); @@ -1031,6 +1168,14 @@ extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; const occ_max_depth: u8 = 8; const occ_max_visited: usize = 32; +/// Where `ttyTaken` answers from evidence rather than from `false`. The two +/// implementations are different walks over the same question, so they share +/// one suite rather than each asserting half of it. +const tty_probe_platform = switch (builtin.os.tag) { + .linux, .macos => true, + else => false, +}; + const TtyProbe = struct { self_exe: [std.fs.max_path_bytes]u8 = undefined, exe: [std.fs.max_path_bytes]u8 = undefined, @@ -1085,10 +1230,94 @@ pub fn ttyTaken(shell_pid: libc.pid_t, master_fd: c_int) bool { } return !saw_fg; }, + .macos => { + const fg = tcgetpgrp(master_fd); + if (fg <= 0) return false; + if (fg == shell_pid) return false; + return darwin.taken(shell_pid, fg); + }, else => return false, } } +/// The same question the Linux walk asks, answered the way macOS can answer +/// it. There is no /proc to descend and no children list, but the tty's +/// foreground process group can be enumerated in one call — and "is anything +/// but the shell itself holding this terminal?" is exactly a statement about +/// the executables in that group. The test is the shell's own executable and +/// never its pid, which is what keeps a nested interactive shell a prompt, +/// and what still catches `bash -c 'sleep 30'`: the group holds `sleep` too. +/// +/// Until this existed, `ttyTaken` answered `false` on darwin for every pane, +/// so `Pardes.takesCommandLine` was permanently true and every bare Escape in +/// a raw terminal ran the `Last` builtin instead of reaching the child. +const darwin = struct { + const proc_pgrp_only: u32 = 2; + const proc_pidt_shortbsdinfo: c_int = 13; + const zombie_status: u32 = 5; // SZOMB + /// PROC_PIDPATHINFO_MAXSIZE. + const path_max = 4 * 1024; + /// A foreground group is a pipeline; anything larger is not a prompt. + const group_max = 64; + + const ShortBsdInfo = extern struct { + pid: u32, + ppid: u32, + pgid: u32, + status: u32, + comm: [16]u8, + flags: u32, + uid: u32, + gid: u32, + ruid: u32, + rgid: u32, + svuid: u32, + svgid: u32, + rfu: u32, + }; + + extern "c" fn proc_listpids(kind: u32, typeinfo: u32, buffer: ?*anyopaque, buffersize: c_int) c_int; + extern "c" fn proc_pidpath(pid: c_int, buffer: [*]u8, buffersize: u32) c_int; + + fn exe(pid: libc.pid_t, buf: *[path_max]u8) ?[]const u8 { + const got = proc_pidpath(pid, buf, buf.len); + if (got <= 0) return null; + return buf[0..@intCast(got)]; + } + + /// A pid with no readable path is either gone or not ours. Only a zombie + /// is provably harmless — it holds no tty — so everything else is taken. + fn zombie(pid: libc.pid_t) bool { + var info: ShortBsdInfo = undefined; + const got = proc_pidinfo(pid, proc_pidt_shortbsdinfo, 0, &info, @sizeOf(ShortBsdInfo)); + if (got != @sizeOf(ShortBsdInfo)) return false; + return info.status == zombie_status; + } + + fn taken(shell_pid: libc.pid_t, fg: libc.pid_t) bool { + var shell_buf: [path_max]u8 = undefined; + const shell_exe = exe(shell_pid, &shell_buf) orelse return false; + var group: [group_max]libc.pid_t = undefined; + const bytes = proc_listpids(proc_pgrp_only, @intCast(fg), &group, @sizeOf(@TypeOf(group))); + // An empty group is a group whose last member just exited: the shell + // is about to have its terminal back, and calling that taken would + // blink the prompt heuristic off for a frame every time a job ends. + if (bytes <= 0) return false; + const n = @as(usize, @intCast(bytes)) / @sizeOf(libc.pid_t); + if (n >= group.len) return true; + var exe_buf: [path_max]u8 = undefined; + for (group[0..n]) |pid| { + if (pid <= 0 or pid == shell_pid) continue; + const path = exe(pid, &exe_buf) orelse { + if (zombie(pid)) continue; + return true; + }; + if (!std.mem.eql(u8, path, shell_exe)) return true; + } + return false; + } +}; + pub fn signalTty(shell_pid: libc.pid_t, master_fd: c_int, which: pardes.PtySignal) void { const sig = switch (which) { .int => libc.SIG.INT, @@ -1329,23 +1558,33 @@ const TestShell = struct { } fn stop(sh: *TestShell) void { - var probe: TtyProbe = undefined; - var pending: usize = 0; - var doomed: [occ_max_visited]libc.pid_t = undefined; - var n: usize = 0; - _ = pushChildren(&probe, &pending, sh.pid, 1); - while (pending > 0) { - pending -= 1; - const node = probe.pending[pending]; - if (n == doomed.len) break; - doomed[n] = node.pid; - n += 1; - if (node.depth < occ_max_depth) _ = pushChildren(&probe, &pending, node.pid, node.depth + 1); - } - _ = libc.kill(sh.pid, libc.SIG.KILL); - for (doomed[0..n]) |kid| { - _ = libc.kill(kid, libc.SIG.KILL); - _ = libc.kill(-kid, libc.SIG.KILL); + if (comptime builtin.os.tag == .linux) { + var probe: TtyProbe = undefined; + var pending: usize = 0; + var doomed: [occ_max_visited]libc.pid_t = undefined; + var n: usize = 0; + _ = pushChildren(&probe, &pending, sh.pid, 1); + while (pending > 0) { + pending -= 1; + const node = probe.pending[pending]; + if (n == doomed.len) break; + doomed[n] = node.pid; + n += 1; + if (node.depth < occ_max_depth) _ = pushChildren(&probe, &pending, node.pid, node.depth + 1); + } + _ = libc.kill(sh.pid, libc.SIG.KILL); + for (doomed[0..n]) |kid| { + _ = libc.kill(kid, libc.SIG.KILL); + _ = libc.kill(-kid, libc.SIG.KILL); + } + } else { + // No children list to descend. forkpty made the shell a session + // leader, so its own group plus whichever group currently holds + // the tty covers the job the test left running. + const fg = tcgetpgrp(sh.master); + if (fg > 0 and fg != sh.pid) _ = libc.kill(-fg, libc.SIG.KILL); + _ = libc.kill(-sh.pid, libc.SIG.KILL); + _ = libc.kill(sh.pid, libc.SIG.KILL); } _ = libc.waitpid(sh.pid, null, 0); _ = libc.close(sh.master); @@ -1374,7 +1613,7 @@ fn sleepMs(ms: i64) void { } test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (comptime !tty_probe_platform) return error.SkipZigTest; var sh = TestShell.start() orelse return error.SkipZigTest; defer sh.stop(); @@ -1390,7 +1629,7 @@ test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands i } test "a background job is not the tty's owner" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (comptime !tty_probe_platform) return error.SkipZigTest; var sh = TestShell.start() orelse return error.SkipZigTest; defer sh.stop(); @@ -1403,7 +1642,7 @@ test "a background job is not the tty's owner" { } test "a nested interactive shell is still a prompt" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (comptime !tty_probe_platform) return error.SkipZigTest; var sh = TestShell.start() orelse return error.SkipZigTest; defer sh.stop(); @@ -1424,7 +1663,7 @@ test "a nested interactive shell is still a prompt" { } test "the walk reaches the leaf: bash -c 'sleep 30' takes the tty" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (comptime !tty_probe_platform) return error.SkipZigTest; var sh = TestShell.start() orelse return error.SkipZigTest; defer sh.stop(); @@ -1436,23 +1675,40 @@ test "the walk reaches the leaf: bash -c 'sleep 30' takes the tty" { sh.send("bash --norc -c 'sleep 30; :'\n"); try std.testing.expect(sh.waitTaken(true, 10_000)); - var probe: TtyProbe = undefined; - var pending: usize = 0; - try std.testing.expectEqual(Pushed.pushed, pushChildren(&probe, &pending, sh.pid, 1)); - try std.testing.expectEqual(@as(usize, 1), pending); - var wrapper_buf: [std.fs.max_path_bytes]u8 = undefined; - var shell_buf: [std.fs.max_path_bytes]u8 = undefined; - try std.testing.expectEqualStrings( - procExe(sh.pid, &shell_buf).?, - procExe(probe.pending[0].pid, &wrapper_buf).?, - ); + // Why the shallow answer is the wrong one, in each walk's own evidence: + // the wrapper between the shell and `sleep` wears the shell's executable, + // so a probe that stopped at it would report a prompt. + if (comptime builtin.os.tag == .linux) { + var probe: TtyProbe = undefined; + var pending: usize = 0; + try std.testing.expectEqual(Pushed.pushed, pushChildren(&probe, &pending, sh.pid, 1)); + try std.testing.expectEqual(@as(usize, 1), pending); + var wrapper_buf: [std.fs.max_path_bytes]u8 = undefined; + var shell_buf: [std.fs.max_path_bytes]u8 = undefined; + try std.testing.expectEqualStrings( + procExe(sh.pid, &shell_buf).?, + procExe(probe.pending[0].pid, &wrapper_buf).?, + ); + } else { + const fg = tcgetpgrp(sh.master); + try std.testing.expect(fg > 0 and fg != sh.pid); + var leader_buf: [darwin.path_max]u8 = undefined; + var shell_buf: [darwin.path_max]u8 = undefined; + // The group's leader IS that wrapper, and it is the shell's binary. + try std.testing.expectEqualStrings( + darwin.exe(sh.pid, &shell_buf).?, + darwin.exe(fg, &leader_buf).?, + ); + // Taken all the same, because the rest of the group is not. + try std.testing.expect(darwin.taken(sh.pid, fg)); + } sh.send("\x03"); try std.testing.expect(sh.waitTaken(false, 10_000)); } test "a full-screen program takes the tty until it quits" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (comptime !tty_probe_platform) return error.SkipZigTest; const cases = [_]struct { bin: [*:0]const u8, run: []const u8, quit: []const u8 }{ .{ .bin = "/usr/bin/vim", .run = "vim -u NONE -i NONE\n", .quit = "\x1b:q!\r" }, .{ .bin = "/usr/bin/less", .run = "env LESS= less /etc/hosts\n", .quit = "q" }, diff --git a/src/layout.zig b/src/layout.zig index 47b2c1a4..c6cb7503 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -8,7 +8,7 @@ pub const Rect = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; pub const Snapshot = struct { serial: u32, box: Box }; const MAX_COLS = pardes.MAX_COLS; const MAX_PANES = pardes.MAX_PANES; -const TOPBAR_H = pardes.TOPBAR_H; + const BOX_H = pardes.BOX_H; pub const Presentation = struct { @@ -795,7 +795,7 @@ pub fn movePlacement(p: *Pardes, id: usize, cur_x: u16, cur_y: u16) ?MovePlaceme const sib = if (src.idx > 0) p.col_panes[src.col][src.idx - 1] else p.col_panes[src.col][src.idx + 1]; heights[sib] +|= p.rects[id].h; } - var y: u16 = TOPBAR_H + p.columnBarHeight(); + var y: u16 = p.topBarHeight() + p.columnBarHeight(); var last: ?MovePlacement = null; for (0..p.col_n[tc]) |k| { const pid = p.col_panes[tc][k]; @@ -1123,7 +1123,7 @@ fn collapseNeighbor(p: *Pardes, col: usize, index: usize) ?usize { } fn computeCollapsedColumn(p: *Pardes, c: usize, x: u16, width: u16, folded: usize) void { - var y: u16 = TOPBAR_H + p.columnBarHeight(); + var y: u16 = p.topBarHeight() + p.columnBarHeight(); const available = p.screen_h -| y; var expanded_left: usize = 0; var weight: f32 = 0; @@ -1196,7 +1196,7 @@ pub fn compute(p: *Pardes) void { } if (vsum <= 0) vsum = 1; - var y: u16 = TOPBAR_H + p.columnBarHeight(); + var y: u16 = p.topBarHeight() + p.columnBarHeight(); const avail_h = p.screen_h -| y; for (0..p.col_n[c]) |k| { const id = p.col_panes[c][k]; diff --git a/src/macos.zig b/src/macos.zig index 79036c3e..d263cfc6 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -106,6 +106,7 @@ const color_default: u32 = 0x01000000; const color_indexed: u32 = 0x02000000; const cell_flag_default: u8 = 1; const cell_flag_tagline: u8 = 2; +const cell_flag_hover: u8 = 4; const scene_flag_crt: u32 = 1 << 0; const scene_flag_ripple: u32 = 1 << 1; const scene_flag_glitch: u32 = 1 << 2; @@ -730,6 +731,16 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { const core = try pardes.Pardes.init(allocs.pardes, opts); errdefer core.deinit(); + // The workspace tag row is the macOS menu bar's business here (see + // docs/macos.md): the build option says whether this shell keeps the + // acme topbar or hands its commands to native chrome. The e2e harness + // opts back in with PARDES_WORKSPACE_TAG=1 — its scripts speak to a + // grid that has the row. Applied before the first resize so the layout + // has never seen it the other way. + core.settings.workspace_tag = if (std.c.getenv("PARDES_WORKSPACE_TAG")) |v| + std.mem.eql(u8, std.mem.span(v), "1") + else + @import("pardes_config").workspace_tag; core.native_images = true; var prompt_rcs = host_io.Shell.prepare(); @@ -917,7 +928,7 @@ export fn pardes_gui_tagline_font_percent() u8 { } export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { - return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h); + return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h, if (state) |*st| st.core.settings.workspace_tag else true); } export fn pardes_topbar_pane_border_px(cell_h: u32, tagline_h: u32) u32 { @@ -942,6 +953,11 @@ export fn pardes_topbar_pane_border_rgb() u32 { return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; } +export fn pardes_tag_active_bg() u32 { + const st = state orelse return color_default; + const rgb = st.core.chromeTheme().tag_active_bg; + return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; +} export fn pardes_tagline_bg() u32 { const st = state orelse return color_default; const rgb = st.core.chromeTheme().tag_bg; @@ -1756,12 +1772,18 @@ fn clearFrame(st: *State) void { st.panel_diff_len = 0; } -fn blankTagCells(cells: []Cell, cols: u16, rows: u16, layers: []const pardes.TagLayer) void { +fn blankTagCells(cells: []Cell, cols: u16, rows: u16, source: []const pardes.Cell, layers: []const pardes.TagLayer) void { for (layers) |layer| { if (layer.cols == 0 or layer.viewport.y >= rows or layer.viewport.x >= cols) continue; const start = @as(usize, layer.viewport.y) * cols + layer.viewport.x; const count = @min(layer.viewport.w, cols - layer.viewport.x); - for (cells[start..][0..count]) |*cell| cell.* = encodeCell(.{}); + for (cells[start..][0..count], source[start..][0..count]) |*cell, was| { + // The tag text is the layer's to draw, but a look-hover on a tag + // word is a canonical fact: carry the hover bit through so the + // glass overlay still finds the affordance rect. + cell.* = encodeCell(.{}); + cell.flags |= @as(u8, @intFromBool(was.hover)) * cell_flag_hover; + } } } @@ -1800,7 +1822,7 @@ fn presentFrame(ctx: ?*anyopaque, surface: *const pardes.Surface) void { defer tz_cells.end(); for (surface.cells, st.cells[0..count]) |cell, *out| out.* = encodeCell(cell); } - blankTagCells(st.cells[0..count], surface.cols, surface.rows, &surface.tag_layers); + blankTagCells(st.cells[0..count], surface.cols, surface.rows, surface.cells, &surface.tag_layers); collectPanelDiff(st, surface, count); collectImages(st, surface); collectPanelTracks(st, surface); @@ -1831,7 +1853,7 @@ fn collectPanelDiff(st: *State, surface: *const pardes.Surface, count: usize) vo } for (surface.previous_cells, st.previous_cells[0..count]) |cell, *out| out.* = encodeCell(cell); - blankTagCells(st.previous_cells[0..count], surface.cols, surface.rows, surface.previous_tag_layers); + blankTagCells(st.previous_cells[0..count], surface.cols, surface.rows, surface.previous_cells, surface.previous_tag_layers); for (surface.cell_diffs, st.changed_cells[0..count]) |diff, *out| out.* = encodeChanged(diff); st.panel_diff_len = count; @@ -2395,8 +2417,8 @@ fn encodeCell(cell: pardes.Cell) Cell { .fg = encodeColor(cell.style.fg), .bg = encodeColor(cell.style.bg), .attrs = encodeAttrs(cell.style), + .flags = encodeCellFlags(cell.default, cell.style.font_role, cell.hover), .len = if (cell.default) 1 else cell.len, - .flags = encodeCellFlags(cell.default, cell.style.font_role), }; if (cell.default) out.text[0] = ' ' @@ -2418,9 +2440,10 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { return attrs; } -fn encodeCellFlags(default: bool, role: pardes.FontRole) u8 { +fn encodeCellFlags(default: bool, role: pardes.FontRole, hover: bool) u8 { return @as(u8, @intFromBool(default)) * cell_flag_default | - @as(u8, @intFromBool(role == .tagline)) * cell_flag_tagline; + @as(u8, @intFromBool(role == .tagline)) * cell_flag_tagline | + @as(u8, @intFromBool(hover)) * cell_flag_hover; } fn noteScrollVelocity(st: *State, delta_rows: f32, delta_cols: f32) void { @@ -2566,7 +2589,8 @@ test "pardes.h declares every export the way it is defined" { try expectSameAbi(@TypeOf(c.pardes_animating), @TypeOf(pardes_animating)); try expectSameAbi(@TypeOf(c.pardes_gui_tagline_font_percent), @TypeOf(pardes_gui_tagline_font_percent)); try expectSameAbi(@TypeOf(c.pardes_tagline_band_offset), @TypeOf(pardes_tagline_band_offset)); - try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_px), @TypeOf(pardes_topbar_pane_border_px)); + try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_rgb), @TypeOf(pardes_topbar_pane_border_rgb)); + try expectSameAbi(@TypeOf(c.pardes_tag_active_bg), @TypeOf(pardes_tag_active_bg)); try expectSameAbi(@TypeOf(c.pardes_tagline_origin_col), @TypeOf(pardes_tagline_origin_col)); try expectSameAbi(@TypeOf(c.pardes_grid_col_at), @TypeOf(pardes_grid_col_at)); try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_rgb), @TypeOf(pardes_topbar_pane_border_rgb)); @@ -2658,6 +2682,7 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u32, c.PARDES_COLOR_INDEXED), color_indexed); try expectEqual(@as(u8, c.PARDES_CELL_DEFAULT), cell_flag_default); try expectEqual(@as(u8, c.PARDES_CELL_TAGLINE), cell_flag_tagline); + try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); try expectEqual(@as(u32, c.PARDES_SCENE_CRT), scene_flag_crt); try expectEqual(@as(u32, c.PARDES_SCENE_RIPPLE), scene_flag_ripple); @@ -2723,9 +2748,10 @@ test "pardes.h matches the Zig boundary" { encodeAttrs(.{ .ul = .curly }), ); - try expectEqual(@as(u8, 0), encodeCellFlags(false, .body)); - try expectEqual(cell_flag_tagline, encodeCellFlags(false, .tagline)); - try expectEqual(cell_flag_default | cell_flag_tagline, encodeCellFlags(true, .tagline)); + try expectEqual(@as(u8, 0), encodeCellFlags(false, .body, false)); + try expectEqual(cell_flag_hover, encodeCellFlags(false, .body, true)); + try expectEqual(cell_flag_tagline, encodeCellFlags(false, .tagline, false)); + try expectEqual(cell_flag_default | cell_flag_tagline, encodeCellFlags(true, .tagline, false)); try expectEqual(pardes.config.gui_tagline_font_percent, pardes_gui_tagline_font_percent()); } @@ -2947,10 +2973,16 @@ test "mac tag layer ABI preserves logical capacity and physical grip" { try std.testing.expectEqual(@as(u32, 11), pardes_tag_layer_value(0, 8)); try std.testing.expectEqual(@as(u8, 'Z'), pardes_tag_layer_cells(0).?[11].text[0]); var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{'G'} ++ .{0} ** 6, .len = 1, .default = false })); - blankTagCells(&canonical, 8, 3, &core.surface.tag_layers); + // A look-hover under the layer is a canonical fact and survives the blank; + // the glyph it marks does not, because the layer redraws that text itself. + var source: [24]pardes.Cell = @splat(.{}); + source[11].hover = true; + blankTagCells(&canonical, 8, 3, &source, &core.surface.tag_layers); try std.testing.expectEqual(@as(u8, 'G'), canonical[9].text[0]); try std.testing.expectEqual(@as(u8, 'G'), canonical[18].text[0]); try std.testing.expectEqual(encodeCell(.{}).len, canonical[10].len); + try std.testing.expectEqual(@as(u8, 0), canonical[10].flags & cell_flag_hover); + try std.testing.expectEqual(cell_flag_hover, canonical[11].flags & cell_flag_hover); } test "mac window blur builtin reaches the ABI without changing opacity" { diff --git a/src/macos/Sources/AppDelegate.swift b/src/macos/Sources/AppDelegate.swift index cbe9cdc9..3cce7592 100644 --- a/src/macos/Sources/AppDelegate.swift +++ b/src/macos/Sources/AppDelegate.swift @@ -310,6 +310,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { file.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") + // The workspace tag row's commands, in the place macOS keeps window + // commands. The build hands that row to this menu bar (see + // docs/macos.md): the words are the same builtins the tag carried, + // spelled exactly as a tag Exec would type them, and nothing here is + // editable — the menu is the tag's buttons, not the tag. + let builtins = submenu("Builtins", of: main) + for word in ["Newcol", "Joincol", "Find", "Grep", "Changelog", + "Dump", "NextColor", "Debug", "Kill"] { + builtins.addItem(command(word, #selector(menuBuiltin(_:)), "")) + } let edit = submenu("Edit", of: main) // Paste and nothing else. Copy, Cut, Undo and Select All have no // builtin behind them — the core yanks into the clipboard on its own @@ -379,13 +389,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { // here would hide half of what Look does. panel.canChooseDirectories = true panel.allowsMultipleSelection = true - panel.resolvesAliases = true - guard panel.runModal() == .OK else { return } for url in panel.urls where url.isFileURL { look(url.path) } } + /// Any workspace-tag word. The title is the builtin's own spelling, so + /// this is the same `run` a tag Exec performs and there is no second + /// vocabulary to keep in step. + @objc private func menuBuiltin(_ sender: NSMenuItem) { run(sender.title) } + + @objc private func menuNew(_ sender: Any?) { run("New") } @objc private func menuSave(_ sender: Any?) { run("Save") } @objc private func menuHelp(_ sender: Any?) { run("Help") } diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 7981cf46..5ad09c38 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -433,7 +433,26 @@ private struct Metrics { let symbolic = (traits?[kCTFontSymbolicTrait] as? UInt32) ?? 0 return symbolic & UInt32(CTFontSymbolicTraits.traitBold.rawValue | CTFontSymbolicTraits.traitItalic.rawValue) == 0 } - let face = CTFontCreateWithFontDescriptor(plain ?? descriptors[0], size, nil) + let chosen = CTFontCreateWithFontDescriptor(plain ?? descriptors[0], size, nil) + // A variable face's descriptor carries no variation, and CoreText + // picks whichever named instance it likes for it — Maple Mono's + // variable file comes up Thin. Pin every axis to its own default: + // the face the file itself calls regular. + var face = chosen + if let axes = CTFontCopyVariationAxes(face) as? [[CFString: Any]] { + var defaults: [CFNumber: Any] = [:] + for axis in axes { + guard let tag = axis[kCTFontVariationAxisIdentifierKey], + let value = axis[kCTFontVariationAxisDefaultValueKey] else { continue } + defaults[tag as! CFNumber] = value + } + if !defaults.isEmpty { + let descriptor = CTFontDescriptorCreateCopyWithAttributes( + CTFontCopyFontDescriptor(face), + [kCTFontVariationAttribute: defaults] as CFDictionary) + face = CTFontCreateWithFontDescriptor(descriptor, size, nil) + } + } // The core already filtered for fixed pitch by reading the file's own // advances. This is the same question asked of the face CoreText // actually built, which is the one that will be drawn with. @@ -577,7 +596,14 @@ final class PardesView: NSView { // full redraw does not allocate 24 times. private var runGlyphs: [CGGlyph] = [] private var runPositions: [CGPoint] = [] - + /// Ligature shaping, keyed by face and text. A sequence ligates when + /// shaping it produces fewer glyphs than it has characters — the only + /// answer CoreText gives without interrogating the font's own features. + /// Cleared with the glyph caches, because it belongs to one face. + private var ligatureShaped: [String: Bool] = [:] + /// Columns the current row has already consumed as part of a ligature + /// drawn further left. One row's worth at a time. + private var ligatureCovered: Set = [] /// Constructed lazily because the ordinary path is still a direct /// CoreText/CoreGraphics frame. No scene bit and no panel track means no /// bitmap, no Core Image context and no Metal work. @@ -748,6 +774,7 @@ final class PardesView: NSView { bodyGlyphCache.removeAll(keepingCapacity: true) taglineGlyphCache.removeAll(keepingCapacity: true) gripGlyphCache.removeAll(keepingCapacity: true) + ligatureShaped.removeAll(keepingCapacity: true) metrics = next taglines = TaglineMetrics(body: next, percent: taglines.percent, scale: scale) metricsScale = scale @@ -844,12 +871,12 @@ final class PardesView: NSView { // whatever we do, so clipping would save fills and nothing else. Narrow // the row loops to the dirty band if that ever shows up in a profile. let count = pardes_frame() - let nextLinkPointer = pardes_pointer_shape() == 1 - if nextLinkPointer != linkPointer { - linkPointer = nextLinkPointer + let nextPointer = pointerShape() + if nextPointer != pointer { + pointer = nextPointer window?.invalidateCursorRects(for: self) if let window, bounds.contains(convert(window.mouseLocationOutsideOfEventStream, from: nil)) { - (linkPointer ? NSCursor.pointingHand : NSCursor.iBeam).set() + cursorFor(pointer).set() } } let scene = pardes_scene() @@ -1178,10 +1205,13 @@ final class PardesView: NSView { drawTagLayers(ctx, hideCursor:hideCursor, canonical:cells, cols:cols, rows:rows) } else { for layer in presentedTagLayers { - drawTagGrip(ctx, values:layer.values, canonical:cells, cols:cols, rows:rows) - layer.cells.withUnsafeBufferPointer { cells in - if let base = cells.baseAddress { drawTagLayer(ctx, values:layer.values, cells:base, hideCursor:true) } + layer.cells.withUnsafeBufferPointer { tagCells in + if let base = tagCells.baseAddress { + drawTagLayer(ctx, values: layer.values, cells: base, hideCursor: true, + canonical: cells, cols: cols) + } } + drawTagGrip(ctx, values: layer.values, canonical: cells, cols: cols, rows: rows) } for layer in presentedBodyLayers { layer.cells.withUnsafeBufferPointer { cells in @@ -1190,6 +1220,7 @@ final class PardesView: NSView { } drawTagRules(ctx, layers: presentedTagLayers.map { $0.values }) } + drawHoverGlass(ctx, cells: cells, cols: cols, rows: rows) } private var presentedTagLayers: [FrozenBodyLayer] = [] @@ -1212,16 +1243,22 @@ final class PardesView: NSView { let values = (0...12).map { Int(pardes_tag_layer_value(index, UInt32($0))) } if values[0] == 0 { continue } layers.append(values) - drawTagGrip(ctx, values:values, canonical:canonical, cols:cols, rows:rows) - if let cells = pardes_tag_layer_cells(index) { drawTagLayer(ctx, values: values, cells: cells, hideCursor: hideCursor) } + // The layer's full-row fill must land before the grip: the row + // background now spans the anchor columns, and the grip glyph + // and the anchor fills have to come back on top of it. + if let cells = pardes_tag_layer_cells(index) { + drawTagLayer(ctx, values: values, cells: cells, hideCursor: hideCursor, + canonical: canonical, cols: cols) + } + drawTagGrip(ctx, values: values, canonical: canonical, cols: cols, rows: rows) } drawTagRules(ctx, layers: layers) } /// SDL's chrome overlay is drawn after its compact layers. Keep these - /// one-pixel rules above the full-row tag backgrounds as well. + /// one-point rules above the full-row tag backgrounds as well. private func drawTagRules(_ ctx: CGContext, layers: [[Int]]) { - let pixel = 1 / metricsScale + let pixel = CGFloat(1) for values in layers where values[1] != 0 { let kind = values[1] let bottom = kind == 2 && values[11] != 0 @@ -1252,15 +1289,17 @@ final class PardesView: NSView { } private func drawTagGrip(_ ctx: CGContext, values: [Int], canonical: UnsafePointer, cols: Int, rows: Int) { - let width = Int(pardes_grip_columns()) let x = values[4] - Int(pardes_tag_text_inset()), y = values[5] if values[1] != 2 || x < 0 || x >= cols || y < 0 || y >= rows { return } var cell = canonical[y * cols + x] let text = withUnsafeBytes(of: &cell.text) { String(decoding: $0.prefix(Int(cell.len)), as: UTF8.self) } if text.isEmpty { return } let style = resolve(cell, block:false, ground:themeBG ?? pardesDefaultBG, clearGround:false) - let centerX = (CGFloat(x) + CGFloat(width) / 2) * cellWidth - let centerY = CGFloat(y) * cellHeight + taglines.top(row:y, canvasHeight:bounds.height) + taglines.height / 2 + // The box drawTagLayer filled is this mark's ground, so the mark + // centres on that same square rather than on the grip columns: one + // rect measures both and the two cannot drift apart. + guard let square = anchorSquare(values: values) else { return } + let centerX = square.midX, centerY = square.midY if text != " " { let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) @@ -1268,9 +1307,7 @@ final class PardesView: NSView { let originX = ((centerX - measured.ink.midX) * metricsScale).rounded() / metricsScale let baseline = ((bounds.height - centerY - measured.ink.midY) * metricsScale).rounded() / metricsScale ctx.saveGState() - ctx.clip(to: CGRect(x: CGFloat(x) * cellWidth, - y: CGFloat(y) * cellHeight + taglines.top(row:y, canvasHeight:bounds.height), - width: CGFloat(width) * cellWidth, height: taglines.height)) + ctx.clip(to: square) ctx.translateBy(x: 0, y: bounds.height) ctx.scaleBy(x: 1, y: -1) ctx.textMatrix = .identity @@ -1286,16 +1323,36 @@ final class PardesView: NSView { fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY+1), width:2*halfWidth, height:1), style.fg, 1) } - private func drawTagLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer, hideCursor: Bool) { + private func drawTagLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer, + hideCursor: Bool, canonical: UnsafePointer, cols: Int) { let left = CGFloat(values[4]) * cellWidth let y = CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height) // SDL gives the tag a full body-row background; only its glyphs - // and per-cell highlights use the compact band. - let viewport = CGRect(x: left, y: CGFloat(values[5]) * cellHeight, - width: CGFloat(values[6]) * cellWidth, height: cellHeight) + // and per-cell highlights use the compact band. The band spans the + // row's whole extent, not just its text: the grip and the mode box + // live in the inset columns to the left of `values[4]`, and their + // own fills cover only the compact band — a row background that + // stops at the text leaves holes of ground under those anchors. + // The rule in drawTagRules spans exactly this left-to-right range. + let rowLeft = CGFloat(max(0, values[4] - Int(pardes_tag_text_inset()))) * cellWidth + let rowRight = CGFloat(values[4] + values[6]) * cellWidth + let viewport = CGRect(x: rowLeft, y: CGFloat(values[5]) * cellHeight, + width: rowRight - rowLeft, height: cellHeight) ctx.saveGState() ctx.clip(to: viewport) fillBackground(ctx, viewport, UInt32(values[10]), backgroundAlpha) + // The anchor (grip, mode box) lives in the inset columns that fill + // just covered, so its own box goes back on top: one solid fill in + // the box colour the anchor cell wears, with drawTagGrip's mark + // drawn over it afterwards. + if let square = anchorSquare(values: values) { + let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) + let cell = canonical[values[5] * cols + anchorX] + let style = resolve(cell, block: false, + ground: UInt32(values[10]), clearGround: false) + if style.visible { fillBackground(ctx, square.integral, style.bg, backgroundAlpha) } + } + for pass in 0...1 { for col in 0.. CGRect? { + let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) + guard anchorX < values[4] else { return nil } + let pad = (cellHeight - taglines.height) / 2 + return CGRect(x: CGFloat(anchorX) * cellWidth + pad, + y: CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height), + width: taglines.height, height: taglines.height) + } + + /// The look-hover affordance as liquid glass: the core marks the word's + /// cells (PARDES_CELL_HOVER), and this composes a real material over the + /// run — the drawn frame snapshot refracted through CoreImage (a small + /// blur, then a lens scale about the pill's centre, which is what makes + /// the edges swim), the theme's selection colour as a faint tint, a + /// specular sheen from the top edge, and a light rim — with the word's + /// own glyphs drawn back on top, crisp, the way text sits on a real + /// material rather than behind one. + private func drawHoverGlass(_ ctx: CGContext, cells: UnsafePointer, cols: Int, rows: Int) { + var drew = false + for row in 0..= 0 { + let rect = CGRect(x: CGFloat(start) * cellWidth, y: CGFloat(row) * cellHeight, + width: CGFloat(col - start) * cellWidth, height: cellHeight) + drawLiquidGlass(ctx, rect, tint: tint) + redrawHoverRun(ctx, cells, cols: cols, row: row, start: start, end: col) + drew = true + start = -1 + } + } + } + // No affordance this frame: the held snapshot describes a frame + // that no longer exists, and the next hover must take a fresh one. + if !drew { glassShot = nil } + } + + /// A CoreImage context for the glass refraction, created once. + private lazy var glassContext = CIContext() + /// The snapshot behind the current pill. Refraction reads the already + /// drawn frame, and re-reading it every pump would blur a moving pill + /// out of its own budget, so the shot is taken when the rect changes. + private var glassShot: (rect: CGRect, image: CGImage)? + + private func drawLiquidGlass(_ ctx: CGContext, _ rect: CGRect, tint: UInt32) { + let radius = min(rect.height / 4, 6) + let pill = CGPath(roundedRect: rect.insetBy(dx: 1, dy: 1.5), + cornerWidth: radius, cornerHeight: radius, transform: nil) + // The refraction: the frame as drawn, blurred a little and scaled + // about the pill's centre, so the rim bends what surrounds it. The + // shot extends past the pill for exactly this — the lens needs + // pixels from outside the glass to pull in. + let lens = rect.insetBy(dx: -10, dy: -10) + if refract(ctx, pill: pill, rect: rect, lens: lens, tint: tint) { + // Specular: light caught at the top edge, fading as it falls. + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + let shine = [CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.22), + CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.0)] as CFArray + if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), + colors: shine, locations: [0, 0.55]) { + ctx.drawLinearGradient(gradient, + start: CGPoint(x: rect.minX, y: rect.minY), + end: CGPoint(x: rect.minX, y: rect.maxY), options: []) + } + ctx.restoreGState() + } else { + // No refraction without a snapshot: the tint alone, faint. + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, + green: CGFloat((tint >> 8) & 0xFF) / 255, + blue: CGFloat(tint & 0xFF) / 255, + alpha: 0.18)) + ctx.fill(rect) + ctx.restoreGState() + } + // The lens edge: a light rim and a darker bottom hairline, the way a + // real material catches its own edge. + ctx.addPath(pill) + ctx.setStrokeColor(CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.35)) + ctx.setLineWidth(1) + ctx.strokePath() + ctx.addPath(pill) + ctx.setStrokeColor(CGColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.25)) + ctx.setLineWidth(0.5) + ctx.clip() + ctx.stroke(CGRect(x: rect.minX, y: rect.maxY - 2, width: rect.width, height: 1.5)) + } + + /// True when the refraction composited. The snapshot is taken when the + /// pill moves and reused while it sits still. + private func refract(_ ctx: CGContext, pill: CGPath, rect: CGRect, lens: CGRect, tint: UInt32) -> Bool { + guard let shot = snapshotFor(ctx, lens: lens) else { return false } + var image = CIImage(cgImage: shot) + // The blur is grown slightly past the crop and the whole thing is + // pulled toward the centre by a few percent: the rim bends what + // surrounds it, which is the refraction the eye reads as glass. + let blur = image.applyingGaussianBlur(sigma: 2 * metricsScale) + let grown = blur.extent.insetBy(dx: -8 * metricsScale, dy: -8 * metricsScale) + let centre = CGPoint(x: grown.midX, y: grown.midY) + let scale = 1.06 + let lensTransform = CGAffineTransform(translationX: centre.x * (1 - scale), + y: centre.y * (1 - scale)).scaledBy(x: scale, y: scale) + image = blur.transformed(by: lensTransform) + guard let filtered = glassContext.createCGImage(image, from: grown) else { return false } + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + ctx.draw(filtered, in: rect) + // The glass's own body colour: the theme's selection, faint — the + // refraction and the sheen carry the material, not opacity. + ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, + green: CGFloat((tint >> 8) & 0xFF) / 255, + blue: CGFloat(tint & 0xFF) / 255, + alpha: 0.15)) + ctx.fill(rect) + ctx.restoreGState() + return true + } + + private func snapshotFor(_ ctx: CGContext, lens: CGRect) -> CGImage? { + if let held = glassShot, held.rect == lens { return held.image } + guard let whole = ctx.makeImage() else { return nil } + // makeImage hands back backing pixels; the lens is in view points. + let region = CGRect(x: lens.minX * metricsScale, y: lens.minY * metricsScale, + width: lens.width * metricsScale, height: lens.height * metricsScale) + guard let cropped = whole.cropping(to: region) else { return nil } + glassShot = (lens, cropped) + return cropped + } + + /// The hovered word's glyphs, back on top of the material, crisp: text + /// sits on liquid glass, not behind it. + private func redrawHoverRun(_ ctx: CGContext, _ cells: UnsafePointer, + cols: Int, row: Int, start: Int, end: Int) { + ctx.saveGState() + ctx.textMatrix = .identity + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + let baseline = bounds.height - (CGFloat(row) * cellHeight + metrics.ascent) + for col in start.. = [ + "<", ">", "=", "!", "&", "|", "-", "/", ":", ".", "#", "*", "+", "~", "^", "%", + ] + + private func ligates(_ face: Face, _ text: String) -> Bool { + let key = "\(face.rawValue):\(text)" + if let cached = ligatureShaped[key] { return cached } + let attributed = NSAttributedString(string: text, attributes: [fontAttribute: metrics.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + let shaped = CTLineCreateWithAttributedString(attributed as CFAttributedString) + var glyphs: [CGGlyph] = [] + for run in (CTLineGetGlyphRuns(shaped) as? [CTRun]) ?? [] { + let count = CTRunGetGlyphCount(run) + var runGlyphs = [CGGlyph](repeating: 0, count: count) + CTRunGetGlyphs(run, CFRange(location: 0, length: count), &runGlyphs) + glyphs.append(contentsOf: runGlyphs) + } + // A ligature is any divergence from per-character mapping. A font may + // collapse the pair into one glyph (JetBrains Mono) or swap each + // character for a joining half kept at the same count (Maple Mono) — + // either way the sequence must be shaped, not mapped. + let singles = text.utf16.map { glyph(face, $0, tagline: false) } + let result = glyphs.count != singles.count + || zip(glyphs, singles).contains { $0 != $1 } + ligatureShaped[key] = result + return result + } + + /// When the cells at `col` ligate under `face`, the text to shape and how + /// many cells the ligature covers. Nil when they do not. Ligature cells + /// must carry the same face, colour and alpha and no rules of their own — + /// a ligature is one glyph of one style, not a style transition. + private func ligatureSpan(_ cells: UnsafePointer, base: Int, cols: Int, col: Int, + face: Face, fg: UInt32, alpha: CGFloat, + blockCol: Int, paneGripCells: Set) -> (text: String, covered: Int)? { + func eligible(_ index: Int) -> String? { + let cell = cells[base + index] + if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { return nil } + if cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 { return nil } + if cell.attrs >> UInt16(PARDES_ATTR_UL_SHIFT) != 0 + || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { return nil } + if paneGripCells.contains(base + index) { return nil } + let text = withUnsafeBytes(of: cell.text) { raw in + String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) + } + guard text.utf16.count == 1 else { return nil } + let other = resolve(cell, block: blockCol == index, + ground: themeBG ?? pardesDefaultBG, clearGround: false) + guard other.visible, other.fg == fg, other.alpha == alpha, + Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) == face else { return nil } + return text + } + guard let head = eligible(col), PardesView.ligatureHeads.contains(head.first!) else { return nil } + guard col + 1 < cols, let second = eligible(col + 1) else { return nil } + let pair = head + second + if col + 2 < cols, let third = eligible(col + 2) { + let triple = pair + third + if ligates(face, triple) { return (triple, 3) } + } + if ligates(face, pair) { return (pair, 2) } + return nil + } + private func drawRules( _ ctx: CGContext, _ cell: pardes_cell_s, @@ -1921,6 +2243,13 @@ final class PardesView: NSView { override func keyDown(with event: NSEvent) { let flags = event.modifierFlags + // Same reason as the trackpad trace below: whether AppKit delivered a + // keystroke at all is not something this process can otherwise answer, + // and "Escape does nothing" has two entirely different causes + // depending on whether this line prints. + trace("key: code=\(event.keyCode) mods=\(flags.rawValue) chars=" + + (event.charactersIgnoringModifiers?.unicodeScalars + .map { String($0.value, radix: 16) }.joined(separator: ",") ?? "-")) // The ABI has no super bit, so a Command chord cannot be expressed at all. // Anything the main menu claims never reaches here; the rest is swallowed // rather than delivered as the bare keystroke the core would insert. @@ -2328,12 +2657,35 @@ final class PardesView: NSView { userInfo: nil)) } - private var linkPointer = false + private enum Pointer: Equatable { case text, link, target } + private var pointer: Pointer = .text + + /// The core's pointer_shape, in this shell's cursor vocabulary: a link + /// is a PDF hyperlink (the hand), a target is a word the core's own + /// Look-hover plumbing validated as a real Look or Exec operand, and + /// anything else is text — the I-beam. + private func pointerShape() -> Pointer { + switch pardes_pointer_shape() { + case 1: return .link + case 2: return .target + default: return .text + } + } + + private func cursorFor(_ shape: Pointer) -> NSCursor { + switch shape { + case .link: return .pointingHand + case .target: return .arrow + case .text: return .iBeam + } + } override func resetCursorRects() { - // Every cell in this view is text, including the tags. An arrow over a - // grid you can sweep and click words in is the wrong affordance. - addCursorRect(bounds, cursor: linkPointer ? .pointingHand : .iBeam) + // Every cell in this view is text, including the tags. An arrow over + // plain text is the wrong affordance — but a word the core has + // validated as a Look or Exec target earns it: middle- and + // right-clicking there acts, and the cursor says so before it does. + addCursorRect(bounds, cursor: cursorFor(pointer)) } override func setFrameSize(_ newSize: NSSize) { diff --git a/src/macos/pardes.h b/src/macos/pardes.h index df3ba04f..f74330e5 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -76,6 +76,11 @@ typedef struct { #define PARDES_CELL_DEFAULT 0x01u #define PARDES_CELL_TAGLINE 0x02u +// The look-hover affordance: the word under the pointer is a real Look or +// Exec operand. Hosts that draw the affordance as more than the quiet tint +// (macOS composes a liquid-glass overlay) read this instead of guessing +// from the background colour, which a real selection shares. +#define PARDES_CELL_HOVER 0x04u // One coherent snapshot for the full-window shader pass. The bitmask lets the // host run CRT, ripple and glitch in one kernel instead of stacking filters; @@ -323,6 +328,10 @@ uint32_t pardes_topbar_pane_border_rgb(void); // pardes.TOPBAR_H, and src/macos.zig asserts the two agree. #define PARDES_TOPBAR_H 1u +// The active pane's tag row background, for hosts that afford the active +// tagline more than a tint — macOS raises it like an old-school bevel. +uint32_t pardes_tag_active_bg(void); + // Persistent full-window effect switches and their display-clock time. A zero // flags word means draw the CoreText frame directly; any nonzero combination // is one postprocess pass. Snapshot by value, with no borrowed storage. @@ -510,7 +519,8 @@ bool pardes_active_dirty(void); int32_t pardes_cursor_x(void); int32_t pardes_cursor_y(void); bool pardes_cursor_bar(void); -// Mouse pointer affordance: 0 = default text pointer, 1 = link hand. +// Mouse pointer affordance: 0 = default text pointer, 1 = link hand, +// 2 = a validated Look/Exec target under the pointer (the acme arrow). uint32_t pardes_pointer_shape(void); // The Look or Exec the core performed since this was last asked, and clears diff --git a/src/pardes.zig b/src/pardes.zig index ed71102e..dee8a902 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -88,12 +88,19 @@ pub const BOX_H: u16 = 1; pub const TAG_GAP: u16 = 1; pub const TAG_TEXT_INSET: u16 = config.GUTTER + TAG_GAP; -pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { +pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32, workspace: bool) u32 { const spare = cell_h -| tagline_h; const border = topbarPaneBorderPixels(cell_h, tagline_h); + const rows: u32 = @max(1, @as(u32, @intFromFloat(@floor(canvas_h / @as(f32, @floatFromInt(cell_h)))))); + if (!workspace) { + // No workspace row: nothing above row 0 to share a rule with, so + // every band centers in its cell the way the middle rows always + // have. The anchor boxes this lets the hosts draw stay symmetric. + if (@as(u32, row) + 1 >= rows) return spare; + return spare / 2; + } if (row == 0) return spare - border / 2; if (row == TOPBAR_H) return border - border / 2; - const rows: u32 = @max(1, @as(u32, @intFromFloat(@floor(canvas_h / @as(f32, @floatFromInt(cell_h)))))); if (@as(u32, row) + 1 >= rows) return spare; return spare / 2; } @@ -104,8 +111,8 @@ pub fn topbarPaneBorderPixels(cell_h: u32, tagline_h: u32) u32 { } pub fn taglineOriginCol(p: *const Pardes, col: u16, row: u16, track: ?layout.Track) f32 { - if (row < TOPBAR_H) return 0; - if (row < TOPBAR_H + p.columnBarHeight()) { + if (row < p.topBarHeight()) return 0; + if (row < p.topBarHeight() + p.columnBarHeight()) { for (p.col_x[0..p.ncol], p.col_w[0..p.ncol]) |x, w| if (col >= x and col - x < w) return @floatFromInt(x); } @@ -164,8 +171,8 @@ test "paint order is moving, then opening, then closing tombstones on top" { pub fn gridColAt(p: ?*const Pardes, x: f32, row: u16, body_w: f32, tagline_w: f32) u16 { const body = @max(body_w, 1); const tag = @max(tagline_w, 1); - if (row < TOPBAR_H) return colFromSpan(x, tag); - if (p) |core| if (row < TOPBAR_H + core.columnBarHeight()) { + if (row < (if (p) |core| core.topBarHeight() else TOPBAR_H)) return colFromSpan(x, tag); + if (p) |core| if (row < core.topBarHeight() + core.columnBarHeight()) { for (core.col_x[0..core.ncol], core.col_w[0..core.ncol]) |origin, width| { if (width == 0) continue; const left = @as(f32, @floatFromInt(origin)) * body; @@ -3395,6 +3402,12 @@ pub const Cell = struct { len: u8 = 1, style: CellStyle = .{}, default: bool = true, + /// The look-hover affordance is on this cell: the word under the pointer + /// is a real Look or Exec operand, and hosts that draw the quiet tint as + /// more than a flat fill — macOS renders it as a glass overlay — read + /// this instead of guessing from the background colour, which a real + /// selection shares. + hover: bool = false, pub fn grapheme(c: *const Cell) []const u8 { return c.text[0..c.len]; @@ -3670,8 +3683,12 @@ test "pixel attachment fit and pan do not invalidate cached pixels" { /// The canonical interface: what a frame of pardes IS. The tty shell writes /// these cells to vaxis one-to-one; the SDL shells rasterize them. pub const Surface = struct { - pub const PointerShape = enum(u8) { arrow, link }; + pub const PointerShape = enum(u8) { arrow, link, target }; pointer_shape: PointerShape = .arrow, + /// Set only for the duration of the look-hover paint, so the cells that + /// paint the quiet affordance can carry the hover bit through the ABI + /// without every selection painter learning a new parameter. + mark_hover: bool = false, body_layers: [MAX_PANES]BodyLayer = @splat(.{}), tag_layers: [MAX_TAG_LAYERS]TagLayer = @splat(.{}), cols: u16 = 0, @@ -3717,7 +3734,11 @@ pub const Surface = struct { pub fn at(s: *Surface, x: u16, y: u16) *Cell { std.debug.assert(x < s.cols and y < s.rows); - return &s.cells[@as(usize, y) * s.cols + x]; + const cell = &s.cells[@as(usize, y) * s.cols + x]; + // The look-hover paint runs with mark_hover set, and its cells are + // exactly the ones this marks — see render's preview block. + if (s.mark_hover) cell.hover = true; + return cell; } pub fn set(s: *Surface, x: u16, y: u16, text: []const u8, style: CellStyle) void { @@ -6263,6 +6284,14 @@ pub const Pardes = struct { return config.topbar_str; } + /// The workspace tag row's height: `TOPBAR_H` while the setting keeps + /// it, zero once a native shell takes its commands over. Layout and hit + /// testing read this rather than the constant, the way they read + /// `columnBarHeight`. + pub fn topBarHeight(p: *const Pardes) u16 { + return if (p.settings.workspace_tag) TOPBAR_H else 0; + } + pub fn columnBarHeight(p: *const Pardes) u16 { return if (p.settings.column_tags and p.screen_h >= 3) COLBAR_H else 0; } @@ -7765,7 +7794,7 @@ pub const Pardes = struct { } var dest: ?usize = null; for (p.panes, 0..) |slot, i| { - if (slot == null or p.rects[i].y != TOPBAR_H + p.columnBarHeight()) continue; + if (slot == null or p.rects[i].y != p.topBarHeight() + p.columnBarHeight()) continue; if (p.header_column) |c| if (p.rects[i].x != p.col_x[c]) continue; if (i == p.active) { dest = i; @@ -11015,7 +11044,7 @@ pub const Pardes = struct { pub const ChromeTarget = struct { col: u16, row: u16 }; pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { - if (row < TOPBAR_H + p.columnBarHeight()) return .{ .col = col, .row = row }; + if (row < p.topBarHeight() + p.columnBarHeight()) return .{ .col = col, .row = row }; for (p.panes, 0..) |slot, id| { if (slot == null) continue; const rect = p.rects[id]; @@ -11330,7 +11359,7 @@ pub const Pardes = struct { p.chord_arg = null; } } - if (mrow >= TOPBAR_H and mrow < TOPBAR_H + p.columnBarHeight() and m.kind == .press) { + if (mrow >= p.topBarHeight() and mrow < p.topBarHeight() + p.columnBarHeight() and m.kind == .press) { for (0..p.ncol) |column| { if (mcol < p.col_x[column] or mcol >= p.col_x[column] + @min(config.GUTTER, p.col_w[column])) continue; if (m.button == config.select_button) { @@ -11347,7 +11376,7 @@ pub const Pardes = struct { if (m.kind == .release) p.header_drag = false; return; } - if (mrow < TOPBAR_H + p.columnBarHeight() and m.kind == .press and + if (mrow < p.topBarHeight() + p.columnBarHeight() and m.kind == .press and (m.button == config.select_button or m.button == config.exec_button or m.button == config.look_button)) { if (m.button == config.select_button) if (p.panes[p.active]) |pane| { @@ -11355,7 +11384,7 @@ pub const Pardes = struct { }; var column: ?usize = null; var x: u16 = 0; - if (mrow >= TOPBAR_H) { + if (mrow >= p.topBarHeight()) { for (0..p.ncol) |c| if (mcol >= p.col_x[c] and mcol < p.col_x[c] + p.col_w[c]) { column = c; x = p.col_x[c] + TAG_TEXT_INSET; @@ -13186,6 +13215,15 @@ pub const Pardes = struct { } } }; + // A look-hover preview means the pointed word is a real Look or Exec + // operand: the same plumbing a click would act on. Hosts that model + // the pointer per-text (the macOS I-beam) read this as "target" and + // afford it the arrow instead. + if (p.look_hover_preview != null) s.pointer_shape = .target; + // Stale hover bits must not survive into a frame whose pointer has + // moved on: the ordinary content paint does not clear fields it + // never set. + for (s.cells) |*c| c.hover = false; for (&s.body_layers) |*layer| layer.rows = 0; for (&s.tag_layers) |*layer| layer.cols = 0; s.nimages = 0; @@ -13252,21 +13290,24 @@ pub const Pardes = struct { } } - // global tagbar: full width, top row + // global tagbar: full width, top row — unless a native shell has + // taken its commands over, in which case the row is not ours to draw p.revealHeader(); - s.fill(0, 0, s.cols, TOPBAR_H, .{ - .bg = .{ .rgb = chrome.tag_bg }, - .font_role = .tagline, - }); var tb_buf: [1200]u8 = undefined; const global_bar = p.topbar(&tb_buf); const global_scroll = if (p.topbar_col != null and p.header_column == null) p.header_scroll else 0; - _ = s.print(0, 0, s.cols, global_bar[panes.File.rawAtDisplay(global_bar, global_scroll)..], .{ - .fg = .{ .rgb = chrome.tag_fg }, - .bg = .{ .rgb = chrome.tag_bg }, - .font_role = .tagline, - }); - if (p.pointer_inside and p.hover_row < TOPBAR_H) { + if (p.settings.workspace_tag) { + s.fill(0, 0, s.cols, TOPBAR_H, .{ + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, + }); + _ = s.print(0, 0, s.cols, global_bar[panes.File.rawAtDisplay(global_bar, global_scroll)..], .{ + .fg = .{ .rgb = chrome.tag_fg }, + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, + }); + } + if (p.pointer_inside and p.hover_row < p.topBarHeight()) { const bar = p.topbar(&tb_buf); if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col + global_scroll))) |bounds| { var col = panes.File.rawDisplayCol(bar, bounds.lo) -| global_scroll; @@ -13296,24 +13337,24 @@ pub const Pardes = struct { const lum = (@as(u16, grip_bg[0]) * 3 + @as(u16, grip_bg[1]) * 6 + @as(u16, grip_bg[2])) / 10; const ink: [3]u8 = if (lum > 140) .{ 0, 0, 0 } else .{ 255, 255, 255 }; const grip_style: CellStyle = .{ .bg = .{ .rgb = grip_bg }, .fg = .{ .rgb = ink }, .font_role = .tagline }; - s.fill(p.col_x[c], TOPBAR_H, grip, 1, grip_style); - s.fill(p.col_x[c] + grip, TOPBAR_H, inset - grip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + s.fill(p.col_x[c], p.topBarHeight(), grip, 1, grip_style); + s.fill(p.col_x[c] + grip, p.topBarHeight(), inset - grip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - s.fill(x, TOPBAR_H, w, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + s.fill(x, p.topBarHeight(), w, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); const bar_scroll = if (p.topbar_col != null and p.header_column == c) p.header_scroll else 0; const tag = p.columnTag(c); - _ = s.print(x, TOPBAR_H, w, tag[panes.File.rawAtDisplay(tag, bar_scroll)..], .{ + _ = s.print(x, p.topBarHeight(), w, tag[panes.File.rawAtDisplay(tag, bar_scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline, }); - if (p.pointer_inside and p.hover_row == TOPBAR_H and p.hover_col >= x and p.hover_col < x + w) { + if (p.pointer_inside and p.hover_row == p.topBarHeight() and p.hover_col >= x and p.hover_col < x + w) { const bar = p.columnTag(c); if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col - x + bar_scroll))) |bounds| { var col = panes.File.rawDisplayCol(bar, bounds.lo) -| bar_scroll; const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| bar_scroll; while (col < hi and col < w) : (col += 1) { - const cell = s.at(x + @as(u16, @intCast(col)), TOPBAR_H); + const cell = s.at(x + @as(u16, @intCast(col)), p.topBarHeight()); cell.style.bg = .{ .rgb = th.sel_bg }; cell.style.fg = .{ .rgb = th.sel_fg }; } @@ -13324,7 +13365,7 @@ pub const Pardes = struct { const bar = p.headerText(); const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; const w = if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else s.cols; - const y: u16 = if (p.header_column != null) TOPBAR_H else 0; + const y: u16 = if (p.header_column != null) p.topBarHeight() else 0; const anchor = p.header_anchor orelse cur; var col = panes.File.rawDisplayCol(bar, @min(cur, anchor)) -| p.header_scroll; const hi = panes.File.rawDisplayCol(bar, @max(cur, anchor)) -| p.header_scroll; @@ -13342,7 +13383,7 @@ pub const Pardes = struct { switch (p.drag) { .border_v => |d| { if (d.cur_x < s.cols) { - var row: u16 = TOPBAR_H; + var row: u16 = p.topBarHeight(); while (row < s.rows) : (row += 1) s.overlayDash(d.cur_x, row, "╎"); } if (d.corner) |k| if (d.cur_y < s.rows) { @@ -13367,11 +13408,11 @@ pub const Pardes = struct { for (&s.body_layers) |*layer| if (layer.rows > 0 and layer.viewport.x + layer.viewport.w == s.cols) { layer.viewport.w -|= 1; }; - for (&s.tag_layers) |*layer| if (layer.cols > 0 and layer.viewport.x + layer.viewport.w == s.cols and layer.viewport.y >= TOPBAR_H) { + for (&s.tag_layers) |*layer| if (layer.cols > 0 and layer.viewport.x + layer.viewport.w == s.cols and layer.viewport.y >= p.topBarHeight()) { layer.viewport.w -|= 1; }; } - var row: u16 = TOPBAR_H; + var row: u16 = p.topBarHeight(); while (row < s.rows) : (row += 1) s.overlayDash(x, row, "╎"); } }, @@ -13389,7 +13430,7 @@ pub const Pardes = struct { var c: usize = 0; while (c + 1 < p.ncol) : (c += 1) { if (p.hover_col == p.col_x[c] + p.col_w[c] -| 1) { - var row: u16 = TOPBAR_H; + var row: u16 = p.topBarHeight(); while (row < s.rows) : (row += 1) s.overlayDash(p.hover_col, row, "╎"); } } @@ -13443,27 +13484,27 @@ pub const Pardes = struct { const ow: u16 = 38; const oh: u16 = 10; const ox: u16 = if (s.cols > ow) s.cols - ow else 0; - if (ox + ow <= s.cols and TOPBAR_H + oh <= s.rows) { + if (ox + ow <= s.cols and p.topBarHeight() + oh <= s.rows) { // vaxis single_rounded border ring, default style - s.set(ox, TOPBAR_H, "╭", .{}); - s.set(ox + ow - 1, TOPBAR_H, "╮", .{}); - s.set(ox, TOPBAR_H + oh - 1, "╰", .{}); - s.set(ox + ow - 1, TOPBAR_H + oh - 1, "╯", .{}); + s.set(ox, p.topBarHeight(), "╭", .{}); + s.set(ox + ow - 1, p.topBarHeight(), "╮", .{}); + s.set(ox, p.topBarHeight() + oh - 1, "╰", .{}); + s.set(ox + ow - 1, p.topBarHeight() + oh - 1, "╯", .{}); var bx = ox + 1; while (bx < ox + ow - 1) : (bx += 1) { - s.set(bx, TOPBAR_H, "─", .{}); - s.set(bx, TOPBAR_H + oh - 1, "─", .{}); + s.set(bx, p.topBarHeight(), "─", .{}); + s.set(bx, p.topBarHeight() + oh - 1, "─", .{}); } - var by = TOPBAR_H + 1; - while (by < TOPBAR_H + oh - 1) : (by += 1) { + var by = p.topBarHeight() + 1; + while (by < p.topBarHeight() + oh - 1) : (by += 1) { s.set(ox, by, "│", .{}); s.set(ox + ow - 1, by, "│", .{}); } - s.fill(ox + 1, TOPBAR_H + 1, ow - 2, oh - 2, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(ox + 1, p.topBarHeight() + 1, ow - 2, oh - 2, .{ .bg = .{ .rgb = chrome.scroll_track } }); var lines = std.mem.splitScalar(u8, text, '\n'); - var ly: u16 = TOPBAR_H + 1; + var ly: u16 = p.topBarHeight() + 1; while (lines.next()) |line| : (ly += 1) { - if (ly >= TOPBAR_H + oh - 1) break; + if (ly >= p.topBarHeight() + oh - 1) break; _ = s.print(ox + 1, ly, ow - 2, line, .{ .fg = .{ .rgb = chrome.tag_fg } }); } } @@ -13702,11 +13743,14 @@ pub const Pardes = struct { layer.cursor = if (p.topbar_col == null and pane.promptAt() == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; } var text_buf: [1200]u8 = undefined; - try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, p.topbar(&text_buf), chrome.tag_bg, chrome.tag_fg); + // With the workspace tag row handed to native chrome there is no + // workspace layer to render; the menu bar carries its commands. + if (p.settings.workspace_tag) + try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, p.topbar(&text_buf), chrome.tag_bg, chrome.tag_fg); if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { if (p.col_w[column] == 0) continue; const active = if (layout.findPane(p, p.active)) |found| found.col == column and p.settings.focus_tint else false; - try p.renderHeaderLayer(arena, MAX_PANES + column, .column, @intCast(column), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = TOPBAR_H, .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, p.columnTag(column), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); + try p.renderHeaderLayer(arena, MAX_PANES + column, .column, @intCast(column), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight(), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, p.columnTag(column), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); }; } @@ -14010,13 +14054,14 @@ pub const Pardes = struct { if (p.look_hover_preview) |preview| { if (preview.pane == id and preview.serial == pane.serial) { // Preserve body ink, then let every real user selection below - // win over this quiet affordance. + // win over this quiet affordance. mark_hover carries the + // cells this paints out to the hosts as the affordance rect — + // macOS composes its glass overlay over exactly these. const preview_bg = mix(page_rgb, mix(page_rgb, th.sel_bg)); if (preview.file_word) |word| panes.File.paintWordSelection(p, pane, r, word.row, word.lo, word.hi, preview_bg) else if (preview.sel) |sel| - if (@max(sel.r0, sel.r1) >= BOX_H) - p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); + p.paintPointerSelection(pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); } } const modal_hover = if (p.look_hover_preview) |preview| diff --git a/src/themes/acme.zig b/src/themes/acme.zig index 87183ebc..d91e626b 100644 --- a/src/themes/acme.zig +++ b/src/themes/acme.zig @@ -14,13 +14,13 @@ pub const theme = .{ .name = "acme", .bg = .{ 0xff, 0xff, 0xea }, .fg = .{ 0x00, 0x00, 0x00 }, - .sel_bg = .{ 0xee, 0xee, 0x9e }, + .sel_bg = .{ 0xfa, 0xfa, 0x92 }, .sel_fg = .{ 0x00, 0x00, 0x00 }, .tag_bg = .{ 0xea, 0xff, 0xff }, .tag_fg = .{ 0x00, 0x00, 0x00 }, - .box = .{ 0x6e, 0x4f, 0xd0 }, - .box_dim = .{ 0x38, 0x3c, 0x54 }, - .kw = .{ 0x88, 0x22, 0x99 }, + .box = .{ 0x66, 0x3f, 0xe0 }, + .box_dim = .{ 0x35, 0x3a, 0x58 }, + .kw = .{ 0x97, 0x0d, 0xae }, .str = .{ 0x00, 0x77, 0x33 }, .num = .{ 0xa0, 0x52, 0x00 }, .comment = .{ 0x55, 0x55, 0x55 }, diff --git a/src/themes/atelier.zig b/src/themes/atelier.zig index 0193e2e9..f367c341 100644 --- a/src/themes/atelier.zig +++ b/src/themes/atelier.zig @@ -11,27 +11,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0x65, 0x3f, 0x6b }, .tag_active_bg = .{ 0xd3, 0xe7, 0xdf }, .tag_active_fg = .{ 0x35, 0x58, 0x4d }, - .box = .{ 0x3e, 0x7a, 0x68 }, - .box_dim = .{ 0x99, 0xb6, 0xa3 }, - .column_box = .{ 0x88, 0x57, 0x22 }, - .column_box_dim = .{ 0xb6, 0xa3, 0x87 }, - .kw = .{ 0x76, 0x4d, 0x80 }, - .str = .{ 0x3c, 0x6c, 0x43 }, - .num = .{ 0x88, 0x57, 0x22 }, - .comment = .{ 0x35, 0x73, 0x3a }, + .box = .{ 0x36, 0x82, 0x6b }, + .box_dim = .{ 0x95, 0xba, 0xa2 }, + .column_box = .{ 0x95, 0x58, 0x15 }, + .column_box_dim = .{ 0xbc, 0xa4, 0x81 }, + .kw = .{ 0x7b, 0x44, 0x89 }, + .str = .{ 0x34, 0x74, 0x3d }, + .num = .{ 0x9a, 0x58, 0x10 }, + .comment = .{ 0x29, 0x7c, 0x30 }, .lineno = .{ 0x90, 0x98, 0x80 }, .lineno_active = .{ 0x88, 0x90, 0x78 }, .scroll_track = .{ 0xee, 0xec, 0xcf }, - .scroll_thumb = .{ 0x9d, 0xa9, 0x7b }, - .border = .{ 0xb8, 0xc8, 0xb4 }, - .sel_bg = .{ 0xe5, 0xe9, 0xae }, + .scroll_thumb = .{ 0x9f, 0xae, 0x76 }, + .border = .{ 0xff, 0xff, 0xff }, + .sel_bg = .{ 0xed, 0xf2, 0xa5 }, .sel_fg = .{ 0x35, 0x49, 0x2d }, - .search_bg = .{ 0xf0, 0xd7, 0x94 }, + .search_bg = .{ 0xfe, 0xdd, 0x86 }, .search_fg = .{ 0x61, 0x47, 0x15 }, - .diagnostic_error = .{ 0xa3, 0x3d, 0x37 }, - .diagnostic_warning = .{ 0x81, 0x59, 0x08 }, - .diagnostic_info = .{ 0x33, 0x65, 0x78 }, - .diagnostic_hint = .{ 0x52, 0x6e, 0x3d }, + .diagnostic_error = .{ 0xb3, 0x2f, 0x27 }, + .diagnostic_warning = .{ 0x89, 0x5c, 0x00 }, + .diagnostic_info = .{ 0x29, 0x6a, 0x82 }, + .diagnostic_hint = .{ 0x51, 0x75, 0x36 }, .palette = .{ .{ 0x29, 0x3f, 0x35 }, .{ 0xa3, 0x3d, 0x37 }, diff --git a/src/themes/clay.zig b/src/themes/clay.zig index af824764..85487d48 100644 --- a/src/themes/clay.zig +++ b/src/themes/clay.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xb5, 0xec, 0xec }, .tag_active_bg = .{ 0x42, 0x4f, 0x40 }, .tag_active_fg = .{ 0xe3, 0xe2, 0xc2 }, - .box = .{ 0x8e, 0xc0, 0x7c }, - .box_dim = .{ 0x67, 0x77, 0x52 }, - .column_box = .{ 0xd3, 0x86, 0x9b }, - .column_box_dim = .{ 0x83, 0x62, 0x68 }, - .kw = .{ 0xfb, 0x8a, 0x69 }, - .str = .{ 0xb8, 0xbb, 0x26 }, - .num = .{ 0xd3, 0x86, 0x9b }, - .comment = .{ 0xe2, 0xb5, 0x6f }, + .box = .{ 0x8a, 0xc8, 0x74 }, + .box_dim = .{ 0x68, 0x7c, 0x4d }, + .column_box = .{ 0xdd, 0x7c, 0x97 }, + .column_box_dim = .{ 0x87, 0x5e, 0x65 }, + .kw = .{ 0xff, 0x88, 0x65 }, + .str = .{ 0xd1, 0xd5, 0x0c }, + .num = .{ 0xe0, 0x79, 0x95 }, + .comment = .{ 0xf6, 0xb9, 0x5b }, .lineno = .{ 0x69, 0x64, 0x55 }, .lineno_active = .{ 0x71, 0x6c, 0x5d }, .scroll_track = .{ 0x22, 0x21, 0x19 }, - .scroll_thumb = .{ 0x8a, 0x90, 0x6b }, - .border = .{ 0x56, 0x64, 0x48 }, - .sel_bg = .{ 0x4f, 0x58, 0x3c }, + .scroll_thumb = .{ 0x8c, 0x94, 0x67 }, + .border = .{ 0x74, 0x87, 0x61 }, + .sel_bg = .{ 0x50, 0x5c, 0x38 }, .sel_fg = .{ 0xfb, 0xf1, 0xc7 }, - .search_bg = .{ 0x66, 0x51, 0x28 }, + .search_bg = .{ 0x6f, 0x54, 0x1f }, .search_fg = .{ 0xff, 0xe2, 0xa0 }, - .diagnostic_error = .{ 0xfb, 0x8a, 0x69 }, - .diagnostic_warning = .{ 0xfa, 0xbd, 0x2f }, - .diagnostic_info = .{ 0x83, 0xb5, 0xa8 }, - .diagnostic_hint = .{ 0x8e, 0xc0, 0x7c }, + .diagnostic_error = .{ 0xff, 0x88, 0x65 }, + .diagnostic_warning = .{ 0xff, 0xbf, 0x2a }, + .diagnostic_info = .{ 0x7b, 0xbd, 0xac }, + .diagnostic_hint = .{ 0x89, 0xca, 0x72 }, .palette = .{ .{ 0x10, 0x10, 0x0e }, .{ 0xfb, 0x8a, 0x69 }, diff --git a/src/themes/dark.zig b/src/themes/dark.zig index 5b39b1c7..82396397 100644 --- a/src/themes/dark.zig +++ b/src/themes/dark.zig @@ -13,15 +13,15 @@ pub const theme = .{ .name = "dark", .bg = null, .fg = null, - .sel_bg = .{ 0x4a, 0x3a, 0x1e }, + .sel_bg = .{ 0x51, 0x3c, 0x17 }, .sel_fg = .{ 0xd8, 0xc8, 0xa8 }, .tag_bg = .{ 0x2c, 0x2a, 0x3e }, .tag_fg = .{ 0x96, 0x96, 0x96 }, - .box = .{ 0x6e, 0x4f, 0xd0 }, - .box_dim = .{ 0x38, 0x3c, 0x54 }, - .kw = .{ 0xcc, 0x70, 0xd8 }, - .str = .{ 0x8a, 0xb8, 0x7a }, - .num = .{ 0xd0, 0xc0, 0x70 }, + .box = .{ 0x66, 0x3f, 0xe0 }, + .box_dim = .{ 0x35, 0x3a, 0x58 }, + .kw = .{ 0xda, 0x5e, 0xea }, + .str = .{ 0x85, 0xc3, 0x6f }, + .num = .{ 0xe1, 0xcb, 0x5f }, .comment = .{ 0xf0, 0xf0, 0xf0 }, .lineno = .{ 0x5a, 0x5a, 0x5a }, .scroll_track = .{ 0x2a, 0x2a, 0x2a }, diff --git a/src/themes/daybreak.zig b/src/themes/daybreak.zig index c55069a9..80f4883c 100644 --- a/src/themes/daybreak.zig +++ b/src/themes/daybreak.zig @@ -11,27 +11,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0x52, 0x25, 0x5f }, .tag_active_bg = .{ 0xdf, 0xea, 0xf3 }, .tag_active_fg = .{ 0x21, 0x3e, 0x56 }, - .box = .{ 0x07, 0x5f, 0x91 }, - .box_dim = .{ 0x81, 0x9d, 0xb1 }, - .column_box = .{ 0x76, 0x42, 0x09 }, - .column_box_dim = .{ 0xb1, 0x9a, 0x80 }, - .kw = .{ 0x62, 0x2a, 0x88 }, - .str = .{ 0x24, 0x5b, 0x30 }, - .num = .{ 0x76, 0x42, 0x09 }, - .comment = .{ 0x14, 0x56, 0x38 }, + .box = .{ 0x00, 0x61, 0x98 }, + .box_dim = .{ 0x7b, 0x9e, 0xb7 }, + .column_box = .{ 0x7f, 0x42, 0x00 }, + .column_box_dim = .{ 0xb7, 0x9a, 0x7a }, + .kw = .{ 0x65, 0x1a, 0x98 }, + .str = .{ 0x1a, 0x65, 0x2b }, + .num = .{ 0x7f, 0x42, 0x00 }, + .comment = .{ 0x08, 0x62, 0x39 }, .lineno = .{ 0x88, 0x93, 0x9b }, .lineno_active = .{ 0x80, 0x8b, 0x93 }, .scroll_track = .{ 0xe6, 0xed, 0xf3 }, - .scroll_thumb = .{ 0x6b, 0x85, 0x9b }, - .border = .{ 0x85, 0x9b, 0xac }, - .sel_bg = .{ 0xc1, 0xde, 0xf3 }, + .scroll_thumb = .{ 0x66, 0x85, 0xa0 }, + .border = .{ 0xc5, 0xcf, 0xd7 }, + .sel_bg = .{ 0xb9, 0xdf, 0xfb }, .sel_fg = .{ 0x10, 0x36, 0x4f }, .search_bg = .{ 0xff, 0xe3, 0x96 }, .search_fg = .{ 0x4b, 0x35, 0x00 }, - .diagnostic_error = .{ 0xa1, 0x1c, 0x30 }, + .diagnostic_error = .{ 0xb3, 0x08, 0x22 }, .diagnostic_warning = .{ 0x70, 0x49, 0x00 }, - .diagnostic_info = .{ 0x07, 0x5a, 0x83 }, - .diagnostic_hint = .{ 0x38, 0x55, 0x2b }, + .diagnostic_info = .{ 0x00, 0x5c, 0x8a }, + .diagnostic_hint = .{ 0x36, 0x5b, 0x25 }, .palette = .{ .{ 0x14, 0x2d, 0x40 }, .{ 0xa1, 0x1c, 0x30 }, diff --git a/src/themes/dusk.zig b/src/themes/dusk.zig index 32948d02..b9377992 100644 --- a/src/themes/dusk.zig +++ b/src/themes/dusk.zig @@ -11,27 +11,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xa1, 0xd5, 0xc4 }, .tag_active_bg = .{ 0x3b, 0x2f, 0x3b }, .tag_active_fg = .{ 0xd2, 0xc2, 0xd1 }, - .box = .{ 0xe4, 0xb3, 0x9b }, - .box_dim = .{ 0x71, 0x57, 0x68 }, - .column_box = .{ 0xba, 0xc8, 0x94 }, - .column_box_dim = .{ 0x73, 0x77, 0x62 }, - .kw = .{ 0xcf, 0xb1, 0xe8 }, - .str = .{ 0xba, 0xc8, 0x94 }, - .num = .{ 0xe8, 0xb5, 0x92 }, - .comment = .{ 0xf1, 0xb9, 0x89 }, + .box = .{ 0xed, 0xb0, 0x92 }, + .box_dim = .{ 0x74, 0x54, 0x69 }, + .column_box = .{ 0xbd, 0xce, 0x8e }, + .column_box_dim = .{ 0x75, 0x7a, 0x5f }, + .kw = .{ 0xd0, 0xa7, 0xf2 }, + .str = .{ 0xbe, 0xd1, 0x8b }, + .num = .{ 0xf7, 0xb2, 0x83 }, + .comment = .{ 0xff, 0xb8, 0x7b }, .lineno = .{ 0x82, 0x71, 0x7e }, .lineno_active = .{ 0x8a, 0x79, 0x86 }, .scroll_track = .{ 0x3d, 0x35, 0x40 }, - .scroll_thumb = .{ 0x8b, 0x69, 0x7c }, - .border = .{ 0x51, 0x41, 0x4f }, - .sel_bg = .{ 0x61, 0x44, 0x53 }, + .scroll_thumb = .{ 0x8e, 0x66, 0x7c }, + .border = .{ 0x6d, 0x58, 0x6b }, + .sel_bg = .{ 0x65, 0x40, 0x53 }, .sel_fg = .{ 0xff, 0xf0, 0xeb }, - .search_bg = .{ 0x5e, 0x49, 0x2e }, + .search_bg = .{ 0x65, 0x4a, 0x27 }, .search_fg = .{ 0xff, 0xe3, 0xa2 }, - .diagnostic_error = .{ 0xf6, 0xaa, 0xa4 }, - .diagnostic_warning = .{ 0xed, 0xca, 0x8a }, - .diagnostic_info = .{ 0xaa, 0xcb, 0xdc }, - .diagnostic_hint = .{ 0xc2, 0xcd, 0xa1 }, + .diagnostic_error = .{ 0xff, 0xa2, 0x9b }, + .diagnostic_warning = .{ 0xfc, 0xce, 0x7b }, + .diagnostic_info = .{ 0xa2, 0xcd, 0xe4 }, + .diagnostic_hint = .{ 0xc5, 0xd4, 0x9a }, .palette = .{ .{ 0x39, 0x32, 0x3b }, .{ 0xf6, 0xaa, 0xa4 }, diff --git a/src/themes/forge.zig b/src/themes/forge.zig index 7f78f2ca..a27f66fb 100644 --- a/src/themes/forge.zig +++ b/src/themes/forge.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xf8, 0xcb, 0xa7 }, .tag_active_bg = .{ 0x2d, 0x34, 0x40 }, .tag_active_fg = .{ 0xd1, 0xd5, 0xde }, - .box = .{ 0xa5, 0xc4, 0xee }, - .box_dim = .{ 0x59, 0x65, 0x77 }, - .column_box = .{ 0xb5, 0xce, 0xa8 }, - .column_box_dim = .{ 0x6b, 0x79, 0x69 }, - .kw = .{ 0x75, 0xb5, 0xe8 }, - .str = .{ 0xce, 0x91, 0x78 }, - .num = .{ 0xb5, 0xce, 0xa8 }, + .box = .{ 0x9c, 0xc3, 0xf7 }, + .box_dim = .{ 0x55, 0x64, 0x7b }, + .column_box = .{ 0xb4, 0xd3, 0xa3 }, + .column_box_dim = .{ 0x6a, 0x7b, 0x67 }, + .kw = .{ 0x61, 0xb7, 0xfc }, + .str = .{ 0xdd, 0x8b, 0x69 }, + .num = .{ 0xb3, 0xd5, 0xa1 }, .comment = .{ 0xb3, 0xca, 0xff }, .lineno = .{ 0x62, 0x65, 0x6c }, .lineno_active = .{ 0x6a, 0x6d, 0x74 }, .scroll_track = .{ 0x1a, 0x1c, 0x21 }, - .scroll_thumb = .{ 0x73, 0x80, 0x92 }, - .border = .{ 0x47, 0x52, 0x63 }, - .sel_bg = .{ 0x26, 0x4f, 0x68 }, + .scroll_thumb = .{ 0x70, 0x80, 0x95 }, + .border = .{ 0x60, 0x6f, 0x86 }, + .sel_bg = .{ 0x1c, 0x51, 0x72 }, .sel_fg = .{ 0xe2, 0xee, 0xf4 }, - .search_bg = .{ 0x59, 0x4a, 0x25 }, + .search_bg = .{ 0x61, 0x4d, 0x1d }, .search_fg = .{ 0xf5, 0xdf, 0xa1 }, - .diagnostic_error = .{ 0xf2, 0x8a, 0x81 }, - .diagnostic_warning = .{ 0xd7, 0xba, 0x7d }, + .diagnostic_error = .{ 0xff, 0x7f, 0x74 }, + .diagnostic_warning = .{ 0xe4, 0xbf, 0x70 }, .diagnostic_info = .{ 0x75, 0xbe, 0xff }, - .diagnostic_hint = .{ 0x8b, 0xce, 0xba }, + .diagnostic_hint = .{ 0x81, 0xd8, 0xbe }, // ANSI roles are semantic colors, independent of peach string syntax. .palette = .{ .{ 0x0c, 0x0c, 0x0e }, diff --git a/src/themes/forge_black.zig b/src/themes/forge_black.zig index d9835110..85f6132e 100644 --- a/src/themes/forge_black.zig +++ b/src/themes/forge_black.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xf8, 0xcb, 0xa7 }, .tag_active_bg = .{ 0x2d, 0x34, 0x40 }, .tag_active_fg = .{ 0xd1, 0xd5, 0xde }, - .box = .{ 0xa5, 0xc4, 0xee }, - .box_dim = .{ 0x59, 0x65, 0x77 }, - .column_box = .{ 0xb5, 0xce, 0xa8 }, - .column_box_dim = .{ 0x6b, 0x79, 0x69 }, - .kw = .{ 0x75, 0xb5, 0xe8 }, - .str = .{ 0xce, 0x91, 0x78 }, - .num = .{ 0xb5, 0xce, 0xa8 }, + .box = .{ 0x9c, 0xc3, 0xf7 }, + .box_dim = .{ 0x55, 0x64, 0x7b }, + .column_box = .{ 0xb4, 0xd3, 0xa3 }, + .column_box_dim = .{ 0x6a, 0x7b, 0x67 }, + .kw = .{ 0x61, 0xb7, 0xfc }, + .str = .{ 0xdd, 0x8b, 0x69 }, + .num = .{ 0xb3, 0xd5, 0xa1 }, .comment = .{ 0xb3, 0xca, 0xff }, .lineno = .{ 0x62, 0x65, 0x6c }, .lineno_active = .{ 0x6a, 0x6d, 0x74 }, .scroll_track = .{ 0x14, 0x16, 0x1a }, - .scroll_thumb = .{ 0x73, 0x80, 0x92 }, - .border = .{ 0x47, 0x52, 0x63 }, - .sel_bg = .{ 0x26, 0x4f, 0x68 }, + .scroll_thumb = .{ 0x70, 0x80, 0x95 }, + .border = .{ 0x60, 0x6f, 0x86 }, + .sel_bg = .{ 0x1c, 0x51, 0x72 }, .sel_fg = .{ 0xe2, 0xee, 0xf4 }, - .search_bg = .{ 0x59, 0x4a, 0x25 }, + .search_bg = .{ 0x61, 0x4d, 0x1d }, .search_fg = .{ 0xf5, 0xdf, 0xa1 }, - .diagnostic_error = .{ 0xf2, 0x8a, 0x81 }, - .diagnostic_warning = .{ 0xd7, 0xba, 0x7d }, + .diagnostic_error = .{ 0xff, 0x7f, 0x74 }, + .diagnostic_warning = .{ 0xe4, 0xbf, 0x70 }, .diagnostic_info = .{ 0x75, 0xbe, 0xff }, - .diagnostic_hint = .{ 0x8b, 0xce, 0xba }, + .diagnostic_hint = .{ 0x81, 0xd8, 0xbe }, // ANSI roles are semantic colors, independent of peach string syntax. .palette = .{ .{ 0x00, 0x00, 0x00 }, diff --git a/src/themes/forge_soft.zig b/src/themes/forge_soft.zig index 896bd9e8..0ca062a4 100644 --- a/src/themes/forge_soft.zig +++ b/src/themes/forge_soft.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xf8, 0xcb, 0xa7 }, .tag_active_bg = .{ 0x37, 0x3e, 0x49 }, .tag_active_fg = .{ 0xd1, 0xd5, 0xde }, - .box = .{ 0xa5, 0xc4, 0xee }, - .box_dim = .{ 0x59, 0x65, 0x77 }, - .column_box = .{ 0xb5, 0xce, 0xa8 }, - .column_box_dim = .{ 0x6f, 0x7d, 0x6e }, - .kw = .{ 0x75, 0xb5, 0xe8 }, - .str = .{ 0xda, 0xa5, 0x8e }, - .num = .{ 0xb5, 0xce, 0xa8 }, + .box = .{ 0x9c, 0xc3, 0xf7 }, + .box_dim = .{ 0x55, 0x64, 0x7b }, + .column_box = .{ 0xb4, 0xd3, 0xa3 }, + .column_box_dim = .{ 0x6d, 0x7f, 0x6c }, + .kw = .{ 0x61, 0xb7, 0xfc }, + .str = .{ 0xe7, 0xa0, 0x81 }, + .num = .{ 0xb3, 0xd5, 0xa1 }, .comment = .{ 0xb3, 0xca, 0xff }, .lineno = .{ 0x86, 0x89, 0x91 }, .lineno_active = .{ 0x8e, 0x91, 0x99 }, .scroll_track = .{ 0x3d, 0x40, 0x47 }, - .scroll_thumb = .{ 0x73, 0x80, 0x92 }, - .border = .{ 0x47, 0x52, 0x63 }, - .sel_bg = .{ 0x26, 0x4f, 0x68 }, + .scroll_thumb = .{ 0x70, 0x80, 0x95 }, + .border = .{ 0x60, 0x6f, 0x86 }, + .sel_bg = .{ 0x1c, 0x51, 0x72 }, .sel_fg = .{ 0xe2, 0xee, 0xf4 }, - .search_bg = .{ 0x59, 0x4a, 0x25 }, + .search_bg = .{ 0x61, 0x4d, 0x1d }, .search_fg = .{ 0xf5, 0xdf, 0xa1 }, - .diagnostic_error = .{ 0xf2, 0x8a, 0x81 }, - .diagnostic_warning = .{ 0xd7, 0xba, 0x7d }, + .diagnostic_error = .{ 0xff, 0x7f, 0x74 }, + .diagnostic_warning = .{ 0xe4, 0xbf, 0x70 }, .diagnostic_info = .{ 0x75, 0xbe, 0xff }, - .diagnostic_hint = .{ 0x8b, 0xce, 0xba }, + .diagnostic_hint = .{ 0x81, 0xd8, 0xbe }, // ANSI roles are semantic colors, independent of peach string syntax. .palette = .{ .{ 0x35, 0x38, 0x3e }, diff --git a/src/themes/harvest.zig b/src/themes/harvest.zig index bf367a24..cf10a779 100644 --- a/src/themes/harvest.zig +++ b/src/themes/harvest.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xc5, 0xe7, 0xf7 }, .tag_active_bg = .{ 0x42, 0x4d, 0x38 }, .tag_active_fg = .{ 0xe1, 0xe4, 0xc4 }, - .box = .{ 0xcf, 0xba, 0x8b }, - .box_dim = .{ 0x77, 0x79, 0x53 }, - .column_box = .{ 0xf0, 0x7d, 0x63 }, - .column_box_dim = .{ 0x92, 0x5c, 0x48 }, - .kw = .{ 0xf0, 0x7d, 0x63 }, - .str = .{ 0x99, 0xbe, 0x70 }, - .num = .{ 0xfa, 0xd5, 0x66 }, - .comment = .{ 0xef, 0xc7, 0x8c }, + .box = .{ 0xd8, 0xbd, 0x83 }, + .box_dim = .{ 0x7b, 0x7e, 0x4e }, + .column_box = .{ 0xff, 0x74, 0x54 }, + .column_box_dim = .{ 0x9b, 0x58, 0x3f }, + .kw = .{ 0xff, 0x74, 0x54 }, + .str = .{ 0x9a, 0xcc, 0x62 }, + .num = .{ 0xff, 0xd8, 0x61 }, + .comment = .{ 0xff, 0xca, 0x7c }, .lineno = .{ 0x6a, 0x64, 0x56 }, .lineno_active = .{ 0x72, 0x6c, 0x5e }, .scroll_track = .{ 0x20, 0x1d, 0x17 }, - .scroll_thumb = .{ 0x85, 0x8a, 0x62 }, - .border = .{ 0x59, 0x65, 0x47 }, - .sel_bg = .{ 0x4d, 0x54, 0x38 }, + .scroll_thumb = .{ 0x88, 0x8e, 0x5e }, + .border = .{ 0x78, 0x88, 0x60 }, + .sel_bg = .{ 0x4f, 0x58, 0x34 }, .sel_fg = .{ 0xf3, 0xf2, 0xcc }, - .search_bg = .{ 0x66, 0x45, 0x2d }, + .search_bg = .{ 0x6f, 0x44, 0x24 }, .search_fg = .{ 0xff, 0xe2, 0xac }, - .diagnostic_error = .{ 0xf5, 0x8a, 0x73 }, - .diagnostic_warning = .{ 0xfa, 0xd5, 0x66 }, - .diagnostic_info = .{ 0x86, 0xc1, 0xb9 }, - .diagnostic_hint = .{ 0xb5, 0xc6, 0x8c }, + .diagnostic_error = .{ 0xff, 0x84, 0x69 }, + .diagnostic_warning = .{ 0xff, 0xd8, 0x61 }, + .diagnostic_info = .{ 0x7d, 0xca, 0xbf }, + .diagnostic_hint = .{ 0xb9, 0xcf, 0x83 }, .palette = .{ .{ 0x10, 0x0e, 0x0b }, .{ 0xf5, 0x8a, 0x73 }, diff --git a/src/themes/helix.zig b/src/themes/helix.zig index 3c2934f7..76eaeab2 100644 --- a/src/themes/helix.zig +++ b/src/themes/helix.zig @@ -45,9 +45,9 @@ pub const theme = .{ .tag_fg = .{ 0x94, 0x94, 0x94 }, .box = .{ 0x62, 0x62, 0x62 }, .box_dim = .{ 0x26, 0x26, 0x26 }, - .kw = .{ 0xcf, 0x87, 0xe8 }, - .str = .{ 0xe3, 0xc7, 0x8a }, - .num = .{ 0xe3, 0xc7, 0x8a }, + .kw = .{ 0xd7, 0x76, 0xf9 }, + .str = .{ 0xf3, 0xcd, 0x7a }, + .num = .{ 0xf3, 0xcd, 0x7a }, .comment = .{ 0xff, 0xff, 0xff }, .lineno = .{ 0x62, 0x62, 0x62 }, .scroll_track = .{ 0x12, 0x12, 0x12 }, diff --git a/src/themes/ink.zig b/src/themes/ink.zig index 3b92a635..1e254a3c 100644 --- a/src/themes/ink.zig +++ b/src/themes/ink.zig @@ -12,26 +12,26 @@ pub const theme = .{ .tag_active_bg = .{ 0x22, 0x33, 0x42 }, .tag_active_fg = .{ 0xe1, 0xee, 0xf9 }, .box = .{ 0x86, 0xd8, 0xff }, - .box_dim = .{ 0x64, 0x79, 0x8b }, + .box_dim = .{ 0x5f, 0x79, 0x90 }, .column_box = .{ 0xff, 0xd6, 0x94 }, - .column_box_dim = .{ 0x8a, 0x7b, 0x60 }, + .column_box_dim = .{ 0x8f, 0x7d, 0x5b }, .kw = .{ 0xd5, 0xb8, 0xff }, - .str = .{ 0xb5, 0xee, 0xae }, + .str = .{ 0xac, 0xf9, 0xa3 }, .num = .{ 0xff, 0xd6, 0x94 }, - .comment = .{ 0xa8, 0xe7, 0xf4 }, + .comment = .{ 0x9d, 0xee, 0xff }, .lineno = .{ 0x62, 0x6b, 0x75 }, .lineno_active = .{ 0x6a, 0x73, 0x7d }, .scroll_track = .{ 0x15, 0x21, 0x2c }, - .scroll_thumb = .{ 0x8b, 0xa7, 0xbd }, - .border = .{ 0x59, 0x6f, 0x83 }, - .sel_bg = .{ 0x26, 0x52, 0x71 }, + .scroll_thumb = .{ 0x86, 0xa8, 0xc2 }, + .border = .{ 0x80, 0x95, 0xa9 }, + .sel_bg = .{ 0x1b, 0x54, 0x7c }, .sel_fg = .{ 0xff, 0xff, 0xff }, - .search_bg = .{ 0x75, 0x50, 0x1b }, + .search_bg = .{ 0x7c, 0x4e, 0x0d }, .search_fg = .{ 0xff, 0xff, 0xff }, .diagnostic_error = .{ 0xff, 0xb1, 0xb1 }, .diagnostic_warning = .{ 0xff, 0xe2, 0x9c }, .diagnostic_info = .{ 0x9b, 0xde, 0xff }, - .diagnostic_hint = .{ 0xc6, 0xe4, 0xb5 }, + .diagnostic_hint = .{ 0xc4, 0xeb, 0xae }, .palette = .{ .{ 0x00, 0x00, 0x00 }, .{ 0xff, 0xb1, 0xb1 }, diff --git a/src/themes/lagoon.zig b/src/themes/lagoon.zig index 516639b0..4d975794 100644 --- a/src/themes/lagoon.zig +++ b/src/themes/lagoon.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xf0, 0xce, 0xf8 }, .tag_active_bg = .{ 0x34, 0x57, 0x4d }, .tag_active_fg = .{ 0xc7, 0xe3, 0xd7 }, - .box = .{ 0x89, 0xc7, 0xb4 }, - .box_dim = .{ 0x59, 0x7e, 0x71 }, + .box = .{ 0x81, 0xcf, 0xb7 }, + .box_dim = .{ 0x54, 0x83, 0x72 }, .column_box = .{ 0xff, 0xad, 0x91 }, - .column_box_dim = .{ 0x94, 0x78, 0x68 }, - .kw = .{ 0xd5, 0xa8, 0xed }, - .str = .{ 0xc3, 0xe8, 0x8d }, + .column_box_dim = .{ 0x9a, 0x76, 0x62 }, + .kw = .{ 0xd9, 0x9c, 0xf9 }, + .str = .{ 0xc6, 0xf8, 0x7d }, .num = .{ 0xff, 0xad, 0x91 }, - .comment = .{ 0x92, 0xe1, 0xd1 }, + .comment = .{ 0x84, 0xef, 0xd9 }, .lineno = .{ 0x7b, 0x91, 0x94 }, .lineno_active = .{ 0x83, 0x99, 0x9c }, .scroll_track = .{ 0x3a, 0x4c, 0x50 }, - .scroll_thumb = .{ 0x72, 0x97, 0x8a }, - .border = .{ 0x50, 0x74, 0x68 }, - .sel_bg = .{ 0x39, 0x5b, 0x65 }, + .scroll_thumb = .{ 0x6e, 0x9b, 0x8b }, + .border = .{ 0x6e, 0x9b, 0x8c }, + .sel_bg = .{ 0x32, 0x5f, 0x6c }, .sel_fg = .{ 0xe6, 0xf2, 0xf3 }, - .search_bg = .{ 0x60, 0x53, 0x27 }, + .search_bg = .{ 0x69, 0x58, 0x1e }, .search_fg = .{ 0xff, 0xf0, 0xb9 }, .diagnostic_error = .{ 0xff, 0x9d, 0xa1 }, .diagnostic_warning = .{ 0xff, 0xcb, 0x6b }, - .diagnostic_info = .{ 0x82, 0xc9, 0xfa }, - .diagnostic_hint = .{ 0x89, 0xdd, 0xcc }, + .diagnostic_info = .{ 0x7d, 0xca, 0xff }, + .diagnostic_hint = .{ 0x7c, 0xea, 0xd4 }, .palette = .{ .{ 0x34, 0x46, 0x4c }, .{ 0xff, 0x9d, 0xa1 }, diff --git a/src/themes/orchard.zig b/src/themes/orchard.zig index 888a5b27..f927c50e 100644 --- a/src/themes/orchard.zig +++ b/src/themes/orchard.zig @@ -11,27 +11,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xdf, 0xbc, 0xe5 }, .tag_active_bg = .{ 0x26, 0x36, 0x2d }, .tag_active_fg = .{ 0xbe, 0xcf, 0xc4 }, - .box = .{ 0xad, 0xcc, 0x91 }, - .box_dim = .{ 0x4c, 0x63, 0x56 }, - .column_box = .{ 0xe9, 0xbf, 0x91 }, - .column_box_dim = .{ 0x83, 0x73, 0x5a }, - .kw = .{ 0xc9, 0xb0, 0xe4 }, - .str = .{ 0xb6, 0xce, 0x94 }, - .num = .{ 0xe9, 0xbf, 0x91 }, - .comment = .{ 0xb9, 0xe5, 0x8f }, + .box = .{ 0xad, 0xd3, 0x8a }, + .box_dim = .{ 0x49, 0x66, 0x56 }, + .column_box = .{ 0xf4, 0xc0, 0x86 }, + .column_box_dim = .{ 0x88, 0x74, 0x55 }, + .kw = .{ 0xc9, 0xa7, 0xed }, + .str = .{ 0xb8, 0xd8, 0x8a }, + .num = .{ 0xf8, 0xc0, 0x82 }, + .comment = .{ 0xb9, 0xf4, 0x80 }, .lineno = .{ 0x59, 0x67, 0x5c }, .lineno_active = .{ 0x61, 0x6f, 0x64 }, .scroll_track = .{ 0x15, 0x20, 0x19 }, - .scroll_thumb = .{ 0x63, 0x7f, 0x6a }, - .border = .{ 0x35, 0x48, 0x3d }, - .sel_bg = .{ 0x40, 0x5d, 0x4b }, + .scroll_thumb = .{ 0x60, 0x82, 0x69 }, + .border = .{ 0x48, 0x61, 0x52 }, + .sel_bg = .{ 0x3c, 0x61, 0x4a }, .sel_fg = .{ 0xf5, 0xf7, 0xee }, - .search_bg = .{ 0x57, 0x47, 0x2a }, + .search_bg = .{ 0x5e, 0x49, 0x23 }, .search_fg = .{ 0xf7, 0xe4, 0xa5 }, - .diagnostic_error = .{ 0xf1, 0xa3, 0x9b }, - .diagnostic_warning = .{ 0xe9, 0xc6, 0x80 }, - .diagnostic_info = .{ 0x9b, 0xcb, 0xd5 }, - .diagnostic_hint = .{ 0xb6, 0xc5, 0x9e }, + .diagnostic_error = .{ 0xfe, 0x98, 0x8e }, + .diagnostic_warning = .{ 0xf9, 0xcb, 0x70 }, + .diagnostic_info = .{ 0x92, 0xd1, 0xde }, + .diagnostic_hint = .{ 0xb7, 0xcb, 0x98 }, .palette = .{ .{ 0x0d, 0x14, 0x10 }, .{ 0xf1, 0xa3, 0x9b }, diff --git a/src/themes/orchard_black.zig b/src/themes/orchard_black.zig index be960b93..c700947f 100644 --- a/src/themes/orchard_black.zig +++ b/src/themes/orchard_black.zig @@ -11,27 +11,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xdf, 0xbc, 0xe5 }, .tag_active_bg = .{ 0x26, 0x36, 0x2d }, .tag_active_fg = .{ 0xbe, 0xcf, 0xc4 }, - .box = .{ 0xad, 0xcc, 0x91 }, - .box_dim = .{ 0x4c, 0x63, 0x56 }, - .column_box = .{ 0xe9, 0xbf, 0x91 }, - .column_box_dim = .{ 0x83, 0x73, 0x5a }, - .kw = .{ 0xc9, 0xb0, 0xe4 }, - .str = .{ 0xb6, 0xce, 0x94 }, - .num = .{ 0xe9, 0xbf, 0x91 }, - .comment = .{ 0xb9, 0xe5, 0x8f }, + .box = .{ 0xad, 0xd3, 0x8a }, + .box_dim = .{ 0x49, 0x66, 0x56 }, + .column_box = .{ 0xf4, 0xc0, 0x86 }, + .column_box_dim = .{ 0x88, 0x74, 0x55 }, + .kw = .{ 0xc9, 0xa7, 0xed }, + .str = .{ 0xb8, 0xd8, 0x8a }, + .num = .{ 0xf8, 0xc0, 0x82 }, + .comment = .{ 0xb9, 0xf4, 0x80 }, .lineno = .{ 0x59, 0x67, 0x5c }, .lineno_active = .{ 0x61, 0x6f, 0x64 }, .scroll_track = .{ 0x11, 0x18, 0x13 }, - .scroll_thumb = .{ 0x63, 0x7f, 0x6a }, - .border = .{ 0x35, 0x48, 0x3d }, - .sel_bg = .{ 0x40, 0x5d, 0x4b }, + .scroll_thumb = .{ 0x60, 0x82, 0x69 }, + .border = .{ 0x48, 0x61, 0x52 }, + .sel_bg = .{ 0x3c, 0x61, 0x4a }, .sel_fg = .{ 0xf5, 0xf7, 0xee }, - .search_bg = .{ 0x57, 0x47, 0x2a }, + .search_bg = .{ 0x5e, 0x49, 0x23 }, .search_fg = .{ 0xf7, 0xe4, 0xa5 }, - .diagnostic_error = .{ 0xf1, 0xa3, 0x9b }, - .diagnostic_warning = .{ 0xe9, 0xc6, 0x80 }, - .diagnostic_info = .{ 0x9b, 0xcb, 0xd5 }, - .diagnostic_hint = .{ 0xb6, 0xc5, 0x9e }, + .diagnostic_error = .{ 0xfe, 0x98, 0x8e }, + .diagnostic_warning = .{ 0xf9, 0xcb, 0x70 }, + .diagnostic_info = .{ 0x92, 0xd1, 0xde }, + .diagnostic_hint = .{ 0xb7, 0xcb, 0x98 }, .palette = .{ .{ 0x00, 0x00, 0x00 }, .{ 0xf1, 0xa3, 0x9b }, diff --git a/src/themes/paper.zig b/src/themes/paper.zig index b5d24835..f1d6980b 100644 --- a/src/themes/paper.zig +++ b/src/themes/paper.zig @@ -11,27 +11,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0x69, 0x44, 0x7a }, .tag_active_bg = .{ 0xdc, 0xe5, 0xdc }, .tag_active_fg = .{ 0x4a, 0x5a, 0x52 }, - .box = .{ 0x3c, 0x6b, 0x56 }, - .box_dim = .{ 0x91, 0xa3, 0x95 }, - .column_box = .{ 0x87, 0x58, 0x26 }, - .column_box_dim = .{ 0xb7, 0xa1, 0x84 }, - .kw = .{ 0x73, 0x51, 0x90 }, - .str = .{ 0x41, 0x68, 0x48 }, - .num = .{ 0x87, 0x58, 0x26 }, - .comment = .{ 0x2e, 0x71, 0x59 }, + .box = .{ 0x36, 0x71, 0x57 }, + .box_dim = .{ 0x8f, 0xa5, 0x94 }, + .column_box = .{ 0x93, 0x58, 0x1a }, + .column_box_dim = .{ 0xbd, 0xa2, 0x7e }, + .kw = .{ 0x74, 0x46, 0x9b }, + .str = .{ 0x3a, 0x6f, 0x44 }, + .num = .{ 0x98, 0x59, 0x15 }, + .comment = .{ 0x20, 0x75, 0x56 }, .lineno = .{ 0x8b, 0x91, 0x85 }, .lineno_active = .{ 0x83, 0x89, 0x7d }, .scroll_track = .{ 0xe5, 0xe8, 0xdf }, - .scroll_thumb = .{ 0x88, 0x9b, 0x8b }, - .border = .{ 0xb5, 0xc1, 0xb3 }, - .sel_bg = .{ 0xc8, 0xdf, 0xd1 }, + .scroll_thumb = .{ 0x86, 0x9d, 0x8a }, + .border = .{ 0xfb, 0xfb, 0xfb }, + .sel_bg = .{ 0xc5, 0xe2, 0xd0 }, .sel_fg = .{ 0x20, 0x3e, 0x31 }, - .search_bg = .{ 0xf0, 0xdd, 0xa8 }, + .search_bg = .{ 0xfb, 0xe2, 0x9d }, .search_fg = .{ 0x61, 0x46, 0x1c }, - .diagnostic_error = .{ 0xa3, 0x39, 0x38 }, - .diagnostic_warning = .{ 0x80, 0x57, 0x0c }, - .diagnostic_info = .{ 0x30, 0x65, 0x75 }, - .diagnostic_hint = .{ 0x52, 0x6d, 0x3e }, + .diagnostic_error = .{ 0xb3, 0x29, 0x28 }, + .diagnostic_warning = .{ 0x8c, 0x5b, 0x00 }, + .diagnostic_info = .{ 0x26, 0x6b, 0x7f }, + .diagnostic_hint = .{ 0x51, 0x74, 0x37 }, .palette = .{ .{ 0x30, 0x3b, 0x3b }, .{ 0xa3, 0x39, 0x38 }, diff --git a/src/themes/solarium.zig b/src/themes/solarium.zig index fe2525a6..21b4c451 100644 --- a/src/themes/solarium.zig +++ b/src/themes/solarium.zig @@ -12,27 +12,27 @@ pub const theme = .{ .tag_active_name_fg = .{ 0xf5, 0xcd, 0xec }, .tag_active_bg = .{ 0x21, 0x4e, 0x50 }, .tag_active_fg = .{ 0xd3, 0xe0, 0xc9 }, - .box = .{ 0xd5, 0xbc, 0x72 }, - .box_dim = .{ 0x4c, 0x79, 0x72 }, - .column_box = .{ 0x6a, 0xae, 0xdd }, - .column_box_dim = .{ 0x3e, 0x76, 0x90 }, - .kw = .{ 0x6a, 0xae, 0xdd }, - .str = .{ 0xaf, 0xbd, 0x52 }, - .num = .{ 0xd9, 0x9a, 0x5e }, - .comment = .{ 0xe2, 0xc4, 0x6e }, + .box = .{ 0xe1, 0xc2, 0x66 }, + .box_dim = .{ 0x46, 0x7f, 0x76 }, + .column_box = .{ 0x5c, 0xb1, 0xeb }, + .column_box_dim = .{ 0x34, 0x7a, 0x9a }, + .kw = .{ 0x56, 0xb2, 0xf1 }, + .str = .{ 0xbd, 0xd0, 0x3f }, + .num = .{ 0xef, 0x99, 0x48 }, + .comment = .{ 0xf6, 0xce, 0x5a }, .lineno = .{ 0x64, 0x7e, 0x7c }, .lineno_active = .{ 0x6c, 0x86, 0x84 }, .scroll_track = .{ 0x1c, 0x45, 0x4c }, - .scroll_thumb = .{ 0x69, 0x93, 0x8a }, - .border = .{ 0x38, 0x65, 0x5f }, - .sel_bg = .{ 0x27, 0x56, 0x5c }, + .scroll_thumb = .{ 0x65, 0x97, 0x8c }, + .border = .{ 0x4c, 0x88, 0x80 }, + .sel_bg = .{ 0x1f, 0x5c, 0x64 }, .sel_fg = .{ 0xee, 0xe8, 0xd5 }, - .search_bg = .{ 0x64, 0x53, 0x26 }, + .search_bg = .{ 0x6d, 0x57, 0x1d }, .search_fg = .{ 0xff, 0xf0, 0xb9 }, - .diagnostic_error = .{ 0xed, 0x84, 0x77 }, - .diagnostic_warning = .{ 0xdf, 0xb6, 0x5b }, - .diagnostic_info = .{ 0x6a, 0xae, 0xdd }, - .diagnostic_hint = .{ 0x69, 0xbd, 0xb0 }, + .diagnostic_error = .{ 0xff, 0x7a, 0x6a }, + .diagnostic_warning = .{ 0xf3, 0xbe, 0x47 }, + .diagnostic_info = .{ 0x59, 0xb1, 0xee }, + .diagnostic_hint = .{ 0x5c, 0xca, 0xb9 }, .palette = .{ .{ 0x17, 0x3e, 0x45 }, .{ 0xed, 0x84, 0x77 }, diff --git a/src/themes/spectrum.zig b/src/themes/spectrum.zig index 5a1cecc6..a0faf897 100644 --- a/src/themes/spectrum.zig +++ b/src/themes/spectrum.zig @@ -13,26 +13,26 @@ pub const theme = .{ .tag_active_bg = .{ 0x4d, 0x47, 0x36 }, .tag_active_fg = .{ 0xe9, 0xe4, 0xc7 }, .box = .{ 0xff, 0xd8, 0x66 }, - .box_dim = .{ 0x8b, 0x80, 0x56 }, - .column_box = .{ 0xab, 0x9d, 0xf2 }, - .column_box_dim = .{ 0x73, 0x6a, 0x91 }, + .box_dim = .{ 0x92, 0x84, 0x4f }, + .column_box = .{ 0xa4, 0x92, 0xfd }, + .column_box_dim = .{ 0x70, 0x65, 0x96 }, .kw = .{ 0xff, 0x61, 0x88 }, - .str = .{ 0xa9, 0xdc, 0x76 }, - .num = .{ 0xab, 0x9d, 0xf2 }, + .str = .{ 0xa9, 0xee, 0x64 }, + .num = .{ 0xa2, 0x90, 0xff }, .comment = .{ 0xff, 0xe0, 0x9b }, .lineno = .{ 0x68, 0x61, 0x6b }, .lineno_active = .{ 0x70, 0x69, 0x73 }, .scroll_track = .{ 0x21, 0x1d, 0x23 }, - .scroll_thumb = .{ 0x91, 0x8b, 0x72 }, - .border = .{ 0x6a, 0x64, 0x50 }, - .sel_bg = .{ 0x51, 0x43, 0x5c }, + .scroll_thumb = .{ 0x94, 0x8d, 0x6f }, + .border = .{ 0x8f, 0x87, 0x6c }, + .sel_bg = .{ 0x51, 0x3f, 0x60 }, .sel_fg = .{ 0xfc, 0xfc, 0xfa }, - .search_bg = .{ 0x66, 0x56, 0x27 }, + .search_bg = .{ 0x6f, 0x5b, 0x1e }, .search_fg = .{ 0xff, 0xf0, 0xb0 }, .diagnostic_error = .{ 0xff, 0x79, 0x9b }, .diagnostic_warning = .{ 0xff, 0xd8, 0x66 }, - .diagnostic_info = .{ 0x78, 0xdc, 0xe8 }, - .diagnostic_hint = .{ 0xa9, 0xdc, 0x76 }, + .diagnostic_info = .{ 0x67, 0xe9, 0xf9 }, + .diagnostic_hint = .{ 0xa9, 0xeb, 0x67 }, .palette = .{ .{ 0x10, 0x0e, 0x11 }, .{ 0xff, 0x79, 0x9b }, diff --git a/src/web.zig b/src/web.zig index b5a992ae..7325af54 100644 --- a/src/web.zig +++ b/src/web.zig @@ -376,7 +376,7 @@ export fn pardes_tag_layer_cells(index: u32) ?[*]const WebCell { } export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { - return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h); + return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h, true); } export fn pardes_body_layer_value(index: u32, field: u32) u32 { diff --git a/test/macos_e2e.swift b/test/macos_e2e.swift index 5efc366c..5f172f9d 100644 --- a/test/macos_e2e.swift +++ b/test/macos_e2e.swift @@ -628,8 +628,8 @@ private final class Driver: PardesViewDelegate { let bottom = kind == 2 && pardes_tag_layer_value(i, 11) != 0 for pixel in 0..= height - 2) { rgb = 0x606f86 } + if pardes_tag_layer_value(i, 5) == UInt32(PARDES_TOPBAR_H) && pixel == 0 { rgb = 0x606f86 } try check(x: x, y: top + (CGFloat(pixel) + 0.5) / scale, rgb: rgb, name: "tag \(i), pixel \(pixel)") } @@ -656,7 +656,7 @@ private final class Driver: PardesViewDelegate { guard let c = sample(rep, x: Int(x * scale), y: Int(y * scale)) else { throw ScriptError(message: "context: no separator pixel") } - let rgb: UInt32 = 0x475263 // Forge border, also used by the Linux chrome overlay. + let rgb: UInt32 = 0x606f86 // Forge border, also used by the Linux chrome overlay. guard abs(c.redComponent * 255 - CGFloat((rgb >> 16) & 255)) < 4, abs(c.greenComponent * 255 - CGFloat((rgb >> 8) & 255)) < 4, abs(c.blueComponent * 255 - CGFloat(rgb & 255)) < 4, @@ -1270,6 +1270,10 @@ private func buildWorld(stem: String) throws -> String { // A wall clock cannot live in a golden. Everything that would print one // prints fixed characters instead when this is set. _ = setenv("PARDES_NOTIME", "1", 1) + // The scripts speak to a grid that HAS the workspace tag row: the app + // hands that row to its native menu bar, but this harness is the + // topbar's test bench, so opt back in before pardes_init reads it. + _ = setenv("PARDES_WORKSPACE_TAG", "1", 1) guard fm.changeCurrentDirectoryPath(work) else { throw ScriptError(message: "could not chdir into \(work)") } -- cgit v1.3 From f6738c7edfff2249e0b13f2a76962f45d02c86bb Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 23 Sep 2026 02:00:00 -0300 Subject: Center tagline bands, frame anchors evenly, fill to the window edge, and resize columns from their grip Every tag band (workspace, column, pane) is centred in its row, so text sits at one baseline offset. Anchors are inset from the column rule by that same margin, so they are square and the band frames them on the left, top and bottom; the pane mark moves to stay centred. When the window is not a whole number of cells, the bands, rules, spines and scroll thumbs at the right and bottom edges run on through the leftover pixels. A column grip dropped short of another column's place now moves the column's left edge, with a dashed rail preview, sharing setColumnPairWidth with the border drag. A release still on the grip changes nothing, and a pair too narrow for two MINW columns is left alone. PARDES_TEST_PAD adds leftover pixels to a test-mode window and capture. --- docs/config.md | 16 ++++--- features.txt | 2 +- src/gui/gui.zig | 88 ++++++++++++++++++++++++++------------ src/layout.zig | 17 ++++++++ src/macos.zig | 2 +- src/macos/Sources/PardesView.swift | 5 +-- src/pardes.zig | 60 +++++++++++++------------- src/web.zig | 2 +- test/column_drag.zig | 40 +++++++++++++++++ 9 files changed, 161 insertions(+), 71 deletions(-) (limited to 'src/macos/Sources') diff --git a/docs/config.md b/docs/config.md index 27818b5b..ab5e5617 100644 --- a/docs/config.md +++ b/docs/config.md @@ -398,16 +398,18 @@ band would overlap its pane body or a neighbour instead of leaving the body grid stable. `Config` reports the active percentage. The browser applies the same compiled percentage to its DOM glyphs but has no runtime setter. -Both native GUIs join the reduced-height global and pane tagline bands with -`gui_topbar_pane_border_px` physical pixels. Set it to zero for a direct join. +Both native GUIs separate the reduced-height global and pane tagline bands with +a `gui_topbar_pane_border_px` physical-pixel rule. Set it to zero to leave it out. `gui_topbar_pane_border_rgb` can pin an RGB color; its default `null` follows the theme's `border` role in SDL (falling back to `scroll_track` for older -themes), and `scroll_track` in the macOS shell. With `Tagbottom` enabled, a tagline -on the final grid row is bottom-aligned so the same unused half-band does not -show beneath it. The rule itself lives in the core +themes), and `scroll_track` in the macOS shell. Every band is centred in its +row, so the workspace, column and pane tag text share one baseline offset and +the anchors get the same margin above, below and to the left. With `Tagbottom` +enabled, a tagline on the final grid row is bottom-aligned so the unused +half-band does not show beneath it. The rule lives in the core (`pardes.taglineBandOffset`), and the macOS shell reaches it over the C ABI -rather than keeping its own copy — it had one, it only ever centred, and the -seam that leaves between the two bands is what this setting exists to close. +rather than keeping its own copy. When the window is not a whole number of cells, +bands and rules at the right and bottom edges run on through the leftover pixels. What happens to a codepoint the chosen face has no glyph for differs by shell. The SDL GUI falls back through a chain it builds itself: embedded Adwaita diff --git a/features.txt b/features.txt index 0db7c497..86b2a834 100644 --- a/features.txt +++ b/features.txt @@ -162,7 +162,7 @@ Found by adversarial review and NOT fixed, because they are upstream or macOS-on contributes 0, and PardesView's liquid-glass affordance never draws. The tests pass only because they set the flag by hand. The comment in the look_hover_preview paint block claims it carries those cells out to the hosts; it does not. - -Dworkspace-tag is read only in src/macos.zig, and core.settings.workspace_tag is assigned only there, so the option builds cleanly for gui/tty/web and is - silently ignored. gui.zig hard-codes `true` at six taglineBandOffset call sites and still uses raw TOPBAR_H at five more. + silently ignored. (taglineBandOffset no longer takes it: every band is centred since 2026-09-23.) gui.zig still uses raw TOPBAR_H at five sites. - The detached wire encodes the pointer shape in the frame header variant (full_link/diff_link), so the newer `.target` shape collapses to `.arrow` for an attached frontend. Fixing it means a new header variant, i.e. a protocol change. - A shell that outlives its editor keeps PARDES_PID; if that pid is reused, `pardes ` now exits 1 instead of falling back to starting an editor. Exiting 1 diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 7f28124c..48087d0b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1809,6 +1809,8 @@ const Gui = struct { pointer_cell: ?MouseCell = null, capture: bool = false, + /// Pixels the capture holds past the grid (PARDES_TEST_PAD). + capture_pad: u32 = 0, capture_dir: []const u8 = "", capture_tex: ?*c.SDL_GPUTexture = null, capture_tex_w: u32 = 0, @@ -2196,7 +2198,9 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u if (test_mode) { const cols = envU16(env, "PARDES_TEST_COLS") orelse 80; const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24; - _ = c.SDL_SetWindowSize(window, @intCast(cols * cell_w), @intCast(rows * cell_h)); + // PARDES_TEST_PAD: extra pixels past the grid, as a real window has. + const pad = envU16(env, "PARDES_TEST_PAD") orelse 0; + _ = c.SDL_SetWindowSize(window, @intCast(cols * cell_w + pad), @intCast(rows * cell_h + pad)); _ = c.SDL_SyncWindow(window); } @@ -2284,6 +2288,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .atlas_stage = atlas_stage, .glyphs = std.AutoHashMap(GlyphKey, Slot).init(gpa), .capture = test_mode, + .capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0, .capture_dir = capture_dir orelse "", .soft_present = soft_present, .transparent = config.gui_transparent, @@ -4909,8 +4914,8 @@ fn renderFrame( var sh: u32 = 0; var target: *c.SDL_GPUTexture = undefined; if (g.capture) { - sw = @as(u32, surface.cols) * g.cell_w; - sh = @as(u32, surface.rows) * g.cell_h; + sw = @as(u32, surface.cols) * g.cell_w + g.capture_pad; + sh = @as(u32, surface.rows) * g.cell_h + g.capture_pad; if (sw == 0 or sh == 0) { command_consumed = true; _ = c.SDL_SubmitGPUCommandBuffer(cmd); @@ -5360,18 +5365,14 @@ fn bottomTaglinePresent(surface: *const pardes.Surface) bool { return false; } -test "tagline bands face the topbar rule and Tagbottom faces the window edge" { +test "tagline bands center in their cells and Tagbottom faces the window edge" { const cell_h: u32 = 20; const tagline_h: u32 = 16; const canvas_h: f32 = 200; - const border = topbarPaneBorderPixels(cell_h, tagline_h); - try std.testing.expectEqual(@as(u32, 1), border); - try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(0, canvas_h, cell_h, tagline_h, true)); - try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(0, canvas_h, cell_h, tagline_h, false)); - try std.testing.expectEqual(@as(u32, 1), taglineBandOffset(1, canvas_h, cell_h, tagline_h, true)); - try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(1, canvas_h, cell_h, tagline_h, false)); - try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(5, canvas_h, cell_h, tagline_h, true)); - try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(9, canvas_h, cell_h, tagline_h, true)); + // Workspace, column and pane rows alike: text lines up across bands. + for ([_]u16{ 0, 1, 2, 5, 8 }) |row| + try std.testing.expectEqual(@as(u32, 2), taglineBandOffset(row, canvas_h, cell_h, tagline_h)); + try std.testing.expectEqual(@as(u32, 4), taglineBandOffset(9, canvas_h, cell_h, tagline_h)); } fn resolveCell(g: *Gui, cell: *const pardes.Cell, role: pardes.FontRole, is_cursor: bool, page: Ground) ResolvedCell { @@ -5502,7 +5503,10 @@ fn emitTagLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const p // it comes out from under whatever is above it. const slide = layer.slide * bh; const top = @as(f32, @floatFromInt(layer.viewport.y)) * bh; - emitInstance(g, instances, next.*, 0, layer.viewport.y, .{ .w = right - left, .h = bh, .x_off = left, .y_off = slide }, win_w, win_h, track, .body, &background, old_layer, false, page); + // A window is rarely a whole number of cells wide: a band that ends at + // the last column runs on through the leftover pixels to the edge. + const band_right = if (win_w - right < bw) @max(right, win_w) else right; + emitInstance(g, instances, next.*, 0, layer.viewport.y, .{ .w = band_right - left, .h = bh, .x_off = left, .y_off = slide }, win_w, win_h, track, .body, &background, old_layer, false, page); if (slide != 0) clipInstanceTop(&instances[next.*], top, win_h); next.* += 1; for (0..tagLayerCellCount(g, layer)) |col| { @@ -5578,7 +5582,7 @@ fn emitBodyLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const if (left + @as(f32, @floatFromInt(col)) * width >= right) break; const cell = &layer.cells[index * layer.cols + col]; const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == row else false; - const glyph_top = top - (if (header) @as(f32, @floatFromInt(taglineBandOffset(0, win_h, g.cell_h, g.tagline_height, true))) else 0); + const glyph_top = top - (if (header) @as(f32, @floatFromInt(taglineBandOffset(0, win_h, g.cell_h, g.tagline_height))) else 0); emitInstance(g, instances, next.*, 0, 0, .{ .w = width, .h = height, .x_off = left + @as(f32, @floatFromInt(col)) * width, .y_off = glyph_top }, win_w, win_h, track, role, cell, old_layer, cursor, page); clipBodyInstance(&instances[next.*], bottom, win_h); clipInstanceRight(&instances[next.*], right, win_w); @@ -5628,6 +5632,10 @@ fn paneGripCell(layers: []const pardes.TagLayer, cells: []const pardes.Cell, col return null; } +fn anchorInset(g: *const Gui, row: u16, win_h: f32) u32 { + return taglineBandOffset(row, win_h, g.cell_h, g.tagline_height); +} + fn emitSurfaceCell( g: *Gui, core: ?*const pardes.Pardes, @@ -5657,19 +5665,27 @@ fn emitSurfaceCell( next.* += 1; // Tag glyphs keep their font size inside a full physical-width grip. emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, track, .tagline, cell, old_layer, is_cursor, page); + // An anchor starts at its column's rule: its left edge is inset by + // its top margin so the band frames it on the left as above and + // below, and its mark moves right by half that to stay centered. + const inset: u32 = if (core) |p| if (std.mem.indexOfScalar(u16, p.col_x[0..p.ncol], col -| (if (grip) |indicator| indicator.offset else 0)) != null) anchorInset(g, row, win_h) else 0 else 0; if (grip) |indicator| { const cached = cachedGlyph(g, cellCodepoint(indicator.cell), .tagline, GlyphDecoration.fromCell(indicator.cell), true); const slot = cached orelse g.space_slot; - const offset: u32 = if (cached != null) @as(u32, indicator.offset) * g.cell_w else 0; + const offset: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, indicator.offset) * g.cell_w)) - @as(f32, @floatFromInt(inset / 2)) else 0; const resolved = resolveCell(g, indicator.cell, .tagline, false, page); instances[next.*].fr = @as(f32, @floatFromInt(resolved.fg[0])) / 255; instances[next.*].fg = @as(f32, @floatFromInt(resolved.fg[1])) / 255; instances[next.*].fb = @as(f32, @floatFromInt(resolved.fg[2])) / 255; - instances[next.*].u0 = @as(f32, @floatFromInt(slot.u + offset)) / atlas_w; + instances[next.*].u0 = (@as(f32, @floatFromInt(slot.u)) + offset) / atlas_w; instances[next.*].v0 = @as(f32, @floatFromInt(slot.v)) / atlas_h; instances[next.*].v1 = @as(f32, @floatFromInt(slot.v + g.tagline_height)) / atlas_h; } instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; + if (inset > 0 and (grip == null or grip.?.offset == 0)) { + instances[next.*].x0 += @as(f32, @floatFromInt(inset)) / win_w * 2; + instances[next.*].u0 += @as(f32, @floatFromInt(inset)) / atlas_w; + } next.* += 1; return; } @@ -5690,7 +5706,8 @@ test "small tagline fonts leave no background gutters between adjacent tags" { var instances: [6]CellInstance = undefined; var next: u32 = 0; for (0..3) |row| { - emitSurfaceCell(&g, core, &instances, &next, 0, @intCast(row), fixedCellLayout(&g), 800, 480, null, &cell, &cell, null, false, false, Ground.opaqueRgb(bg_default)); + // Column 1: past the anchor's inset edge at the column's left. + emitSurfaceCell(&g, core, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, null, &cell, &cell, null, false, false, Ground.opaqueRgb(bg_default)); const base = instances[row * 2]; const ink = instances[row * 2 + 1]; try std.testing.expectApproxEqAbs(@as(f32, 20.0 / 480.0 * 2), base.y0 - base.y1, 0.0001); @@ -5700,6 +5717,13 @@ test "small tagline fonts leave no background gutters between adjacent tags" { try std.testing.expectApproxEqAbs(@as(f32, 10) / atlas_w, ink.u1 - ink.u0, 0.0001); if (row > 0) try std.testing.expectApproxEqAbs(instances[(row - 1) * 2].y1, base.y0, 0.0001); } + // Column 0 is an anchor's edge: its ink is inset by the band's margin + // (2 px here) and its underlay still covers the whole cell. + next = 0; + emitSurfaceCell(&g, core, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, null, &cell, &cell, null, false, false, Ground.opaqueRgb(bg_default)); + try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), instances[0].x1 - instances[0].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 8.0 / 800.0 * 2), instances[1].x1 - instances[1].x0, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 8) / atlas_w, instances[1].u1 - instances[1].u0, 0.0001); next = 0; emitSurfaceCell(&g, null, &instances, &next, 0, 2, fixedCellLayout(&g), 800, 480, null, &cell, &cell, null, true, false, Ground.opaqueRgb(bg_default)); try std.testing.expectEqual(@as(u32, 2), next); @@ -5730,7 +5754,7 @@ fn emitInstance( else layout.h; const band_offset: f32 = if (resolved.role == .tagline) - @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height, true)) + @floatFromInt(taglineBandOffset(row, win_h, g.cell_h, g.tagline_height)) else 0; const py0 = layout.y_off + @as(f32, @floatFromInt(row)) * layout.h + band_offset; @@ -6562,7 +6586,7 @@ fn addCursorBar( const x0 = layout.x_off + @as(f32, @floatFromInt(x)) * layout.w; const height = std.math.clamp(visual_height, 1.0, layout.h); const y0 = layout.y_off + @as(f32, @floatFromInt(y)) * layout.h + - @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, @intFromFloat(layout.h), @intFromFloat(height), true))); + @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, @intFromFloat(layout.h), @intFromFloat(height)))); builder.addRect( x0, y0, @@ -6662,7 +6686,7 @@ fn buildOverlay( const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; const x = left + @as(f32, @floatFromInt(cursor.col)) * width; if (x >= right) continue; - const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(layer.viewport.y, builder.win_h, g.cell_h, g.tagline_height, true))); + const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(layer.viewport.y, builder.win_h, g.cell_h, g.tagline_height))); builder.addRect(x, top, @min(right, x + @max(1, width / 8)), top + @as(f32, @floatFromInt(g.tagline_height)), overlayRgb(cursorColor(core, &layer.cells[cursor.col], .tagline))); }; if (transient_on) appendTouchOverlay(g, &builder, debug_on); @@ -6683,7 +6707,7 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard if (cellCodepoint(cell) != ' ') occupied = i + 1; } const editing = p.topbar_col != null and p.header_column == null; - const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height, true)); + const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); const region = if (occupied >= surface.cols) null else pet.lane( occupied, @floatFromInt(g.tagline_width), @@ -6810,7 +6834,10 @@ fn appendPaneChrome( } else true; if (tag_visible) { const rule_y = @as(f32, @floatFromInt(tag_y + @as(u16, if (core.settings.tag_bottom) 0 else 1))) * layout.h; - builder.addRect(x0, rule_y - @as(f32, if (core.settings.tag_bottom) 0 else 1), x1, rule_y + @as(f32, if (core.settings.tag_bottom) 1 else 0), overlayRgb(chrome.border)); + // Like the band above it, the rule of a pane at the right edge + // runs on through the pixels past the last whole cell. + const rule_x1 = if (builder.win_w - x1 < layout.w) @max(x1, builder.win_w) else x1; + builder.addRect(x0, rule_y - @as(f32, if (core.settings.tag_bottom) 0 else 1), rule_x1, rule_y + @as(f32, if (core.settings.tag_bottom) 1 else 0), overlayRgb(chrome.border)); } // Do not paint over resize previews or debug text occupying the rail. @@ -6827,12 +6854,13 @@ fn appendPaneChrome( } if (row != body_end) continue; const y0 = @as(f32, @floatFromInt(body_y)) * layout.h; - const y1 = @as(f32, @floatFromInt(body_end)) * layout.h; + const body_y1 = @as(f32, @floatFromInt(body_end)) * layout.h; + const y1 = if (body_end == surface.rows and builder.win_h - body_y1 < layout.h) @max(body_y1, builder.win_h) else body_y1; builder.addRect(x0, y0, x0 + layout.w, y1, page); appendSquareRail(builder, x0, y0, y1, layout.w, false, overlayRgb(chrome.scroll_track)); if (thumb_start) |first| { const thumb_y0 = @as(f32, @floatFromInt(first)) * layout.h; - const thumb_y1 = @as(f32, @floatFromInt(thumb_end)) * layout.h; + const thumb_y1 = if (thumb_end == body_end) y1 else @as(f32, @floatFromInt(thumb_end)) * layout.h; appendSquareRail(builder, x0, thumb_y0, thumb_y1, layout.w, true, overlayRgb(chrome.scroll_thumb)); } } @@ -6854,8 +6882,8 @@ fn appendTagGrips(g: *const Gui, surface: *const pardes.Surface, layout: CellLay .rgb => |rgb| rgb, else => continue, }; - const center_x = (@as(f32, @floatFromInt(x)) + @as(f32, @floatFromInt(config.GUTTER)) / 2) * layout.w; - const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, g.cell_h, g.tagline_height, true))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; + const center_x = (@as(f32, @floatFromInt(x)) + @as(f32, @floatFromInt(config.GUTTER)) / 2) * layout.w + @as(f32, @floatFromInt(anchorInset(g, y, builder.win_h) / 2)); + const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, builder.win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; const half_w = @max(1, @min(3, layout.w - 2)); builder.addRect(@floor(center_x - half_w), @floor(center_y - 2), @floor(center_x + half_w), @floor(center_y - 1), overlayRgb(rgb)); builder.addRect(@floor(center_x - half_w), @floor(center_y + 1), @floor(center_x + half_w), @floor(center_y + 2), overlayRgb(rgb)); @@ -6875,7 +6903,9 @@ test "column grips stay unmarked while pane marks retain physical centering" { var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 200, .win_h = 80 }; appendTagGrips(&g, &surface, .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }, &builder); try std.testing.expectEqual(@as(usize, 12), builder.len); - try std.testing.expectApproxEqAbs(@as(f32, 57.0 / 200.0 * 2.0 - 1.0), vertices[0].x, 0.0001); + // Centered in the anchor, whose left edge is inset by the band's offset + // (8 px on this last row): the mark moves right by half of it. + try std.testing.expectApproxEqAbs(@as(f32, 61.0 / 200.0 * 2.0 - 1.0), vertices[0].x, 0.0001); } fn appendSquareRail(builder: *OverlayBuilder, x: f32, y0: f32, y1: f32, cell_w: f32, thumb: bool, color: OverlayColor) void { @@ -6885,7 +6915,9 @@ fn appendSquareRail(builder: *OverlayBuilder, x: f32, y0: f32, y1: f32, cell_w: fn appendColumnSpines(core: *const pardes.Pardes, rows: u16, layout: CellLayout, builder: *OverlayBuilder) void { const y0 = @as(f32, @floatFromInt(pardes.TOPBAR_H)) * layout.h; - const y1 = @as(f32, @floatFromInt(rows)) * layout.h; + const grid_y1 = @as(f32, @floatFromInt(rows)) * layout.h; + // Down through the pixels past the last whole row, as tags run right. + const y1 = if (builder.win_h - grid_y1 < layout.h) @max(grid_y1, builder.win_h) else grid_y1; if (y1 <= y0) return; // A single boundary spans all panes, including their tags. Its left edge // agrees with the square scroll markers and existing move-box hit area. diff --git a/src/layout.zig b/src/layout.zig index c6cb7503..8db05a07 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -723,6 +723,23 @@ pub fn columnMoveTarget(p: *const Pardes, source: usize, x: u16) usize { return insertion; } +/// Share out the width of columns `left` and `left + 1` so the left one is +/// `left_width` cells, neither below MINW. A border drag and a column grip +/// dropped inside its own place both end here. +pub fn setColumnPairWidth(p: *Pardes, left: usize, left_width: u64) void { + if (left + 1 >= p.ncol) return; + const combined: u64 = p.col_w[left] + p.col_w[left + 1]; + // Too narrow for both to keep MINW: any split would squeeze one away. + if (combined < 2 * @as(u64, config.MINW)) return; + const width = std.math.clamp(left_width, config.MINW, @max(@as(u64, config.MINW), combined -| config.MINW)); + const pair = p.col_weight[left] + p.col_weight[left + 1]; + if (pair <= 1 or combined == 0) return; + const numerator = @as(u128, pair) * width + combined / 2; + const share = std.math.clamp(@as(u64, @intCast(numerator / combined)), 1, pair - 1); + p.col_weight[left] = share; + p.col_weight[left + 1] = pair - share; +} + pub fn reorderColumn(p: *Pardes, from: usize, to: usize) void { if (from >= p.ncol or to >= p.ncol or from == to) return; const ids = p.col_panes[from]; diff --git a/src/macos.zig b/src/macos.zig index c359eb3f..3ff8bdfa 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -951,7 +951,7 @@ export fn pardes_gui_tagline_font_percent() u8 { export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { pardes.turn.wake(); defer pardes.turn.rest(); - return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h, if (state) |*st| st.core.settings.workspace_tag else true); + return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h); } export fn pardes_topbar_pane_border_px(cell_h: u32, tagline_h: u32) u32 { diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 5ad09c38..70f467e3 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -523,9 +523,8 @@ private struct TaglineMetrics { /// Where this band sits inside row `row`, measured down from the row's top. /// The rule belongs to the core (`pardes_tagline_band_offset`) so that this - /// shell and the SDL one cannot disagree about it: row zero and the first - /// pane-tag row meet at a shared rule, a Tagbottom band on the last row - /// faces the window edge, and everything between is centred. + /// shell and the SDL one cannot disagree about it: every band is centred, + /// except a Tagbottom band on the last row, which faces the window edge. func top(row: Int, canvasHeight: CGFloat) -> CGFloat { CGFloat(pardes_tagline_band_offset( UInt16(clamping: row), Float(canvasHeight * scale), cellPixels, bandPixels)) / scale diff --git a/src/pardes.zig b/src/pardes.zig index fae14f47..ca2c34a4 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -232,19 +232,12 @@ pub const BOX_H: u16 = 1; pub const TAG_GAP: u16 = 1; pub const TAG_TEXT_INSET: u16 = config.GUTTER + TAG_GAP; -pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32, workspace: bool) u32 { +pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { const spare = cell_h -| tagline_h; - const border = topbarPaneBorderPixels(cell_h, tagline_h); const rows: u32 = @max(1, @as(u32, @intFromFloat(@floor(canvas_h / @as(f32, @floatFromInt(cell_h)))))); - if (!workspace) { - // No workspace row: nothing above row 0 to share a rule with, so - // every band centers in its cell the way the middle rows always - // have. The anchor boxes this lets the hosts draw stay symmetric. - if (@as(u32, row) + 1 >= rows) return spare; - return spare / 2; - } - if (row == 0) return spare - border / 2; - if (row == TOPBAR_H) return border - border / 2; + // Every band centers in its cell, so text and anchors sit at the same + // height in the workspace, column and pane tags alike. Only the last row + // faces the window edge (Tagbottom). if (@as(u32, row) + 1 >= rows) return spare; return spare / 2; } @@ -5160,7 +5153,9 @@ const Drag = union(enum) { border_v: struct { left_col: usize, cur_x: u16, corner: ?struct { col: usize, idx: usize } = null, cur_y: u16 = 0 }, border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, move: struct { id: usize, cur_x: u16, cur_y: u16 }, - column_move: struct { column: usize, serial: u32, cur_x: u16 }, + /// `grab`: how far into the grip it was pressed, so the column's left + /// edge lands at `cur_x - grab`. A release still on the grip moves nothing. + column_move: struct { column: usize, serial: u32, cur_x: u16, grab: u16 = 0 }, tag: struct { id: usize }, /// chorded: a 1-2/1-3 cut/paste chord fired during this left drag — /// the drag's own release is then inert @@ -12022,7 +12017,7 @@ pub const Pardes = struct { if (mcol < p.col_x[column] or mcol >= p.col_x[column] + @min(config.GUTTER, p.col_w[column])) continue; if (m.button == config.select_button) { p.header_drag = false; - p.drag = .{ .column_move = .{ .column = column, .serial = p.col_serial[column], .cur_x = mcol } }; + p.drag = .{ .column_move = .{ .column = column, .serial = p.col_serial[column], .cur_x = mcol, .grab = mcol - p.col_x[column] } }; } return; } @@ -12482,20 +12477,10 @@ pub const Pardes = struct { .border_v => |d| { const c = d.left_col; const old_seam = p.col_x[c] + p.col_w[c] -| 1; - if (c + 1 < p.ncol and d.cur_x != old_seam) { - const combined: u64 = p.col_w[c] + p.col_w[c + 1]; - // the handle is the left pane's LAST column (inclusive), so - // the new width includes it — a no-drag click changes nothing - var nl: u64 = (d.cur_x + 1) -| p.col_x[c]; - nl = std.math.clamp(nl, config.MINW, @max(@as(u64, config.MINW), combined -| config.MINW)); - const pair = p.col_weight[c] + p.col_weight[c + 1]; - if (pair > 1 and combined > 0) { - const numerator = @as(u128, pair) * nl + combined / 2; - const left = std.math.clamp(@as(u64, @intCast(numerator / combined)), 1, pair - 1); - p.col_weight[c] = left; - p.col_weight[c + 1] = pair - left; - } - } + // the handle is the left pane's LAST column (inclusive), so + // the new width includes it — a no-drag click changes nothing + if (c + 1 < p.ncol and d.cur_x != old_seam) + layout.setColumnPairWidth(p, c, (d.cur_x + 1) -| p.col_x[c]); if (d.corner) |k| { if (d.cur_y != seamRowOf(p, k.col, k.idx)) layout.applyRowSplit(p, k.col, k.idx, d.cur_y); @@ -12503,9 +12488,15 @@ pub const Pardes = struct { }, .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), - .column_move => |d| { - if (layout.columnBySerial(p, d.serial)) |column| - layout.reorderColumn(p, column, layout.columnMoveTarget(p, column, d.cur_x)); + .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| { + const target = layout.columnMoveTarget(p, column, d.cur_x); + if (target != column) { + layout.reorderColumn(p, column, target); + } else if (column > 0 and (d.cur_x < p.col_x[column] or d.cur_x >= p.col_x[column] + config.GUTTER)) { + // Dropped short of another column's place: as in acme, + // the column's left edge moves to where it was dropped. + layout.setColumnPairWidth(p, column - 1, (d.cur_x -| d.grab) -| p.col_x[column - 1]); + } }, .move => |d| { layout.movePane(p, d.id, d.cur_x, d.cur_y); @@ -14181,6 +14172,15 @@ pub const Pardes = struct { } var row: u16 = p.topBarHeight(); while (row < s.rows) : (row += 1) s.overlayDash(x, row, "╎"); + } else if (source > 0 and source < p.ncol and (d.cur_x < p.col_x[source] or d.cur_x >= p.col_x[source] + config.GUTTER) and + p.col_w[source - 1] + p.col_w[source] >= 2 * config.MINW) + { + // Where the left edge would land: the border drag's rail. + const lo = p.col_x[source - 1] + config.MINW; + const hi = (p.col_x[source] + p.col_w[source]) -| config.MINW; + const x = @min(std.math.clamp(d.cur_x -| d.grab, lo, @max(lo, hi)), s.cols -| 1); + var row: u16 = p.topBarHeight(); + while (row < s.rows) : (row += 1) s.overlayDash(x, row, "╎"); } }, .move => |d| if (d.cur_x < s.cols) { diff --git a/src/web.zig b/src/web.zig index 7325af54..b5a992ae 100644 --- a/src/web.zig +++ b/src/web.zig @@ -376,7 +376,7 @@ export fn pardes_tag_layer_cells(index: u32) ?[*]const WebCell { } export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { - return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h, true); + return pardes.taglineBandOffset(row, canvas_h, cell_h, tagline_h); } export fn pardes_body_layer_value(index: u32, field: u32) u32 { diff --git a/test/column_drag.zig b/test/column_drag.zig index be4e33a3..85dca66b 100644 --- a/test/column_drag.zig +++ b/test/column_drag.zig @@ -212,3 +212,43 @@ test "column grips stay blank and muted across focus hover and drag" { } } } + +test "column grip dropped in its own place moves the column's left edge" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 24 }); + defer p.deinit(); + _ = try p.setTestFile("body\n"); + p.presentation.enabled = false; + p.settings.column_tags = true; + try std.testing.expect(p.executeBuiltinLine(0, "New")); + try std.testing.expect(layout.splitColumn(p, p.active, p.active, false)); + p.update(.tick); + var frame = std.heap.ArenaAllocator.init(p.gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const serials = .{ p.col_serial[0], p.col_serial[1] }; + const edge = p.col_x[1]; + const total = p.col_w[0] + p.col_w[1]; + // A click in place, from either grip cell, changes nothing. + for (0..config.GUTTER) |offset| { + const x = edge + @as(u16, @intCast(offset)); + mouse(p, .press, x); + mouse(p, .release, x); + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(edge, p.col_x[1]); + } + // Grabbed by its second cell and dropped 7 cells left: the edge follows. + mouse(p, .press, edge + 1); + mouse(p, .drag, edge + 1 - 7); + _ = try p.render(frame.allocator()); + mouse(p, .release, edge + 1 - 7); + _ = try p.render(frame.allocator()); + try std.testing.expectEqual(edge - 7, p.col_x[1]); + try std.testing.expectEqual(total, p.col_w[0] + p.col_w[1]); + try std.testing.expectEqual(serials[0], p.col_serial[0]); + try std.testing.expectEqual(serials[1], p.col_serial[1]); + // Past the neighbour's middle it is still a reorder, not a resize. + mouse(p, .press, p.col_x[1]); + mouse(p, .release, p.col_x[0] + 1); + try std.testing.expectEqual(serials[1], p.col_serial[0]); + try std.testing.expectEqual(serials[0], p.col_serial[1]); +} -- cgit v1.3 From a007457cb007b03f310bca55c339e8cd5d9baafc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:44:51 -0300 Subject: Ripple and Glitch are gone; Crt stays The user tried them live and wants them removed entirely: the builtins, their levels, config keys and leader paths (tR, tg), their slots in the built-in chain, their shaders (source and prebuilt), EffectCode paths, and on macOS their scene flags (pardes.h), the Metal kernel's coordinate warps and the Swift pointer mapping that mirrored them. Docs say so (decision 8 in docs/render-pipeline.md); config.md documents Crt's levels, Shader and ShaderAnimation instead. Shared files touched: macos.zig (flags). Not touched: pardes.zig, Messages.zig, mouse.zig, gui.zig, detached/*. --- build.zig | 5 +- docs/config.md | 15 ++-- docs/design.typ | 5 +- docs/macos.md | 21 ++--- docs/render-pipeline.md | 19 ++-- docs/web.md | 2 +- shaders/crt.ci.metal | 75 ++-------------- shaders/post/glitch.glsl | 64 ------------- shaders/post/ripple.glsl | 52 ----------- shaders/prebuilt/post-glitch.frag.glsl | 138 ----------------------------- shaders/prebuilt/post-glitch.frag.spv | Bin 10764 -> 0 bytes shaders/prebuilt/post-ripple.frag.glsl | 126 -------------------------- shaders/prebuilt/post-ripple.frag.spv | Bin 9096 -> 0 bytes src/config.zig | 22 ++--- src/effect_sources.zig | 8 +- src/gui/Post.zig | 8 +- src/macos.zig | 17 +--- src/macos/Sources/PardesView.swift | 2 +- src/macos/Sources/ScenePostprocessor.swift | 48 +--------- src/macos/pardes.h | 5 +- test/output.zig | 2 +- 21 files changed, 61 insertions(+), 573 deletions(-) delete mode 100644 shaders/post/glitch.glsl delete mode 100644 shaders/post/ripple.glsl delete mode 100644 shaders/prebuilt/post-glitch.frag.glsl delete mode 100644 shaders/prebuilt/post-glitch.frag.spv delete mode 100644 shaders/prebuilt/post-ripple.frag.glsl delete mode 100644 shaders/prebuilt/post-ripple.frag.spv (limited to 'src/macos/Sources') diff --git a/build.zig b/build.zig index c1117593..97d51a51 100644 --- a/build.zig +++ b/build.zig @@ -51,10 +51,9 @@ const gui_shaders = [_][]const u8{ "overlay.vert", "overlay.frag", "image.vert", "image.frag", "post.vert", - // The bundled post passes: shaders/post/.glsl behind the Shadertoy + // The bundled post pass: shaders/post/crt.glsl behind the Shadertoy // prefix (shaderSource). - "post-crt.frag", "post-ripple.frag", - "post-glitch.frag", + "post-crt.frag", }; pub fn build(b: *std.Build) void { diff --git a/docs/config.md b/docs/config.md index 9c51f329..16fd59e5 100644 --- a/docs/config.md +++ b/docs/config.md @@ -513,18 +513,19 @@ immediately and remains the one authoritative geometry. DOM web intentionally does not expose these builtins: its renderer is selectable HTML/CSS and has no canvas or shader stage. -The scene effects are independent switches and can be combined: +The scene effect is `Crt`, at a level from 0 (off) to 3; `on` is 2: ```text Crt -Ripple -Glitch +Crt 3 ``` -They share one full-scene shader pass in SDL and macOS. With all three off the -pass is bypassed. CRT works in linear light with restrained scanlines, mask, -bloom, curvature, and noise rather than remapping the theme to a strong fixed -palette; Ripple and Glitch primarily perturb sample coordinates. +The SDL GUI runs it as the bundled pass of its post chain, which also takes +Shadertoy files written for ghostty (`Shader ~/crt.glsl`, `Shader off`), and +`ShaderAnimation off|on|always` says when the chain animates on its own. With +the chain empty the pass is bypassed. CRT works in linear light with restrained +scanlines, mask, bloom and vignette, and no curvature, so clicks land where +they are drawn. `EffectCode PanelAscii` or `EffectCode Crt` lists the current backend's build-embedded source paths under `/virtual`. Look opens each full file; diff --git a/docs/design.typ b/docs/design.typ index 234c3692..caa35b37 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -913,8 +913,9 @@ while its geometry moves and placed again on the last active sample. SDL supplies old/new glyph data, diff flags, final/presented boxes, and effect parameters to the glyph and native-image shaders. Pixel attachments bypass ASCII because they have no character byte. macOS passes the same records across its -plain C ABI and composites old/new panel images in Metal and Core Image. Scene -`Crt`, `Ripple` and `Glitch` bits share one full-window pass in each native GUI. +plain C ABI and composites old/new panel images in Metal and Core Image. The +scene `Crt` is one full-window pass in each native GUI; the SDL GUI's post +chain also runs Shadertoy files (`Shader`). DOM web is a separate platform, not a shader GUI: retaining selectable HTML and CSS is more important than duplicating the renderer in canvas, so it exposes diff --git a/docs/macos.md b/docs/macos.md index e104d3a6..5166e2d5 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -102,8 +102,8 @@ asking for a thin insert caret instead of a block. `Surface.images` crosses separately as `pardes_frame_images` / `pardes_frame_image_list` — see "Pixel attachments" below. -`pardes_scene` is the matching full-window snapshot: a bit each for CRT, -ripple, and glitch, plus the 60 Hz time/frame that animates them. It is returned +`pardes_scene` is the matching full-window snapshot: a bit for CRT, plus the +60 Hz time/frame that animates it. It is returned by value, so the renderer never holds a pointer into live core state. A zero flags word is also the fast-path contract: draw the CoreText frame directly. @@ -662,8 +662,7 @@ longer leaves a dark titlebar over a cream grid. ## Scene effects -`Crt`, `Ripple`, and `Glitch` are three switches over one postprocess, not three -stacked filters. Their canonical macOS source is `shaders/crt.ci.metal`, which +`Crt` is one full-window postprocess. Its canonical macOS source is `shaders/crt.ci.metal`, which the build installs as `pardes.app/Contents/Resources/crt.ci.metal`. The Swift shell loads that exact asset with `CIKernel.kernels(withMetalString:)` and runs it through a `CIContext` created from the system Metal device. The source is @@ -673,14 +672,12 @@ The ordinary CoreText/attachment/cursor pass is one function. With any scene bit or panel track it targets a retained, backing-scale bitmap; kernels then sample the complete frame into the flipped view. PDFs, image panes, taglines, rules, and the caret therefore receive the same effect. With every bit off and -no panel track the bitmap and Core Image context are bypassed entirely. Ripple -and glitch alter sample coordinates only, preserving theme colors; CRT works +no panel track the bitmap and Core Image context are bypassed entirely. CRT works in linear light with restrained bloom, scan/mask, vignette, hum, and noise instead of applying a broad color remap. The scene kernel alone receives a `clampedToExtent` image and the final output -is cropped back to the original finite extent. Coordinate tears and chroma -samples therefore clamp to the edge exactly like SDL's scene sampler instead +is cropped back to the original finite extent. Chroma samples therefore clamp to the edge exactly like SDL's scene sampler instead of acquiring transparent-black seams from Core Image's finite source image. The Zig side owns the clock. `pardes_animation_tick` increments its wrapped @@ -689,8 +686,8 @@ from that integer. Input bursts cannot accelerate the shader. Pointer input follows the same destination-to-source transform as the last presented scene frame before it is divided by the cell metrics. The view keeps -that exact `pardes_scene_s` snapshot and mirrors the Metal barrel, ripple and -glitch sampling arithmetic in `ScenePostprocessor.sourcePoint`; pixels outside +that exact `pardes_scene_s` snapshot and mirrors the Metal barrel arithmetic +in `ScenePostprocessor.sourcePoint`; pixels outside the CRT tube have no cell. The resulting displayed-grid cell then reaches the core, whose panel-track mapping resolves it to canonical pane content. @@ -716,8 +713,8 @@ while `pardesComposedInCore` effects only clip the already-composed core cells; pixel attachments have no character value and pass through unchanged. Because the input is the finished bitmap rather than a glyph-only batch, backgrounds, glyphs, taglines, rules, the caret, PDF pages, and image -panes move and dissolve together. Scene CRT/ripple/glitch runs once after the -panel composition. +panes move and dissolve together. The scene CRT runs once after the panel +composition. With no scene bit and no panel track the retained bitmap, Core Image context, and Metal passes are bypassed. `EffectCode Panel*` links to this Metal diff --git a/docs/render-pipeline.md b/docs/render-pipeline.md index 2fd6045b..7c94fbea 100644 --- a/docs/render-pipeline.md +++ b/docs/render-pipeline.md @@ -505,16 +505,14 @@ Mirror ghostty 1.3.2 (`zig-pkg/ghostty-*/src/renderer/shadertoy.zig`, `custom-shader-animation`): off = redraw only when content changes; on = continuous while the window is focused; always = continuous. Continuous means the shell redraws its retained Surface (3.1), never a core tick or render. -- **Existing crt/ripple/glitch** become bundled Shadertoy files in - `shaders/post/` selected by the same builtins (decision 2: kept, polished); - `scene_effects` and `crt.frag.glsl`/`crt.zig` are deleted. Each bundled pass - takes a level, `Crt 0..3` (0 off, `on` the default 2, `off` and bare still - work), passed as `pardesLevel`: 2 is the polished rewrite, 3 at least as - strong as the old effects (pixels changed by more than 8 in a channel, - against a plain frame: Crt 18.3% vs 17.4% old, Ripple 11.1% vs 9.5%, Glitch - 9.3% a frame vs 8.1%); a Glitch level raises how often it slips as well as - how hard. The chain is - `Crt`, `Ripple`, `Glitch` and `Shader ` in the order they were put in +- **Existing crt** becomes a bundled Shadertoy file in `shaders/post/` under + the same builtin; `scene_effects` and `crt.frag.glsl`/`crt.zig` are deleted. + It takes a level, `Crt 0..3` (0 off, `on` the default 2, `off` and bare + still work), passed as `pardesLevel`: 2 is the polished rewrite, 3 at least + as strong as the old CRT (pixels changed by more than 8 in a channel against + a plain frame: 18.3% vs 17.4%). Ripple and Glitch were rewritten too, then + removed at the user's word after a live look (decision 8). The chain is + `Crt` and `Shader ` in the order they were put in (`Shader off` empties it of files), `ShaderAnimation off|on|always` (default on). The core keeps no clock for it: level A redraws are the shell's. @@ -905,3 +903,4 @@ goldens; ssh/tty byte budgets; wire version bump breaks mixed-version attach. 5. The animation pacing fix goes into the no-visual-change phase. 6. Cursor blink is on by default. 7. The bundled CRT has no barrel distortion, so clicks stay exact. +8. (After trying them live) Ripple and Glitch are removed entirely; Crt stays. diff --git a/docs/web.md b/docs/web.md index 3a68f958..bbbed8a3 100644 --- a/docs/web.md +++ b/docs/web.md @@ -42,7 +42,7 @@ shells, and two comptime capability flags say so once each. It exposes no `PanelAscii`, `PanelVertical`, `PanelEdges`, `PanelFall`, `PanelWave`, `PanelCurtain`, `PanelScramble`, `PanelType`) because `capabilities.panel_transitions` is `pardes.hosted`, and no -`Crt`/`Ripple`/`Glitch` because `capabilities.scene_shaders` is +`Crt` or `Shader` because `capabilities.scene_shaders` is `platform == .gui or platform == .macos` (`builtins.capabilities`; the words themselves carry those availabilities in `config.Runtime.settings`). Applying either faithfully would require a second canvas renderer and give up diff --git a/shaders/crt.ci.metal b/shaders/crt.ci.metal index c7e91a7e..9159af18 100644 --- a/shaders/crt.ci.metal +++ b/shaders/crt.ci.metal @@ -1,7 +1,6 @@ // Native macOS panel and scene postprocess. Panel kernels consume the core's -// plain tracks; the final full-window kernel ports crt.frag.glsl and combines -// CRT, ripple and glitch. Scene constants and sampling geometry stay in step -// with GLSL, while panel easing/noise stays in step with panel_animation.zig. +// plain tracks; the final full-window kernel is the CRT. Panel easing/noise +// stays in step with panel_animation.zig. // // The three entry points are `extern "C" [[stitchable]]`. Both halves are // load-bearing: this source is compiled at runtime by @@ -38,24 +37,6 @@ float pardesCellNoise(float2 serialParts, float colValue, float rowValue) { return float(x & 0xffffu) / 65535.0; } -float2 pardesSceneUV(float2 uv, float timeSeconds, float rippleOn, float glitchOn) { - if (rippleOn > 0.5) { - float2 centered = uv - 0.5; - float radius = length(centered); - // Reversed smoothstep edges are undefined in GLSL and Metal alike. - float envelope = 1.0 - smoothstep(0.04, 0.72, radius); - float wave = sin(radius * 42.0 - timeSeconds * 5.2); - uv += centered / max(radius, 0.00001) * wave * envelope * 0.0032; - } - if (glitchOn > 0.5) { - float band = floor(uv.y * 96.0); - float seed = pardesNoise(float2(band, floor(timeSeconds * 13.0))); - float tear = smoothstep(0.955, 1.0, seed); - uv.x += (pardesNoise(float2(seed, band)) - 0.5) * tear * 0.020; - } - return uv; -} - float4 pardesSceneSample( coreimage::sampler source, float2 origin, @@ -66,42 +47,13 @@ float4 pardesSceneSample( source.sample(source.transform(origin + uv * size))); } -// Keep this ordering identical to crt.frag.glsl's sceneSrgb: every caller -// supplies its own pre-warp coordinate, then ripple/glitch move that sample, -// then glitch splits its red/blue channels around the moved center. -float4 pardesSceneSrgb( - coreimage::sampler source, - float2 origin, - float2 size, - float2 uv, - float timeSeconds, - float rippleOn, - float glitchOn -) { - float2 warped = pardesSceneUV(uv, timeSeconds, rippleOn, glitchOn); - float4 center = pardesSceneSample(source, origin, size, warped); - if (glitchOn <= 0.5) return center; - - float band = floor(warped.y * 96.0); - float seed = pardesNoise(float2(band, floor(timeSeconds * 13.0))); - float tear = smoothstep(0.955, 1.0, seed); - float2 chroma = float2((0.35 + 1.25 * tear) / size.x, 0.0); - float4 red = pardesSceneSample(source, origin, size, warped + chroma); - float4 blue = pardesSceneSample(source, origin, size, warped - chroma); - return float4(red.r, center.g, blue.b, center.a); -} - float3 pardesSceneLinear( coreimage::sampler source, float2 origin, float2 size, - float2 uv, - float timeSeconds, - float rippleOn, - float glitchOn + float2 uv ) { - return coreimage::srgb_to_linear(pardesSceneSrgb( - source, origin, size, uv, timeSeconds, rippleOn, glitchOn).rgb); + return coreimage::srgb_to_linear(pardesSceneSample(source, origin, size, uv).rgb); } bool pardesInside(float2 p, float4 box) { @@ -242,8 +194,6 @@ extern "C" [[stitchable]] float4 pardesScene( float timeSeconds, float frame, float crtOn, - float rippleOn, - float glitchOn, float2 sceneSize, float2 sceneOrigin, coreimage::destination destination @@ -277,24 +227,18 @@ extern "C" [[stitchable]] float4 pardesScene( // transparent theme. if (crtOn > 0.5 && edge <= 0.0) return float4(0.0, 0.0, 0.0, 1.0); - float4 center = pardesSceneSrgb( - source, origin, size, uv, timeSeconds, rippleOn, glitchOn); + float4 center = pardesSceneSample(source, origin, size, uv); float3 scene = center.rgb; - // Ripple/glitch alone are coordinate effects. Returning the sampled sRGB - // values directly keeps exact theme colors exact. + // Without the CRT the scene passes through, exact. if (crtOn <= 0.5) { return coreimage::premultiply(float4(clamp(scene, 0.0, 1.0), center.a)); } float3 centerLinear = coreimage::srgb_to_linear(scene); float2 radialChroma = cc * (chromaPx * r2) * texel; - float3 redSample = pardesSceneLinear( - source, origin, size, uv + radialChroma, - timeSeconds, rippleOn, glitchOn); - float3 blueSample = pardesSceneLinear( - source, origin, size, uv - radialChroma, - timeSeconds, rippleOn, glitchOn); + float3 redSample = pardesSceneLinear(source, origin, size, uv + radialChroma); + float3 blueSample = pardesSceneLinear(source, origin, size, uv - radialChroma); float3 col = float3( redSample.r, centerLinear.g, @@ -308,8 +252,7 @@ extern "C" [[stitchable]] float4 pardesScene( float2(0.0, bloom.y), float2(0.0, -bloom.y) }; for (uint i = 0; i < 4; i++) { - // Deliberately raw, like GLSL brightPass: bloom belongs to the source - // image and does not recursively warp through the scene effects. + // Deliberately raw, like GLSL brightPass. float4 sampleValue = pardesSceneSample( source, origin, size, uv + bloomOffsets[i]); float3 linearValue = coreimage::srgb_to_linear(sampleValue.rgb); diff --git a/shaders/post/glitch.glsl b/shaders/post/glitch.glsl deleted file mode 100644 index 8f420d9c..00000000 --- a/shaders/post/glitch.glsl +++ /dev/null @@ -1,64 +0,0 @@ -// Glitch: now and then the signal slips. At the default level, every couple -// of seconds a short -// burst tears a few horizontal bands sideways and pulls their red and blue -// apart; the bands are sized in pixels and the burst eases in and out over -// a fraction of a second, so it reads as one event rather than a flicker, -// and it looks the same at 60 or 144 Hz because every step is keyed to -// iTime, not to frames. Between bursts the page is left exactly as it is. -// A torn band's brightness dips in linear light. It is a Shadertoy file: -// pardes puts its prefix before it. - -// Each at levels 1, 2 and 3 (`Glitch 1`..`Glitch 3`); 2 is the default. A -// higher level slips more often and harder. -float period() { return pardesByLevel(4.5, 2.4, 0.55); } // seconds between bursts, on average -float burst() { return pardesByLevel(0.2, 0.28, 0.5); } // seconds a burst lasts -float stepHz() { return pardesByLevel(20.0, 24.0, 30.0); } // how often a burst re-tears -float shiftPx() { return pardesByLevel(8.0, 14.0, 34.0); } -float splitPx() { return pardesByLevel(1.5, 2.5, 6.0); } -float dip() { return pardesByLevel(0.08, 0.12, 0.22); } -float tearFrom() { return pardesByLevel(0.8, 0.72, 0.35); } // how few bands tear - -float hash(vec2 p) { - vec3 q = fract(vec3(p.xyx) * 0.1031); - q += dot(q, q.yzx + 33.33); - return fract((q.x + q.y) * q.z); -} - -vec3 toLinear(vec3 c) { - return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, lessThanEqual(c, vec3(0.04045))); -} - -vec3 toSrgb(vec3 c) { - c = max(c, vec3(0.0)); - return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, lessThanEqual(c, vec3(0.0031308))); -} - -void mainImage(out vec4 fragColor, in vec2 fragCoord) { - vec2 size = iResolution.xy; - vec2 uv = fragCoord / size; - // Which burst window this is, when in it the burst starts, and how far - // into the burst we are: 0 outside one. - float window = floor(iTime / period()); - float start = window * period() + hash(vec2(window, 7.0)) * (period() - burst()); - float t = (iTime - start) / burst(); - float live = step(0.0, t) * step(t, 1.0); - float envelope = live * sin(3.14159265 * clamp(t, 0.0, 1.0)); - if (envelope <= 0.0) { - fragColor = texture(iChannel0, uv); - return; - } - // Bands of 6 to 40 px, re-cut at stepHz() during the burst; about one - // band in four tears. - float tick = floor(iTime * stepHz()); - float band_px = mix(6.0, 40.0, hash(vec2(tick, 3.0))); - float band = floor(fragCoord.y / band_px); - float roll = hash(vec2(band, tick)); - float tear = smoothstep(tearFrom(), tearFrom() + 0.18, roll) * envelope; - float shift = (hash(vec2(tick, band + 11.0)) - 0.5) * 2.0 * shiftPx() * tear; - vec2 at = vec2(fragCoord.x + shift, fragCoord.y); - vec2 split = vec2(splitPx() * tear, 0.0); - vec4 center = texture(iChannel0, at / size); - vec3 col = vec3(texture(iChannel0, (at + split) / size).r, center.g, texture(iChannel0, (at - split) / size).b); - col = toSrgb(toLinear(col) * (1.0 - dip() * tear)); - fragColor = vec4(col, center.a); -} diff --git a/shaders/post/ripple.glsl b/shaders/post/ripple.glsl deleted file mode 100644 index 3236d339..00000000 --- a/shaders/post/ripple.glsl +++ /dev/null @@ -1,52 +0,0 @@ -// Ripple: the page as a still pool a slow swell crosses. Rings travel out -// from the middle of the window at a fixed speed in pixels, so they look -// the same at any size and frame rate; at the default level the displacement -// is at most a couple of pixels, so text stays readable, and it eases in over its first half -// second instead of snapping on. Each ring catches the light a little on its -// rising side, in linear light, and the result is dithered so the shading -// never bands. It is a Shadertoy file: pardes puts its prefix before it. - -const float TAU = 6.28318530718; -const float EASE_IN = 0.5; // seconds - -// Each at levels 1, 2 and 3 (`Ripple 1`..`Ripple 3`); 2 is the default. -float wavelengthPx() { return pardesByLevel(170.0, 150.0, 120.0); } -float speedPx() { return pardesByLevel(40.0, 55.0, 80.0); } // outward, per second -float amplitudePx() { return pardesByLevel(1.2, 2.2, 5.0); } -float shade() { return pardesByLevel(0.02, 0.035, 0.09); } // light on a slope, linear -float reachEnd() { return pardesByLevel(0.85, 0.95, 1.3); } // how far out it dies away - -vec3 toLinear(vec3 c) { - return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, lessThanEqual(c, vec3(0.04045))); -} - -vec3 toSrgb(vec3 c) { - c = max(c, vec3(0.0)); - return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, lessThanEqual(c, vec3(0.0031308))); -} - -float ign(vec2 p) { - return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); -} - -void mainImage(out vec4 fragColor, in vec2 fragCoord) { - vec2 size = iResolution.xy; - vec2 center = 0.5 * size; - vec2 offset = fragCoord - center; - float radius = length(offset); - float reach = 0.5 * length(size); - // Strongest a third of the way out, fading to nothing at the middle - // and at the edges, so the window's frame never wobbles. - float envelope = smoothstep(0.0, 0.18, radius / reach) * (1.0 - smoothstep(0.35, reachEnd(), radius / reach)); - float ease = smoothstep(0.0, EASE_IN, iTime); - float phase = (radius - iTime * speedPx()) * TAU / wavelengthPx(); - float height = sin(phase); - float slope = cos(phase); - vec2 dir = offset / max(radius, 1e-3); - vec2 moved = fragCoord + dir * height * amplitudePx() * envelope * ease; - - vec4 s = texture(iChannel0, moved / size); - vec3 col = toLinear(s.rgb) * (1.0 + shade() * slope * envelope * ease); - vec3 srgb = toSrgb(col) + (ign(fragCoord + float(iFrame % 64) * 5.588238) - 0.5) / 255.0; - fragColor = vec4(clamp(srgb, 0.0, 1.0), s.a); -} diff --git a/shaders/prebuilt/post-glitch.frag.glsl b/shaders/prebuilt/post-glitch.frag.glsl deleted file mode 100644 index 7b288237..00000000 --- a/shaders/prebuilt/post-glitch.frag.glsl +++ /dev/null @@ -1,138 +0,0 @@ -#version 450 -// pardes's Shadertoy prefix (docs/render-pipeline.md §6), put before every -// post pass: a bundled one in shaders/post/ at build time, a user's file at -// run time. The uniform names, types and std140 order are ghostty 1.3.2's -// (src/renderer/shaders/shadertoy_prefix.glsl), so a shader written for -// ghostty runs here; only the bindings are SDL GPU's (a fragment shader's -// textures in set 2, its uniform blocks in set 3). Y is down everywhere, as -// on ghostty's Metal renderer: fragCoord, iChannel0's uv and the cursor -// rectangles share one top-left space, and iCurrentCursor is (left x, -// BOTTOM-edge y, width, height) in framebuffer pixels. - -layout(set = 3, binding = 0, std140) uniform Globals { - uniform vec3 iResolution; - uniform float iTime; - uniform float iTimeDelta; - uniform float iFrameRate; - uniform int iFrame; - uniform float iChannelTime[4]; - uniform vec3 iChannelResolution[4]; - uniform vec4 iMouse; - uniform vec4 iDate; - uniform float iSampleRate; - uniform vec4 iCurrentCursor; - uniform vec4 iPreviousCursor; - uniform vec4 iCurrentCursorColor; - uniform vec4 iPreviousCursorColor; - uniform int iCurrentCursorStyle; - uniform int iPreviousCursorStyle; - uniform int iCursorVisible; - uniform float iTimeCursorChange; - uniform float iTimeFocus; - uniform int iFocus; - uniform vec3 iPalette[256]; - uniform vec3 iBackgroundColor; - uniform vec3 iForegroundColor; - uniform vec3 iCursorColor; - uniform vec3 iCursorText; - uniform vec3 iSelectionForegroundColor; - uniform vec3 iSelectionBackgroundColor; -}; - -// pardes's own: pardesOpaque is 1 when the window is opaque, so a pass -// cannot punch holes in it through its alpha; pardesLevel is a bundled -// pass's strength, 1 to 3 (`Crt 3`), and 0 for a user's file. -layout(set = 3, binding = 1, std140) uniform PardesPost { - float pardesOpaque; - float pardesLevel; -}; - -// A bundled pass's constant at levels 1, 2 and 3. -float pardesByLevel(float one, float two, float three) { - return pardesLevel < 1.5 ? one : (pardesLevel < 2.5 ? two : three); -} - -#define CURSORSTYLE_BLOCK 0 -#define CURSORSTYLE_BLOCK_HOLLOW 1 -#define CURSORSTYLE_BAR 2 -#define CURSORSTYLE_UNDERLINE 3 -#define CURSORSTYLE_LOCK 4 - -layout(set = 2, binding = 0) uniform sampler2D iChannel0; - -layout(location = 0) out vec4 _fragColor; - -#define texture2D texture - -void mainImage(out vec4 fragColor, in vec2 fragCoord); -void main() { - mainImage(_fragColor, gl_FragCoord.xy); - if (pardesOpaque > 0.5) _fragColor.a = 1.0; -} - -// The shader's own lines count from 1, so glslc's errors name them. -#line 1 -// Glitch: now and then the signal slips. At the default level, every couple -// of seconds a short -// burst tears a few horizontal bands sideways and pulls their red and blue -// apart; the bands are sized in pixels and the burst eases in and out over -// a fraction of a second, so it reads as one event rather than a flicker, -// and it looks the same at 60 or 144 Hz because every step is keyed to -// iTime, not to frames. Between bursts the page is left exactly as it is. -// A torn band's brightness dips in linear light. It is a Shadertoy file: -// pardes puts its prefix before it. - -// Each at levels 1, 2 and 3 (`Glitch 1`..`Glitch 3`); 2 is the default. A -// higher level slips more often and harder. -float period() { return pardesByLevel(4.5, 2.4, 0.55); } // seconds between bursts, on average -float burst() { return pardesByLevel(0.2, 0.28, 0.5); } // seconds a burst lasts -float stepHz() { return pardesByLevel(20.0, 24.0, 30.0); } // how often a burst re-tears -float shiftPx() { return pardesByLevel(8.0, 14.0, 34.0); } -float splitPx() { return pardesByLevel(1.5, 2.5, 6.0); } -float dip() { return pardesByLevel(0.08, 0.12, 0.22); } -float tearFrom() { return pardesByLevel(0.8, 0.72, 0.35); } // how few bands tear - -float hash(vec2 p) { - vec3 q = fract(vec3(p.xyx) * 0.1031); - q += dot(q, q.yzx + 33.33); - return fract((q.x + q.y) * q.z); -} - -vec3 toLinear(vec3 c) { - return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, lessThanEqual(c, vec3(0.04045))); -} - -vec3 toSrgb(vec3 c) { - c = max(c, vec3(0.0)); - return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, lessThanEqual(c, vec3(0.0031308))); -} - -void mainImage(out vec4 fragColor, in vec2 fragCoord) { - vec2 size = iResolution.xy; - vec2 uv = fragCoord / size; - // Which burst window this is, when in it the burst starts, and how far - // into the burst we are: 0 outside one. - float window = floor(iTime / period()); - float start = window * period() + hash(vec2(window, 7.0)) * (period() - burst()); - float t = (iTime - start) / burst(); - float live = step(0.0, t) * step(t, 1.0); - float envelope = live * sin(3.14159265 * clamp(t, 0.0, 1.0)); - if (envelope <= 0.0) { - fragColor = texture(iChannel0, uv); - return; - } - // Bands of 6 to 40 px, re-cut at stepHz() during the burst; about one - // band in four tears. - float tick = floor(iTime * stepHz()); - float band_px = mix(6.0, 40.0, hash(vec2(tick, 3.0))); - float band = floor(fragCoord.y / band_px); - float roll = hash(vec2(band, tick)); - float tear = smoothstep(tearFrom(), tearFrom() + 0.18, roll) * envelope; - float shift = (hash(vec2(tick, band + 11.0)) - 0.5) * 2.0 * shiftPx() * tear; - vec2 at = vec2(fragCoord.x + shift, fragCoord.y); - vec2 split = vec2(splitPx() * tear, 0.0); - vec4 center = texture(iChannel0, at / size); - vec3 col = vec3(texture(iChannel0, (at + split) / size).r, center.g, texture(iChannel0, (at - split) / size).b); - col = toSrgb(toLinear(col) * (1.0 - dip() * tear)); - fragColor = vec4(col, center.a); -} diff --git a/shaders/prebuilt/post-glitch.frag.spv b/shaders/prebuilt/post-glitch.frag.spv deleted file mode 100644 index 619616a8..00000000 Binary files a/shaders/prebuilt/post-glitch.frag.spv and /dev/null differ diff --git a/shaders/prebuilt/post-ripple.frag.glsl b/shaders/prebuilt/post-ripple.frag.glsl deleted file mode 100644 index d29a4c22..00000000 --- a/shaders/prebuilt/post-ripple.frag.glsl +++ /dev/null @@ -1,126 +0,0 @@ -#version 450 -// pardes's Shadertoy prefix (docs/render-pipeline.md §6), put before every -// post pass: a bundled one in shaders/post/ at build time, a user's file at -// run time. The uniform names, types and std140 order are ghostty 1.3.2's -// (src/renderer/shaders/shadertoy_prefix.glsl), so a shader written for -// ghostty runs here; only the bindings are SDL GPU's (a fragment shader's -// textures in set 2, its uniform blocks in set 3). Y is down everywhere, as -// on ghostty's Metal renderer: fragCoord, iChannel0's uv and the cursor -// rectangles share one top-left space, and iCurrentCursor is (left x, -// BOTTOM-edge y, width, height) in framebuffer pixels. - -layout(set = 3, binding = 0, std140) uniform Globals { - uniform vec3 iResolution; - uniform float iTime; - uniform float iTimeDelta; - uniform float iFrameRate; - uniform int iFrame; - uniform float iChannelTime[4]; - uniform vec3 iChannelResolution[4]; - uniform vec4 iMouse; - uniform vec4 iDate; - uniform float iSampleRate; - uniform vec4 iCurrentCursor; - uniform vec4 iPreviousCursor; - uniform vec4 iCurrentCursorColor; - uniform vec4 iPreviousCursorColor; - uniform int iCurrentCursorStyle; - uniform int iPreviousCursorStyle; - uniform int iCursorVisible; - uniform float iTimeCursorChange; - uniform float iTimeFocus; - uniform int iFocus; - uniform vec3 iPalette[256]; - uniform vec3 iBackgroundColor; - uniform vec3 iForegroundColor; - uniform vec3 iCursorColor; - uniform vec3 iCursorText; - uniform vec3 iSelectionForegroundColor; - uniform vec3 iSelectionBackgroundColor; -}; - -// pardes's own: pardesOpaque is 1 when the window is opaque, so a pass -// cannot punch holes in it through its alpha; pardesLevel is a bundled -// pass's strength, 1 to 3 (`Crt 3`), and 0 for a user's file. -layout(set = 3, binding = 1, std140) uniform PardesPost { - float pardesOpaque; - float pardesLevel; -}; - -// A bundled pass's constant at levels 1, 2 and 3. -float pardesByLevel(float one, float two, float three) { - return pardesLevel < 1.5 ? one : (pardesLevel < 2.5 ? two : three); -} - -#define CURSORSTYLE_BLOCK 0 -#define CURSORSTYLE_BLOCK_HOLLOW 1 -#define CURSORSTYLE_BAR 2 -#define CURSORSTYLE_UNDERLINE 3 -#define CURSORSTYLE_LOCK 4 - -layout(set = 2, binding = 0) uniform sampler2D iChannel0; - -layout(location = 0) out vec4 _fragColor; - -#define texture2D texture - -void mainImage(out vec4 fragColor, in vec2 fragCoord); -void main() { - mainImage(_fragColor, gl_FragCoord.xy); - if (pardesOpaque > 0.5) _fragColor.a = 1.0; -} - -// The shader's own lines count from 1, so glslc's errors name them. -#line 1 -// Ripple: the page as a still pool a slow swell crosses. Rings travel out -// from the middle of the window at a fixed speed in pixels, so they look -// the same at any size and frame rate; at the default level the displacement -// is at most a couple of pixels, so text stays readable, and it eases in over its first half -// second instead of snapping on. Each ring catches the light a little on its -// rising side, in linear light, and the result is dithered so the shading -// never bands. It is a Shadertoy file: pardes puts its prefix before it. - -const float TAU = 6.28318530718; -const float EASE_IN = 0.5; // seconds - -// Each at levels 1, 2 and 3 (`Ripple 1`..`Ripple 3`); 2 is the default. -float wavelengthPx() { return pardesByLevel(170.0, 150.0, 120.0); } -float speedPx() { return pardesByLevel(40.0, 55.0, 80.0); } // outward, per second -float amplitudePx() { return pardesByLevel(1.2, 2.2, 5.0); } -float shade() { return pardesByLevel(0.02, 0.035, 0.09); } // light on a slope, linear -float reachEnd() { return pardesByLevel(0.85, 0.95, 1.3); } // how far out it dies away - -vec3 toLinear(vec3 c) { - return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, lessThanEqual(c, vec3(0.04045))); -} - -vec3 toSrgb(vec3 c) { - c = max(c, vec3(0.0)); - return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, lessThanEqual(c, vec3(0.0031308))); -} - -float ign(vec2 p) { - return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); -} - -void mainImage(out vec4 fragColor, in vec2 fragCoord) { - vec2 size = iResolution.xy; - vec2 center = 0.5 * size; - vec2 offset = fragCoord - center; - float radius = length(offset); - float reach = 0.5 * length(size); - // Strongest a third of the way out, fading to nothing at the middle - // and at the edges, so the window's frame never wobbles. - float envelope = smoothstep(0.0, 0.18, radius / reach) * (1.0 - smoothstep(0.35, reachEnd(), radius / reach)); - float ease = smoothstep(0.0, EASE_IN, iTime); - float phase = (radius - iTime * speedPx()) * TAU / wavelengthPx(); - float height = sin(phase); - float slope = cos(phase); - vec2 dir = offset / max(radius, 1e-3); - vec2 moved = fragCoord + dir * height * amplitudePx() * envelope * ease; - - vec4 s = texture(iChannel0, moved / size); - vec3 col = toLinear(s.rgb) * (1.0 + shade() * slope * envelope * ease); - vec3 srgb = toSrgb(col) + (ign(fragCoord + float(iFrame % 64) * 5.588238) - 0.5) / 255.0; - fragColor = vec4(clamp(srgb, 0.0, 1.0), s.a); -} diff --git a/shaders/prebuilt/post-ripple.frag.spv b/shaders/prebuilt/post-ripple.frag.spv deleted file mode 100644 index 5f05f9f3..00000000 Binary files a/shaders/prebuilt/post-ripple.frag.spv and /dev/null differ diff --git a/src/config.zig b/src/config.zig index e8c5a705..d1e5f23d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -129,8 +129,6 @@ pub const leader_path = paths: { } if (builtins.capabilities.scene_shaders) { table.set(.Crt, "tr"); - table.set(.Ripple, "tR"); - table.set(.Glitch, "tg"); table.set(.Shader, null); table.set(.ShaderAnimation, null); } @@ -622,7 +620,7 @@ pub const Runtime = struct { pub const ShaderAnimation = enum { off, on, always }; - /// Each pass a bundled effect (Crt, Ripple, Glitch) or a Shadertoy file. + /// Each pass the bundled Crt or a Shadertoy file. pub const Post = struct { pub const max = 8; pub const Entry = struct { @@ -774,8 +772,8 @@ pub const Runtime = struct { pub const MessageTime = enum { linger, fall, dissolve }; pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold, verbose, message_animation, ligatures }; - /// The bundled post passes, each a Shadertoy file in shaders/post/. - pub const Scene = enum { crt, ripple, glitch }; + /// The bundled post pass, a Shadertoy file in shaders/post/. + pub const Scene = enum { crt }; pub const Action = union(enum) { toggle: Toggle, @@ -843,8 +841,6 @@ pub const Runtime = struct { .{ .word = "PanelScramble", .action = .{ .transition = .scramble }, .availability = .panel_transitions }, .{ .word = "PanelType", .action = .{ .transition = .typewriter }, .availability = .panel_transitions }, .{ .word = "Crt", .action = .{ .scene = .crt }, .availability = .scene_shaders }, - .{ .word = "Ripple", .action = .{ .scene = .ripple }, .availability = .scene_shaders }, - .{ .word = "Glitch", .action = .{ .scene = .glitch }, .availability = .scene_shaders }, .{ .word = "Shader", .action = .shader, .availability = .scene_shaders }, .{ .word = "ShaderAnimation", .action = .shader_animation, .availability = .scene_shaders }, }; @@ -1263,18 +1259,18 @@ pub const Runtime = struct { test "the post chain runs in the order its passes were put in, and Shader off empties it of files" { var state: Runtime = .{}; try std.testing.expect(apply(&state, find("Shader").?, " ~/a.glsl\n")); - try std.testing.expect(apply(&state, find("Glitch").?, "on")); + try std.testing.expect(apply(&state, find("Crt").?, "on")); try std.testing.expect(apply(&state, find("Shader").?, "/b.glsl")); const chain = state.post.list(); try std.testing.expectEqual(@as(usize, 3), chain.len); try std.testing.expectEqualStrings("~/a.glsl", chain[0].path.get()); - try std.testing.expectEqual(Scene.glitch, chain[1].scene.?); + try std.testing.expectEqual(Scene.crt, chain[1].scene.?); try std.testing.expectEqualStrings("/b.glsl", chain[2].path.get()); const moved = state.post.generation; // A file named again leaves; the others keep their order. try std.testing.expect(apply(&state, find("Shader").?, "~/a.glsl")); try std.testing.expect(state.post.generation != moved); - try std.testing.expectEqual(Scene.glitch, state.post.list()[0].scene.?); + try std.testing.expectEqual(Scene.crt, state.post.list()[0].scene.?); try std.testing.expect(apply(&state, find("Shader").?, "off")); try std.testing.expectEqual(@as(usize, 1), state.post.len); try std.testing.expect(!apply(&state, find("Shader").?, null)); @@ -1288,7 +1284,7 @@ pub const Runtime = struct { const crt = find("Crt").?; try std.testing.expect(apply(&state, crt, "on")); try std.testing.expectEqual(@as(u8, Post.default_level), state.post.level(.crt)); - try std.testing.expect(apply(&state, find("Glitch").?, "1")); + try std.testing.expect(apply(&state, find("Shader").?, "/after.glsl")); const moved = state.post.generation; try std.testing.expect(apply(&state, crt, "3")); try std.testing.expectEqual(@as(u8, 3), state.post.level(.crt)); @@ -1472,8 +1468,6 @@ pub const Runtime = struct { }, .scene => |effect| switch (effect) { .crt => "Crt 2\n", - .ripple => "Ripple 2\n", - .glitch => "Glitch 2\n", }, .shader => "Shader ~/crt.glsl\n", .shader_animation => "ShaderAnimation always\n", @@ -1544,8 +1538,6 @@ pub const Runtime = struct { try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Font requested") == null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Panel transition off\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Crt unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Ripple unsupported\n") != null); - try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Glitch unsupported\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "TaglineSize unsupported\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Look hover delay: off\n") != null); try std.testing.expect(std.mem.indexOf(u8, defaults_report, "Native images: off\n") != null); diff --git a/src/effect_sources.zig b/src/effect_sources.zig index 6ce11160..83bd1313 100644 --- a/src/effect_sources.zig +++ b/src/effect_sources.zig @@ -12,10 +12,8 @@ const ui_fragment_path = shader_dir ++ "ui.frag.glsl"; const image_vertex_path = shader_dir ++ "image.vert.glsl"; const image_fragment_path = shader_dir ++ "image.frag.glsl"; const post_vertex_path = shader_dir ++ "post.vert.glsl"; -// The bundled post passes as compiled: the prefix and the pass together. +// The bundled post pass as compiled: the prefix and the pass together. const post_crt_path = shader_dir ++ "post-crt.frag.glsl"; -const post_ripple_path = shader_dir ++ "post-ripple.frag.glsl"; -const post_glitch_path = shader_dir ++ "post-glitch.frag.glsl"; pub const Backend = @TypeOf(build_config.platform); pub const backend: Backend = build_config.platform; @@ -55,8 +53,6 @@ pub const files = switch (backend) { .{ .path = image_fragment_path, .contents = @embedFile("effect-source-image.frag.glsl") }, .{ .path = post_vertex_path, .contents = @embedFile("effect-source-post.vert.glsl") }, .{ .path = post_crt_path, .contents = @embedFile("effect-source-post-crt.frag.glsl") }, - .{ .path = post_ripple_path, .contents = @embedFile("effect-source-post-ripple.frag.glsl") }, - .{ .path = post_glitch_path, .contents = @embedFile("effect-source-post-glitch.frag.glsl") }, }, .macos => [_]filesystem.Source{ .{ .path = "src/macos/Sources/PardesView.swift", .contents = @embedFile("macos/Sources/PardesView.swift") }, @@ -77,8 +73,6 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { .scene => |effect| switch (backend) { .gui => switch (effect) { .crt => &.{ "src/gui/Post.zig", "src/gui/gui.zig", post_vertex_path, post_crt_path }, - .ripple => &.{ "src/gui/Post.zig", "src/gui/gui.zig", post_vertex_path, post_ripple_path }, - .glitch => &.{ "src/gui/Post.zig", "src/gui/gui.zig", post_vertex_path, post_glitch_path }, }, .macos => &.{ "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, .tty, .web, .esp32p4 => null, diff --git a/src/gui/Post.zig b/src/gui/Post.zig index d9d3d53e..f715965f 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -1,7 +1,7 @@ //! The post chain (docs/render-pipeline.md §6): Shadertoy passes over the //! finished frame, each reading the one before it (the frame first) and the -//! last one writing the window. A pass is bundled (Crt, Ripple, Glitch: -//! shaders/post/, compiled with the build) or a user's file (Shader ), +//! last one writing the window. A pass is the bundled Crt (shaders/post/, +//! compiled with the build) or a user's file (Shader ), //! compiled when it joins the chain by the build's own glslc invocation on a //! thread of its own, never on the frame path. A file whose compile fails //! keeps its last good pipeline, and glslc missing is said once. @@ -28,8 +28,6 @@ const prefix = @embedFile("post-prefix.glsl"); const vert_spv = @embedFile("post.vert.spv"); const bundled_spv = std.EnumArray(Scene, []const u8).init(.{ .crt = @embedFile("post-crt.frag.spv"), - .ripple = @embedFile("post-ripple.frag.spv"), - .glitch = @embedFile("post-glitch.frag.spv"), }); /// ghostty's Shadertoy uniform block, member for member in the GLSL block's @@ -170,7 +168,7 @@ fn collect(post: *Post, gpa: std.mem.Allocator, device: *c.SDL_GPUDevice, format .none => {}, .missing => if (!post.missing_said) { post.missing_said = true; - core.setMessage(core.active, "Shader: glslc is not on PATH, so Shadertoy files do not run (Crt, Ripple and Glitch do)"); + core.setMessage(core.active, "Shader: glslc is not on PATH, so Shadertoy files do not run (Crt does)"); }, .failed => |text| { defer gpa.free(text); diff --git a/src/macos.zig b/src/macos.zig index 0bad86ee..6cd7838f 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -112,8 +112,6 @@ const cell_flag_default: u8 = 1; const cell_flag_tagline: u8 = 2; const cell_flag_hover: u8 = 4; const scene_flag_crt: u32 = 1 << 0; -const scene_flag_ripple: u32 = 1 << 1; -const scene_flag_glitch: u32 = 1 << 2; const scene_frame_hz: u32 = 60; const scene_wrap_ns: u64 = 4096 * std.time.ns_per_s; @@ -850,13 +848,11 @@ export fn pardes_should_quit() bool { return st.core.quit; } -// The Metal shell keeps its own CRT, ripple and glitch kernel: the bundled -// passes of the GUI's post chain, as flags. +// The Metal shell keeps its own CRT kernel: the GUI's bundled post pass, as +// a flag. fn encodeSceneEffects(post: *const pardes.config.Runtime.Post) u32 { var flags: u32 = 0; if (post.has(.crt)) flags |= scene_flag_crt; - if (post.has(.ripple)) flags |= scene_flag_ripple; - if (post.has(.glitch)) flags |= scene_flag_glitch; return flags; } @@ -2842,8 +2838,6 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); try expectEqual(@as(u32, c.PARDES_SCENE_CRT), scene_flag_crt); - try expectEqual(@as(u32, c.PARDES_SCENE_RIPPLE), scene_flag_ripple); - try expectEqual(@as(u32, c.PARDES_SCENE_GLITCH), scene_flag_glitch); try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @intFromEnum(animation.Phase.opening)); try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @intFromEnum(animation.Phase.moving)); try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @intFromEnum(animation.Phase.closing)); @@ -2918,13 +2912,6 @@ test "scene effect flags and display clock are compact and independent" { try expectEqual(@as(u32, 0), encodeSceneEffects(&post)); _ = post.set(.crt, "", true); try expectEqual(scene_flag_crt, encodeSceneEffects(&post)); - _ = post.set(.ripple, "", true); - _ = post.set(.glitch, "", true); - try expectEqual(scene_flag_crt | scene_flag_ripple | scene_flag_glitch, encodeSceneEffects(&post)); - try expectEqual( - scene_flag_crt | scene_flag_ripple | scene_flag_glitch, - encodeSceneEffects(.{ .crt = true, .ripple = true, .glitch = true }), - ); var st: State = undefined; st.scene_ns = scene_wrap_ns - (std.time.ns_per_ms * 5); diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 70f467e3..8ba9c84b 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -684,7 +684,7 @@ final class PardesView: NSView { private var latchedButton: pardes_mouse_button_e? private var latchedCell: GridPoint? /// Last physical point delivered by AppKit and its mapping through the - /// accepted scene. Ripple/glitch can move a source cell under a stationary + /// accepted scene. The CRT's barrel moves a source cell under a stationary /// hand, so successful scene presentations reconcile this point again. private var pointerPoint: CGPoint? private var pointerCell: GridPoint? diff --git a/src/macos/Sources/ScenePostprocessor.swift b/src/macos/Sources/ScenePostprocessor.swift index cf7892b3..41d54e34 100644 --- a/src/macos/Sources/ScenePostprocessor.swift +++ b/src/macos/Sources/ScenePostprocessor.swift @@ -205,11 +205,9 @@ final class ScenePostprocessor { if scene.flags != 0 { let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 - let ripple: Float = scene.flags & UInt32(PARDES_SCENE_RIPPLE) != 0 ? 1 : 0 - let glitch: Float = scene.flags & UInt32(PARDES_SCENE_GLITCH) != 0 ? 1 : 0 // SDL samples the scene with CLAMP_TO_EDGE. A finite Core Image // instead supplies transparent black outside its extent, which - // would make ripple/glitch tear dark seams at the window edge. + // would tear dark seams at the window edge. // Clamp the input only; the kernel still emits true black before // sampling when a destination lies outside the CRT tube. let sceneInput = filtered.clampedToExtent() @@ -218,7 +216,7 @@ final class ScenePostprocessor { roiCallback: { _, _ in extent }, arguments: [ sceneInput, scene.time_seconds, Float(scene.frame), - crt, ripple, glitch, + crt, CIVector(x: extent.width, y: extent.height), CIVector(x: extent.minX, y: extent.minY), ]) @@ -291,7 +289,7 @@ final class ScenePostprocessor { /// The scene kernel is a destination-to-source mapping. Pointer input must /// apply that same mapping before the grid and its panel tracks see a cell, - /// otherwise a visible word under ripple/glitch is not the word Look gets. + /// otherwise a visible word under the barrel is not the word Look gets. static func sourcePoint( _ point: CGPoint, size: CGSize, @@ -311,27 +309,8 @@ final class ScenePostprocessor { ccY *= barrel uvX = ccX * 0.5 + 0.5 uvY = ccY * 0.5 + 0.5 - // Only CRT has a black tube. Ripple/glitch without CRT sample through - // the texture's clamp-to-edge policy and remain clickable there. + // The CRT's black tube has no cell under it. if crt > 0.5 && min(min(uvX, uvY), min(1 - uvX, 1 - uvY)) <= 0 { return nil } - - let time = scene.time_seconds - if scene.flags & UInt32(PARDES_SCENE_RIPPLE) != 0 { - let centeredX = uvX - 0.5 - let centeredY = uvY - 0.5 - let radius = sqrtf(centeredX * centeredX + centeredY * centeredY) - let envelope = 1 - smoothstep(0.04, 0.72, radius) - let wave = sinf(radius * 42 - time * 5.2) - let travel = wave * envelope * 0.0032 / max(radius, 0.00001) - uvX += centeredX * travel - uvY += centeredY * travel - } - if scene.flags & UInt32(PARDES_SCENE_GLITCH) != 0 { - let band = floorf(uvY * 96) - let seed = noise(band, floorf(time * 13)) - let tear = smoothstep(0.955, 1, seed) - uvX += (noise(seed, band) - 0.5) * tear * 0.020 - } uvX = min(max(uvX, 0), max(0, 1 - 1 / Float(size.width))) uvY = min(max(uvY, 0), max(0, 1 - 1 / Float(size.height))) return CGPoint( @@ -339,23 +318,4 @@ final class ScenePostprocessor { y: CGFloat(1 - uvY) * size.height) } - private static func smoothstep(_ edge0: Float, _ edge1: Float, _ x: Float) -> Float { - let t = min(max((x - edge0) / (edge1 - edge0), 0), 1) - return t * t * (3 - 2 * t) - } - - /// Scalar spelling of pardesNoise in crt.ci.metal. Float arithmetic is - /// deliberate: the shader's band decision must not move at a Double round. - private static func noise(_ x: Float, _ y: Float) -> Float { - var qx = fract(x * 0.1031) - var qy = fract(y * 0.1031) - var qz = fract(x * 0.1031) - let d = qx * (qy + 33.33) + qy * (qz + 33.33) + qz * (qx + 33.33) - qx += d - qy += d - qz += d - return fract((qx + qy) * qz) - } - - private static func fract(_ x: Float) -> Float { x - floorf(x) } } diff --git a/src/macos/pardes.h b/src/macos/pardes.h index f74330e5..29f8a37d 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -82,8 +82,7 @@ typedef struct { // from the background colour, which a real selection shares. #define PARDES_CELL_HOVER 0x04u -// One coherent snapshot for the full-window shader pass. The bitmask lets the -// host run CRT, ripple and glitch in one kernel instead of stacking filters; +// One coherent snapshot for the full-window shader pass (CRT); // time/frame advance only on pardes_animation_tick's display clock. typedef struct { uint32_t flags; @@ -92,8 +91,6 @@ typedef struct { } pardes_scene_s; #define PARDES_SCENE_CRT 0x01u -#define PARDES_SCENE_RIPPLE 0x02u -#define PARDES_SCENE_GLITCH 0x04u // One backend-neutral pane transition. Boxes are logical cell rectangles; // the native shader converts them to backing pixels using the same measured diff --git a/test/output.zig b/test/output.zig index 0fdd9f4d..e49ec4ff 100644 --- a/test/output.zig +++ b/test/output.zig @@ -669,7 +669,7 @@ test "every enabled setting builtin mutates the State Config reports" { try std.testing.expect(std.mem.indexOf(u8, report, transition) != null); // A bare word turns a bundled pass on at its default level. const scene_status = if (builtins.capabilities.scene_shaders) "2" else "unsupported"; - for ([_][]const u8{ "Crt", "Ripple", "Glitch" }) |name| { + for ([_][]const u8{"Crt"}) |name| { const line = try std.fmt.bufPrint(&buf, "{s} {s}\n", .{ name, scene_status }); try std.testing.expect(std.mem.indexOf(u8, report, line) != null); } -- cgit v1.3 From 8eeab5df9c09caafc07c93c2fc3baf6e6700afed Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 12:44:06 -0300 Subject: Alt/Option-click is B2 and Super/Cmd-click is B3, sweeps included, as in plan9port: a one-button trackpad can execute and look The core decides it at the press (mouse.emulateButton) and keeps it to the release, whatever keys are let go between. Ctrl-click stays a definition, and a program tracking the mouse still gets the plain click (Alt as its meta, Super as nothing). The SDL, macOS and web shells now pass Super; the macOS and web shells pass Alt on a click too. A terminal's mouse report has no Super bit, so in a terminal only Alt-click is B2. Co-Authored-By: Claude Opus 5.5 --- src/gui/gui.zig | 5 ++-- src/macos.zig | 3 ++ src/macos/Sources/PardesView.swift | 1 + src/macos/pardes.h | 2 ++ src/mouse.zig | 58 ++++++++++++++++++++++++++++++++++++-- src/pardes.zig | 6 ++++ src/web.zig | 3 ++ src/web/app.mjs | 2 +- 8 files changed, 75 insertions(+), 5 deletions(-) (limited to 'src/macos/Sources') diff --git a/src/gui/gui.zig b/src/gui/gui.zig index e8dc99b9..65b3f926 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -4020,7 +4020,7 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, mods: PointerMods = .{} }; /// The modifiers held with a pointer event, as the core's Mouse carries them. -const PointerMods = struct { ctrl: bool = false, shift: bool = false, alt: bool = false }; +const PointerMods = struct { ctrl: bool = false, shift: bool = false, alt: bool = false, super: bool = false }; /// The core's Mouse for an SDL press, release or move over cell `mc`. fn pointerMouse(button: pardes.Mouse.Button, kind: pardes.Mouse.Kind, mc: MouseCell, mods: PointerMods) pardes.Mouse { @@ -4035,12 +4035,13 @@ fn pointerMouse(button: pardes.Mouse.Button, kind: pardes.Mouse.Kind, mc: MouseC .ctrl = mods.ctrl, .shift = mods.shift, .alt = mods.alt, + .super = mods.super, }; } fn pointerMods() PointerMods { const m = c.SDL_GetModState(); - return .{ .ctrl = (m & c.SDL_KMOD_CTRL) != 0, .shift = (m & c.SDL_KMOD_SHIFT) != 0, .alt = (m & c.SDL_KMOD_ALT) != 0 }; + return .{ .ctrl = (m & c.SDL_KMOD_CTRL) != 0, .shift = (m & c.SDL_KMOD_SHIFT) != 0, .alt = (m & c.SDL_KMOD_ALT) != 0, .super = (m & c.SDL_KMOD_GUI) != 0 }; } fn mouseCellWithGeometry(g: *const Gui, core: ?*const pardes.Pardes, x: f32, y: f32, geometry: WindowGeometry) ?MouseCell { diff --git a/src/macos.zig b/src/macos.zig index e839816c..20463481 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1725,6 +1725,9 @@ fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u3 .col = col, .row = row, .ctrl = mods & 1 != 0, + // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, } }); } diff --git a/src/macos/Sources/PardesView.swift b/src/macos/Sources/PardesView.swift index 8ba9c84b..4ea4475a 100644 --- a/src/macos/Sources/PardesView.swift +++ b/src/macos/Sources/PardesView.swift @@ -562,6 +562,7 @@ private func modifiers(_ flags: NSEvent.ModifierFlags) -> UInt32 { if flags.contains(.control) { mods |= UInt32(PARDES_MOD_CTRL) } if flags.contains(.option) { mods |= UInt32(PARDES_MOD_ALT) } if flags.contains(.shift) { mods |= UInt32(PARDES_MOD_SHIFT) } + if flags.contains(.command) { mods |= UInt32(PARDES_MOD_SUPER) } return mods } diff --git a/src/macos/pardes.h b/src/macos/pardes.h index 46453429..33db3bb5 100644 --- a/src/macos/pardes.h +++ b/src/macos/pardes.h @@ -141,6 +141,8 @@ typedef struct { #define PARDES_MOD_CTRL 0x0001u #define PARDES_MOD_ALT 0x0002u #define PARDES_MOD_SHIFT 0x0004u +// Command. Only a click reads it (Cmd-click is B3); a Command key chord never reaches the core. +#define PARDES_MOD_SUPER 0x0008u // Keys that carry no text. The four editing keys are their ASCII controls; // everything else lives in a private-use plane so it can never collide with a diff --git a/src/mouse.zig b/src/mouse.zig index 41362249..21961cf8 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -446,7 +446,23 @@ fn programMouse(p: *Pardes, m: Mouse) bool { } } -pub fn handleMouse(p: *Pardes, m: Mouse) void { +/// plan9port's convention for a mouse or trackpad with one button: +/// Alt-click is B2 and Super-click (Cmd) is B3, sweeps included, decided at +/// the press and kept through its release, whatever keys are let go +/// meanwhile. Ctrl-click keeps its own meaning (a definition). Run after +/// programMouse: a program that takes the click gets it as it was. +fn emulateButton(p: *Pardes, m: *Mouse) void { + if (m.button != .left) return; + if (m.kind == .press) p.click_as = if (m.ctrl) null else if (m.super) .right else if (m.alt) .middle else null; + const as = p.click_as orelse return; + m.button = as; + m.alt = false; + m.super = false; + if (m.kind == .release) p.click_as = null; +} + +pub fn handleMouse(p: *Pardes, event: Mouse) void { + var m = event; // A click goes somewhere else: the question it leaves unanswered is // taken back, and the pane stays. A wheel only looks around. if (m.kind == .press and switch (m.button) { @@ -496,6 +512,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } p.pointer_inside = true; if (programMouse(p, m)) return; + emulateButton(p, &m); if (m.button == .none and m.kind == .motion) { p.raw_hover_intent = true; look.refreshLookHoverFromRaw(p); @@ -2007,6 +2024,35 @@ test "a wheel over a program that owns it is the program's, in the form it asked try std.testing.expectEqualStrings("\x1b[<64;6;4M", try ptyWrites(p, &out)); } +test "Alt-click is B2 and Super-click B3, kept from the press through the release; Ctrl-click stays B1" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const file = try p.setTestFile("Newcol here\n"); + p.acknowledgePanelPresentation(&.{}); + const r = p.rects[0]; + const col = r.x + config.GUTTER + panes.File.gutterWidth(file) + 1; + const row = p.bodyTop(file, r); + // A Super-press sweeps with B3's selection, not B1's. + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row, .super = true } }); + try std.testing.expect(p.drag == .select and file.sel[2].state != .none and file.sel[0].state == .none); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row } }); + try std.testing.expect(p.drag == .none); + try std.testing.expectEqual(@as(?Mouse.Button, null), p.click_as); + // Ctrl with Alt is Ctrl's: a B1 click (a definition), never B2. + const cols = p.ncol; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row, .ctrl = true, .alt = true } }); + try std.testing.expectEqual(@as(?Mouse.Button, null), p.click_as); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row, .ctrl = true } }); + try std.testing.expectEqual(cols, p.ncol); + // Alt-click on Newcol runs it, as B2 does, though Alt is let go + // before the button. + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = col, .row = row, .alt = true } }); + try std.testing.expectEqual(@as(?Mouse.Button, .middle), p.click_as); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = col, .row = row } }); + try std.testing.expectEqual(cols + 1, p.ncol); + try std.testing.expectEqual(@as(?Mouse.Button, null), p.click_as); +} + test "a program tracking the mouse gets its clicks, drags and moves over its grid as xterm reports them; Shift and chrome stay pardes's" { if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; @@ -2023,7 +2069,7 @@ test "a program tracking the mouse gets its clicks, drags and moves over its gri const r = p.rects[0]; const col = r.x + config.GUTTER + 5; const row = p.bodyTop(pane, r) + 3; - const Ev = struct { button: Mouse.Button, kind: Mouse.Kind, dx: i32 = 0, dy: i32 = 0, shift: bool = false, alt: bool = false, ctrl: bool = false }; + const Ev = struct { button: Mouse.Button, kind: Mouse.Kind, dx: i32 = 0, dy: i32 = 0, shift: bool = false, alt: bool = false, ctrl: bool = false, super: bool = false }; const send = struct { fn f(pp: *Pardes, o: *std.ArrayList(u8), c: u16, rw: u16, e: Ev) ![]const u8 { pp.update(.{ .mouse = .{ @@ -2034,6 +2080,7 @@ test "a program tracking the mouse gets its clicks, drags and moves over its gri .shift = e.shift, .alt = e.alt, .ctrl = e.ctrl, + .super = e.super, } }); return ptyWrites(pp, o); } @@ -2046,6 +2093,13 @@ test "a program tracking the mouse gets its clicks, drags and moves over its gri // 1000 has no drags; the release is reported where it lands. try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .left, .kind = .drag, .dx = 1 })); try std.testing.expectEqualStrings("\x1b[<0;7;4m", try send(p, &out, col, row, .{ .button = .left, .kind = .release, .dx = 1 })); + // An Alt- or Super-click (B2, B3 elsewhere) is still the program's + // button 1, Alt its meta and Super no bit at all. + try std.testing.expectEqualStrings("\x1b[<8;6;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .press, .alt = true })); + try std.testing.expectEqualStrings("\x1b[<0;6;4m", try send(p, &out, col, row, .{ .button = .left, .kind = .release })); + try std.testing.expectEqualStrings("\x1b[<0;6;4M", try send(p, &out, col, row, .{ .button = .left, .kind = .press, .super = true })); + try std.testing.expectEqualStrings("\x1b[<0;6;4m", try send(p, &out, col, row, .{ .button = .left, .kind = .release, .super = true })); + try std.testing.expect(p.drag == .none); // B2 and B3 are pardes's execute and look, as in any pane. try std.testing.expectEqualStrings("", try send(p, &out, col, row, .{ .button = .right, .kind = .press })); try std.testing.expect(p.drag == .select); diff --git a/src/pardes.zig b/src/pardes.zig index 41ed0e5a..38373266 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3515,6 +3515,9 @@ pub const Mouse = struct { shift: bool = false, /// Alt, which xterm's mouse reports call meta. alt: bool = false, + /// Super: Cmd on a Mac, the Windows key elsewhere. A terminal's mouse + /// report has no such bit, so only a pixel shell sets it. + super: bool = false, body_hit: ?BodyHit = null, tag_hit: ?TagHit = null, /// A pixel frontend's press on the rule it draws at the top of this row, @@ -4414,6 +4417,9 @@ pub const Pardes = struct { /// The last plain B1 click, for acme's double-click (text.c:881, /// textselect: a second click at the same point within 500 ms). last_click: ?struct { id: usize, on_tag: bool, row: i32, col: i32, ms: i64 } = null, + /// The button an Alt- or Super-click of button 1 stands for, from its + /// press through its release (mouse.emulateButton). + click_as: ?Mouse.Button = null, /// A B1 chord's edits share the undo point it took (mouse.zig). chord_hold: bool = false, /// The look just run found nothing (look.zig missed). diff --git a/src/web.zig b/src/web.zig index ac0ecbbf..fed2ba5a 100644 --- a/src/web.zig +++ b/src/web.zig @@ -266,6 +266,9 @@ fn mouseWithHit(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods .col = @intCast(@min(col_arg, std.math.maxInt(u16))), .row = @intCast(@min(row_arg, std.math.maxInt(u16))), .ctrl = mods & 1 != 0, + // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, } }); } diff --git a/src/web/app.mjs b/src/web/app.mjs index c053d663..d2405cf4 100644 --- a/src/web/app.mjs +++ b/src/web/app.mjs @@ -678,7 +678,7 @@ function rgb(r, g, b) { } function modifiers(event) { - return (event.ctrlKey ? 1 : 0) | (event.altKey ? 2 : 0) | (event.shiftKey ? 4 : 0); + return (event.ctrlKey ? 1 : 0) | (event.altKey ? 2 : 0) | (event.shiftKey ? 4 : 0) | (event.metaKey ? 8 : 0); } function pointerButton(button) { -- cgit v1.3