diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 21:23:22 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 21:43:03 -0300 |
| commit | f9a3179542012ec1a700e2020ac9f616b819f972 (patch) | |
| tree | 73f4cb241876196331f7b28c9f773301bd341a7f /src/gui | |
| parent | a75956bb3443aa8aac778d2ff12c42f5ef99e0e9 (diff) | |
| download | pardes-f9a3179542012ec1a700e2020ac9f616b819f972.tar.gz pardes-f9a3179542012ec1a700e2020ac9f616b819f972.zip | |
dev: the frontends (dev/tui, dev/gui, the macOS app's Swift and resources in dev/macos), host_io, file_watch, fonts, the lsp client and Scip, Art, jump_trail, glide and vaxis_input into dev/ (the reorganisation's tree, step 2b): module `dev` (dev/root.zig) beside the core and the runtime, each naming the others; the window wired into it, sketchbook's devices imported as `sketchbook` (its `dev` would be ours); pardes.zig keeps its re-exports (host_io, file_watch, glide, fonts) so every caller reads as before; core-test and shell-test run the devices' test program too, so the same tests run (the ledger, tui and gui); nothing else changes: frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/gui')
| -rw-r--r-- | src/gui/Trackpad.zig | 142 | ||||
| -rw-r--r-- | src/gui/deck.zig | 204 | ||||
| -rw-r--r-- | src/gui/gui.zig | 8319 | ||||
| -rw-r--r-- | src/gui/macos_trackpad.h | 21 | ||||
| -rw-r--r-- | src/gui/macos_trackpad.m | 176 | ||||
| -rw-r--r-- | src/gui/pet.zig | 215 |
6 files changed, 0 insertions, 9077 deletions
diff --git a/src/gui/Trackpad.zig b/src/gui/Trackpad.zig deleted file mode 100644 index ef28d211..00000000 --- a/src/gui/Trackpad.zig +++ /dev/null @@ -1,142 +0,0 @@ -//! Mac trackpad policy, after AppKit decoding. Buttons use SDL's 1/2/3. -const std = @import("std"); -const Trackpad = @This(); - -fingers: usize = 0, -stream: ?u8 = null, -button: ?u8 = null, -forced: bool = false, -rotation: f32 = 0, -rotation_total: f32 = 0, -gesture: enum { none, pinch, rotate } = .none, -pinch_base: f32 = 0, -pinch_total: f32 = 1, - -pub fn countFingers(t: *Trackpad, count: usize) void { - if (count < 2 or t.fingers < 2) { - t.gesture = .none; - t.rotation_total = 0; - t.pinch_base = 0; - t.pinch_total = 1; - } - t.fingers = count; -} - -pub fn press(t: *Trackpad, stream: u8) u8 { - if (t.fingers == 0 or stream > 3) return stream; - t.stream = stream; - t.button = if (t.fingers >= 2) 2 else stream; - t.forced = false; - return t.button.?; -} - -pub fn release(t: *Trackpad, stream: u8) ?u8 { - if (t.stream != stream) return stream; - defer { - t.stream = null; - t.button = null; - t.forced = false; - } - return if (t.forced) null else t.button; -} - -/// The caller releases this button before issuing one Look click. The -/// physical release afterwards is swallowed, so it cannot become a chord. -pub fn force(t: *Trackpad, stage: f32) ?u8 { - if (stage < 2 or t.forced or t.button == null or t.button == 3) return null; - t.forced = true; - return t.button; -} - -pub fn rotate(t: *Trackpad, degrees: f32, phase: u32) i32 { - if (phase == 1 or phase == 3) { - t.rotation = 0; - t.rotation_total = 0; - } - if (phase == 3 or !std.math.isFinite(degrees)) return 0; - if (t.gesture == .pinch) return 0; - t.rotation_total += std.math.clamp(degrees, -640, 640); - if (@abs(t.rotation_total) >= 3) t.gesture = .rotate; - const next = t.rotation + std.math.clamp(degrees, -640, 640); - const ticks: i32 = @intFromFloat(@trunc(next / 10)); - t.rotation = next - @as(f32, @floatFromInt(ticks)) * 10; - return ticks; -} - -/// Ignore small magnification noise, especially while twisting. Once a -/// deliberate pinch wins, half the logarithmic gain makes fine zoom easier. -pub fn magnify(t: *Trackpad, size: f32, scale: f32, phase: u32) ?f32 { - if (phase == 1 or t.pinch_base == 0) { - t.pinch_base = size; - t.pinch_total = 1; - } - if (phase == 3) { - t.pinch_base = 0; - if (t.gesture == .pinch) t.gesture = .none; - return null; - } - if (t.gesture == .rotate or !std.math.isFinite(scale) or scale <= 0) return null; - t.pinch_total = std.math.clamp(t.pinch_total * scale, 0.01, 100); - if (t.gesture == .none) { - if (t.pinch_total > 1 / @as(f32, 1.1) and t.pinch_total < 1.1) return null; - t.gesture = .pinch; - } - return std.math.clamp(t.pinch_base * @sqrt(t.pinch_total), 8, 72); -} - -pub fn pinch(size: f32, scale: f32) f32 { - if (!std.math.isFinite(scale) or scale <= 0) return size; - return std.math.clamp(size * scale, 8, 72); -} - -test "Mac trackpad multi-finger buttons stay latched after the fingers lift" { - var t: Trackpad = .{}; - try std.testing.expectEqual(@as(u8, 3), t.press(3)); // real mouse - try std.testing.expectEqual(@as(?u8, 3), t.release(3)); - for ([_]usize{ 2, 3 }) |n| { - t.fingers = n; - try std.testing.expectEqual(@as(u8, 2), t.press(3)); - t.fingers = 0; - try std.testing.expectEqual(@as(?u8, 2), t.release(3)); - } -} - -test "Mac trackpad force click upgrades Exec once without a paste chord or stray release" { - var t: Trackpad = .{ .fingers = 2 }; - try std.testing.expectEqual(@as(u8, 2), t.press(3)); - try std.testing.expect(t.force(1) == null); - try std.testing.expectEqual(@as(?u8, 2), t.force(2)); - try std.testing.expect(t.force(2) == null); - try std.testing.expect(t.release(3) == null); - t.fingers = 1; - try std.testing.expectEqual(@as(u8, 1), t.press(1)); - try std.testing.expectEqual(@as(?u8, 1), t.release(1)); -} - -test "Mac trackpad rotate and pinch reject invalid input and reset cancelled gestures" { - var t: Trackpad = .{}; - try std.testing.expectEqual(@as(i32, 0), t.rotate(7, 1)); - try std.testing.expectEqual(@as(i32, 1), t.rotate(5, 0)); - try std.testing.expectEqual(@as(i32, -1), t.rotate(-12, 0)); - try std.testing.expectEqual(@as(i32, 0), t.rotate(9, 3)); - try std.testing.expectEqual(@as(f32, 0), t.rotation); - try std.testing.expectEqual(@as(f32, 18), pinch(18, 1)); - try std.testing.expectEqual(@as(f32, 36), pinch(18, 2)); - try std.testing.expectEqual(@as(f32, 72), pinch(18, 100)); - try std.testing.expectEqual(@as(f32, 18), pinch(18, std.math.nan(f32))); -} - -test "trackpad pinch ignores twist noise and uses gentler deliberate zoom" { - var t: Trackpad = .{}; - t.countFingers(2); - try std.testing.expect(t.magnify(18, 1, 1) == null); - for (0..5) |_| try std.testing.expect(t.magnify(18, 1.01, 0) == null); - _ = t.rotate(7, 1); - try std.testing.expect(t.magnify(18, 1.3, 0) == null); - t.countFingers(0); - t.countFingers(2); - const zoom = t.magnify(18, 1.2, 1) orelse return error.PinchNotRecognized; - try std.testing.expect(zoom > 18 and zoom < 20.5); - try std.testing.expectEqual(@as(i32, 0), t.rotate(30, 1)); - try std.testing.expect(t.magnify(zoom, 1, 3) == null); -} diff --git a/src/gui/deck.zig b/src/gui/deck.zig deleted file mode 100644 index 1859bae8..00000000 --- a/src/gui/deck.zig +++ /dev/null @@ -1,204 +0,0 @@ -//! Steam Deck controls -> editor input, as a pure state machine: gui.zig -//! feeds SDL gamepad events in and applies the returned actions (cursor -//! moves, synthetic clicks, wheel ticks, keys, rumble), so the whole -//! mapping replays off-device from deckcap recordings (test/deck/). -//! -//! Layout: right pad moves the pointer (relative, laptop-touchpad-style) and -//! a firm press on it = select (button 1); left pad scrolls and a firm press -//! = look (button 3); R2 = select, L2 = execute (button 2), L1 = look, dpad -//! down/up = n/N, A = Enter, Y = Tab, the back paddles (L4/R4/L5/R5) toggle -//! the terminal (Ctrl-b); execute, look and pad-clicks request a brief rumble -//! ack. (The GUI mirrors this on the sticks: right stick = pointer, left -//! stick = scroll.) - -const std = @import("std"); - -// SDL_GamepadButton / SDL_GamepadAxis / touchpad indices (SDL3), verified -// against real deck recordings (test/deck/*.zon) and the pinned SDL's -// hidapi deck driver (touchpad 0 = left pad, 1 = right pad). -pub const BTN_A = 0; // SOUTH -pub const BTN_Y = 3; // NORTH -pub const BTN_L1 = 9; // LEFT_SHOULDER -pub const BTN_DPAD_UP = 11; -pub const BTN_DPAD_DOWN = 12; -// rear grip paddles (from a deckcap deckmap capture): the two-digit indices -pub const BTN_R4 = 16; -pub const BTN_L4 = 17; -pub const BTN_R5 = 18; -pub const BTN_L5 = 19; -pub const AXIS_L2 = 4; // LEFT_TRIGGER, analog 0..32767 -pub const AXIS_R2 = 5; // RIGHT_TRIGGER -pub const PAD_LEFT = 0; -pub const PAD_RIGHT = 1; - -/// feel knobs: a full-pad finger sweep covers this many screen pixels -/// (the deck's screen is 1280x800) / this many wheel ticks -pub const POINTER_SCALE: f32 = 600.0; -pub const SCROLL_SCALE: f32 = 24.0; -/// the pinned SDL 3.4.4 deck driver skips upstream's pad-Y negation, so -/// touch y arrives 0 = pad bottom; flip this when the sdl dep is bumped -pub const PAD_Y_SIGN: f32 = -1.0; -// analog triggers click at 30% and release at 20%: the gap keeps a value -// hovering near one threshold from chattering press/release pairs -pub const TRIG_PRESS: i16 = 9830; -pub const TRIG_RELEASE: i16 = 6553; -// a firm pad press (pressure 0..1) counts as a click, with the same release -// hysteresis. Real light-touch drags read ~0.03 in captures, so this is well -// clear of them; tune on-device against a real click capture. -pub const PAD_CLICK_PRESS: f32 = 0.10; -pub const PAD_CLICK_RELEASE: f32 = 0.06; - -pub const Input = union(enum) { - button: struct { idx: u8, down: bool }, - axis: struct { idx: u8, value: i16 }, - touch: struct { pad: u8, phase: enum { down, motion, up }, x: f32, y: f32, pressure: f32 }, -}; - -pub const Click = enum { select, execute, look }; // mouse buttons 1/2/3 -pub const Keytap = enum { n, cap_n, enter, tab, tty_toggle }; - -pub const Action = union(enum) { - move: struct { dx: f32, dy: f32 }, // pointer delta in screen pixels - click: struct { which: Click, down: bool }, - wheel: i32, // whole ticks, positive = wheel_down - key: Keytap, - rumble, -}; - -pub const Deck = struct { - rpad_on: bool = false, - rpad_x: f32 = 0, - rpad_y: f32 = 0, - lpad_on: bool = false, - lpad_y: f32 = 0, - scroll: f32 = 0, // fractional wheel ticks carried between motions - l2_held: bool = false, - r2_held: bool = false, - look_held: bool = false, - rpad_click: bool = false, // firm-press click state, per pad (hysteresis) - lpad_click: bool = false, - - pub fn feed(d: *Deck, in: Input, out: *[3]Action) usize { - var n: usize = 0; - switch (in) { - .button => |b| switch (b.idx) { - BTN_A => if (b.down) { - out[0] = .{ .key = .enter }; - n = 1; - }, - BTN_Y => if (b.down) { - out[0] = .{ .key = .tab }; - n = 1; - }, - BTN_DPAD_UP => if (b.down) { - out[0] = .{ .key = .cap_n }; - n = 1; - }, - BTN_DPAD_DOWN => if (b.down) { - out[0] = .{ .key = .n }; - n = 1; - }, - // any back paddle toggles the terminal (Ctrl-b), applied in gui.zig - BTN_L4, BTN_R4, BTN_L5, BTN_R5 => if (b.down) { - out[0] = .{ .key = .tty_toggle }; - n = 1; - }, - BTN_L1 => { - d.look_held = b.down; - out[0] = .{ .click = .{ .which = .look, .down = b.down } }; - n = 1; - if (b.down) { - out[1] = .rumble; - n = 2; - } - }, - else => {}, - }, - .axis => |a| { - if (a.idx != AXIS_L2 and a.idx != AXIS_R2) return 0; - const held = if (a.idx == AXIS_L2) &d.l2_held else &d.r2_held; - const which: Click = if (a.idx == AXIS_L2) .execute else .select; - if (!held.* and a.value >= TRIG_PRESS) { - held.* = true; - out[0] = .{ .click = .{ .which = which, .down = true } }; - n = 1; - if (which == .execute) { - out[1] = .rumble; - n = 2; - } - } else if (held.* and a.value <= TRIG_RELEASE) { - held.* = false; - out[0] = .{ .click = .{ .which = which, .down = false } }; - n = 1; - } - }, - .touch => |t| { - switch (t.pad) { - PAD_RIGHT => switch (t.phase) { - // a fresh touch only re-anchors — deltas start from the - // landing point, so the pointer never jumps to it - .down => { - d.rpad_on = true; - d.rpad_x = t.x; - d.rpad_y = t.y; - }, - .motion => if (d.rpad_on) { - out[n] = .{ .move = .{ - .dx = (t.x - d.rpad_x) * POINTER_SCALE, - .dy = (t.y - d.rpad_y) * PAD_Y_SIGN * POINTER_SCALE, - } }; - n += 1; - d.rpad_x = t.x; - d.rpad_y = t.y; - }, - .up => d.rpad_on = false, - }, - PAD_LEFT => switch (t.phase) { - .down => { - d.lpad_on = true; - d.lpad_y = t.y; - }, - .motion => if (d.lpad_on) { - d.scroll += (t.y - d.lpad_y) * PAD_Y_SIGN * SCROLL_SCALE; - d.lpad_y = t.y; - const ticks: i32 = @intFromFloat(d.scroll); - if (ticks != 0) { - d.scroll -= @floatFromInt(ticks); - out[n] = .{ .wheel = ticks }; - n += 1; - } - }, - .up => d.lpad_on = false, - }, - else => {}, - } - // a firm press on either pad is a click: right pad -> select - // (left button), left pad -> look (right button). The press - // rumbles as click feedback, mirroring the stock driver (SDL - // exposes no per-pad haptic, so it's a short whole-pad buzz). - if (t.pad == PAD_RIGHT or t.pad == PAD_LEFT) { - const which: Click = if (t.pad == PAD_RIGHT) .select else .look; - const held = if (t.pad == PAD_RIGHT) &d.rpad_click else &d.lpad_click; - if (t.phase == .up) { - if (held.*) { - held.* = false; - out[n] = .{ .click = .{ .which = which, .down = false } }; - n += 1; - } - } else if (!held.* and t.pressure >= PAD_CLICK_PRESS) { - held.* = true; - out[n] = .{ .click = .{ .which = which, .down = true } }; - n += 1; - out[n] = .rumble; - n += 1; - } else if (held.* and t.pressure <= PAD_CLICK_RELEASE) { - held.* = false; - out[n] = .{ .click = .{ .which = which, .down = false } }; - n += 1; - } - } - }, - } - return n; - } -}; diff --git a/src/gui/gui.zig b/src/gui/gui.zig deleted file mode 100644 index c772ac1d..00000000 --- a/src/gui/gui.zig +++ /dev/null @@ -1,8319 +0,0 @@ -const dev = @import("dev"); // sketchbook's devices -const SketchGpu = dev.Executor; -const Cells = dev.Cells; -const Atlas = dev.Atlas; -const Present = dev.Present; -const GpuScene = dev.scene; -const filesystem = @import("../fs.zig"); -const std = @import("std"); -const builtin = @import("builtin"); -const posix = std.posix; -/// libc: pipes and fcntl for the window's wakes, and a test harness's capture files written from the render thread. -const libc = std.c; -const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser -const pardes = @import("../pardes.zig"); -const vaxis_input = @import("../vaxis_input.zig"); -const dump = @import("../dump.zig"); -const config = @import("../config.zig"); -const look = @import("../look.zig"); -const message = pardes.Messages.Message; -const file_watch = @import("../file_watch.zig"); -const deck = @import("deck.zig"); -const pet = @import("pet.zig"); -const Trackpad = @import("Trackpad.zig"); -const JumpTrail = @import("../jump_trail.zig"); -const Art = @import("../Art.zig"); -const fonts = @import("../fonts.zig"); // the fallback faces -const selection_pipe = @import("../selection_pipe.zig"); -const c_heap = @import("c_heap"); - -const ninep_io = @import("runtime").ninep_io; - -const daemon = @import("runtime").daemon; -const upgrade = @import("runtime").upgrade; -const replica = @import("../replica.zig"); -const tracy = @import("../tracy.zig"); - -pub const c = @import("gui_c"); // SDL3 and font.h, translated by build.zig - -const host_io = @import("../host_io.zig"); -const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); - -const log = std.log.scoped(.gui); - -const font_ttf = @embedFile("AdwaitaMono-Regular.ttf"); - -const bg_default = [3]u8{ 18, 18, 18 }; -const fg_default = [3]u8{ 204, 204, 204 }; - -const p9_arrow_clr = [32]u8{ - 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, - 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, - 0x80, 0x02, 0x80, 0x01, 0x80, 0x02, 0x8C, 0x04, - 0x92, 0x08, 0x91, 0x10, 0xA0, 0xA0, 0xC0, 0x40, -}; -const p9_arrow_set = [32]u8{ - 0x00, 0x00, 0x7F, 0xFE, 0x7F, 0xFC, 0x7F, 0xF0, - 0x7F, 0xE0, 0x7F, 0xE0, 0x7F, 0xF0, 0x7F, 0xF8, - 0x7F, 0xFC, 0x7F, 0xFE, 0x7F, 0xFC, 0x73, 0xF8, - 0x61, 0xF0, 0x60, 0xE0, 0x40, 0x40, 0x00, 0x00, -}; -/// acme's boxcursor (acme.c:956), while a grip carries a pane or column. -const p9_box_clr = [32]u8{ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, - 0xF8, 0x1F, 0xF8, 0x1F, 0xF8, 0x1F, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, -}; -const p9_box_set = [32]u8{ - 0x00, 0x00, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, - 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, - 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, 0x70, 0x0E, - 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x00, 0x00, -}; -const p9_box_mask = blk: { - var m: [32]u8 = undefined; - for (&m, p9_box_set, p9_box_clr) |*b, s, cl| b.* = s | cl; - break :blk m; -}; -const p9_arrow_mask = blk: { - var m: [32]u8 = undefined; - for (&m, p9_arrow_set, p9_arrow_clr) |*b, s, cl| b.* = s | cl; - break :blk m; -}; - -const atlas_w = Atlas.atlas_w; -const atlas_h = Atlas.atlas_h; -const Slot = Atlas.Slot; -const GlyphKey = Atlas.Key; -const ruleArms = Atlas.ruleArms; - -const GlyphDecoration = packed struct(u5) { - bold: bool = false, - underline: @FieldType(pardes.CellStyle, "ul") = .off, - strikethrough: bool = false, - - fn fromCell(cell: *const pardes.Cell) GlyphDecoration { - if (cell.default or cell.style.invisible) return .{}; - return .{ .bold = cell.style.bold, .underline = cell.style.ul, .strikethrough = cell.style.strikethrough }; - } - - fn drawsBlank(decoration: GlyphDecoration) bool { - return decoration.underline != .off or decoration.strikethrough; - } -}; - -// The atlas's Key holds a GlyphDecoration and a FontRole as its own -// Decoration and Role (@bitCast, @enumFromInt): the same bits, so the same -// slots. -comptime { - std.debug.assert(@bitSizeOf(GlyphDecoration) == @bitSizeOf(Atlas.Decoration)); - for (.{ .{ @FieldType(pardes.CellStyle, "ul"), Atlas.Underline }, .{ pardes.FontRole, Atlas.Role } }) |pair| { - const ours = @typeInfo(pair[0]).@"enum"; - const its = @typeInfo(pair[1]).@"enum"; - std.debug.assert(ours.tag_type == its.tag_type and ours.field_names.len == its.field_names.len); - for (ours.field_names, its.field_names, ours.field_values, its.field_values) |a, b, x, y| std.debug.assert(std.mem.eql(u8, a, b) and x == y); - } -} - -const TaglineRaster = struct { - px: f32, - width: u32, - baseline: i32, - height: u32, -}; - -fn taglineRaster(atlas: *const Atlas, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster { - const px = body_px * @as(f32, @floatFromInt(percent)) / 100.0; - var own_w: c_int = 1; - var own_h: c_int = 1; - var own_ascent: c_int = 1; - atlas.cellMetrics(px, &own_w, &own_h, &own_ascent); - const fixed_w: c_int = @intCast(body_cell_w); - const fixed_h: c_int = @intCast(body_cell_h); - const band_h = std.math.clamp(own_h, 1, fixed_h); - return .{ - .px = px, - .width = @intCast(std.math.clamp(own_w, 1, fixed_w)), - .baseline = std.math.clamp(own_ascent, 1, band_h), - .height = @intCast(band_h), - }; -} -/// What FreeType and HarfBuzz allocate from, through ui_malloc and friends: -/// the shared C heap, exported under the names font.c and HarfBuzz's -/// hb_malloc_impl expect. runNative points it at the gui's gpa once -/// HarfBuzz's process-wide objects exist (ui_font_prime), so a Debug build's -/// leak report is about fonts; a test that counts what fonts leak points it -/// at std.testing.allocator the same way. Only the render thread calls into -/// fonts, and every allocator it is pointed at is thread-safe anyway. -var font_allocator: std.mem.Allocator = std.heap.smp_allocator; -const font_heap = c_heap.Heap(&font_allocator); -comptime { - @export(&font_heap.malloc, .{ .name = "ui_malloc" }); - @export(&font_heap.calloc, .{ .name = "ui_calloc" }); - @export(&font_heap.realloc, .{ .name = "ui_realloc" }); - @export(&font_heap.free, .{ .name = "ui_free" }); -} - -/// What SDL allocates from, on its own threads as well as the render thread: -/// the gui's gpa, through the shared C heap, which is thread-safe in every -/// build. runNative hands everything back and calls SDL_Quit on the way out. -var sdl_allocator: std.mem.Allocator = undefined; -const sdl_heap = c_heap.Heap(&sdl_allocator); - -const max_fallback_fonts = 1 + fonts.fallback_names.len; -comptime { - std.debug.assert(max_fallback_fonts <= Atlas.max_fallbacks); -} - -const max_touch_points: usize = 16; -const touch_scroll_tick: f32 = 0.02; - -// The triangle overlay holds only the pet, a jump's trail and the cursor's -// glide quad: the chrome is decor. -const max_overlay_vertices: usize = pet.max_vertices + 5 * 6 + 6; - -const font_px_step: f32 = 2.0; -const font_px_min: f32 = 8.0; -const font_px_max: f32 = 72.0; - -const CellInstance = Cells.CellInstance; -const OverlayVertex = Cells.OverlayVertex; -const ImageInstance = Cells.ImageInstance; -const opaque_bg_bit = Cells.opaque_bg_bit; - -const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 }; - -const PreparedImage = struct { - premultiplied: bool = false, - place: pardes.Placement, - texture: *c.SDL_GPUTexture, -}; - -fn updateCoreResize(core: *pardes.Pardes, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) bool { - core.update(resizeOf(core.view(), cols, rows, cell_w, cell_h, tag_w, tag_h) orelse return false); - return true; -} - -/// The resize a window of `cols` by `rows` cells of these sizes is to the -/// live view, or null when it is that already. -fn resizeOf(v: *const pardes.Pardes.View, cols: u16, rows: u16, cell_w: u32, cell_h: u32, tag_w: u32, tag_h: u32) ?pardes.Event { - const metrics: pardes.RowMetrics = .{ .body_w = @intCast(cell_w), .body_h = @intCast(cell_h), .tagline_w = @intCast(tag_w), .tagline_h = @intCast(tag_h) }; - const same_metrics = std.meta.eql(metrics, v.row_metrics); - const cell_px_w: u16 = @intCast(@min(@max(1, cell_w), std.math.maxInt(u16))); - const cell_px_h: u16 = @intCast(@min(@max(1, cell_h), std.math.maxInt(u16))); - if (cols == v.screen_w and rows == v.screen_h and - cell_px_w == v.cell_pixels.w and cell_px_h == v.cell_pixels.h and same_metrics) return null; - return .{ .resize = .{ - .cols = cols, - .rows = rows, - .cell_pixels = .{ .w = cell_px_w, .h = cell_px_h }, - .row_metrics = metrics, - } }; -} - -const TouchPoint = struct { - active: bool = false, - id: u64 = 0, - x: f32 = 0, - y: f32 = 0, -}; - -const TouchNormPoint = struct { x: f32 = 0, y: f32 = 0 }; - -const Finger = struct { kind: enum { down, motion, up, cancel }, id: u64, x: f32, y: f32 }; - -const Touch = struct { - points: [max_touch_points]TouchPoint = @splat(.{}), - scroll: struct { - active: bool = false, - ids: [2]u64 = .{ 0, 0 }, - accum_y: f32 = 0, - scrolled: bool = false, - last_center: TouchNormPoint = .{}, - } = .{}, - - fn findSlot(t: *const Touch, id: u64) ?usize { - for (&t.points, 0..) |*tp, i| if (tp.active and tp.id == id) return i; - return null; - } - - fn updatePoint(t: *Touch, f: Finger) void { - switch (f.kind) { - .up, .cancel => if (t.findSlot(f.id)) |i| { - t.points[i].active = false; - }, - .down, .motion => { - const idx = t.findSlot(f.id) orelse blk: { - for (&t.points, 0..) |*tp, i| if (!tp.active) break :blk i; - break :blk @as(usize, @intCast(f.id % max_touch_points)); - }; - const tp = &t.points[idx]; - if (!tp.active or tp.id != f.id) tp.* = .{ .active = true, .id = f.id }; - tp.x = f.x; - tp.y = f.y; - }, - } - } - - fn pairCenter(t: *const Touch, ids: [2]u64) ?TouchNormPoint { - var sum: TouchNormPoint = .{}; - for (ids) |id| { - const i = t.findSlot(id) orelse return null; - sum.x += t.points[i].x; - sum.y += t.points[i].y; - } - return .{ .x = sum.x * 0.5, .y = sum.y * 0.5 }; - } - - fn syncPair(t: *Touch) void { - var ids: [2]u64 = .{ 0, 0 }; - var count: usize = 0; - for (&t.points) |*tp| { - if (!tp.active) continue; - if (count >= 2) { - t.scroll = .{}; - return; - } - ids[count] = tp.id; - count += 1; - } - if (count != 2) { - t.scroll = .{}; - return; - } - if (ids[0] > ids[1]) std.mem.swap(u64, &ids[0], &ids[1]); - if (t.scroll.active and t.scroll.ids[0] == ids[0] and t.scroll.ids[1] == ids[1]) return; - t.scroll = .{ .active = true, .ids = ids, .last_center = t.pairCenter(ids) orelse .{} }; - } - - fn finishPair(t: *Touch, f: Finger) ?TouchNormPoint { - if (!t.scroll.active or (t.scroll.ids[0] != f.id and t.scroll.ids[1] != f.id)) return null; - const tap = f.kind == .up and !t.scroll.scrolled; - var center: ?TouchNormPoint = null; - if (tap) { - var sum: TouchNormPoint = .{}; - var ok = true; - for (t.scroll.ids) |id| { - if (id == f.id) { - sum.x += f.x; - sum.y += f.y; - } else if (t.findSlot(id)) |i| { - sum.x += t.points[i].x; - sum.y += t.points[i].y; - } else ok = false; - } - center = if (ok) .{ .x = sum.x * 0.5, .y = sum.y * 0.5 } else t.scroll.last_center; - } - t.scroll = .{}; - return center; - } - - fn noteMotion(t: *Touch, f: Finger) ?struct { center: TouchNormPoint, ticks: i32 } { - if (!t.scroll.active or (t.scroll.ids[0] != f.id and t.scroll.ids[1] != f.id)) return null; - const center = t.pairCenter(t.scroll.ids) orelse t.scroll.last_center; - const delta_y = center.y - t.scroll.last_center.y; - t.scroll.last_center = center; - t.scroll.accum_y += delta_y; - const ticks = takeScrollTicks(&t.scroll.accum_y); - if (ticks == 0) return null; - t.scroll.scrolled = true; - return .{ .center = center, .ticks = ticks }; - } -}; - -fn takeScrollTicks(accum: *f32) i32 { - var ticks: i32 = 0; - while (accum.* >= touch_scroll_tick) : (ticks += 1) accum.* -= touch_scroll_tick; - while (accum.* <= -touch_scroll_tick) : (ticks -= 1) accum.* += touch_scroll_tick; - return ticks; -} - -fn handleFinger(t: *Touch, in: *Input, f: Finger, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { - std.debug.assert(cell_w > 0 and cell_h > 0); - switch (f.kind) { - .down => { - t.updatePoint(f); - t.syncPair(); - }, - .motion => { - const had_pair = t.scroll.active; - t.updatePoint(f); - t.syncPair(); - if (!had_pair) return; - const res = t.noteMotion(f) orelse return; - emitTouchScroll(in, res.center, res.ticks, win_w, win_h, cell_w, cell_h, tagline_w); - }, - .up, .cancel => { - const tap_center = t.finishPair(f); - t.updatePoint(f); - t.syncPair(); - if (tap_center) |center| emitTouchClick(in, center, .middle, win_w, win_h, cell_w, cell_h, tagline_w); - }, - } -} - -fn emitTouchScroll(in: *Input, center: TouchNormPoint, ticks: i32, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { - const cell = gridCellAtDimensions(in.core, center.x * win_w, center.y * win_h, cell_w, cell_h, tagline_w); - const button: pardes.Mouse.Button = if (ticks > 0) .wheel_up else .wheel_down; - var remaining: u32 = @abs(ticks); - while (remaining > 0) : (remaining -= 1) - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); -} - -fn emitTouchClick(in: *Input, point: TouchNormPoint, button: pardes.Mouse.Button, win_w: f32, win_h: f32, cell_w: f32, cell_h: f32, tagline_w: f32) void { - const cell = gridCellAtDimensions(in.core, point.x * win_w, point.y * win_h, cell_w, cell_h, tagline_w); - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); - in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); -} - -const Pty = struct { - fd: c_int, - pid: libc.pid_t, - serial: u32, - /// Its reader, blocked in an Io read: `closePty` cancels it. - reader: ?std.Io.Future(void) = null, - /// A command pane's child, watched to its exit (host_io.watchExit); - /// the pty stays open until both its end of file and its exit. - cmd: host_io.CommandWatch = .{}, -}; - -const Queue = host_io.Inbox; - -/// Wakes a blocking SDL_WaitEventTimeout from another thread: a push to -/// the queue, a link's message. -fn sdlWake(_: ?*anyopaque) void { - var sev = std.mem.zeroes(c.SDL_Event); - sev.type = c.SDL_EVENT_USER; - _ = c.SDL_PushEvent(&sev); -} -const PipeTasks = selection_pipe.Tasks; -const output_capacity = Queue.output_capacity; - -fn stopPipe() ![2]c_int { - var fds: [2]c_int = undefined; - if (libc.pipe(&fds) != 0) return error.PipeFailed; - errdefer for (fds) |fd| { - _ = libc.close(fd); - }; - for (fds) |fd| if (libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)) < 0) return error.PipeFailed; - return fds; -} - -fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { - while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, - }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - return; - } - if (fds[0].revents != 0) return; - if ((fds[1].revents & (libc.POLL.ERR | libc.POLL.HUP | libc.POLL.NVAL)) != 0) return; - if (fds[1].revents != 0 and file_watch.drain(fd)) q.push(.files_changed); - } -} - -const Gui = struct { - addon_gpu: ?SketchGpu = null, - addon_hash: [pardes.MAX_PANES]u64 = @splat(0), - addon_serial: [pardes.MAX_PANES]u32 = @splat(0), - addon_failed: [pardes.MAX_PANES]u64 = @splat(0), - window: *c.SDL_Window, - /// The device, the window's claim or soft presenter, the frame's target - /// and the capture's read back (runNative owns it). - present: *Present, - /// The pipelines, the atlas's texture, the pictures' textures and the - /// buffers the frame is drawn from, on present's device (runNative owns - /// it). - cells: *Cells, - overlay_vertices: []OverlayVertex, - prepared_images: std.ArrayListUnmanaged(PreparedImage) = .empty, - /// The glyph art of the placements whose panes ask for it (Petscii - /// on), and the frame copy it is drawn into. - art: Art = .{}, - art_arena: ?std.heap.ArenaAllocator = null, - /// renderFrame's cover of the grid (coverFrame). - cover: std.ArrayListUnmanaged(Cover) = .empty, - /// renderFrame's decor instances, group by group (buildDecor). - decor: std.ArrayListUnmanaged(CellInstance) = .empty, - - /// The faces and the glyphs drawn from them. - atlas: Atlas, - font_name: [255]u8 = @splat(0), - font_name_len: u8 = 0, - /// A replica client's: the session's font request it last followed - /// (syncReplicaFont), as a hash of the request. - session_font_request: ?u64 = null, - px: f32, - tagline_px: f32, - tagline_percent: u8, - tagline_width: u32, - tagline_height: u32, - cell_w: u32, - cell_h: u32, - ascent: i32, - tagline_baseline: i32, - - words: Words = .{}, - - touch: Touch = .{}, - /// A Mac trackpad's gestures (macos_trackpad.m decodes them). - trackpad: Trackpad = .{}, - /// The workspace tag's pet (Pet), on the window's own clock. - pet_state: pet.State = .{}, - /// The cursor's jump trail (JumpTrail), on the window's own clock. - trail: JumpTrail = .{}, - /// The caret's ease, on the window's own clock (Caret). - caret: Caret = .{}, - /// The window's clock for the frame being drawn (Shell.ownNow), and - /// what moved the glide's view since the last (stepGlide): the pane a - /// wheel scrolled, one a touchpad moves by the pixel. - now_ns: u64 = 0, - glide_wheeled: ?usize = null, - glide_direct: ?usize = null, - /// The last key, click or wheel, which the blink holds for. - input_ns: u64 = 0, - live_ctrl: bool = false, - live_alt: bool = false, - - scroll_pane: ?usize = null, - scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, - scroll_body_y: u16 = 0, // that rect's first BODY row - scroll_body_h: u16 = 0, // and its BODY rows, which a taller tag leaves fewer of - scroll_held_px: f32 = 0, // its tree-sitter context band, which never moves - scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered - scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since - scroll_delta: f32 = 0, // finite raw distance waiting for the render batch - scroll_lag: f32 = 0, // picture position - core position, in rows - scroll_edge: []pardes.Cell = &.{}, // the row that just left the pane - scroll_edge_len: u16 = 0, - /// Loop steps since the last fractional turn: past `settle_after`, a - /// resting `scroll_lag` eases onto the core's row (stepScroll). - scroll_idle: u8 = 0, - /// G6: a wheel's notches, whole lines, scroll the core at once and the - /// picture follows on a spring (Glide), never the other way round. - scroll_notch: i32 = 0, - /// A touchpad's fraction toward the next turn sent to a program that - /// owns the wheel (Term.Modes.wheel). - program_wheel: f32 = 0, - /// A trackpad's horizontal fraction toward the next turn (wheelAt). - program_wheel_x: f32 = 0, - glide: Glide = .{}, - /// PARDES_FRAMES_DEMO: the timedemo (its script's steps), its next step - /// and when it started; null when none runs. - demo: []const pardes.FrameStats.Step = &.{}, - demo_next: ?usize = null, - demo_start_ns: u64 = 0, - /// The tick the last paced frame was sampled at (waitInput), and - /// whether this loop's wait read an input (drawn at once, not paced). - pace_ns: u64 = 0, - input_seen: bool = false, - /// G14: the cells last drawn and when each last changed. - /// The cursor's blink (blinkNow): when the frame drawn last arrived, - /// a redraw owed for an edge, and this frame's cursor mode and alpha. - frame_arrival_ns: u64 = 0, - blink_due: bool = false, - no_blink: bool = false, - cursor_quad_alpha: f32 = 0, - pointer_present: bool = false, - arrow_cursor: ?*c.SDL_Cursor = null, - link_cursor: ?*c.SDL_Cursor = null, - box_cursor: ?*c.SDL_Cursor = null, - pointer_shape: pardes.Surface.PointerShape = .arrow, - pointer_cell: ?MouseCell = null, - /// The core the hit test asks (hitTest), while a local session runs; - /// null attached, where the session's tag is another process's. - hit_core: ?*pardes.Pardes = null, - - /// Pixels the capture holds past the grid (PARDES_TEST_PAD). - capture_pad: u32 = 0, - capture_dir: []const u8 = "", - /// PARDES_TEST_SERIES: every captured frame is kept too, numbered, for a - /// frame series to look at. - capture_series: bool = false, - captured: u32 = 0, - - applied_window_opacity: u8 = 100, - /// What a window is opened again with (reopenWindow): the flags (not - /// hidden), its size when it was closed (present keeps its present mode). - win_flags: c.SDL_WindowFlags = 0, - /// A native Wayland window: transparent at the first WindowOpacity - /// under 100 (syncWindowOpacity). - wayland: bool = false, - window_w: c_int = 1120, - window_h: c_int = 720, - /// The window runNative destroys at the end: the one open then, if any. - window_slot: ?*?*c.SDL_Window = null, - - gamepad: ?*c.SDL_Gamepad = null, - /// The gamepad subsystem started (startGamepads). - gamepads: bool = false, - pad_x: f32 = 0, - pad_y: f32 = 0, - pad_scroll: f32 = 0, // fractional vertical wheel ticks (left stick) - pad_scroll_h: f32 = 0, // fractional horizontal wheel ticks (left stick) - deck: deck.Deck = .{}, -}; - -/// What a window held of its own let go (closeWindow lets the window go). -fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { - g.glide.deinit(gpa); - gpa.free(g.scroll_edge); - g.prepared_images.deinit(gpa); -} - -fn setGuiFontName(g: *Gui, fallback: []const u8) void { - const name = if (g.atlas.fontName()) |name_z| std.mem.span(name_z) else fallback; - const len = @min(name.len, g.font_name.len); - @memcpy(g.font_name[0..len], name[0..len]); - g.font_name_len = @intCast(len); -} - -fn observeGuiFont(g: *const Gui, core: *pardes.Pardes) void { - const size: u16 = @intFromFloat(@round(g.px * 100.0)); - _ = core.observeFont(g.font_name[0..g.font_name_len], size, .pixels); -} - -fn acknowledgeGuiFont(g: *const Gui, core: *pardes.Pardes) void { - const size: u16 = @intFromFloat(@round(g.px * 100.0)); - _ = core.acknowledgeFont(g.font_name[0..g.font_name_len], size, .pixels); -} - -/// A replica client's font is the window's raster state: it follows the -/// session's request by the face's name on this machine (fonts.fromSession), -/// never acknowledging it or otherwise changing the replicated core. -fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator) bool { - const f = &core.settings.font; - const path = f.requested_path.get(); - const name = f.requested_name.get(); - if (path.len == 0 and name.len == 0) return false; - var hash = std.hash.Wyhash.init(0); - hash.update(path); - hash.update(name); - hash.update(std.mem.asBytes(&f.requested_size_hundredths)); - const request = hash.final(); - if (g.session_font_request == request) return false; - g.session_font_request = request; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const face = fonts.fromSession(arena.allocator(), path, name) orelse { - log.warn("the session's font is not installed here: {s}", .{name}); - return false; - }; - const bytes = filesystem.readFile(gpa, face.path) catch return false; - if (!g.atlas.setFont(gpa, bytes)) return false; - if (f.requested_size_hundredths != 0) - g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100; - setGuiFontName(g, face.name); - refitFont(g, null); - return true; -} - -fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { - _ = g.atlas.addFallback(gpa, font_ttf, false); - - var arena_state = std.heap.ArenaAllocator.init(gpa); - defer arena_state.deinit(); - for (fonts.fallbacks(arena_state.allocator())) |candidate| { - if (g.atlas.fallback_count == max_fallback_fonts) break; - const bytes = filesystem.readFile(gpa, candidate.path) catch continue; - _ = g.atlas.addFallback(gpa, bytes, true); - } -} - -const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 }; -const MouseCell = struct { col: u16, row: u16, body_hit: ?pardes.Mouse.BodyHit = null, tag_hit: ?pardes.TagHit = null, rule_above: bool = false }; - -/// How near a row's top edge a press is on the rule drawn there between two -/// panes: the rule's 2 px and a pixel either side, in logical pixels (dp). -const rule_grab_px: f32 = 3; -const WindowGeometry = struct { - window_w: f32, - window_h: f32, - pixel_w: f32, - pixel_h: f32, -}; - -fn windowGeometry(window: *c.SDL_Window) WindowGeometry { - var ww: c_int = 0; - var wh: c_int = 0; - var pw: c_int = 0; - var ph: c_int = 0; - _ = c.SDL_GetWindowSize(window, &ww, &wh); - _ = c.SDL_GetWindowSizeInPixels(window, &pw, &ph); - return .{ - .window_w = @floatFromInt(@max(ww, 1)), - .window_h = @floatFromInt(@max(wh, 1)), - .pixel_w = @floatFromInt(@max(pw, 1)), - .pixel_h = @floatFromInt(@max(ph, 1)), - }; -} - -const GridCells = struct { cols: u16, rows: u16 }; - -fn windowCells(g: *const Gui) GridCells { - var pw: c_int = 0; - var ph: c_int = 0; - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - return .{ - .cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))), - .rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))), - }; -} - -const Point = struct { x: f32, y: f32 }; - -fn windowPointToPixels(geometry: WindowGeometry, x: f32, y: f32) Point { - return .{ - .x = x * geometry.pixel_w / geometry.window_w, - .y = y * geometry.pixel_h / geometry.window_h, - }; -} - -fn fixedCellLayout(g: *const Gui) CellLayout { - return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; -} - -const Group = Cells.Group; - -/// The frame's draw groups, bottom to top: the page and the panes, the -/// notices floating over them, the debug box the core paints over those, -/// and ink (the bar cursors; the cursor's glide draws after it). -const Groups = struct { - items: [4]Group = @splat(.{}), - notices: usize = 1, - debug: usize = 2, - ink: usize = 3, - len: usize = 4, -}; - -/// What draws a grid cell, marked once a frame from the layers and the -/// regions (coverFrame), so the cell loops read it rather than search. -const Cover = packed struct(u16) { - /// A layer draws it; the grid's copy is not drawn. - layer: bool = false, - /// Under the debug box: drawn from the grid over the panes. - floating: bool = false, - /// In a pane's grip, `grip_offset` cells from its left: the grip's - /// glyph is the cell that far to the left. - grip: bool = false, - grip_offset: u4 = 0, - /// In the focused pane's or column's tag rows. - focus: bool = false, - /// At a column's left edge, where a tag's anchor is inset. - anchor: bool = false, - /// In a dirty pane's grip. - dirty: bool = false, - /// In a pane's grip (not a column's). - pane_grip: bool = false, - /// In a grip's first row, where its button is. - grip_top: bool = false, - /// In an unfocused pane's tag or body rows while InactiveDim fades them. - dim: bool = false, - _: u3 = 0, -}; - -/// Marks the grid cells a body or tag layer covers, which the layers paint -/// themselves, and what the regions say of the rest. Filling each rectangle -/// once replaces scanning every layer for every cell, which was a third of -/// the gui's CPU on a full screen of text. -fn coverFrame(cover: []Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer, regions: []const pardes.Region) void { - @memset(cover, .{}); - const mark = struct { - fn rect(into: []Cover, width: u16, height: u16, r: pardes.Rect, comptime field: []const u8, value: anytype) void { - const right = @min(width, @as(u32, r.x) + r.w); - if (r.x >= right) return; - var y: u32 = r.y; - while (y < @min(height, @as(u32, r.y) + r.h)) : (y += 1) - for (into[y * width ..][r.x..right]) |*cell| { - @field(cell, field) = value; - }; - } - }; - for (body_layers) |*layer| { - if (layer.rows != 0) mark.rect(cover, cols, rows, layer.viewport, "layer", true); - } - for (tag_layers) |*layer| { - if (layer.rows != 0) mark.rect(cover, cols, rows, .{ .x = layer.viewport.x, .y = layer.viewport.y, .w = layer.viewport.w, .h = layer.rows }, "layer", true); - } - // The column bar's rows, which the focused column's tint spans. - var bar: ?pardes.Rect = null; - for (regions) |region| { - if (region.kind == .column_grip) bar = region.rect; - } - // InactiveDim: an unfocused pane's tag and body rows (Dim.begin). - if (dim.amount > 0) for (regions) |region| { - if ((region.kind == .tag or region.kind == .body) and dim.of(region.owner)) mark.rect(cover, cols, rows, region.rect, "dim", true); - }; - for (regions) |region| switch (region.kind) { - .grip, .column_grip => { - mark.rect(cover, cols, rows, region.rect, "grip", true); - for (0..@min(region.rect.w, 16)) |offset| mark.rect(cover, cols, rows, .{ .x = region.rect.x +| @as(u16, @intCast(offset)), .y = region.rect.y, .w = 1, .h = region.rect.h }, "grip_offset", @as(u4, @intCast(offset))); - if (region.kind == .grip and region.active) mark.rect(cover, cols, rows, region.rect, "focus", true); - if (region.dirty) mark.rect(cover, cols, rows, region.rect, "dirty", true); - if (region.kind == .grip) mark.rect(cover, cols, rows, region.rect, "pane_grip", true); - mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w, .h = @min(1, region.rect.h) }, "grip_top", true); - }, - .tag => if (region.active) mark.rect(cover, cols, rows, region.rect, "focus", true), - .column => { - mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = 0, .w = 1, .h = rows }, "anchor", true); - if (region.active) if (bar) |b| mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = b.y, .w = region.rect.w, .h = b.h }, "focus", true); - }, - .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), - else => {}, - }; -} - -pub fn run(init: std.process.Init, opts: pardes.Options, detached: bool) !void { - return runNative(init, opts, detached, null); -} - -/// `pardes-gui --attach=<socket>:<session>` (and `<host>:<session>`, -/// through ssh, main.zig): this window a replica client of a session -/// elsewhere, as the tty's `runClient` is a terminal's (`clientSession`). -pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8, far: bool) !void { - return runNative(init, opts, false, .{ .path = path, .session = session, .far = far }); -} - -const Dial = struct { path: []const u8, session: []const u8, far: bool }; - -fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, dial: ?Dial) !void { - const gpa = init.gpa; - const env = init.environ_map; - - const test_mode = env.get("PARDES_TEST") != null; - const capture_dir = env.get("PARDES_TEST_CAPTURE_DIR"); - if (test_mode and capture_dir == null) { - log.err("PARDES_TEST requires PARDES_TEST_CAPTURE_DIR", .{}); - return error.SdlInit; - } - if (test_mode) if (env.get("PARDES_TEST_LATENCY")) |path| { - var path_buf: [4096]u8 = undefined; - if (std.fmt.bufPrintSentinel(&path_buf, "{s}", .{path}, 0)) |z| - latency_fd = libc.open(z, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)) - else |_| {} - }; - - // SDL frees with whichever functions are current, so they go in before - // its first call, while nothing of SDL's exists yet. - sdl_allocator = gpa; - if (!c.SDL_SetMemoryFunctions(sdl_heap.malloc, sdl_heap.calloc, sdl_heap.realloc, sdl_heap.free)) { - log.err("SDL_SetMemoryFunctions: {s}", .{c.SDL_GetError()}); - return error.SdlInit; - } - _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI", "1"); // SDL_HINT_JOYSTICK_HIDAPI - _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI_STEAMDECK", "1"); // ..._STEAMDECK - if (comptime builtin.os.tag == .macos) _ = c.SDL_SetHint(c.SDL_HINT_MAC_SCROLL_MOMENTUM, "1"); - // The gamepads after the first frame (startGamepads). - if (!c.SDL_Init(c.SDL_INIT_VIDEO)) { - log.err("SDL_Init: {s}", .{c.SDL_GetError()}); - return error.SdlInit; - } - // SDL allocates from gpa (above), so what it still holds at exit is in a - // Debug build's leak report. The window, the GPU device and everything - // made on it go back first (the defers below run before this one). What - // is left is SDL 3.4.4's: its Vulkan backend never frees two 32-byte - // arrays per command buffer (VULKAN_INTERNAL_DestroyCommandPool; SDL's - // main branch frees them). - defer c.SDL_Quit(); - // No title bar or frame from anyone: borderless asks the compositor for - // none (xdg-decoration's client side, which SDL then leaves undrawn). - var win_flags: c.SDL_WindowFlags = c.SDL_WINDOW_RESIZABLE | c.SDL_WINDOW_BORDERLESS; - if (!test_mode) win_flags |= c.SDL_WINDOW_HIGH_PIXEL_DENSITY; - // A test run renders to the capture texture; keep it off the desktop. - if (test_mode) win_flags |= c.SDL_WINDOW_HIDDEN; - // Background-only opacity needs per-pixel alpha (whole-window compositor - // opacity would dim the text as well), so a transparent window, which - // the GPU API will not claim: it presents through SDL_Renderer, EGL and - // GL beside Vulkan, and its first present is slow. So a window starts - // opaque, and is made again transparent at the first WindowOpacity - // under 100 (syncWindowOpacity): SDL takes the flag only at creation. - const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); - const reopen_flags = win_flags; - // `--detach`: a window never shown, closed once the session is up. - if (detached) win_flags |= c.SDL_WINDOW_HIDDEN; - // `--geometry=WxH[+X+Y]`, as X11 programs take it. - var want_w: c_int = 1120; - var want_h: c_int = 720; - var want_at: ?[2]c_int = null; - if (opts_in.geometry) |spec| geometry: { - const x_at = std.mem.indexOfScalar(u8, spec, 'x') orelse break :geometry; - const plus = std.mem.indexOfAnyPos(u8, spec, x_at, "+-") orelse spec.len; - want_w = std.math.clamp(std.fmt.parseInt(c_int, spec[0..x_at], 10) catch break :geometry, 200, 16384); - want_h = std.math.clamp(std.fmt.parseInt(c_int, spec[x_at + 1 .. plus], 10) catch break :geometry, 120, 16384); - if (plus == spec.len) break :geometry; - const second = std.mem.indexOfAnyPos(u8, spec, plus + 1, "+-") orelse break :geometry; - const gx = std.fmt.parseInt(c_int, spec[plus + @intFromBool(spec[plus] == '+') .. second], 10) catch break :geometry; - const gy = std.fmt.parseInt(c_int, spec[second + @intFromBool(spec[second] == '+') ..], 10) catch break :geometry; - want_at = .{ gx, gy }; - } - const window = c.SDL_CreateWindow("pardes", want_w, want_h, win_flags) orelse { - log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); - return error.SdlInit; - }; - var window_slot: ?*c.SDL_Window = window; - if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); - defer if (window_slot) |open| c.SDL_DestroyWindow(open); - if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); - updateDisplayScale(window); - // On Linux the desktop's own cursor theme draws them (the compositor's - // cursor-shape protocol, else XCURSOR_THEME), at its size and scale: - // the arrow is its default, acme's box its move, as the plan9 theme - // has them. Elsewhere acme's bitmaps, at 16 pixels. - const themed_cursors = builtin.os.tag == .linux; - const arrow_cursor = if (themed_cursors) - c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_DEFAULT) - else - c.SDL_CreateCursor(&p9_arrow_set, &p9_arrow_mask, 16, 16, 1, 1); - defer if (arrow_cursor) |cursor| c.SDL_DestroyCursor(cursor); - const link_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER); - defer if (link_cursor) |cursor| c.SDL_DestroyCursor(cursor); - // Its hot spot the middle, as acme's {-7, -7} offset puts it. - const box_cursor = if (themed_cursors) - c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_MOVE) - else - c.SDL_CreateCursor(&p9_box_set, &p9_box_mask, 16, 16, 7, 7); - defer if (box_cursor) |cursor| c.SDL_DestroyCursor(cursor); - if (arrow_cursor) |cur| { - _ = c.SDL_SetCursor(cur); - } else log.err("SDL_CreateCursor: {s}", .{c.SDL_GetError()}); - var presenter = try Present.init(window, .{ - .test_mode = test_mode, - .surface_opacity = false, - .present_modes = &.{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }, - .debug = true, - }); - defer presenter.deinit(); - - font_allocator = gpa; - var atlas = Atlas.init(gpa, font_ttf) catch |err| { - log.err("the font atlas: {t}", .{err}); - return err; - }; - // HarfBuzz's process-wide objects are made once and never freed: made - // from the default heap, they stay out of a Debug build's leak report. - font_allocator = std.heap.smp_allocator; - atlas.prime(); - font_allocator = gpa; - // A harness forcing a density (PARDES_TEST_SCALE) draws the text as a - // person on that display would size it, so its chrome is seen at the - // proportion it has there. A live window keeps the size the user sets. - const px: f32 = if (test_mode) 27.0 * std.math.clamp(display_scale, 1, 4) else 27.0; - var cw: c_int = 10; - var chh: c_int = 20; - var asc: c_int = 16; - atlas.cellMetrics(px, &cw, &chh, &asc); - const cell_w: u32 = @intCast(@max(cw, 1)); - const cell_h: u32 = @intCast(@max(chh, 1)); - const tagline = taglineRaster(&atlas, px, cell_w, cell_h, config.gui_tagline_font_percent); - if (test_mode) { - const cols = envU16(env, "PARDES_TEST_COLS") orelse 80; - const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24; - // 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); - } - - var cells = try Cells.init(presenter.device, presenter.swapchain_format, max_overlay_vertices); - // The pipelines, textures and buffers it holds, whatever they were - // regrown to, before the device (presenter's defer). - defer cells.deinit(gpa); - - const overlay_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices); - defer gpa.free(overlay_vertices); - - var g: Gui = .{ - .window = window, - .arrow_cursor = arrow_cursor, - .link_cursor = link_cursor, - .box_cursor = box_cursor, - .present = &presenter, - .cells = &cells, - .overlay_vertices = overlay_vertices, - .atlas = atlas, - .px = px, - .tagline_px = tagline.px, - .tagline_percent = config.gui_tagline_font_percent, - .tagline_width = tagline.width, - .tagline_height = tagline.height, - .cell_w = cell_w, - .cell_h = cell_h, - .ascent = asc, - .tagline_baseline = tagline.baseline, - .capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0, - .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, - .capture_dir = capture_dir orelse "", - .demo = if (env.get("PARDES_FRAMES_DEMO")) |path| try pardes.FrameStats.readScript(init.arena.allocator(), init.io, path) else &.{}, - .demo_next = if (env.get("PARDES_FRAMES_DEMO") != null) 0 else null, - .win_flags = reopen_flags, - .wayland = native_wayland, - .window_w = want_w, - .window_h = want_h, - .window_slot = &window_slot, - }; - defer if (g.gamepad) |pad| c.SDL_CloseGamepad(pad); - setGuiFontName(&g, "Adwaita Mono"); - loadFallbackFonts(&g, gpa); - defer g.atlas.deinit(gpa); - defer g.words.deinit(gpa); - defer { - if (g.addon_gpu) |*gpu| gpu.deinit(); - g.prepared_images.deinit(gpa); - g.art.deinit(gpa); - if (g.art_arena) |*arena| arena.deinit(); - g.cover.deinit(gpa); - g.decor.deinit(gpa); - } - defer gpa.free(g.scroll_edge); // grown on demand by stepScroll - defer g.glide.deinit(gpa); - resetGlyphAtlas(&g); - - // The window is dragged by the workspace tag's blank (hitTest): the - // compositor moves it, as it does a title bar. - if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) - log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); - if (dial) |to| return clientSession(init, &g, opts_in, test_mode, to); - try localSession(init, &g, opts_in, test_mode, detached); -} - -/// Detach: the window closed (and with it its swapchain or renderer); the -/// device, the atlas and the pipelines stay for the next one. -fn closeWindow(g: *Gui) void { - _ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h); - _ = c.SDL_StopTextInput(g.window); - g.present.detach(g.window); - c.SDL_DestroyWindow(g.window); - if (g.window_slot) |slot| if (slot.* == g.window) { - slot.* = null; - }; -} - -/// `pardes-gui --attach`: a window again, as the first was made, at the -/// size the last one had. False when the display will not give one. -fn reopenWindow(g: *Gui) bool { - const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; - if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); - if (!g.present.attach(window)) { - c.SDL_DestroyWindow(window); - return false; - } - g.window = window; - if (g.window_slot) |slot| slot.* = window; - updateDisplayScale(window); - // ponytail: another view's window asks the hit test of whichever - // window's share the Gui holds then (the workspace tag sits in the same - // place in every view); a test per window if one moves it. - if (!g.present.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g); - _ = c.SDL_StartTextInput(window); - return true; -} - -fn localSession( - init: std.process.Init, - g: *Gui, - opts_in: pardes.Options, - test_mode: bool, - detached: bool, -) !void { - const io = init.io; - const gpa = init.gpa; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - host_io.startWorkers(allocs); - defer host_io.stopWorkers(); - var opts = opts_in; - opts.addons = pardes.Addon.scan(); - opts.image_allocator = allocs.image; - opts.tree_sitter_allocator = allocs.tree_sitter; - opts.frame_allocator = allocs.frame; - var pw: c_int = 0; - var ph: c_int = 0; - if (opts.load_path != null) { - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))); - opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))); - } - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, opts, rec) - else if (opts.load_path) |lp| blk: { - const bytes = try @import("../fs.zig").readFile(gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); - } else try pardes.Pardes.init(allocs.pardes, opts); - defer core.deinit(); - g.hit_core = core; - defer g.hit_core = null; - core.view().frontend.windowed = true; - core.view().frontend.native_images = true; - core.view().frontend.native_image_patches = true; - observeGuiFont(g, core); - syncTaglineFont(g, core); - - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); - - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(0); - var queue: Queue = .{ - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .wake_fn = sdlWake, - }; - defer { - if (queue.lsp_task) |*task| task.future.cancel(io); - // Its worker may be waiting on the queue for room. - core.stream.cancelTask(); - queue.deinit(); - } - var pipe_tasks: PipeTasks = .{}; - defer pipe_tasks.cancelAll(io); - var inotify_fd: c_int = file_watch.init(true); - var watch_reader: ?std.Thread = null; - var watch_stop: [2]c_int = .{ -1, -1 }; - defer if (inotify_fd >= 0) { - if (watch_reader) |thread| { - _ = host_io.writeFd(watch_stop[1], "x"); - thread.join(); - } - for (watch_stop) |fd| if (fd >= 0) { - _ = libc.close(fd); - }; - file_watch.stop(inotify_fd); - _ = libc.close(inotify_fd); - inotify_fd = -1; - }; - var watches: file_watch.Table = @splat(null); - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); - - var shell: Shell = .{ - .core = core, - .gui = g, - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .prompt_rcs = &prompt_rcs, - .ptys = &ptys, - .gens = &gens, - .queue = &queue, - .pipe_tasks = &pipe_tasks, - .inotify_fd = inotify_fd, - .watches = &watches, - .fs = fs, - .test_mode = test_mode, - .test_clock = if (test_mode) host_io.testClock() else null, - .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, - }; - defer shell.job_tasks.cancelAll(io); - defer shell.shutdownPtys(); - // A virtual clock never blinks: goldens and feel series hold still. - g.no_blink = shell.test_clock != null; - frame_probe = &core.frames; - frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; - const host = shell.host(); - core.host = host; - pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; - defer pardes.Kind.drawer = null; - shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .detached = detached }; - defer shell.peers.deinit(); - // Before the core goes: each client sees its link end. - defer shell.peers.dropAll(shell.core); - - while (core.nextEffect()) |e| core.perform(e); - // An upgraded session's shells, once a fresh session's own has a - // directory to adopt them in. - if (upgrade.resumed) |*rec| { - shell.resumePtys(rec); - while (core.nextEffect()) |e| core.perform(e); - } - for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), gens[id]); - }; - if (inotify_fd >= 0) { - watch_stop = try stopPipe(); - watch_reader = try std.Thread.spawn(.{}, watchThread, .{ inotify_fd, watch_stop[0], &queue }); - } - if (fs) |f| try f.watch(&queue, wakeFs); - - _ = c.SDL_StartTextInput(g.window); - // An upgraded session's window, its view's again. - if (upgrade.resumed) |*rec| if (!rec.fresh and !detached) shell.resumeWindow(); - - if (test_mode) setStdinRaw() catch {}; - shell.threads_ok = true; - pardes.lsp.setStatusSink(&queue, Queue.lspStatus); - defer pardes.lsp.setStatusSink(null, null); - host_io.setExitWake(&queue, Queue.wakeForExit); - defer host_io.setExitWake(null, null); - if (detached) { - shell.closeTheWindow(); - // Nothing else may wake the first wait. - daemon.watch(&shell, deliverNote); - } - - while (!core.quit) { - pardes.turn.bump(&pardes.turn.restores); - try core.pump(host); - // Its unit to each replica client, and theirs taken in. - shell.peers.boundary(core); - upgrade.locate(); - // Asked in the step (the word), done between steps: the session whole. - if (shell.upgrade_asked) |pane| shell.upgradeNow(pane); - // A window asked for again, or an adopted shell, from the daemon's - // thread through the queue; started after the first frame. - daemon.watch(&shell, deliverNote); - if (core.quit) break; // a session that ended does not restore into one - if (core.takeRestore()) |rp| blk: { - const nc = host_io.restoreCore(gpa, core, rp, &shell.peers, inotify_fd, &watches) orelse break :blk; - pipe_tasks.cancelAll(io); - queue.discardCompletions(); - // One view, the window's (host_io.restoreCore). - shell.gview = 0; - shell.stopPtys(); - g.cells.clearImages(); - g.prepared_images.clearRetainingCapacity(); - nc.view().frontend.native_images = true; - nc.view().frontend.native_image_patches = true; - nc.host = host; - if (fs) |f| f.reset(nc); - nc.view().frontend.windowed = true; - core.deinit(); - core = nc; - frame_probe = &nc.frames; // the old core's ring went with it - g.hit_core = nc; - shell.core = nc; - shell.surface = null; - observeGuiFont(g, core); - syncTaglineFont(g, core); - } - } - - if (fs) |f| { - f.deinit(gpa); - fs = null; - shell.fs = null; - } -} - -/// A window's link to a session elsewhere (`clientSession`): what the -/// window's input made, fed to the replica once its own view is put back, -/// and what the link's reader took off the stream. -const Client = struct { - link: replica.Link, - io: std.Io, - gpa: std.mem.Allocator, - /// The window's inputs since the last feed, their texts in `texts`: - /// read over its own view (`Replica.within`), applied after it. - pending: std.ArrayListUnmanaged(pardes.Event) = .empty, - texts: std.heap.ArenaAllocator, - /// The reader's, under `lock`: what it took, and whether the link ended. - lock: std.Io.Mutex = .init, - inbox: std.ArrayListUnmanaged(replica.Said) = .empty, - taken: std.ArrayListUnmanaged(replica.Said) = .empty, - ended: bool = false, - /// The size the window last posted while its view is not that size - /// yet (the session has not taken it, or speculation stopped at it): - /// posted once, not again each pass while it waits. - posted: ?@FieldType(pardes.Event, "resize") = null, - - fn deinit(cl: *Client) void { - cl.pending.deinit(cl.gpa); - cl.texts.deinit(); - cl.inbox.deinit(cl.gpa); - cl.taken.deinit(cl.gpa); - } - - fn post(cl: *Client, ev: pardes.Event) void { - var e = ev; - const a = cl.texts.allocator(); - switch (e) { - .key => |*k| k.text = a.dupe(u8, k.text) catch "", - .paste, .command => |*b| b.* = a.dupe(u8, b.*) catch return, - else => {}, - } - cl.pending.append(cl.gpa, e) catch {}; - } - - /// What the window's input made, applied at once and sent. - fn feed(cl: *Client) void { - for (cl.pending.items) |ev| { - const r = cl.link.r; - const predicted = r.echo.stats.predicted; - cl.link.input(ev); - // PARDES_TEST_LATENCY: the input, and whether it shows at once - // (applied, or its echo predicted), for the frame that shows it. - latencyNote("I {d} {d} {d}\n", .{ r.next_seq - 1, monoNs(), @intFromBool(r.applied == r.pending.items.len or r.echo.stats.predicted > predicted) }); - } - cl.pending.clearRetainingCapacity(); - _ = cl.texts.reset(.retain_capacity); - } - - /// The reader's: a message of the stream, for the loop, which it wakes. - fn said(cl: *Client, msg: replica.Said) bool { - cl.lock.lockUncancelable(cl.io); - defer cl.lock.unlock(cl.io); - cl.inbox.append(cl.gpa, msg) catch return false; - sdlWake(null); - return true; - } - - /// What the reader took, in its order, and the link's end after it. - fn takeSaid(cl: *Client) void { - cl.lock.lockUncancelable(cl.io); - std.mem.swap(std.ArrayListUnmanaged(replica.Said), &cl.inbox, &cl.taken); - const ended = cl.ended; - cl.lock.unlock(cl.io); - for (cl.taken.items) |msg| { - // PARDES_TEST_LATENCY: when a terminal's delta came (an echo's). - if (msg == .screen) latencyNote("S {d}\n", .{monoNs()}); - cl.link.take(msg); - // And after a unit, the first of its own inputs not confirmed. - if (msg == .unit) { - const r = cl.link.r; - latencyNote("U {d} {d}\n", .{ monoNs(), if (r.pending.items.len > 0) r.pending.items[0].seq else r.next_seq }); - } - } - cl.taken.clearRetainingCapacity(); - if (ended) { - cl.link.quit = true; - cl.link.gone = true; - } - } - - /// Its own view drawn in the window, outside any step, as the tty's - /// client draws its terminal (tui.zig `Client.draw`): what presenting - /// writes in the core (a frame skipped, one owed) is put back. - fn draw(cl: *Client, s: *Shell) void { - const r = cl.link.r; - const core = r.core(); - const skipped = core.present_skipped; - const needs = core.needs_frame; - core.frames.mark_start = pardes.FrameStats.nowNs(); - core.frames.mark_update = core.frames.mark_start; - // Its render's end is marked as it presents (`present`). - core.frames.mark_render = core.frames.mark_update; - r.draw(.{ .ctx = s, .f = present }); - cl.link.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), if (s.gui) |g| frontendMoving(g) else false, cl.link.owed); - core.present_skipped = skipped; - core.needs_frame = needs; - cl.link.drawn(s.presented); - } -}; - -/// The session's stream, onto the client's inbox: its units, and its end. -fn clientReader(cl: *Client, fd: c_int, rest: *replica.Framer) void { - replica.readLink(cl.gpa, fd, rest, cl, Client.said); - cl.lock.lockUncancelable(cl.io); - cl.ended = true; - cl.lock.unlock(cl.io); - sdlWake(null); -} - -/// What the window does over its own view (`Replica.within`), its inputs -/// posted to the client (`Input.client`): an SDL event dispatched, its size -/// (the tagline's face too), the pointer under a frame that moved, the -/// timedemo's and the test feed's steps. -const OwnView = struct { - g: *Gui, - in: *Input, - s: *Shell, - sev: ?*const c.SDL_Event = null, - pointer: bool = false, - eof: bool = false, - - fn run(v: *OwnView, core: *pardes.Pardes) anyerror!void { - if (v.sev) |sev| return dispatch(v.g, v.in, sev); - const g = v.g; - if (syncReplicaFont(g, core, v.s.gpa)) v.s.client.?.link.dirty = true; - if (scrollRows(g, v.in, v.s.gpa)) v.s.client.?.link.dirty = true; - if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.client.?.link.dirty = true; - const geom = windowCells(g); - const cl = v.s.client.?; - if (resizeOf(core.view(), geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| { - if (cl.posted == null or !std.meta.eql(cl.posted.?, ev.resize)) v.in.post(ev); - cl.posted = ev.resize; - } else cl.posted = null; - if (v.pointer) refreshPresentedPointer(g, v.in); - runDemo(g, v.in, core); - if (v.s.test_mode) { - if (v.s.feed.pump(v.s.gpa, v.in, g) catch return error.TestFeed) v.eof = true; - } - } -}; - -/// `pardes-gui --attach=<where>:<session>`: the window, made as a session's -/// is, a replica client of that session (docs/next-daemon.md, "Phase 6: GUI -/// replica notes"). Its own core, loaded from the session's dump, applies -/// its input at once (src/replica.zig) and draws its own view; the -/// session's units are the truth it rolls back to. The tty's `runClient`, with -/// a window for a terminal. -fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_mode: bool, to: Dial) !void { - const io = init.io; - const gpa = init.gpa; - const Said = struct { - fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { - var buf: [800]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes-gui: --attach: " ++ fmt ++ "\n", args) catch "pardes-gui: --attach failed\n") catch {}; - std.process.exit(1); - } - }; - var why: [600]u8 = @splat(0); - // Far (through ssh, or PARDES_REPLICA_FAR=1): its join's blobs by hash - // and its stream in zstd, as the tty's client (replica.zig `Have`). - const far = if (init.environ_map.get("PARDES_REPLICA_FAR")) |v| std.mem.eql(u8, v, "1") else to.far; - var have_store: replica.Have = if (far) .init(io) else .{ .io = io }; - defer have_store.deinit(); - const have: ?*replica.Have = if (far) &have_store else null; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - pardes.Term.start(allocs.image); - pardes.Kind.heap = allocs.addon; - pardes.syntax.start(allocs.tree_sitter); - defer { - pardes.Term.stop(); - pardes.syntax.stop(); - } - var o = opts_in; - o.image_allocator = allocs.image; - var joined: replica.Joined = undefined; - var r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, null) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - - var client: Client = .{ .link = .{ .r = r, .fd = joined.fd }, .io = io, .gpa = gpa, .texts = .init(gpa) }; - defer client.deinit(); - const link = &client.link; - try link.fromEnv(gpa, init.environ_map); - defer link.deinit(gpa); - // A client spawns, watches and serves nothing: the Shell's tables are - // empty ones, there for what draws. - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(0); - var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, .wake_fn = sdlWake }; - defer queue.deinit(); - var pipe_tasks: PipeTasks = .{}; - var watches: file_watch.Table = @splat(null); - const prompt_rcs: host_io.Shell.PromptFiles = .{}; - var shell: Shell = .{ - .core = r.core(), - .gui = g, - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .prompt_rcs = &prompt_rcs, - .ptys = &ptys, - .gens = &gens, - .queue = &queue, - .pipe_tasks = &pipe_tasks, - .inotify_fd = -1, - .watches = &watches, - .test_mode = test_mode, - .client = &client, - }; - pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; - defer pardes.Kind.drawer = null; - defer shell.job_tasks.cancelAll(io); - g.no_blink = test_mode; - defer g.hit_core = null; - _ = c.SDL_StartTextInput(g.window); - if (test_mode) setStdinRaw() catch {}; - // A join a pass: the first, and one after the replica diverged or the - // session let it go to upgrade. The window stays as it is. - while (true) { - const core = r.core(); - g.session_font_request = null; - shell.core = core; - shell.gview = joined.view; - shell.surface = null; - g.hit_core = core; - frame_probe = &core.frames; - link.reset(r, &joined); - client.posted = null; - client.ended = false; - // ponytail: why it joined again is the window's title (and its - // log) until a key, where a terminal's client draws it over its - // frame: a window's frame is the core's cells, which it cannot write. - var titled = link.notice_len > 0; - if (titled) { - var title: [260]u8 = undefined; - _ = c.SDL_SetWindowTitle(g.window, std.fmt.bufPrintSentinel(&title, "pardes: {s}", .{link.notice()}, 0) catch "pardes"); - log.warn("{s}", .{link.notice()}); - } - const reader = try std.Thread.spawn(.{}, clientReader, .{ &client, joined.fd, &joined.rest }); - var in: Input = .{ .core = core, .shell = &shell, .client = &client }; - // What it is, then its size, are its view's first inputs. - link.input(.{ .frontend = .{ .windowed = true, .native_images = true, .native_image_patches = true } }); - var drew = false; - var again = false; - while (!link.quit) { - core.frames.period_ns = refreshNs(g); - var own: OwnView = .{ .g = g, .in = &in, .s = &shell, .pointer = drew }; - r.within(&own, OwnView.run); - client.feed(); - if (own.eof) break; - // Its predicted echo judged and caught up, once a frame. - if (r.echoFrame()) link.dirty = true; - drew = false; - if (link.dirty) { - client.draw(&shell); - drew = shell.presented; - } else if (again and shell.presented) if (shell.surface) |frame| { - // A blink, the window's own motion: the last frame again, - // moved on, as the session's own window draws it (pollFrame). - g.now_ns = shell.ownNow(); - shell.presented = renderFrame(g, gpa, core, frame) catch false; - drew = shell.presented; - }; - again = false; - // The window's own motions (its glide, its caret, a jump's - // trail) and its blink are on its clock: no unit need come. - const minimized = !test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; - const moving = !minimized and frontendMoving(g); - const blink = if (minimized or shell.surface == null) null else blinkNow(g, core.settings.cursor_blink); - const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; - // A latency trace's feed paces the loop, as the session's own - // window's (waitInput): its poll on stdin is the wait, and SDL's, - // which polls a clock and a lock a millisecond at a time with - // the offscreen driver, is not waited too (a frame a loop more). - var ms: c_int = if (latency_fd >= 0) 0 else if (test_mode) 16 else -1; - if (demoDue(g)) |due| ms = if (ms < 0) due else @min(ms, due); - if (predicting or link.owed) ms = if (ms < 0) frame_ms else @min(ms, frame_ms); - // A touchpad's fraction settling onto a row (scrollRows). - if (moving or g.scroll_lag != 0 or g.scroll_delta != 0) { - const frame_wait: c_int = @intCast(@max(1, (refreshNs(g) + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); - ms = if (ms < 0) frame_wait else @min(ms, frame_wait); - } - if (blink) |b| if (if (b.edge) refreshNs(g) else b.next_ns) |ns| { - const wait: c_int = @intCast(@min(std.math.maxInt(c_int), ns / std.time.ns_per_ms + 1)); - ms = if (ms < 0) wait else @min(ms, wait); - }; - if (link.quietCheck()) |wait| ms = if (ms < 0) @intCast(wait) else @min(ms, @as(c_int, @intCast(wait))); - // Idle, its frame drawn: the next input needs no copy taken. - if (ms != 0 or latency_fd >= 0) r.ready(); - if (shell.surface != null) startGamepads(g); - var sev = std.mem.zeroes(c.SDL_Event); - g.input_seen = false; - var got = c.SDL_WaitEventTimeout(&sev, ms); - const timed_out = !got; - while (got) : (got = c.SDL_PollEvent(&sev)) { - if (sev.type == c.SDL_EVENT_USER) continue; - var one: OwnView = .{ .g = g, .in = &in, .s = &shell, .sev = &sev }; - r.within(&one, OwnView.run); - client.feed(); - if (link.quit) break; - } - client.takeSaid(); - // Its draws done (api.draw: this window's own pictures). - if (shell.takeDraws()) link.dirty = true; - r.settle(); - // A rollback since it drew: drawn again, never moved on from - // cells the copy put back. - if (r.moved) { - r.moved = false; - link.dirty = true; - } - if (titled and link.notice_len == 0) { - titled = false; - _ = c.SDL_SetWindowTitle(g.window, "pardes"); - } - if (link.owed or r.echo.changed) link.dirty = true; - if (moving or (blink != null and (blink.?.edge or timed_out))) again = true; - if (r.diverged != null) link.quit = true; - } - if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(joined.fd, r.diverged != null); - // The reader ends with the link: what it took meanwhile is let go. - _ = libc.shutdown(joined.fd, 2); - reader.join(); - client.lock.lockUncancelable(io); - for (client.inbox.items) |msg| switch (msg) { - .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b), - .checked => {}, - }; - client.inbox.clearRetainingCapacity(); - client.lock.unlock(io); - _ = libc.close(joined.fd); - joined.rest.deinit(gpa); - if (!link.rejoins()) { - // What it made since it joined, kept for its next start. - if (have) |h| h.keep(r.core()); - r.deinit(); - if (link.gone) Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{to.session}); - return; - } - // The session again, the core it leaves held meanwhile. - r = replica.join(gpa, &joined, to.path, to.session, o, have, &why, r) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - } -} - -const frame_ms: c_int = @intCast(pardes.frame_ns / std.time.ns_per_ms); - -const StdinFeed = struct { - parser: vaxis.Parser = .{}, - /// Inside the driver's bracketed paste: its keys are the paste's text. - in_paste: bool = false, - paste: std.ArrayList(u8) = .empty, - cache: vaxis.GraphemeCache = .{}, - buf: [1024]u8 = undefined, - fill: usize = 0, - last_cols: u16 = 0, - last_rows: u16 = 0, - - /// The test driver's keys and events since the last call, posted to - /// `in`; true once its input has ended. - fn pump(f: *StdinFeed, gpa: std.mem.Allocator, in: *Input, g: ?*Gui) !bool { - var ws: posix.winsize = std.mem.zeroes(posix.winsize); - if (posix.system.ioctl(0, posix.T.IOCGWINSZ, @intFromPtr(&ws)) == 0 and - ws.col > 0 and ws.row > 0 and ws.col <= 1000 and ws.row <= 1000 and - (ws.col != f.last_cols or ws.row != f.last_rows)) - { - f.last_cols = ws.col; - f.last_rows = ws.row; - applyResize(in, g, ws.col, ws.row); - } - - var fds = [_]posix.pollfd{.{ .fd = 0, .events = posix.POLL.IN, .revents = 0 }}; - pardes.turn.rest(); - const polled = posix.poll(&fds, 16); - pardes.turn.wake(); - _ = polled catch return false; - if ((fds[0].revents & posix.POLL.IN) == 0) return (fds[0].revents & (posix.POLL.HUP | posix.POLL.ERR)) != 0; - const rn = libc.read(0, f.buf[f.fill..].ptr, f.buf.len - f.fill); - if (rn < 0) return false; - if (rn > 0) latencyNote("R {d}\n", .{monoNs()}); - if (rn == 0) return true; - const len = f.fill + @as(usize, @intCast(rn)); - f.fill = 0; - - var seq_start: usize = 0; - while (seq_start < len) { - // ESC]777;<event>;<fields>BEL, the driver's own: - // mouse;<down|up|motion>;<SDL button, 0 for none>;<x>;<y>[;<mods>] - // mouse;wheel;<amount>;<x>;<y>[;<mods>]: a mouse event at - // window pixels, built as SDL would and run through dispatch, - // so a driver exercises the real pointer path (pixel to cell, - // tag and body hits). SGR mouse carries only cells. - // finger;<kind>;<id>;<x>;<y>;<pressure> - // One the read cut short, or what may yet begin one, waits for - // the next read. - const rest = f.buf[seq_start..len]; - const osc = "\x1b]777;"; - if (std.mem.startsWith(u8, rest, osc) or std.mem.startsWith(u8, osc, rest)) { - const bel = std.mem.indexOfScalar(u8, rest, 0x07) orelse { - std.mem.copyForwards(u8, f.buf[0..rest.len], rest); - f.fill = rest.len; - break; - }; - seq_start += bel + 1; - const event = rest[osc.len..bel]; - const semi = std.mem.indexOfScalar(u8, event, ';') orelse event.len; - const fields = event[@min(semi + 1, event.len)..]; - if (std.mem.eql(u8, event[0..semi], "mouse")) { - if (g) |gp| { - var parts = std.mem.splitScalar(u8, fields, ';'); - const kind = parts.next() orelse ""; - const second = parts.next() orelse ""; - const button = std.fmt.parseInt(u8, second, 10) catch 0; - const x = std.fmt.parseFloat(f32, parts.next() orelse "") catch 0; - const y = std.fmt.parseFloat(f32, parts.next() orelse "") catch 0; - // An optional fifth field holds modifiers as xterm - // counts them: shift 4, meta (alt) 8, ctrl 16. - const held = std.fmt.parseInt(u8, parts.next() orelse "0", 10) catch 0; - var sev = std.mem.zeroes(c.SDL_Event); - const k = std.meta.stringToEnum(enum { wheel, focus, motion, down, up }, kind) orelse .up; - switch (k) { - .wheel => { - // ESC]777;mouse;wheel;<y, SDL's sign: up positive>;<x>;<y>BEL: - // a whole number is a mouse's notches, else a touchpad's. - const amount = std.fmt.parseFloat(f32, second) catch 0; - sev.type = c.SDL_EVENT_MOUSE_WHEEL; - sev.wheel.y = amount; - sev.wheel.integer_y = @intFromFloat(@trunc(amount)); - sev.wheel.mouse_x = x; - sev.wheel.mouse_y = y; - }, - // ESC]777;mouse;focus;<1 gained, 0 lost>;0;0BEL - .focus => sev.type = if (button != 0) c.SDL_EVENT_WINDOW_FOCUS_GAINED else c.SDL_EVENT_WINDOW_FOCUS_LOST, - .motion => { - sev.type = c.SDL_EVENT_MOUSE_MOTION; - sev.motion.x = x; - sev.motion.y = y; - sev.motion.state = if (button == 0 or button > 5) 0 else @as(u32, 1) << @intCast(button - 1); - }, - .down, .up => { - sev.type = if (k == .down) c.SDL_EVENT_MOUSE_BUTTON_DOWN else c.SDL_EVENT_MOUSE_BUTTON_UP; - sev.button.button = button; - sev.button.down = k == .down; - sev.button.x = x; - sev.button.y = y; - }, - } - const before = c.SDL_GetModState(); - var mods: c.SDL_Keymod = 0; - if (held & 4 != 0) mods |= c.SDL_KMOD_LSHIFT; - if (held & 8 != 0) mods |= c.SDL_KMOD_LALT; - if (held & 16 != 0) mods |= c.SDL_KMOD_LCTRL; - c.SDL_SetModState(mods); - dispatch(gp, in, &sev); - c.SDL_SetModState(before); - } - } else if (std.mem.eql(u8, event[0..semi], "finger")) { - if (parseFinger(fields)) |finger| if (g) |gp| { - var wpw: c_int = 0; - var wph: c_int = 0; - _ = c.SDL_GetWindowSizeInPixels(gp.window, &wpw, &wph); - const win_w: f32 = @floatFromInt(@max(wpw, 1)); - const win_h: f32 = @floatFromInt(@max(wph, 1)); - handleFinger(&gp.touch, in, finger, win_w, win_h, @floatFromInt(gp.cell_w), @floatFromInt(gp.cell_h), @floatFromInt(gp.tagline_width)); - }; - } - continue; - } - - const result = f.parser.parse(f.buf[seq_start..len], gpa) catch break; - if (result.n == 0) { // partial sequence: shift to front, read more - std.mem.copyForwards(u8, f.buf[0 .. len - seq_start], f.buf[seq_start..len]); - f.fill = len - seq_start; - break; - } - seq_start += result.n; - const event = result.event orelse continue; - switch (event) { - .key_press => |key| if (f.in_paste) { - // A newline reads as Ctrl-J, as the tty's paste has it. - const text = vaxis_input.pasteBytes(key); - f.paste.appendSlice(gpa, text) catch {}; - } else { - postKey(in, key, if (key.text) |t| f.cache.put(t) else ""); - }, - .paste_start => { - f.in_paste = true; - f.paste.clearRetainingCapacity(); - }, - .paste_end => { - f.in_paste = false; - if (f.paste.items.len > 0) in.post(.{ .paste = f.paste.items }); - f.paste.clearAndFree(gpa); - }, - .mouse => |m| { - const button: ?pardes.Mouse.Button = switch (m.button) { - .left => .left, - .middle => .middle, - .right => .right, - .wheel_up => .wheel_up, - .wheel_down => .wheel_down, - .wheel_left => .wheel_left, - .wheel_right => .wheel_right, - .none => .none, - else => null, - }; - if (button) |b| { - in.post(.{ .mouse = .{ - .button = b, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, - }, - .col = @intCast(@max(m.col, 0)), - .row = @intCast(@max(m.row, 0)), - .ctrl = m.mods.ctrl, - .shift = m.mods.shift, - .alt = m.mods.alt, - } }); - } - }, - .winsize => |vw| { - applyResize(in, g, @intCast(vw.cols), @intCast(vw.rows)); - }, - .paste => |text| { - in.post(.{ .paste = text }); - gpa.free(@constCast(text)); - }, - else => {}, - } - } - return false; - } - - fn applyResize(in: *Input, g: ?*Gui, cols: u16, rows: u16) void { - if (g) |gp| { - _ = c.SDL_SetWindowSize(gp.window, @intCast(cols * gp.cell_w), @intCast(rows * gp.cell_h)); - _ = c.SDL_SyncWindow(gp.window); - } else { - in.post(.{ .resize = .{ .cols = cols, .rows = rows } }); - } - } -}; - -fn parseFinger(payload: []const u8) ?Finger { - var parts = std.mem.splitScalar(u8, payload, ';'); - const type_name = parts.next() orelse return null; - const id_s = parts.next() orelse return null; - const x_s = parts.next() orelse return null; - const y_s = parts.next() orelse return null; - const pressure_s = parts.next() orelse return null; - if (parts.next() != null) return null; - _ = std.fmt.parseFloat(f32, pressure_s) catch return null; - const Name = enum { SDL_EVENT_FINGER_DOWN, down, SDL_EVENT_FINGER_MOTION, motion, SDL_EVENT_FINGER_UP, up, SDL_EVENT_FINGER_CANCELED, cancel }; - const kind: @FieldType(Finger, "kind") = switch (std.meta.stringToEnum(Name, type_name) orelse return null) { - .SDL_EVENT_FINGER_DOWN, .down => .down, - .SDL_EVENT_FINGER_MOTION, .motion => .motion, - .SDL_EVENT_FINGER_UP, .up => .up, - .SDL_EVENT_FINGER_CANCELED, .cancel => .cancel, - }; - return .{ - .kind = kind, - .id = std.fmt.parseInt(u64, id_s, 10) catch return null, - .x = std.fmt.parseFloat(f32, x_s) catch return null, - .y = std.fmt.parseFloat(f32, y_s) catch return null, - }; -} - -fn setStdinRaw() !void { - var term = try posix.tcgetattr(0); - term.iflag.BRKINT = false; - term.iflag.ICRNL = false; - term.iflag.INPCK = false; - term.iflag.ISTRIP = false; - term.iflag.IXON = false; - term.oflag.OPOST = false; - term.lflag.ECHO = false; - term.lflag.ICANON = false; - term.lflag.IEXTEN = false; - term.lflag.ISIG = false; - term.cc[@backingInt(posix.V.MIN)] = 1; - term.cc[@backingInt(posix.V.TIME)] = 0; - try posix.tcsetattr(0, .NOW, term); -} - -/// A key parsed from the stdin a test window reads, posted as the tty -/// posts one (vaxis_input): F-keys, Insert and the keypad included. `text` -/// is the key's text as the feed keeps it. -fn postKey(in: *Input, key: vaxis.Key, text: []const u8) void { - var ev = vaxis_input.keyEvent(key); - ev.key.text = text; - in.post(ev); -} - -const Input = struct { - core: *pardes.Pardes, - /// The shell whose window this is (views.zig: its view is `gview`). - shell: ?*Shell = null, - /// A replica client's (`runClient`): its inputs go to its link, never - /// straight to the core, which only reads here. - client: ?*Client = null, - quit: bool = false, - - fn post(in: *Input, ev: pardes.Event) void { - if (in.client) |r| return r.post(ev); - // The window's input is its own view's, a replica client's input - // the session's last or not. - if (in.shell) |s| if (s.core.live != s.gview) { - _ = s.windowView(); - }; - in.core.update(ev); - } - - fn close(in: *Input) void { - if (in.client) |r| { - r.link.quit = true; - in.quit = true; - return; - } - if (in.shell) |s| { - // The window, with replica clients: they keep the session, - // as a Detach would, the daemon holding it. - if (s.peers.count() > 0 and daemon.kept()) return s.closeTheWindow(); - } - in.core.quit = true; - in.quit = true; - } -}; - -fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { - if (comptime builtin.os.tag == .macos) { - if (sev.type == c.ui_macos_trackpad_event_type()) { - dispatchTrackpad(g, in, @ptrCast(@alignCast(sev))); - return; - } - } - // An input's time, for its latency to the frame that answers it - // (FrameStats): SDL's stamp, moved onto the monotonic clock. - switch (sev.type) { - c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_WHEEL => { - g.input_seen = true; - g.input_ns = monoNs(); - if (frame_probe) |probe| probe.input(monoNs() -| (c.SDL_GetTicksNS() -| sev.common.timestamp)); - }, - else => {}, - } - switch (sev.type) { - c.SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED => { - updateDisplayScale(g.window); - // Underlines are drawn into the glyphs a logical pixel thick. - resetGlyphAtlas(g); - if (in.client) |r| { - r.link.dirty = true; - } else in.core.needs_frame = true; - }, - else => {}, - } - switch (sev.type) { - c.SDL_EVENT_QUIT => { - in.shell = null; - in.close(); - }, - c.SDL_EVENT_WINDOW_CLOSE_REQUESTED => in.close(), - c.SDL_EVENT_WINDOW_FOCUS_GAINED => { - in.post(.{ .focus = true }); - if (in.client == null) upgrade.noticeNewer(in.core); - }, - c.SDL_EVENT_WINDOW_FOCUS_LOST => in.post(.{ .focus = false }), - c.SDL_EVENT_WINDOW_MOUSE_LEAVE => { - g.pointer_present = false; - in.post(.pointer_leave); - }, - c.SDL_EVENT_KEY_DOWN => { - g.live_ctrl = (sev.key.mod & c.SDL_KMOD_CTRL) != 0; - g.live_alt = (sev.key.mod & c.SDL_KMOD_ALT) != 0; - const step: f32 = if (!g.live_ctrl) 0 else switch (sev.key.key) { - c.SDLK_EQUALS, c.SDLK_PLUS, c.SDLK_KP_PLUS => font_px_step, - c.SDLK_MINUS, c.SDLK_UNDERSCORE, c.SDLK_KP_MINUS => -font_px_step, - else => 0, - }; - if (step != 0) return setFontPx(g, in, std.math.clamp(g.px + step, font_px_min, font_px_max)); - keyDown(in, sev.key.key, sev.key.mod); - }, - c.SDL_EVENT_KEY_UP => { - g.live_ctrl = (sev.key.mod & c.SDL_KMOD_CTRL) != 0; - g.live_alt = (sev.key.mod & c.SDL_KMOD_ALT) != 0; - }, - c.SDL_EVENT_TEXT_INPUT => { - const tptr = sev.text.text orelse return; - var tlen: usize = 0; - while (tptr[tlen] != 0) : (tlen += 1) {} - if (tlen == 0) return; - const text: []const u8 = tptr[0..tlen]; - const view = std.unicode.Utf8View.init(text) catch return; - var it = view.iterator(); - var at: usize = 0; - while (it.nextCodepoint()) |cp| : (at = it.i) { - in.post(.{ .key = .{ .cp = cp, .text = text[at..it.i], .ctrl = g.live_ctrl, .alt = g.live_alt } }); - } - }, - c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => { - const b = sev.button; - const raw_button = if (comptime builtin.os.tag == .macos) - (if (b.down) g.trackpad.press(b.button) else g.trackpad.release(b.button) orelse return) - else - b.button; - const button: pardes.Mouse.Button = switch (raw_button) { - 1 => .left, - 2 => .middle, - 3 => .right, - 4 => .back, - 5 => .forward, - else => return, - }; - const mc = pointAt(g, in.core, b.x, b.y); - var ev = pointerMouse(button, if (b.down) .press else .release, mc, pointerMods()); - // Let go past the window's edge (SDL follows a held button out - // of the window: Wayland's implicit grab, X11's capture). - const win = windowGeometry(g.window); - ev.outside = !b.down and (b.x < 0 or b.y < 0 or b.x >= win.window_w or b.y >= win.window_h); - in.post(.{ .mouse = ev }); - }, - c.SDL_EVENT_MOUSE_MOTION => { - const m = sev.motion; - const physical_held: ?pardes.Mouse.Button = if ((m.state & c.SDL_BUTTON_LMASK) != 0) - .left - else if ((m.state & c.SDL_BUTTON_MMASK) != 0) - .middle - else if ((m.state & c.SDL_BUTTON_RMASK) != 0) - .right - else - null; - // A trackpad's latched button (Trackpad.press), not SDL's. - const held: ?pardes.Mouse.Button = if (comptime builtin.os.tag == .macos) - (if (g.trackpad.forced) null else if (g.trackpad.button) |b| switch (b) { - 1 => .left, - 2 => .middle, - 3 => .right, - else => physical_held, - } else physical_held) - else - physical_held; - const mc = pointAt(g, in.core, m.x, m.y); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, pointerMods()) }); - }, - c.SDL_EVENT_MOUSE_WHEEL => { - const w = sev.wheel; - if (w.y == 0 and w.x == 0) return; - const mc = pointAt(g, in.core, w.mouse_x, w.mouse_y); - wheelAt(g, in, .{ .x = w.x, .y = w.y, .integer_y = w.integer_y, .mods = pointerMods() }, mc); - }, - c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP, c.SDL_EVENT_FINGER_CANCELED => { - const f = sev.tfinger; - // Indirect Mac touches are decoded by AppKit at the pointer, - // never as absolute positions across the window. - if (comptime builtin.os.tag == .macos) if (f.touchID == c.SDL_MOUSE_TOUCHID) return; - const finger: Finger = .{ - .kind = switch (sev.type) { - c.SDL_EVENT_FINGER_DOWN => .down, - c.SDL_EVENT_FINGER_MOTION => .motion, - c.SDL_EVENT_FINGER_UP => .up, - else => .cancel, - }, - .id = @intCast(f.fingerID), - .x = f.x, - .y = f.y, - }; - var pw: c_int = 0; - var ph: c_int = 0; - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - const win_w: f32 = @floatFromInt(@max(pw, 1)); - const win_h: f32 = @floatFromInt(@max(ph, 1)); - const fcw: f32 = @floatFromInt(g.cell_w); - const fch: f32 = @floatFromInt(g.cell_h); - handleFinger(&g.touch, in, finger, win_w, win_h, fcw, fch, @floatFromInt(g.tagline_width)); - }, - // The window's font size; a Linux touchpad's pinch stays unused. - c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => if (comptime builtin.os.tag == .macos) setFontPx(g, in, Trackpad.pinch(g.px, sev.pinch.scale)), - c.SDL_EVENT_GAMEPAD_ADDED => { - if (g.gamepad == null) g.gamepad = c.SDL_OpenGamepad(sev.gdevice.which); - }, - c.SDL_EVENT_GAMEPAD_REMOVED => { - if (g.gamepad) |pad| { - c.SDL_CloseGamepad(pad); - g.gamepad = null; - } - }, - c.SDL_EVENT_GAMEPAD_BUTTON_DOWN, - c.SDL_EVENT_GAMEPAD_BUTTON_UP, - c.SDL_EVENT_GAMEPAD_AXIS_MOTION, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_UP, - => { - const pad_input: deck.Input = switch (sev.type) { - c.SDL_EVENT_GAMEPAD_BUTTON_DOWN, c.SDL_EVENT_GAMEPAD_BUTTON_UP => .{ .button = .{ - .idx = sev.gbutton.button, - .down = sev.gbutton.down, - } }, - c.SDL_EVENT_GAMEPAD_AXIS_MOTION => .{ .axis = .{ - .idx = sev.gaxis.axis, - .value = sev.gaxis.value, - } }, - else => .{ .touch = .{ - .pad = @intCast(std.math.clamp(sev.gtouchpad.touchpad, 0, 255)), - .phase = switch (sev.type) { - c.SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN => .down, - c.SDL_EVENT_GAMEPAD_TOUCHPAD_UP => .up, - else => .motion, - }, - .x = sev.gtouchpad.x, - .y = sev.gtouchpad.y, - .pressure = sev.gtouchpad.pressure, - } }, - }; - var acts: [3]deck.Action = undefined; - for (acts[0..g.deck.feed(pad_input, &acts)]) |act| switch (act) { - .move => |mv| { - const geometry = windowGeometry(g.window); - const old = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - const dx = mv.dx * geometry.window_w / geometry.pixel_w; - const dy = mv.dy * geometry.window_h / geometry.pixel_h; - g.pad_x = std.math.clamp(g.pad_x + dx, 0, geometry.window_w - 1); - g.pad_y = std.math.clamp(g.pad_y + dy, 0, geometry.window_h - 1); - c.SDL_WarpMouseInWindow(g.window, g.pad_x, g.pad_y); - g.pointer_present = true; - const mc = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - g.pointer_cell = mc; - if (mc.col == old.col and mc.row == old.row) continue; - const held = heldPointerButton(g); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); - }, - .click => |ck| { - const button: pardes.Mouse.Button = switch (ck.which) { - .select => .left, - .execute => .middle, - .look => .right, - }; - const mc = pointAt(g, in.core, g.pad_x, g.pad_y); - in.post(.{ .mouse = .{ - .button = button, - .kind = if (ck.down) .press else .release, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - } }); - }, - .wheel => |ticks| { - const mc = pointAt(g, in.core, g.pad_x, g.pad_y); - var left = ticks; - while (left != 0) { - left += if (ticks > 0) -1 else 1; - in.post(.{ .mouse = .{ - .button = if (ticks > 0) .wheel_down else .wheel_up, - .kind = .press, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - } }); - } - }, - .key => |k| in.post(.{ - .key = switch (k) { - .n => .{ .cp = 'n', .text = "n" }, - .cap_n => .{ .cp = 'N', .text = "N" }, - .enter => .{ .cp = pardes.Key.enter }, - .tab => .{ .cp = pardes.Key.tab }, - .tty_toggle => .{ .cp = in.core.opts.tty_toggle, .ctrl = true }, - }, - }), - .rumble => if (g.gamepad) |pad| { - _ = c.SDL_RumbleGamepad(pad, 0x4000, 0x4000, 80); - }, - }; - }, - else => {}, - } -} - -fn keyDown(in: *Input, sym: c.SDL_Keycode, mod: c.SDL_Keymod) void { - const ctrl = (mod & c.SDL_KMOD_CTRL) != 0; - const alt = (mod & c.SDL_KMOD_ALT) != 0; - const shift = (mod & c.SDL_KMOD_SHIFT) != 0; - const gui_mod = (mod & c.SDL_KMOD_GUI) != 0; - const cp: u21 = switch (sym) { - c.SDLK_RETURN, c.SDLK_KP_ENTER => pardes.Key.enter, - c.SDLK_BACKSPACE => pardes.Key.backspace, - c.SDLK_TAB => pardes.Key.tab, - c.SDLK_ESCAPE => pardes.Key.escape, - c.SDLK_LEFT => pardes.Key.left, - c.SDLK_RIGHT => pardes.Key.right, - c.SDLK_UP => pardes.Key.up, - c.SDLK_DOWN => pardes.Key.down, - c.SDLK_HOME => pardes.Key.home, - c.SDLK_END => pardes.Key.end, - c.SDLK_PAGEUP => pardes.Key.page_up, - c.SDLK_PAGEDOWN => pardes.Key.page_down, - c.SDLK_DELETE => pardes.Key.delete, - c.SDLK_INSERT => pardes.Key.insert, - c.SDLK_PRINTSCREEN => pardes.Key.print_screen, - c.SDLK_SCROLLLOCK => pardes.Key.scroll_lock, - c.SDLK_PAUSE => pardes.Key.pause, - c.SDLK_APPLICATION => pardes.Key.menu, - c.SDLK_F1...c.SDLK_F12 => pardes.Key.f1 + @as(u21, @intCast(sym - c.SDLK_F1)), - c.SDLK_F13...c.SDLK_F24 => pardes.Key.f1 + 12 + @as(u21, @intCast(sym - c.SDLK_F13)), - else => blk: { - if (!(ctrl or alt or gui_mod)) break :blk 0; - if (sym < 128 and sym >= ' ') break :blk @intCast(sym); - break :blk 0; - }, - }; - if (cp == 0) return; - in.post(.{ .key = .{ .cp = cp, .ctrl = ctrl, .alt = alt, .shift = shift } }); -} - -fn gridCellAtDimensions( - core: *const pardes.Pardes, - x: f32, - y: f32, - body_w: f32, - body_h: f32, - tagline_w: f32, -) MouseCell { - const row: u16 = @intFromFloat(@min(@floor(@max(y, 0) / @max(body_h, 1)), 10_000)); - var point: MouseCell = .{ .col = @intFromFloat(@min(@floor(@max(x, 0) / @max(body_w, 1)), 10_000)), .row = row }; - // On the rule over this row, which is where two panes meet if they do. - point.rule_above = row > 0 and @max(y, 0) - @as(f32, @floatFromInt(row)) * @max(body_h, 1) < dp(rule_grab_px); - if (onGrid(core, x / @max(body_w, 1), y / @max(body_h, 1))) for (core.surface.tagLayers()) |*layer| { - if (layer.tagHit(x, y, body_w, body_h, tagline_w, @floatFromInt(core.view().row_metrics.tagline_h))) |hit| { - point.tag_hit = hit; - break; - } - }; - return point; -} - -/// Whether a point, in cells, is on the grid. -fn onGrid(core: *const pardes.Pardes, x: f32, y: f32) bool { - return std.math.isFinite(x) and std.math.isFinite(y) and x >= 0 and y >= 0 and - x < @as(f32, @floatFromInt(core.view().screen_w)) and y < @as(f32, @floatFromInt(core.view().screen_h)); -} - -fn gridCellAtPixels(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { - var point = gridCellAtDimensions(core, x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width)); - if (onGrid(core, x / @as(f32, @floatFromInt(g.cell_w)), y / @as(f32, @floatFromInt(g.cell_h)))) for (core.surface.bodyLayers()) |*layer| { - if (layer.bodyHit(x, y, @floatFromInt(g.cell_w), @floatFromInt(g.cell_h), @floatFromInt(g.tagline_width), @floatFromInt(g.tagline_height))) |hit| { - point.body_hit = hit; - break; - } - }; - return point; -} - -/// A wheel turned over grid cell `mc` (SDL's sign: up positive): the -/// part of dispatch after the pointer is placed, so a test can turn it. -fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { - if (w.y != 0 and std.math.isFinite(w.y)) { - const core = in.core; - const hit: ?usize = for (core.panes, 0..) |slot, i| { - if (slot == null) continue; - const r = core.view().rects[i]; - if (mc.col >= r.x and mc.col < r.x + r.w and mc.row >= r.y and mc.row < r.y + r.h) break i; - } else null; - if (g.scroll_pane) |old| if (hit == null or hit.? != old) { - resetScroll(g); - }; - if (hit) |id| { - const pane = core.panes[id].?; - if (pane.addon != null) { - // A kind's (a PDF's strip): the turn as it came, a - // touchpad's fraction of a notch too (pa_mouse.amount). - resetScroll(g); - in.post(.{ .mouse = .{ .button = if (w.y < 0) .wheel_down else .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt, .amount = @abs(w.y) } }); - } else if (!w.mods.shift and pane.isTerminal() and pardes.Term.modes(pane.terminal).wheel) { - // The program's (codex, htop, less): every whole turn goes - // to it, no glide, for nothing of ours moves. Shift keeps - // a terminal's wheel pardes's. - resetScroll(g); - g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y); - while (g.program_wheel >= 1) : (g.program_wheel -= 1) - in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); - while (g.program_wheel <= -1) : (g.program_wheel += 1) - in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit, .ctrl = w.mods.ctrl, .shift = w.mods.shift, .alt = w.mods.alt } }); - } else if (in.client != null) { - // A replica client's notch is whole rows at once, with no - // glide; a touchpad's fraction is the window's picture - // (scrollRows), its whole rows ordinary inputs. - if (notchOf(w.y, w.integer_y)) |lines| { - g.program_wheel = @floatFromInt(lines); - } else { - g.scroll_pane = id; - g.scroll_col = mc.col; - g.scroll_row = mc.row; - g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); - } - while (g.program_wheel >= 1) : (g.program_wheel -= 1) - in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); - while (g.program_wheel <= -1) : (g.program_wheel += 1) - in.post(.{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); - } else { - g.scroll_pane = id; - g.scroll_col = mc.col; - g.scroll_row = mc.row; - // A mouse wheel's notch is a whole line and - // glides (G6); a touchpad's fraction moves the - // picture by itself, under the finger. - if (notchOf(w.y, w.integer_y)) |lines| { - g.scroll_notch +|= lines; - } else g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); - } - } - } - var horizontal: i32 = if (w.x == 0 or !std.math.isFinite(w.x)) 0 else if (w.x > 0) 1 else -1; - if (w.precise and std.math.isFinite(w.x)) { - g.program_wheel_x += std.math.clamp(w.x, -64, 64); - horizontal = @intFromFloat(@trunc(g.program_wheel_x)); - g.program_wheel_x -= @floatFromInt(horizontal); - } - while (horizontal != 0) { - in.post(.{ .mouse = .{ - .button = if (horizontal > 0) .wheel_right else .wheel_left, - .kind = .press, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - .ctrl = w.mods.ctrl, - .shift = w.mods.shift, - .alt = w.mods.alt, - } }); - horizontal += if (horizontal > 0) -1 else 1; - } -} - -/// `precise`: a Mac trackpad's columns (dispatchTrackpad), whose -/// horizontal fraction is kept toward the next turn. -const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, precise: bool = false, mods: PointerMods = .{} }; - -/// The window's font at `want` pixels: a key's step, a pinch. A client's -/// view is sized by its next loop, as its input. -fn setFontPx(g: *Gui, in: *Input, want: f32) void { - if (want == g.px) return; - g.px = want; - if (in.client) |r| { - refitFont(g, null); - r.link.dirty = true; - } else { - refitFont(g, in.core); - observeGuiFont(g, in.core); - } -} - -/// A Mac trackpad's gesture, decoded by macos_trackpad.m (Trackpad.zig's -/// policy): fingers, a pinch's zoom, a swipe's Back/Forward, a rotation's -/// n/N, a force click's Look, and a two-finger scroll by the pixel. -fn dispatchTrackpad(g: *Gui, in: *Input, ev: *const c.UITrackpadEvent) void { - g.input_seen = true; - switch (ev.kind) { - c.UI_TRACKPAD_FINGERS => g.trackpad.countFingers(@intCast(@max(ev.fingers, 0))), - c.UI_TRACKPAD_PINCH => if (g.trackpad.magnify(g.px, ev.a, ev.phase)) |want| setFontPx(g, in, want), - c.UI_TRACKPAD_HISTORY => { - if (ev.a == 0 or !std.math.isFinite(ev.a)) return; - const back = ev.a < 0; - const jumps = &in.core.view().jumps; - const can_jump = jumps.n > 0 and (if (back) jumps.cur > 0 else jumps.cur + 1 < jumps.n); - in.post(.{ .command = if (back) "Back" else "Forward" }); - if (comptime builtin.os.tag == .macos) if (can_jump) c.ui_macos_trackpad_haptic(); - }, - c.UI_TRACKPAD_ROTATE => { - const pane = in.core.panes[in.core.view().active] orelse return; - // Search-step keys never become text in insert/raw mode. - if (pane.body.mode != .normal) return; - var ticks = g.trackpad.rotate(ev.a, ev.phase); - while (ticks != 0) { - in.post(.{ .key = .{ .cp = if (ticks > 0) 'N' else 'n' } }); - if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_haptic(); - ticks += if (ticks > 0) -1 else 1; - } - }, - c.UI_TRACKPAD_PRESSURE => { - const previous = g.trackpad.force(ev.a) orelse return; - const mc = mouseCell(g, in.core, ev.x, ev.y); - in.post(.{ .mouse = pointerMouse(if (previous == 2) .middle else .left, .release, mc, pointerMods()) }); - in.post(.{ .mouse = pointerMouse(.right, .press, mc, pointerMods()) }); - in.post(.{ .mouse = pointerMouse(.right, .release, mc, pointerMods()) }); - }, - c.UI_TRACKPAD_SCROLL => { - const mc = pointAt(g, in.core, ev.x, ev.y); - // AppKit reports points; the grid is measured in backing pixels. - const geometry = windowGeometry(g.window); - const rows = ev.b * geometry.pixel_h / geometry.window_h / @as(f32, @floatFromInt(g.cell_h)); - const cols = -ev.a * geometry.pixel_w / geometry.window_w / @as(f32, @floatFromInt(g.cell_w)); - wheelAt(g, in, .{ .x = cols, .y = rows, .precise = true, .mods = pointerMods() }, mc); - }, - else => {}, - } -} - -/// 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, 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 { - return .{ - .button = button, - .kind = kind, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - .rule_above = (kind == .press or kind == .release) and mc.rule_above, - .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, .super = (m & c.SDL_KMOD_GUI) != 0 }; -} - -fn mouseCellWithGeometry(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32, geometry: WindowGeometry) MouseCell { - const physical = windowPointToPixels(geometry, x, y); - return gridCellAtPixels(g, core, physical.x, physical.y); -} - -fn mouseCell(g: *const Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { - return mouseCellWithGeometry(g, core, x, y, windowGeometry(g.window)); -} - -/// The pointer at window point (x, y), as an event or the gamepad puts it -/// there: where the window keeps it, and the cell under it. -fn pointAt(g: *Gui, core: *const pardes.Pardes, x: f32, y: f32) MouseCell { - g.pad_x = x; - g.pad_y = y; - g.pointer_present = true; - const mc = mouseCell(g, core, x, y); - g.pointer_cell = mc; - return mc; -} - -/// SDL's hit test, asked as the pointer moves over the window: a blank cell -/// of the workspace tag (tagline.workspaceBlank) is the window's to drag, as -/// a title bar is. SDL gives the compositor a B1 press there (Wayland's -/// xdg_toplevel.move, X11's _NET_WM_MOVERESIZE, macOS's own drag), so the -/// press never reaches the core; B2 and B3 there still do. -fn hitTest(_: ?*c.SDL_Window, area: [*c]const c.SDL_Point, data: ?*anyopaque) callconv(.c) c.SDL_HitTestResult { - const g: *Gui = @ptrCast(@alignCast(data orelse return c.SDL_HITTEST_NORMAL)); - const core = g.hit_core orelse return c.SDL_HITTEST_NORMAL; - if (area == null) return c.SDL_HITTEST_NORMAL; - const mc = mouseCell(g, core, @floatFromInt(area.*.x), @floatFromInt(area.*.y)); - return if (pardes.tagline.workspaceBlank(core, mc.col, mc.row, mc.tag_hit)) c.SDL_HITTEST_DRAGGABLE else c.SDL_HITTEST_NORMAL; -} - -fn heldPointerButton(g: *const Gui) ?pardes.Mouse.Button { - const buttons = c.SDL_GetMouseState(null, null); - if ((buttons & c.SDL_BUTTON_LMASK) != 0 or g.deck.r2_held or g.deck.rpad_click) return .left; - if ((buttons & c.SDL_BUTTON_MMASK) != 0 or g.deck.l2_held) return .middle; - if ((buttons & c.SDL_BUTTON_RMASK) != 0 or g.deck.look_held) return .right; - return null; -} - -fn refreshPresentedPointer(g: *Gui, in: *Input) void { - if (!g.pointer_present) return; - const mc = mouseCell(g, in.core, g.pad_x, g.pad_y); - const moved = g.pointer_cell == null or g.pointer_cell.?.col != mc.col or g.pointer_cell.?.row != mc.row; - g.pointer_cell = mc; - if (!moved) return; - const held = heldPointerButton(g); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); -} - -fn pollGamepad(g: *Gui, in: *Input) void { - const pad = g.gamepad orelse return; - const geometry = windowGeometry(g.window); - const deadzone: f32 = 8000; - const ax: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_RIGHTX)); - const ay: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_RIGHTY)); - const old = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - const speed: f32 = @as(f32, @floatFromInt(g.cell_h)) * 0.4; - const speed_x = speed * geometry.window_w / geometry.pixel_w; - const speed_y = speed * geometry.window_h / geometry.pixel_h; - const pointer_moved = @abs(ax) > deadzone or @abs(ay) > deadzone; - if (@abs(ax) > deadzone) g.pad_x = std.math.clamp(g.pad_x + ax / 32767.0 * speed_x, 0, geometry.window_w - 1); - if (@abs(ay) > deadzone) g.pad_y = std.math.clamp(g.pad_y + ay / 32767.0 * speed_y, 0, geometry.window_h - 1); - if (pointer_moved) { - g.pointer_present = true; - c.SDL_WarpMouseInWindow(g.window, g.pad_x, g.pad_y); - } - const mc = mouseCellWithGeometry(g, in.core, g.pad_x, g.pad_y, geometry); - if (g.pointer_present) { - g.pointer_cell = mc; - if (mc.col != old.col or mc.row != old.row) { - const held = heldPointerButton(g); - in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, .{}) }); - } - } - const lx: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_LEFTX)); - const ly: f32 = @floatFromInt(c.SDL_GetGamepadAxis(pad, c.SDL_GAMEPAD_AXIS_LEFTY)); - if (@abs(ly) > deadzone) g.pad_scroll += ly / 32767.0 * 0.15; - if (@abs(lx) > deadzone) g.pad_scroll_h += lx / 32767.0 * 0.15; - while (@abs(g.pad_scroll) >= 1.0) { - const button: pardes.Mouse.Button = if (g.pad_scroll < 0) .wheel_up else .wheel_down; - g.pad_scroll += if (g.pad_scroll < 0) 1.0 else -1.0; - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit } }); - } - while (@abs(g.pad_scroll_h) >= 1.0) { - const button: pardes.Mouse.Button = if (g.pad_scroll_h < 0) .wheel_left else .wheel_right; - g.pad_scroll_h += if (g.pad_scroll_h < 0) 1.0 else -1.0; - in.post(.{ .mouse = .{ .button = button, .kind = .press, .col = mc.col, .row = mc.row, .tag_hit = mc.tag_hit, .body_hit = mc.body_hit } }); - } -} - -const Shell = struct { - core: *pardes.Pardes, - /// The window's, while one is open; null while detached (`detached` has - /// it). - gui: ?*Gui = null, - detached: ?*Gui = null, - /// Shells a dead session left (Adopt), each waiting for the spawn of - /// the terminal pane made for it. - adoptions: host_io.Adoptions = .{}, - io: std.Io, - gpa: std.mem.Allocator, - fs: ?*ninep_io.Listener = null, - lsp_allocator: std.mem.Allocator, - prompt_rcs: *const host_io.Shell.PromptFiles, - ptys: *[pardes.MAX_PANES]?Pty, - gens: *[pardes.MAX_PANES]u32, - queue: *Queue, - /// What drainQueue takes each wakeup, kept rather than rebuilt. - batch: Queue.Batch = .{}, - pipe_tasks: *PipeTasks, - job_tasks: PipeTasks = .{}, - inotify_fd: c_int, - watches: *file_watch.Table, - threads_ok: bool = false, - test_mode: bool = false, - feed: StdinFeed = .{}, - presented: bool = false, - skipped_presents: u8 = 0, - surface: ?*const pardes.Surface = null, - /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), in test mode. - test_clock: ?u64 = null, - /// The display rate a virtual clock stands in for (PARDES_TEST_HZ). - test_hz: u64 = 60, - /// The tick a paced frame is sampled at (waitInput): the clock the - /// core is advanced to while anything moves. - paced_ns: ?u64 = null, - /// The view the window shows (views.zig); a second window on the - /// session is a replica client of it (`pardes-gui --attach`). - gview: u8 = 0, - /// Upgrade was asked from this pane, to be done between steps (`upgradeNow`). - upgrade_asked: ?u8 = null, - /// This window a replica client of a session elsewhere (`runClient`). - client: ?*Client = null, - /// The session's replica clients (src/replica.zig), on sockets: views - /// of their own with no window here. - peers: replica.Peers = .{}, - /// This wait took only a replica's post (its input, its join): the pump - /// after it reads no new time, so it moves nothing the replicas' - /// speculations stand on (tui.zig's `mail_only`). - mail_only: bool = false, - waited: bool = false, - /// With replica clients, a wait takes one person's input (tui.zig - /// `split`): the next is held for the next wait. - took_input: bool = false, - held: ?c.SDL_Event = null, - - fn closePaneShell(ctx: ?*anyopaque, pane: u8) void { - shellOf(ctx).closePty(pane); - } - - fn closePty(s: *Shell, pane: u8) void { - const pt = if (s.ptys[pane]) |*pt| pt else return; - // Out of the queue first, which lets go a reader waiting for room - // in it; then its read is canceled (or, at its end, it is joined). - s.queue.cancelReader(pane, s.gens[pane]); - if (pt.reader) |*reader| { - reader.cancel(s.queue.io); // the Io it was started on (startReader) - pt.reader = null; - } - _ = libc.close(pt.fd); - daemon.closed(pt.pid); - host_io.retireShell(pt.pid); - s.ptys[pane] = null; - } - - fn stopPtys(s: *Shell) void { - for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); - for (s.gens) |*gen| gen.* +%= 1; - } - - fn shutdownPtys(s: *Shell) void { - s.stopPtys(); - host_io.waitRetired(); - } - - fn reconcilePtys(s: *Shell) void { - for (s.ptys, 0..) |slot, pane| if (slot) |pt| { - const current = s.core.panes[pane]; - if (current == null or current.?.serial != pt.serial or !current.?.isTerminal()) - s.closePty(@intCast(pane)); - }; - } - - fn host(s: *Shell) pardes.Host { - return .{ .ctx = s, .vtable = &vtable }; - } - - /// Detach: the window closed, the session left running with no - /// window, for `pardes-gui --attach` to open one again. - fn detachWindow(ctx: ?*anyopaque) void { - const s = shellOf(ctx); - // A replica client's: its link ends. - if (s.peers.detach(s.core.live)) return; - if (s.gui == null) return s.core.reportFailure(s.core.view().active, "Detach: no window is open"); - if (!daemon.kept()) return s.core.reportFailure(s.core.view().active, "Detach: no pardes daemon lists this session; closing its window ends it"); - s.closeTheWindow(); - } - - /// The window's own clock: the test's virtual one, the paced tick, else - /// SDL's. - fn ownNow(s: *const Shell) u64 { - return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); - } - - /// The Gui's window's view live, for what the window does to its own - /// (its size, its scroll): a replica client's input may have been the - /// last. True when it was not, and is now. - fn windowView(s: *Shell) bool { - if (s.core.live == s.gview or !pardes.views.isOpen(s.core, s.gview)) return false; - s.core.toView(s.gview); - return true; - } - - /// With replica clients, a wait takes one person's input and its pump - /// makes one unit of it (tui.zig `split`): whether `sev`, a second, is - /// held for the next wait. Any event but a wake is no replica's post. - fn split(s: *Shell, sev: *const c.SDL_Event) bool { - if (sev.type != c.SDL_EVENT_USER) s.mail_only = false; - if (!s.peers.recording) return false; - const native_gesture = if (comptime builtin.os.tag == .macos) sev.type == c.ui_macos_trackpad_event_type() else false; - if (!native_gesture) switch (sev.type) { - c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP, c.SDL_EVENT_MOUSE_MOTION, c.SDL_EVENT_MOUSE_WHEEL, c.SDL_EVENT_WINDOW_FOCUS_GAINED, c.SDL_EVENT_WINDOW_FOCUS_LOST, c.SDL_EVENT_WINDOW_MOUSE_LEAVE, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP => {}, - else => return false, - }; - if (s.took_input) { - s.held = sev.*; - return true; - } - s.took_input = true; - return false; - } - - fn closeTheWindow(s: *Shell) void { - const g = s.gui orelse return; - closeWindow(g); - s.detached = g; - s.gui = null; - s.presented = false; - s.surface = null; - // Its clients look at it still (Peers keeps it attended). - s.peers.detached = true; - s.core.unattended = s.peers.count() == 0; - daemon.setState(true); - } - - fn openTheWindow(s: *Shell) void { - const g = s.detached orelse return; - if (!reopenWindow(g)) { - log.err("--attach: no window: {s}", .{c.SDL_GetError()}); - return daemon.setState(true); - } - s.gui = g; - s.detached = null; - s.peers.detached = false; - s.core.unattended = false; - s.core.needs_frame = true; - resetScroll(g); - daemon.setState(false); - } - - fn watched(ctx: ?*anyopaque) bool { - return shellOf(ctx).gui != null; - } - - fn adopt(ctx: ?*anyopaque, pane: u8) void { - const s = shellOf(ctx); - s.adoptions.ask(s.core, pane); - } - - fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { - const s = shellOf(ctx); - if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place"); - s.upgrade_asked = pane; - } - - /// Upgrade, between steps: this process exec'd as the pardes now at the - /// path it was started from, the session in its dump and its ptys and - /// daemon link kept open across (upgrade.zig); the new process opens - /// its windows again. Returns only when it could not be, as it was. - fn upgradeNow(s: *Shell, pane: u8) void { - s.upgrade_asked = null; - const core = s.core; - var why: [800]u8 = undefined; - const path = upgrade.exe() orelse return core.reportFailure(pane, "Upgrade: this process does not know the path it was started from"); - // The new process starts SDL's video afresh, and that fails with no - // display at all (the screen off and its outputs gone): it ended the - // session (a detached one's hidden window needs one too). - var displays: c_int = 0; - if (c.SDL_GetDisplays(&displays)) |list| c.SDL_free(list); - if (displays == 0) return core.reportFailure(pane, "Upgrade: the display has no screen now (off, or gone), and the new build could not open its window; this session stays as it is until one is back"); - // 9P is served while the new binary is asked, and not after. - pardes.turn.rest(); - const checked = upgrade.check(path, &why); - pardes.turn.wake(); - switch (checked) { - .no => |w| return core.reportFailure(pane, w), - .ok => {}, - } - // Nothing more read from a pty, and what was read goes in: drained, - // the readers stopped (a reader waiting for room has it then), and - // what they pushed meanwhile drained. - s.drainQueue(); - for (s.ptys) |*slot| if (slot.*) |*pt| if (pt.reader) |*r| { - r.cancel(s.queue.io); - pt.reader = null; - }; - s.drainQueue(); - core.settle(); - // Its replica clients told, their views gone before the dump: each - // dials the session again once it is back. - s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); - var rec: upgrade.Record = .{ .link = daemon.link, .window = s.gui != null, .exe = path }; - for (s.ptys, 0..) |slot, id| if (slot) |pt| if (pt.fd >= 0) rec.addPty(id, pt.pid, pt.fd); - var at_buf: [1024:0]u8 = undefined; - const failed = upgrade.dumpInto(core, &rec, &at_buf, &why) orelse upgrade.execAs(s.gpa, path, &rec, &at_buf, s.fs, &why); - // As it was: its ptys read on. - for (s.ptys, 0..) |*slot, id| if (slot.*) |*pt| if (pt.fd >= 0 and pt.reader == null) { - pt.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), s.gens[id]) catch null; - }; - core.reportFailure(pane, failed); - } - - /// An upgraded session's shells, running on: each its pane's pty again, - /// or, when its dump would not load (`fresh`), adopted as new panes. - fn resumePtys(s: *Shell, rec: *const upgrade.Record) void { - for (rec.ptys[0..rec.nptys]) |k| { - const pane = if (rec.fresh) null else s.core.panes[k.pane]; - if (pane == null or !pane.?.isTerminal()) { - s.adoptions.adoptShell(s.core, k.pid, k.fd); - continue; - } - s.ptys[k.pane] = .{ .fd = k.fd, .pid = k.pid, .serial = pane.?.serial, .cmd = .{ .watched = pane.?.command != null and host_io.watchExit(k.pid), .fd = k.fd } }; - } - } - - /// An upgraded session's window, its view's again; every other view - /// but a replica client's, kept for its rejoin (views.away), closes. - fn resumeWindow(s: *Shell) void { - s.gview = s.core.live; - for (0..pardes.views.max) |i| { - const k: u8 = @intCast(i); - if (k != s.gview and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.core.closeView(k); - } - } - - const vtable: pardes.Host.VTable = .{ - .wait_input = waitInput, - .now = guiNow, - .present = present, - .post_present = postPresent, - .poll_frame = pollFrame, - .watched = watched, - .detach = detachWindow, - .adopt = adopt, - .upgrade = upgradeAsked, - .spawn = spawnPane, - .pty_write = ptyWrite, - .pty_resize = ptyResize, - .pty_signal = ptySignal, - .close_pty = closePaneShell, - .tty_taken = ttyTaken, - .fg_name = fgName, - .kill_job = killJob, - .write_file = writeFile, - .write_dump = writeDump, - .watch_file = watchFile, - .watch_theme = watchTheme, - .dump_themes = dumpThemes, - .set_clipboard = setClipboard, - .read_clipboard = readClipboard, - .open_link = openLink, - .start = host_io.startDetached, - .lsp = lsp, - .pipe = pipe, - .search = search, - .hand_over = handOver, - .job = kindJob, - }; - - /// The command panes' exits, told once their output is in (host_io). - fn takeExits(s: *Shell) void { - host_io.takeExits(s.core, s.ptys, s, closeWatched); - } - - fn closeWatched(s: *Shell, id: usize) void { - s.closePty(@intCast(id)); - } - - /// A client's queue holds its draws alone: each landed for its pane's - /// next paint. Whether any came. - fn takeDraws(s: *Shell) bool { - s.queue.takeInto(&s.batch); - for (s.batch.slice()) |m| switch (m) { - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(s.core); - }, - else => m.deinit(s.gpa, s.lsp_allocator), - }; - return s.batch.slice().len > 0; - } - - fn drainQueue(s: *Shell) void { - s.reconcilePtys(); - // After this batch's output, which an exit is told behind. - defer s.takeExits(); - s.queue.takeInto(&s.batch); - const msgs = &s.batch; - if (msgs.len > 0) s.mail_only = false; - var check_files = false; - for (msgs.slice()) |m| switch (m) { - .output => |o| { - if (s.gens[o.pane] == o.gen) - s.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); - s.gpa.free(o.bytes); - }, - .eof => |e| { - if (s.gens[e.pane] == e.gen) eof: { - if (e.failure) |err| { - s.closePty(e.pane); - s.core.readerFailed(e.pane, err); - break :eof; - } - const pt = if (s.ptys[e.pane]) |*pt| pt else { - s.core.update(.{ .eof = .{ .pane = e.pane } }); - break :eof; - }; - // A command's pty stays open until its child has exited: - // closing it would hang up one that runs on without it. - // Its exit, if it came first, is told now its output is in. - if (pt.cmd.watched) { - host_io.commandEof(s.core, s.ptys, e.pane, s, closeWatched); - break :eof; - } - // Unwatched, a command's exit is read here, as its end, - // and a shell's, for a run waiting on it and the log. - const unwatched = if (s.core.panes[e.pane]) |pane| pane.command != null else false; - const status = host_io.exitStatus(pt.pid, 100); - if (status != null) pt.pid = 0; // reaped: no shell to retire - s.closePty(e.pane); - if (unwatched or status != null) s.core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); - s.core.update(.{ .eof = .{ .pane = e.pane } }); - } - }, - .lsp => |l| { - s.core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } }); - if (l.rows) |rows| s.lsp_allocator.free(rows); - }, - .lsp_status => |text| { - var mbuf: [256]u8 = undefined; - s.core.setStatus(s.core.view().active, message.stamp(&mbuf, "lsp", text)); - s.lsp_allocator.free(text); - }, - .pipe => |response_value| { - var response = response_value; - s.core.update(.{ .pipe_resp = .{ - .id = response.id, - .success = response.success, - .outputs = response.outputs, - .failure = response.failure, - } }); - response.deinit(s.gpa); - s.pipe_tasks.finish(s.io, response_value.id); - }, - .search => |b| { - s.core.update(.{ .search = b }); - b.deinit(s.gpa); - }, - .handed => |h| { - s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); - s.gpa.free(h.words); - }, - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(s.core); - }, - .files_changed => check_files = true, - .fs_ready => {}, - .window => if (s.gui == null) s.openTheWindow(), - .adopted => |a| s.adoptions.adoptShell(s.core, a.pid, a.fd), - }; - if (check_files and file_watch.reloadChanged(s.core, s.io, s.gpa, s.watches)) - s.queue.push(.files_changed); - } -}; - -fn wakeFs(ctx: ?*anyopaque) void { - const q: *Queue = @ptrCast(@alignCast(ctx.?)); - q.push(.fs_ready); -} - -fn shellOf(ctx: ?*anyopaque) *Shell { - return @ptrCast(@alignCast(ctx.?)); -} - -fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { - const s = shellOf(ctx); - const core = s.core; - var in: Input = .{ .core = core, .shell = s }; - s.mail_only = true; - s.took_input = false; - defer s.waited = true; - if (s.gui) |g| { - if (s.surface != null) startGamepads(g); - var sev = std.mem.zeroes(c.SDL_Event); - // Idle is asleep until an event: SDL's own, and the user events the - // shell's queue raises for a terminal's output, a completion, a file - // system request. What the shell moves or times itself polls every - // frame: a smooth scroll, a gamepad's sticks, the test stdin feed, - // a present to retry. A minimized window sleeps through the core's animation - // too: nothing shows it, and it is caught up at once when the window - // is back. - const polls = g.scroll_lag != 0 or g.scroll_delta != 0 or g.scroll_notch != 0 or frontendMoving(g) or g.gamepad != null or s.test_mode or core.needs_frame; - const minimized = !s.test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; - // A latency trace is fed on stdin, whose poll below paces the loop: - // waiting here too would make every tick cost two frames. - const poll_ms: c_int = 16; - const waited: c_int = if (latency_fd >= 0) 0 else if (minimized) -1 else if (timeout_ms != 0) @min(@as(c_int, @intCast(@min(timeout_ms, std.math.maxInt(c_int)))), if (polls) poll_ms else std.math.maxInt(c_int)) else if (polls) poll_ms else -1; - // The cursor's blink is the window's to time (Gui.input_ns): - // a frame a loop through an edge, else a wake at the next one; none - // while the window is minimized or unfocused. A virtual clock never - // blinks, so goldens hold still. - const blink = if (s.test_clock != null or minimized or s.surface == null) null else blinkNow(g, s.core.settings.cursor_blink); - const blink_ms: ?c_int = if (blink) |b| (if (b.edge) 1 else if (b.next_ns) |next| @as(c_int, @intCast(@min(std.math.maxInt(c_int), next / std.time.ns_per_ms + 1))) else null) else null; - const blinked: c_int = if (blink_ms) |b| (if (waited < 0) b else @min(waited, b)) else waited; - // The timedemo's next step is a wake too. - var ms: c_int = if (demoDue(g)) |due| (if (blinked < 0) due else @min(blinked, due)) else blinked; - // While anything moves, frames are paced as a game's are: one a - // display refresh, on a grid of ticks a period apart, each sampled - // at its tick (guiNow), however early or late the loop got there. - // Input that comes between two ticks is acted on as it comes (the - // core's state is never held back) and drawn at the next tick. Not - // paced, the loop ran as fast as it could present (the soft present - // has no vsync), ~230 frames a second on a 60 Hz display, and the - // compositor showed whichever was newest at each refresh: motion - // sampled at random phase, uneven steps, a judder in every scroll. - // ponytail: the period is the display mode's refresh and the grid's - // phase is our own, not the display's (no vblank time to read on the - // soft present); a 59.94 Hz display drifts a tick every 17 s. The - // upgrade: the presentation feedback protocol's timestamps. - const paced = s.test_clock == null and latency_fd < 0 and !s.test_mode and !minimized and frontendMoving(g); - var tick: u64 = 0; - if (paced) { - const period = refreshNs(g); - const now = c.SDL_GetTicksNS(); - // A motion from rest draws at once; one under way, at its next - // tick, skipping (never bunching) the ticks a slow frame missed. - tick = if (g.pace_ns != 0 and now -| g.pace_ns < 2 * period) g.pace_ns + period else now; - if (tick < now) tick += (now - tick) / period * period; - // Waited out polling, below. - ms = 0; - } - g.input_seen = false; - // An input held from the last wait (`split`) is this one's, at once. - const held = s.held; - s.held = null; - if (held) |h| sev = h; - // The wait is the 9P connections' turn with the core. - pardes.turn.rest(); - const got = held != null or c.SDL_WaitEventTimeout(&sev, ms); - pardes.turn.wake(); - // A virtual clock: while a render-time animation moves, each loop - // is a presented frame and moves it by one display frame - // (PARDES_TEST_HZ), events or not, as a real display's present - // would; otherwise a wait that ran out moves it exactly to the - // core's wake. - // Through an edge, or woken for the next: the shell redraws the last - // frame with the new alpha, no core render. - if (blink_ms != null and (blink.?.edge or !got)) g.blink_due = true; - if (s.test_clock) |*virtual| { - if (frontendMoving(g)) { - const display = virtual.* + std.time.ns_per_s / s.test_hz; - virtual.* = if (core.nextWake()) |due| @max(virtual.*, @min(due, display)) else display; - } else if (timeout_ms != 0 and (!got or !core.needs_frame)) { - // A wait that ran out, or one a stray event cut short while - // nothing owes a frame: time moves to the core's wake all - // the same, so a steady trickle of events (a pty's, the - // test feed's) cannot hold a virtual clock still forever. - virtual.* = @max(virtual.*, core.nextWake() orelse virtual.*); - } - } - if (got) { - // A run of queued motions is one move to its last position (the - // handler reads only absolute x/y and held buttons): acting on - // each would repeat hover and selection work the next undoes. - var motion: ?c.SDL_Event = null; - while (true) { - if (s.split(&sev)) break; - if (sev.type == c.SDL_EVENT_MOUSE_MOTION and (motion == null or motion.?.motion.windowID == sev.motion.windowID)) { - motion = sev; - } else { - if (motion) |*m| { - _ = s.windowView(); - dispatch(g, &in, m); - } - motion = null; - if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { - motion = sev; - } else { - _ = s.windowView(); - dispatch(g, &in, &sev); - } - } - if (!c.SDL_PollEvent(&sev)) break; - } - if (motion) |*m| { - _ = s.windowView(); - dispatch(g, &in, m); - } - } - runDemo(g, &in, core); - // Paced: what came before the tick is in; wait out the rest of it, - // unless an input came: its frame is drawn at once (the paced loop - // never adds a tick to an input's latency), and the ticks after it - // run from it. A stream's repeat too: the picture it moves is on - // the stream's straight line wherever it is sampled, so drawing it - // between two ticks costs no evenness, and holding it to the tick - // cost a held key 7 ms of latency. - if (paced and g.input_seen) tick = c.SDL_GetTicksNS(); - // The tick is waited out polling, not asleep, as a game's frame - // limiter spins: asleep between 60 Hz frames, the CPU's clock fell - // (intel_pstate, 4.9 GHz down toward 0.8) and every frame, an - // input's first among them, took 2-5x as long: input-to-present p50 - // 1.9 ms spinning against 7-8 ms asleep. - // ponytail: a core while something moves (~250 ms a scroll); a - // sleep to a millisecond short of the tick if the power matters more. - while (paced and !g.input_seen and s.held == null) { - if (tick -| c.SDL_GetTicksNS() < 50 * std.time.ns_per_us) break; - pardes.turn.rest(); - const more = c.SDL_PollEvent(&sev); - pardes.turn.wake(); - if (more) { - if (!s.split(&sev)) { - _ = s.windowView(); - dispatch(g, &in, &sev); - while (c.SDL_PollEvent(&sev)) { - if (s.split(&sev)) break; - _ = s.windowView(); - dispatch(g, &in, &sev); - } - } - } else { - // The events asked for every 100 µs, the core busy between. - const until = c.SDL_GetTicksNS() + 100 * std.time.ns_per_us; - while (c.SDL_GetTicksNS() < @min(until, tick)) std.atomic.spinLoopHint(); - } - runDemo(g, &in, core); - if (g.input_seen) tick = c.SDL_GetTicksNS(); - } - s.paced_ns = if (paced) tick else null; - if (paced) g.pace_ns = tick; - } else waitDetached(core, timeout_ms); - if (s.test_mode) { - if (s.feed.pump(s.gpa, &in, s.gui) catch true) { - core.quit = true; - return; - } - } - s.drainQueue(); - if (s.gui) |g| pollGamepad(g, &in); -} - -/// Detached: no window, asleep until the queue's wake (an SDL user event: -/// a pty's output, the daemon's window request), the core's next wake, or a -/// quit (SDL makes SIGTERM and SIGINT one). With nobody to dismiss them, -/// messages go on the clock (the pump's, after this wait), which wakes it. -fn waitDetached(core: *pardes.Pardes, timeout_ms: u32) void { - var ms: c_int = if (timeout_ms != 0) @intCast(@min(timeout_ms, std.math.maxInt(c_int))) else -1; - for (core.panes) |slot| if (slot) |pane| if (pane.msg_len > 0) { - ms = if (ms < 0) 100 else @min(ms, 100); - break; - }; - var sev = std.mem.zeroes(c.SDL_Event); - pardes.turn.rest(); - var got = c.SDL_WaitEventTimeout(&sev, ms); - pardes.turn.wake(); - while (got) : (got = c.SDL_PollEvent(&sev)) { - if (sev.type == c.SDL_EVENT_QUIT) core.quit = true; - } -} - -fn pollFrame(ctx: ?*anyopaque) void { - const s = shellOf(ctx); - s.reconcilePtys(); - const core = s.core; - if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); - // The authority owns its terminals even with its window closed. - pollCwds(core, s.ptys); - const g = s.gui orelse { - if (core.settings.window_opacity_pending) { - var unchanged_opacity: u8 = 100; - finishWindowOpacity(core, &unchanged_opacity, if (core.settings.window_opacity == 100) null else "requires a native SDL window"); - } - return; - }; - // A replica client's view live: the window's own view back before what - // the window does to it (its size, its scroll, its font). - if (core.live != s.gview) { - const geom = windowCells(g); - const due = g.scroll_pane != null or g.scroll_notch != 0 or g.glide.moving() or - core.settings.font.tagline_percent != g.tagline_percent or core.settings.font.pending or - (if (core.views[s.gview]) |*own| resizeOf(own, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height) != null else false); - if (due) _ = s.windowView(); - } - syncWindowOpacity(g, core); - core.frames.period_ns = refreshNs(g); - syncTaglineFont(g, core); - if (core.takeFontRequest()) |path| blk: { - const bytes = filesystem.readFile(s.gpa, path) catch { - core.rejectFont(); - break :blk; - }; - if (!g.atlas.setFont(s.gpa, bytes)) { - log.err("ui_font_new failed: {s}", .{path}); - core.rejectFont(); - break :blk; - } - if (core.settings.font.requested_size_hundredths != 0) - g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100; - setGuiFontName(g, core.settings.font.requested_name.get()); - refitFont(g, core); - acknowledgeGuiFont(g, core); - } - const geom = windowCells(g); - if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g); - stepScroll(g, core, s.gpa); - if (s.test_mode) writeTestStatus(g, core, s.presented); - // A blink edge, or the window's own motion (its glide, its caret, a - // jump's trail): the last frame again, moved on, no core render. - if ((g.blink_due or frontendMoving(g)) and !core.needs_frame and s.presented) if (s.surface) |frame| { - g.blink_due = false; - g.now_ns = s.ownNow(); - s.presented = renderFrame(g, s.gpa, core, frame) catch false; - }; -} - -/// PARDES_FRAMES_CAPTURE's directory, and how many frames it has. -var frame_capture_dir: ?[]const u8 = null; -var frame_capture_count: u32 = 0; - -fn captureSeries(pixels: []const u8, w: u32, h: u32) void { - const dir = frame_capture_dir orelse return; - var path_buf: [4096]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{d:0>6}.bgra", .{ dir, frame_capture_count }, 0) catch return; - const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, pixels.ptr, pixels.len); - _ = libc.close(fd); - const times = std.fmt.bufPrintSentinel(&path_buf, "{s}/times.txt", .{dir}, 0) catch return; - const tf = libc.open(times, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, @as(libc.mode_t, 0o644)); - if (tf < 0) return; - var line_buf: [96]u8 = undefined; - const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}\n", .{ frame_capture_count, monoNs(), w, h }) catch unreachable; // four numbers fit 96 - _ = libc.write(tf, line.ptr, line.len); - _ = libc.close(tf); - frame_capture_count += 1; -} - -/// The core's frame probe (FrameStats), for the latency of the inputs the -/// shell reads and the zones its own work goes in; null in tests. -var frame_probe: ?*pardes.FrameStats = null; - -/// How long until the timedemo's next step, ms; null when none runs. -fn demoDue(g: *const Gui) ?c_int { - const next = g.demo_next orelse return null; - if (g.demo_start_ns == 0 or next >= g.demo.len) return 0; - const at = g.demo_start_ns + @as(u64, g.demo[next].at_ms) * std.time.ns_per_ms; - return @intCast(@min(std.math.maxInt(c_int), (at -| monoNs()) / std.time.ns_per_ms)); -} - -/// PARDES_FRAMES_DEMO: the steps of FrameStats.demo whose time has come, -/// through the paths the window's own wheel and keys take, over the -/// focused pane's body; its clock starts at the first loop. Its end -/// ends the session (PARDES_FRAMES has the timings then). -fn runDemo(g: *Gui, in: *Input, core: *pardes.Pardes) void { - const v = core.view(); - const steps = g.demo; - var next = g.demo_next orelse return; - const now = monoNs(); - if (g.demo_start_ns == 0) { - g.demo_start_ns = now; - core.frames.demo_ns = now; - core.frames.demo = g.demo; - } - defer g.demo_next = next; - while (next < steps.len and g.demo_start_ns + @as(u64, steps[next].at_ms) * std.time.ns_per_ms <= now) : (next += 1) { - const r = v.rects[v.active]; - if (steps[next].act != .phase) g.input_seen = true; - switch (steps[next].act) { - .wheel => |notches| { - core.frames.input(now); - wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); - }, - .touch => |lines| { - core.frames.input(now); - wheelAt(g, in, .{ .y = -lines }, .{ .col = r.x + r.w / 2, .row = r.y + r.h / 2 }); - }, - .key => |key| { - core.frames.input(now); - in.post(.{ .key = key }); - }, - .phase => {}, - .click => |click| { - core.frames.input(now); - const pane = core.panes[v.active] orelse continue; - const top = core.bodyTop(pane, r); - const row: u16 = top + @as(u16, @intFromFloat(click.at * @as(f32, @floatFromInt(r.h -| pane.tag_rows -| 1)))); - const col: u16 = if (click.rail) r.x else r.x + config.GUTTER + 4; - for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| in.post(.{ .mouse = .{ .button = click.button, .kind = kind, .col = col, .row = row } }); - }, - .rail_wheel => |notches| { - core.frames.input(now); - wheelAt(g, in, .{ .y = @floatFromInt(-notches), .integer_y = -notches }, .{ .col = r.x, .row = r.y + r.h / 2 }); - }, - .paste => |text| { - core.frames.input(now); - in.post(.{ .paste = text }); - }, - .exec => |line| { - core.frames.input(now); - var newest: u32 = 0; - for (core.panes) |slot| if (slot) |pane| { - newest = @max(newest, pane.serial); - }; - _ = pardes.exec.executeFrom(core, v.active, line, false); - // What it opened is what the next steps scroll. - for (core.panes, 0..) |slot, id| if (slot) |pane| if (pane.serial > newest) { - v.active = id; - core.needs_frame = true; - }; - }, - .end => in.close(), - } - } -} - -/// The blink now, from the frame's time since input and how long ago it -/// arrived; null where nothing blinks (off, idle, an unfocused window). -/// The cursor's opacity under blink: solid while typing and for -/// `hold_ns` after, then on and off with an eased edge, solid again after -/// `idle_ns` of no input. `edge` says whether it is mid-edge (a frame is -/// owed), `next_ns` when the next edge starts (a wake). -pub const Blink = struct { - pub const hold_ns: u64 = 500 * std.time.ns_per_ms; - pub const idle_ns: u64 = 10 * std.time.ns_per_s; - pub const half_ns: u64 = 530 * std.time.ns_per_ms; - pub const edge_ns: u64 = 80 * std.time.ns_per_ms; - - alpha: f32, - edge: bool, - next_ns: ?u64, - - pub fn at(now_ns: u64, input_ns: u64) Blink { - const since = now_ns -| input_ns; - if (since < hold_ns) return .{ .alpha = 1, .edge = false, .next_ns = input_ns + hold_ns + half_ns - edge_ns }; - if (since >= hold_ns + idle_ns) return .{ .alpha = 1, .edge = false, .next_ns = null }; - const t = (since - hold_ns) % (2 * half_ns); - const cycle_start = now_ns - t; - // On for a half, easing out over its last `edge_ns`; off for a half, - // easing back in over its last. - if (t < half_ns - edge_ns) return .{ .alpha = 1, .edge = false, .next_ns = cycle_start + half_ns - edge_ns }; - if (t < half_ns) return .{ .alpha = 1 - smooth(@as(f32, @floatFromInt(t - (half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; - if (t < 2 * half_ns - edge_ns) return .{ .alpha = 0, .edge = false, .next_ns = cycle_start + 2 * half_ns - edge_ns }; - return .{ .alpha = smooth(@as(f32, @floatFromInt(t - (2 * half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; - } - - fn smooth(x: f32) f32 { - const u = std.math.clamp(x, 0, 1); - return u * u * (3 - 2 * u); - } -}; - -fn blinkNow(g: *const Gui, on: bool) ?Blink { - if (g.no_blink or !on or !g.caret.placed) return null; - if (c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_INPUT_FOCUS == 0) return null; - const since = monoNs() -| g.input_ns; - // Relative to now: `next_ns` is how long until the next edge. - const b = Blink.at(since, 0); - return .{ .alpha = b.alpha, .edge = b.edge, .next_ns = if (b.next_ns) |next| next -| since else null }; -} - -/// One refresh of the display the window is on, in ns; a frame of the -/// core's where the display does not say. -fn refreshNs(g: *const Gui) u64 { - const mode = c.SDL_GetCurrentDisplayMode(c.SDL_GetDisplayForWindow(g.window)) orelse return pardes.frame_ns; - if (!(mode.*.refresh_rate > 1)) return pardes.frame_ns; - return @intFromFloat(@as(f64, std.time.ns_per_s) / mode.*.refresh_rate); -} - -fn finishWindowOpacity(core: *pardes.Pardes, applied: *u8, failure: ?[]const u8) void { - core.windowOpacityDone(applied.*, failure); - applied.* = core.settings.window_opacity; -} - -fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void { - if (!core.settings.window_opacity_pending) return; - // The first opacity under 100 on Wayland: the window made again, - // transparent, presenting through SDL_Renderer from then on (the - // capture's format, the swapchain's, is one it uploads). At a start's - // own WindowOpacity this is before its first frame, so unseen. - const unorm = g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM or g.present.swapchain_format == c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; - if (g.wayland and !g.present.surface_opacity and core.settings.window_opacity < 100 and unorm) { - // A `--detach` session's window stays hidden. - const hidden = c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_HIDDEN; - const mode = g.present.present_mode; - closeWindow(g); - g.present.soft_present = true; - g.present.surface_opacity = true; - g.present.present_mode = c.SDL_GPU_PRESENTMODE_VSYNC; - g.win_flags |= c.SDL_WINDOW_TRANSPARENT | hidden; - log.info("WindowOpacity under 100: the window made again, transparent, presenting through SDL_Renderer", .{}); - if (!reopenWindow(g)) { - // No renderer for it: opaque again, as it was. - g.present.soft_present = false; - g.present.surface_opacity = false; - g.present.present_mode = mode; - g.win_flags &= ~@as(c.SDL_WindowFlags, c.SDL_WINDOW_TRANSPARENT); - if (!reopenWindow(g)) core.quit = true; - } - g.win_flags &= ~hidden; - } - // Offscreen captures also support per-pixel alpha. Never approximate this - // with SDL_SetWindowOpacity: that would make foreground text translucent. - finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100) - null - else - "background transparency requires a native Wayland or alpha-capable SDL window"); -} - -fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { - const s = shellOf(ctx); - const core = s.core; - // A replica client draws outside the pump, which marks it there. - if (s.client != null) core.frames.mark_render = pardes.FrameStats.nowNs(); - const g = s.gui orelse return; - frame_started_ns = monoNs(); - const frame = surface; - s.surface = frame; - g.frame_arrival_ns = monoNs(); - g.now_ns = s.ownNow(); - s.presented = renderFrame(g, s.gpa, core, frame) catch |err| blk: { - log.err("render: {t}", .{err}); - break :blk false; - }; - // A skipped swapchain image would otherwise hide this input's frame until - // the next event. A few retries only: a minimized window never gets one. - s.skipped_presents = if (s.presented) 0 else s.skipped_presents +| 1; - if (!s.presented and s.skipped_presents <= 3) core.present_skipped = true; -} - -/// The gamepad subsystem, started once the first frame is drawn, as the -/// loop first waits: its scan (udev, hidapi, libusb) took 40 ms of a start. -/// A pad plugged in already is added by it (GAMEPAD_ADDED). -fn startGamepads(g: *Gui) void { - if (g.gamepads) return; - g.gamepads = true; - if (!c.SDL_InitSubSystem(c.SDL_INIT_GAMEPAD)) log.warn("SDL_InitSubSystem(GAMEPAD): {s}", .{c.SDL_GetError()}); -} - -fn postPresent(ctx: ?*anyopaque) void { - const s = shellOf(ctx); - const g = s.gui orelse return; - // No image (a minimized window): nothing was drawn to point at. - if (!s.presented) return; - // A client's view live: the window's frame counts when its own view is - // live and drawn. - if (s.core.live != s.gview) return; - var in: Input = .{ .core = s.core }; - refreshPresentedPointer(g, &in); - s.core.presented(); -} - -fn guiNow(ctx: ?*anyopaque) u64 { - const s = shellOf(ctx); - if (s.waited) { - s.waited = false; - if (s.mail_only and s.peers.count() > 0 and s.core.clock.started) return s.core.clock.now_ns; - } - return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); -} - -fn spawnPane(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { - const s = shellOf(ctx); - if (s.adoptions.take(pane)) |a| return takeShell(s, pane, a); - // The new shell starts before a running one goes: one that cannot - // start leaves the running one be (pty/ctl's exec). - const running = s.ptys[pane] != null; - const child = host_io.forkShell(s.core, pane, s.prompt_rcs, s.core.shellBin(), cwd, s.core.view().screen_h, s.core.view().screen_w) catch |err| { - if (running) return s.core.restartFailed(pane, err); - return s.core.shellFailed(pane, err); - }; - s.closePty(pane); - if (s.ptys[pane] != null) { - _ = libc.close(child.file.handle); - host_io.retireShell(child.pid); - return s.core.reportError(pane, "shell", error.WorkersBusy); - } - s.gens[pane] +%= 1; - const command = s.core.panes[pane].?.command != null; - const pt: Pty = .{ .fd = child.file.handle, .pid = child.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{ .watched = command and host_io.watchExit(child.pid), .fd = child.file.handle } }; - s.ptys[pane] = pt; - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(pt.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - if (!s.threads_ok) return; - s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { - s.closePty(pane); - return s.core.reportError(pane, "terminal reader", err); - }; -} - -/// An adopted shell, running already, as pane `pane`'s: told the size twice -/// (one it never had, then the pane's), which makes it redraw. -fn takeShell(s: *Shell, pane: u8, a: host_io.Adoption) void { - s.closePty(pane); - s.gens[pane] +%= 1; - s.ptys[pane] = .{ .fd = a.fd, .pid = a.pid, .serial = s.core.panes[pane].?.serial, .cmd = .{} }; - var exe_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - s.core.acknowledgeShell(pane, host_io.processExe(a.pid, &exe_buf) orelse "sh", host_io.marksPrompts(a.pid)); - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.shellCwd(a.pid, &lbuf)) |wd| s.core.setCwd(pane, wd); - const tiny: posix.winsize = .{ .row = 1, .col = 1, .xpixel = 0, .ypixel = 0 }; - _ = posix.system.ioctl(a.fd, TIOCSWINSZ, @intFromPtr(&tiny)); - if (s.core.panes[pane]) |pn| ptyResize(s, pane, @max(pn.cols, 1), @max(pn.rows, 1)); - if (!s.threads_ok) return; - s.ptys[pane].?.reader = s.queue.startReader(.{ .handle = a.fd, .flags = .{ .nonblocking = false } }, pane, s.gens[pane]) catch |err| { - s.closePty(pane); - return s.core.reportError(pane, "terminal reader", err); - }; -} - -/// The daemon's thread: what it says, onto the queue (drainQueue). -fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const s: *Shell = @ptrCast(@alignCast(ctx)); - const q = s.queue; - switch (note) { - .attach => |a| { - // A terminal for a window session: the daemon refuses that kind - // before it is sent, so only an old one's would be here. - if (a.tty >= 0) _ = libc.close(a.tty); - if (a.stub >= 0) daemon.tellStub(a.stub, "r{s}", .{"a window session takes no terminal"}); - if (a.tty < 0) q.push(.window); - }, - .adopted => |a| { - for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); - q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); - }, - // Joined at the next step boundary (Peers, any thread). - .replica => |j| s.peers.handed(j.fd, j.view), - } -} - -fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { - const s = shellOf(ctx); - if (s.ptys[pane]) |pt| _ = host_io.writeFd(pt.fd, bytes); -} - -fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { - const s = shellOf(ctx); - if (s.ptys[pane]) |pt| { - const ws = host_io.ptyWinsize(s.core, cols, rows); - _ = posix.system.ioctl(pt.fd, TIOCSWINSZ, @intFromPtr(&ws)); - } -} - -fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { - const s = shellOf(ctx); - // A command whose exit is recorded is reaped: its group may be another's. - if (s.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.fd, sig, pt.cmd.watched); -} - -fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.ttyTaken(pt.pid, pt.fd); -} - -fn fgName(ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 { - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return null; - return host_io.foregroundName(pt.pid, pt.fd, buf); -} - -fn killJob(ctx: ?*anyopaque, pane: u8) bool { - const s = shellOf(ctx); - const pt = s.ptys[pane] orelse return false; - return host_io.killJob(pt.pid, pt.fd); -} - -fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { - const s = shellOf(ctx); - host_io.writeFile(s.core, s.watches, pane, path, bytes); -} - -fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { - host_io.writeDump(shellOf(ctx).core, bytes); -} - -fn watchFile(ctx: ?*anyopaque, pane: u8, _: []const u8, on: bool, mode: pardes.WatchMode) void { - const s = shellOf(ctx); - if (file_watch.applyEffect(s.core, s.io, s.inotify_fd, s.watches, pane, on, mode)) - s.queue.push(.files_changed); -} - -fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { - const s = shellOf(ctx); - if (file_watch.applyThemeEffect( - s.core, - s.gpa, - s.inotify_fd, - s.watches, - generation, - on, - )) s.queue.push(.files_changed); -} - -fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { - const s = shellOf(ctx); - host_io.dumpThemes(s.core, s.io, s.gpa, pane); -} - -fn putClipboard(gpa: std.mem.Allocator, text: []const u8) void { - const z = gpa.dupeSentinel(u8, text, 0) catch return; - defer gpa.free(z); - _ = c.SDL_SetClipboardText(z.ptr); -} - -fn takeClipboard() ?[:0]u8 { - const raw = c.SDL_GetClipboardText() orelse return null; - const text = std.mem.span(raw); - if (text.len == 0) { - c.SDL_free(raw); - return null; - } - return text; -} - -fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { - putClipboard(shellOf(ctx).gpa, text); -} - -fn readClipboard(ctx: ?*anyopaque) void { - const text = takeClipboard() orelse return; - defer c.SDL_free(text.ptr); - shellOf(ctx).core.update(.{ .paste = text }); -} - -fn openLink(ctx: ?*anyopaque, url: []const u8) void { - _ = ctx; - look.openLink(url); // desktop browser -} - -fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { - const s = shellOf(ctx); - if (s.threads_ok) return s.queue.startLsp(s.core, req); - s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); - s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); -} - -fn pipe(ctx: ?*anyopaque, id: u32) void { - const s = shellOf(ctx); - if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe); - s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); - s.core.reportError(s.core.view().active, "pipe", error.WorkersUnavailable); -} - -/// A draw (api.draw) on a worker, as a job is. -fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { - const s = shellOf(ctx); - return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob); -} - -fn kindJob(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { - const s = shellOf(ctx); - if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob); - host_io.KindJob.runHere(s.core, pane, serial, token); -} - -fn search(ctx: ?*anyopaque, gen: u32) void { - const s = shellOf(ctx); - if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.queue, Queue.pushSearch); - pardes.Stream.runHere(s.core, gen); -} - -/// Handover `seq`'s dump to its file, and a worker to carry it to another -/// window (Handover.start). A new window is as big as this one, and where -/// the pointer let go of it when the display lets a window say where it -/// goes (X11; on Wayland the compositor places it). -fn handOver(ctx: ?*anyopaque, seq: u32, bytes: []const u8) void { - const s = shellOf(ctx); - const Handover = pardes.Handover; - const path = Handover.dumpPath(s.gpa, seq) catch |err| return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); - // A dump not written, or not carried, goes: what failed is said. - const cwd = std.Io.Dir.cwd(); - cwd.writeFile(s.io, .{ .sub_path = path, .data = bytes, .flags = .{ .permissions = .fromMode(0o600) } }) catch { - cwd.deleteFile(s.io, path) catch {}; - s.gpa.free(path); - return s.core.update(.{ .handed = .{ .seq = seq, .failure = "cannot write its dump" } }); - }; - const job = s.gpa.create(Handover.Job) catch { - cwd.deleteFile(s.io, path) catch {}; - s.gpa.free(path); - return s.core.update(.{ .handed = .{ .seq = seq, .failure = "out of memory" } }); - }; - job.* = .{ .gpa = s.gpa, .seq = seq, .path = path, .post = Queue.pushHanded, .post_ctx = s.queue }; - if (s.fs) |f| { - job.own_len = @min(f.path().len, job.own.len); - @memcpy(job.own[0..job.own_len], f.path()[0..job.own_len]); - } - if (s.gui) |g| { - var w: c_int = 0; - var h: c_int = 0; - _ = c.SDL_GetWindowSize(g.window, &w, &h); - var gx: f32 = 0; - var gy: f32 = 0; - _ = c.SDL_GetGlobalMouseState(&gx, &gy); - const placed = !std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); - const geometry = (if (placed) - std.fmt.bufPrint(&job.geometry, "{d}x{d}+{d}+{d}", .{ w, h, @as(i32, @intFromFloat(gx)) - 40, @as(i32, @intFromFloat(gy)) - 10 }) - else - std.fmt.bufPrint(&job.geometry, "{d}x{d}", .{ w, h })) catch unreachable; // four c_ints fit 64 - job.geometry_len = geometry.len; - } - s.core.handover.start(s.io, job) catch |err| { - cwd.deleteFile(s.io, path) catch {}; - s.gpa.free(path); - s.gpa.destroy(job); - return s.core.update(.{ .handed = .{ .seq = seq, .failure = @errorName(err) } }); - }; -} - -fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { - for (ptys, 0..) |slot, id| if (slot) |pt| { - var lbuf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - if (host_io.ttyCwd(pt.pid, pt.fd, core.settings.shell.effective.get(), &lbuf)) |cwd| core.setCwd(id, cwd); - }; -} - -fn accumulateWheelDelta(pending: f32, raw_y: f32) f32 { - if (!std.math.isFinite(raw_y)) return pending; - const next = pending - raw_y; - return if (std.math.isFinite(next)) next else pending; -} - -fn boundScrollDelta(lag: f32, delta: f32, body_rows: u16) f32 { - const limit: f32 = @floatFromInt(body_rows); - return std.math.clamp(lag + delta, -limit, limit) - lag; -} - -fn applyScrollDelta(lag: f32, delta: f32) struct { lag: f32, rows: i32 } { - var l = lag + delta; - var rows: i32 = 0; - while ((delta > 0 and l > 0) or (delta < 0 and l < 0)) { - const down = l > 0; - l += if (down) -1 else 1; - rows += if (down) 1 else -1; - } - return .{ .lag = l, .rows = rows }; -} - -/// A mouse wheel's step as whole lines (down positive), or null for a -/// touchpad's fraction, which follows the finger as it is. -fn notchOf(raw_y: f32, integer_y: i32) ?i32 { - if (!std.math.isFinite(raw_y) or integer_y == 0 or raw_y != @round(raw_y)) return null; - return @intFromFloat(std.math.clamp(-raw_y, -64, 64)); -} - -const Glide = pardes.glide.Glide; - -/// Feeds a wheel's notches to the core, and keeps what moved the view for -/// the frame's glide (Glide.frame). -fn stepGlide(g: *Gui, core: *pardes.Pardes) void { - const notch = g.scroll_notch; - g.scroll_notch = 0; - var wheeled: ?usize = null; - if (notch != 0) wheel: { - const id = g.scroll_pane orelse break :wheel; - const pane = core.panes[id] orelse { - resetScroll(g); - break :wheel; - }; - const r = core.view().rects[id]; - if (r.h <= pane.tag_rows or r.w <= config.GUTTER) { - resetScroll(g); - break :wheel; - } - var left = notch; - while (left != 0) { - const down = left > 0; - left += if (down) -1 else 1; - const was = pane.scroll(); - // Shift: pardes's own scroll, never a program's wheel. - core.update(.{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, .col = g.scroll_col, .row = g.scroll_row, .shift = true } }); - if (pane.scroll() == was) break; - wheeled = id; - } - if (wheeled != null) core.needs_frame = true; - } - if (wheeled != null) g.glide_wheeled = wheeled; - // Not a view a touchpad is moving by the pixel. - g.glide_direct = if (g.scroll_lag != 0 or g.scroll_delta != 0) g.scroll_pane else null; -} - -/// The window's own motions under way (its glide, its caret, a jump's -/// trail): it draws their frames itself, on its own clock. -fn frontendMoving(g: *const Gui) bool { - return g.glide.moving() or g.caret.moving() or g.trail.active; -} - -/// The frame's glide (Glide.frame) on the window's clock, with what moved -/// its view since the last. -fn glideFrame(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { - g.glide.frame(gpa, surface, g.now_ns, g.glide_wheeled, g.glide_direct); - g.glide_wheeled = null; -} - -/// The window's loop over a text pane under a wheel, as waitInput and the -/// pump run it but with no window: a frame's turns (wheelAt), pollFrame's -/// stepScroll, and a frame drawn only when one is owed (the core's -/// needs_frame, or the window's own motion). `drawn` is the picture the -/// window shows, its first line and its offset, as of the last frame drawn; -/// `now` the picture as the window holds it. -const WheelRun = struct { - g: Gui, - core: *pardes.Pardes, - arena: std.heap.ArenaAllocator, - mc: MouseCell, - drawn: f32 = 0, - now_ns: u64 = std.time.ns_per_s, - - fn init(gpa: std.mem.Allocator, core: *pardes.Pardes) !WheelRun { - var wr: WheelRun = .{ .g = testGui(10, 20, 6, 12), .core = core, .arena = .init(gpa), .mc = undefined }; - const r = core.view().rects[core.view().active]; - wr.mc = .{ .col = r.x + 10, .row = r.y + r.h / 2 }; - core.advance(wr.now_ns); - _ = try core.render(wr.arena.allocator()); - try wr.frame(gpa, &.{}); - return wr; - } - - fn deinit(wr: *WheelRun, gpa: std.mem.Allocator) void { - wr.g.glide.deinit(gpa); - gpa.free(wr.g.scroll_edge); - wr.arena.deinit(); - } - - /// The picture as the window holds it now, in lines. - fn picture(wr: *const WheelRun) f32 { - const line: f32 = @floatFromInt(wr.core.panes[wr.core.view().active].?.scroll()); - return line + if (wr.g.glide.follow.offset != 0) wr.g.glide.follow.offset else wr.g.scroll_lag; - } - - /// One frame: SDL's turns (up positive), then a frame if one is owed. - fn frame(wr: *WheelRun, gpa: std.mem.Allocator, turns: []const f32) !void { - var in: Input = .{ .core = wr.core }; - for (turns) |y| wheelAt(&wr.g, &in, .{ .y = y, .integer_y = @intFromFloat(@trunc(y)) }, wr.mc); - wr.now_ns += std.time.ns_per_s / 60; - wr.core.advance(wr.now_ns); - stepScroll(&wr.g, wr.core, gpa); - if (!wr.core.needs_frame and !frontendMoving(&wr.g)) return; - _ = wr.arena.reset(.retain_capacity); - const s = try wr.core.render(wr.arena.allocator()); - wr.g.now_ns = wr.now_ns; - glideFrame(&wr.g, gpa, s); - wr.core.needs_frame = false; - wr.drawn = wr.picture(); - } -}; - -/// The scripted scroll sequence of the glide tests: a frame a 60 Hz -/// refresh, as the paced loop draws them (waitInput, then stepGlide, the -/// core's render and the frame's measure), an input on the frames `script` -/// names; each frame's picture offset and the core's first line. -const GlideRun = struct { - const Step = struct { frame: usize, key: pardes.Key }; - offsets: [600]f32 = undefined, - lines: [600]i64 = undefined, - carets: [600]f32 = undefined, - cells: [600]f32 = undefined, - frames: usize = 0, - - fn play(seq: *GlideRun, g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator, arena: *std.heap.ArenaAllocator, script: []const Step, frames: usize) !void { - var now: u64 = core.clock.now_ns; - var next: usize = 0; - for (0..frames) |frame| { - while (next < script.len and script[next].frame == frame) : (next += 1) core.update(.{ .key = script[next].key }); - now += std.time.ns_per_s / 60; - core.advance(now); - stepGlide(g, core); - _ = arena.reset(.retain_capacity); - const s = try core.render(arena.allocator()); - g.now_ns = now; - glideFrame(g, gpa, s); - seeCaret(g, s, fixedCellLayout(g), @floatFromInt(@as(u32, s.rows) * g.cell_h), now); - seq.offsets[frame] = g.glide.follow.offset; - seq.lines[frame] = @intCast(core.panes[core.view().active].?.file.?.scroll); - seq.carets[frame] = caretRow(g, s, now) orelse -1; - seq.cells[frame] = if (s.cursor) |cu| @floatFromInt(cu.y) else -1; - } - seq.frames = frames; - } - - /// The caret's invariants over the run: while its cell stays and it is - /// on it, it does not move a pixel; it only ever closes on its cell (a - /// twentieth of a row of play for a jump's bow); it lands within half a - /// second of its last change. - fn checkCaret(seq: *const GlideRun) !void { - var changed: usize = 0; - for (1..seq.frames) |k| { - if (seq.cells[k] < 0 or seq.cells[k - 1] < 0) continue; - if (seq.cells[k] != seq.cells[k - 1]) changed = k; - if (seq.cells[k] == seq.cells[k - 1] and seq.carets[k - 1] == seq.cells[k - 1]) try std.testing.expectEqual(seq.carets[k - 1], seq.carets[k]); - try std.testing.expect(@abs(seq.carets[k] - seq.cells[k]) <= @abs(seq.carets[k - 1] - seq.cells[k]) + 0.05); - if (k - changed == 30) try std.testing.expectEqual(seq.cells[k], seq.carets[k]); - } - } - - /// Frames from `from` until the picture is still: the scroll's glide. - fn settle(seq: *const GlideRun, from: usize) usize { - var k = from; - while (k < seq.frames and seq.offsets[k] != 0) k += 1; - return k - from; - } -}; - -fn resetScroll(g: *Gui) void { - g.scroll_pane = null; - g.scroll_delta = 0; - g.scroll_lag = 0; - g.scroll_idle = 0; - g.scroll_edge_len = 0; - g.scroll_notch = 0; - g.glide.stop(); -} - -/// Loop steps with no turn before a resting fraction settles; the share of -/// what is left a step takes (the glide's spring over a 60 Hz frame, -/// Follow.omega); and what is close enough to land on at once (under a -/// pixel of a row). -const settle_after = 2; -const settle_step: f32 = 1 - @exp(-pardes.glide.Follow.omega / 60.0); -const settle_land: f32 = 0.02; - -fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { - stepGlide(g, core); - var in: Input = .{ .core = core }; - _ = scrollRows(g, &in, gpa); -} - -/// A touchpad's fraction: the picture moved by it, and each whole row it -/// crosses posted to `in` (a replica client's go to its link, applied -/// after its view is parked again). True when the picture moved. -fn scrollRows(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { - const core = in.core; - const id = g.scroll_pane orelse return false; - const pane = core.panes[id] orelse { - resetScroll(g); - return false; - }; - // A fine wheel's or a touchpad's turns stopped (SDL tells no gesture's - // end): the picture eases the rest of the way onto the core's row, on - // the glide's law, a step a frame, so it never rests a fraction of a - // row off its cells. The core's row is the next whole row the way the - // turns went (the lag is behind it going down, ahead going up), so the - // settle never moves against them; a turn mid-settle goes on from it. - if (g.scroll_delta != 0) { - g.scroll_idle = 0; - } else if (g.scroll_lag != 0 and g.glide.follow.offset == 0) { - g.scroll_idle +|= 1; - if (g.scroll_idle > settle_after) - g.scroll_delta = if (@abs(g.scroll_lag) < settle_land) -g.scroll_lag else -g.scroll_lag * settle_step; - } - const queued_delta = g.scroll_delta; - g.scroll_delta = 0; - if (queued_delta == 0) { - if (g.scroll_lag == 0 and g.scroll_notch == 0 and !g.glide.moving()) resetScroll(g); - return false; - } - const r = core.view().rects[id]; - if (r.h <= pane.tag_rows) { - resetScroll(g); - return false; - } - const delta = boundScrollDelta(g.scroll_lag, queued_delta, r.h - pane.tag_rows); - const st = applyScrollDelta(g.scroll_lag, delta); - var left = st.rows; - while (left != 0) { - const down = left > 0; - left += if (down) -1 else 1; - const was = pane.scroll(); - in.post(.{ - .mouse = .{ - .button = if (down) .wheel_down else .wheel_up, - .kind = .press, - .col = g.scroll_col, - .row = g.scroll_row, - .shift = true, // pardes's own scroll, never a program's wheel - }, - }); - // A replica client's rows apply after its view is parked again: - // its scroll has not moved yet. - if (in.client == null and pane.scroll() == was) { - resetScroll(g); - return false; - } - } - // The picture moved, by a fraction or back onto the core's row with - // the core where it was: that is a frame too, or the window rests on - // the last one, a fraction of a row off, and the next turn's frame - // jumps from there (against the turn when it reverses). - const moved = st.rows != 0 or st.lag != g.scroll_lag; - if (moved and in.client == null) core.needs_frame = true; - g.scroll_lag = st.lag; - g.scroll_rect = r; - const body_y = core.bodyTop(pane, r); - g.scroll_body_y = body_y; - g.scroll_body_h = r.h -| pane.tag_rows; - if (st.rows != 0) { - const s = &core.surface; - g.scroll_edge_len = 0; - if (r.w > config.GUTTER and r.h > pane.tag_rows and r.x + r.w <= s.cols) { - const bw = r.w - config.GUTTER; - const bh = g.scroll_body_h; - const k: u16 = @intCast(@min(@abs(st.rows), @as(i32, bh))); - const held = @min(pane.context_rows, bh - k); - const srow = body_y + (if (st.rows > 0) held + k - 1 else bh - k); - if (srow < s.rows) { - if (g.scroll_edge.len < bw) { - gpa.free(g.scroll_edge); - g.scroll_edge = gpa.alloc(pardes.Cell, bw) catch &.{}; - } - if (g.scroll_edge.len >= bw) { - @memcpy(g.scroll_edge[0..bw], s.cells[@as(usize, srow) * s.cols + r.x + config.GUTTER ..][0..bw]); - g.scroll_edge_len = bw; - } - } - } - } - if (g.scroll_lag == 0) resetScroll(g); - return moved; -} - -/// A scrolling body's picture: its rows moved by the lag, a glide's or a -/// touchpad's fraction of a row, and in the gap that opens the rows that -/// left. -fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: [3]u8, held: u16) u32 { - g.scroll_held_px = 0; - const glide = &g.glide; - const gliding = glide.follow.offset != 0; - const pane = if (gliding) glide.pane else g.scroll_pane orelse return 0; - const lag = if (gliding) glide.follow.offset else g.scroll_lag; - if (lag == 0) return 0; - const r = if (gliding) glide.rect else g.scroll_rect; - const bh = if (gliding) glide.body_h else g.scroll_body_h; - const y0 = if (gliding) glide.body_y else g.scroll_body_y; - const bw = r.w -| config.GUTTER; - const x0 = r.x + config.GUTTER; - if (bw == 0 or bh == 0 or x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us - // The scissor the shifted rows are drawn in is the scroll's. - g.scroll_rect = r; - g.scroll_body_y = y0; - g.scroll_body_h = bh; - var shifted = layout; - shifted.y_off -= lag * layout.h; - const kept = holdContext(g, surface, pane, held, bh, layout); - shifted.y_off += kept.lift; - // Only the rows the scissor shows: lagging a body or more, every body - // row is past the edge, and drawing them all was twice the frame's - // instances for the length of a long glide. - const gone: u16 = @intFromFloat(@min(@floor(@abs(lag)), @as(f32, @floatFromInt(bh)))); - var row = y0 + kept.rows + if (lag > 0) gone else 0; - const row_end = y0 + bh - if (lag < 0) gone else 0; - // A touchpad's block caret moves with its row; a glide's is drawn from - // its own springs (the quad), never carried by the text. - const caret: u32 = if (surface.cursor) |cu| (if (gliding or cu.bar) std.math.maxInt(u32) else @as(u32, cu.y) * surface.cols + cu.x) else std.math.maxInt(u32); - var n: u32 = 0; - while (row < row_end) : (row += 1) { - const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; - const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; - var col = x0; - while (col < x0 + bw) : (col += 1) { - emitInstance(g, instances, base + n, col, row, shifted, win_w, win_h, cellFontRole(&line[col]), line, col, row_cursor, @as(u32, row) * surface.cols + col == caret, page); - n += 1; - } - } - // A body layer's held rows are compact, so it has rows past the grid's - // (lifted into the body by what they save): the moving rows go on with - // them, or the band under the grid's last row shows the layer's, still. - if (pane < surface.body_layers.len and surface.body_layers[pane].context_rows != 0) { - const layer = &surface.body_layers[pane]; - if (layer.cols == bw) for (bh..layer.rows) |k| { - const line = layer.cells[k * layer.cols ..][0..layer.cols]; - for (0..bw) |c_i| { - emitInstance(g, instances, base + n, x0 + @as(u16, @intCast(c_i)), y0 + @as(u16, @intCast(k)), shifted, win_w, win_h, cellFontRole(&line[c_i]), line, c_i, null, false, page); - n += 1; - } - }; - } - if (!gliding) { - // A touchpad's fraction opens one row, the one that left: under the - // held rows, where the moving rows start. - if (g.scroll_edge_len >= bw) { - const erow: u16 = if (lag > 0) y0 + bh else y0 + kept.rows - 1; - var i: u16 = 0; - while (i < bw) : (i += 1) { - emitInstance(g, instances, base + n, x0 + i, erow, shifted, win_w, win_h, cellFontRole(&g.scroll_edge[i]), g.scroll_edge[0..bw], i, null, false, page); - n += 1; - } - } - return n; - } - // A glide's: rows past the top while the picture lags a move down, past - // the bottom for one up; as many as it opens. - const gap: u16 = @intFromFloat(@min(@ceil(@abs(lag)), @as(f32, @floatFromInt(@as(u32, bh) * Glide.reach)))); - const nkept = if (lag < 0) glide.nabove else glide.nbelow; - const rows = if (lag < 0) glide.above else glide.below; - for (0..@min(gap, nkept)) |i| { - const cells = rows[i * bw ..][0..bw]; - // Row -1 - i above the moving rows (under the held ones), or bh + i - // below the body, in grid rows. - const at_row: i32 = if (lag < 0) @as(i32, y0 + kept.rows) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); - var at = shifted; - // emitInstance takes an unsigned row: move the layout instead. - at.y_off += @as(f32, @floatFromInt(at_row - @as(i32, y0))) * layout.h; - for (0..bw) |c_i| { - emitInstance(g, instances, base + n, x0 + @as(u16, @intCast(c_i)), y0, at, win_w, win_h, cellFontRole(&cells[c_i]), cells, c_i, null, false, page); - n += 1; - } - } - return n; -} - -/// A scrolling body's tree-sitter context rows hold still: the shifted -/// rows start under them and are clipped below their band, and where a -/// body layer stacks them at the tagline's height -/// the rows under them are drawn up to meet them, where the layer has them. -fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh: u16, layout: CellLayout) struct { rows: u16, lift: f32 } { - const rows = @min(held, bh); - const layered = id < surface.body_layers.len and surface.body_layers[id].rows != 0 and surface.body_layers[id].context_rows != 0; - const row_px = if (layered) std.math.clamp(@as(f32, @floatFromInt(g.tagline_height)), 1, @max(1, layout.h)) else layout.h; - g.scroll_held_px = @as(f32, @floatFromInt(rows)) * row_px; - return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; -} - -fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { - const r = g.scroll_rect; - const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; - const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px; - const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px); - const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); - const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); - const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); - const y1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(py + ph))), y0, @as(i32, @intCast(sh))); - return .{ .x = x0, .y = y0, .w = x1 - x0, .h = y1 - y0 }; -} - -/// A placement the window shows as a texture: pixels, not glyph art. -fn texturePlacement(place: pardes.Placement) bool { - return !place.art.glyph and validImageBytes(place) != null; -} - -fn surfaceHasNativeKey(surface: *const pardes.Surface, key: u64) bool { - for (surface.placements.items) |place| { - if (texturePlacement(place) and place.key == key) return true; - } - return false; -} - -fn validImageBytes(place: pardes.Placement) ?u32 { - const r = place.raster; - // Rows packed: a texture upload takes no stride. - if (r.w == 0 or r.h == 0 or r.stride != r.w * 4) return null; - const bytes = std.math.mul(usize, r.stride, r.h) catch return null; - if (bytes > std.math.maxInt(u32)) return null; - return @intCast(bytes); -} - -/// Where the placement's pixels go in its cells: where it says, or fitted -/// there (no larger than it is, at the top left). -fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.NativeGeometry { - if (place.at) |at| return .{ .src = place.src, .dst = at }; - const bound_w = std.math.mul(u32, place.dst.w, g.cell_w) catch return null; - const bound_h = std.math.mul(u32, place.dst.h, g.cell_h) catch return null; - const fit = pardes.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null; - return .{ .src = place.src, .dst = fit.dst }; -} - -fn uploadNativeTexture( - g: *Gui, - gpa: std.mem.Allocator, - cmd: *c.SDL_GPUCommandBuffer, - place: pardes.Placement, -) !void { - const byte_len = validImageBytes(place) orelse return error.BadImage; - const r = place.raster; - const dirty: ?Cells.Dirty = if (place.dirty) |d| .{ .from = d.from, .y = d.y, .h = d.h } else null; - try g.cells.image(gpa, cmd, place.key, r.bytes()[0..byte_len], r.w, r.h, r.stride, dirty); -} - -fn appendPreparedImage(g: *Gui, gpa: std.mem.Allocator, place: pardes.Placement) void { - const texture = g.cells.native_images.get(place.key) orelse return; - if (nativePlaceGeometry(g, place) == null) return; - g.prepared_images.append(gpa, .{ .place = place, .texture = texture }) catch {}; -} - -fn emitPreparedImage( - g: *Gui, - surface: *const pardes.Surface, - instance: *ImageInstance, - prepared: PreparedImage, - win_w: f32, - win_h: f32, -) bool { - const place = prepared.place; - const body_x = @as(u32, place.dst.x) * g.cell_w; - const body_y = @as(u32, place.dst.y) * g.cell_h; - const geometry = nativePlaceGeometry(g, place) orelse return false; - // A strip's pictures lie at its whole pixel: up by the fraction left. - var scroll: f64 = 0; - for (surface.regionList()) |r| if (r.kind == .body and r.owner == place.pane) { - scroll = r.scroll_px; - break; - }; - const px0 = @as(f32, @floatFromInt(body_x + geometry.dst.x)); - const py0 = @as(f32, @floatFromInt(body_y + geometry.dst.y)) - @as(f32, @floatCast(scroll - @floor(scroll))); - const px1 = px0 + @as(f32, @floatFromInt(geometry.dst.w)); - const py1 = py0 + @as(f32, @floatFromInt(geometry.dst.h)); - const image_w: f32 = @floatFromInt(place.raster.w); - const image_h: f32 = @floatFromInt(place.raster.h); - instance.* = .{ - .x0 = (px0 / win_w) * 2.0 - 1.0, - .y0 = 1.0 - (py0 / win_h) * 2.0, - .x1 = (px1 / win_w) * 2.0 - 1.0, - .y1 = 1.0 - (py1 / win_h) * 2.0, - .u0 = @as(f32, @floatFromInt(geometry.src.x)) / image_w, - .v0 = @as(f32, @floatFromInt(geometry.src.y)) / image_h, - .u1 = @as(f32, @floatFromInt(geometry.src.x + geometry.src.w)) / image_w, - .v1 = @as(f32, @floatFromInt(geometry.src.y + geometry.src.h)) / image_h, - }; - return true; -} - -fn prepareNativeImages( - g: *Gui, - gpa: std.mem.Allocator, - cmd: *c.SDL_GPUCommandBuffer, - surface: *const pardes.Surface, - groups: *Groups, - sw: u32, - sh: u32, -) bool { - for (surface.placements.items) |place| { - if (!texturePlacement(place)) continue; - uploadNativeTexture(g, gpa, cmd, place) catch continue; - } - - while (true) { - var stale: [pardes.MAX_PANES]u64 = undefined; - var stale_len: usize = 0; - var iterator = g.cells.native_images.iterator(); - while (iterator.next()) |entry| { - if (surfaceHasNativeKey(surface, entry.key_ptr.*)) continue; - stale[stale_len] = entry.key_ptr.*; - stale_len += 1; - if (stale_len == stale.len) break; - } - for (stale[0..stale_len]) |key| g.cells.releaseImage(key); - if (stale_len < stale.len) break; - } - - g.prepared_images.clearRetainingCapacity(); - // The pictures are the page's: the other groups float over them. - for (surface.placements.items) |place| - if (texturePlacement(place)) appendPreparedImage(g, gpa, place); - prepareAddonGpu(g, gpa, cmd, surface); - groups.items[0].image_start = 0; - groups.items[0].image_count = std.math.cast(u32, g.prepared_images.items.len) orelse return false; - - const capacity = std.math.cast(u32, g.prepared_images.items.len) orelse return false; - if (capacity == 0) return true; - const instances = g.cells.mapImages(gpa, capacity) orelse return false; - const win_w: f32 = @floatFromInt(sw); - const win_h: f32 = @floatFromInt(sh); - var idx: u32 = 0; - for (g.prepared_images.items) |prepared| { - // Drawn in this order, instance by instance (Cells.drawImages). - g.cells.images.appendAssumeCapacity(.{ .premultiplied = prepared.premultiplied, .texture = prepared.texture, .clip = imageScissor(g, prepared.place) }); - if (!emitPreparedImage(g, surface, &instances[idx], prepared, win_w, win_h)) continue; - idx += 1; - } - std.debug.assert(idx == capacity); - g.cells.uploadImages(cmd, idx); - return true; -} - -fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect { - return .{ - .x = @intCast(@as(u32, place.dst.x) * g.cell_w), - .y = @intCast(@as(u32, place.dst.y) * g.cell_h), - .w = @intCast(@as(u32, place.dst.w) * g.cell_w), - .h = @intCast(@as(u32, place.dst.h) * g.cell_h), - }; -} - -fn renderFrame( - g: *Gui, - gpa: std.mem.Allocator, - core: *pardes.Pardes, - canonical: *const pardes.Surface, -) !bool { - // The pictures a pane asks to see as glyph art, drawn into a copy of - // the frame (Art.zig); the rest are textures. - if (g.art_arena == null) g.art_arena = .init(gpa); - _ = g.art_arena.?.reset(.retain_capacity); - const surface = g.art.frame(gpa, g.art_arena.?.allocator(), canonical, true, g.cell_h) catch canonical; - if (surface.pointer_shape != g.pointer_shape) { - g.pointer_shape = surface.pointer_shape; - const cursor = switch (g.pointer_shape) { - .link => g.link_cursor, - .box => g.box_cursor orelse g.arrow_cursor, - else => g.arrow_cursor orelse c.SDL_GetDefaultCursor(), - }; - if (cursor) |value| _ = c.SDL_SetCursor(value); - } - g.words.memo = .{}; // positional, and this frame's cells are new - const cmd = g.cells.begin() orelse return false; - var command_consumed = false; - defer if (!command_consumed) { - Cells.submit(cmd); - }; - const frame_target = try g.present.acquireTarget(cmd, g.window, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse { - command_consumed = true; - Cells.submit(cmd); - return false; - }; - const target = frame_target.texture; - const sw = frame_target.w; - const sh = frame_target.h; - const win_w: f32 = @floatFromInt(sw); - const win_h: f32 = @floatFromInt(sh); - - // The frame's CPU side: groups, decor, cover and every instance, up to - // their upload. - const build_zone = tracy.zone(@src(), "gui frame build"); - const probe_build = monoNs(); - var building = true; - defer if (building) build_zone.end(); - const layout = fixedCellLayout(g); - const chrome = &surface.chrome; - // G6: what the scroll just done moved the pane's rows by, measured on - // this frame against the last (the glide follows it from there). - for (core.panes, &g.glide.held) |slot, *held| held.* = if (slot) |pane| pane.context_rows else 0; - glideFrame(g, gpa, surface); - var groups: Groups = .{}; - const now = g.now_ns; - seeCaret(g, surface, layout, win_h, now); - // While the cursor glides or blinks the cells' cursors are not drawn; - // the focused one is the overlay's quad. One or the other every frame - // (none only at a blink's off half). - const blink_alpha: f32 = if (blinkNow(g, core.settings.cursor_blink)) |b| b.alpha else 1; - // While a glide moves the text, the caret is its quad, drawn from its - // own springs, not a cell of the moving rows. - const gliding = g.caret.moving(); - const quad_mode = g.caret.placed and (gliding or blink_alpha < 1 or g.glide.follow.offset != 0); - // A little less than solid while it glides, so the glyphs it passes - // stay legible; solid again as it lands. - const caret_alpha: f32 = if (gliding) 0.85 + 0.15 * std.math.clamp(1 - g.caret.remaining(now) / 0.5, 0, 1) else 1; - g.cursor_quad_alpha = if (quad_mode) caret_alpha * blink_alpha else 0; - // The probe's view of this frame's motion (FrameStats.Frame). - core.frames.scroll = g.glide.follow.offset; - core.frames.caret = caretRow(g, surface, now) orelse 0; - const cursors_shown = !quad_mode; - var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh); - if (overlay_count != 0 and !g.cells.uploadOverlay(cmd, g.overlay_vertices[0..overlay_count])) - overlay_count = 0; - if (!prepareNativeImages(g, gpa, cmd, surface, &groups, sw, sh)) { - g.prepared_images.clearRetainingCapacity(); - for (groups.items[0..groups.len]) |*group| { - group.image_start = 0; - group.image_count = 0; - } - } - - const cells: u32 = @as(u32, surface.cols) * surface.rows; - try g.cover.resize(gpa, cells); - const covered = g.cover.items[0..cells]; - dim.begin(core.settings.inactive_dim, surface.regionList()); - coverFrame(covered, surface.cols, surface.rows, surface.bodyLayers(), surface.tagLayers(), surface.regionList()); - try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - - const page = chrome.page orelse bg_default; - const background_opacity = backgroundOpacity(g.applied_window_opacity); - const clear: c.SDL_FColor = .{ - .r = @as(f32, @floatFromInt(page[0])) / 255.0 * background_opacity, - .g = @as(f32, @floatFromInt(page[1])) / 255.0 * background_opacity, - .b = @as(f32, @floatFromInt(page[2])) / 255.0 * background_opacity, - .a = background_opacity, - }; - - var shifted: u32 = 0; - var row: u16 = 0; - while (row < surface.rows) : (row += 1) { - var col: u16 = 0; - while (col < surface.cols) : (col += 1) { - const at = @as(usize, row) * surface.cols + col; - if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.debug else 0; - groups.items[group_index].cell_count = std.math.add(u32, groups.items[group_index].cell_count, cellInstanceCount(&surface.cells[at])) catch return error.GpuCapacity; - } - } - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - const group = &groups.items[0]; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; - for (0..layer.rows) |lr| { - if (layer.rowTop(@intCast(lr), layout.h, @floatFromInt(g.tagline_height)) >= bottom) break; - group.cell_count += layer.cols + @as(u32, if (lr < layer.context_rows) 1 else 0) + @as(u32, @intFromBool(layer.hasContextBorderAfter(lr))); - } - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - const group_index = if (layer.kind == .notice) groups.notices else 0; - groups.items[group_index].cell_count += (tagLayerCellCount(g, layer) + 1) * layer.rows; - } - var cell_next: [4]u32 = @splat(0); - var cell_total: u32 = 0; - for (groups.items[0..groups.len], 0..) |*group, index| { - group.cell_start = cell_total; - cell_next[index] = cell_total; - cell_total = std.math.add(u32, cell_total, group.cell_count) catch return error.GpuCapacity; - } - const decor_len: u32 = @intCast(g.decor.items.len); - if (cell_total != 0 or decor_len != 0) { - // The shifted rows of a scroll: its body, a glide's rows past it, and - // a body layer's rows past the grid's. - const capacity = std.math.add(u32, cell_total, 3 * cells + decor_len) catch return error.GpuCapacity; - const instances = try g.cells.mapCells(capacity) orelse { - command_consumed = true; - Cells.submit(cmd); - return false; - }; - const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else cells; - const cursor_bar = if (surface.cursor) |cu| cu.bar else false; - row = 0; - while (row < surface.rows) : (row += 1) { - const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; - const line_cover = covered[@as(usize, row) * surface.cols ..][0..surface.cols]; - const line_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; - var col: u16 = 0; - while (col < surface.cols) : (col += 1) { - const at = @as(usize, row) * surface.cols + col; - if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.debug else 0; - emitSurfaceCell( - g, - chrome, - instances, - &cell_next[group_index], - col, - row, - layout, - win_w, - win_h, - line, - line_cover, - col, - line_cursor, - cursors_shown and at == cursor_idx and !cursor_bar and bodyLayerIn(surface.bodyLayers(), col, row) == null, - page, - ); - } - } - // Body layers first: a notice chip over a tree-sitter context band - // is a tag layer, and instances paint in emission order. - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - emitBodyLayer(g, instances, &cell_next[0], layer, win_w, win_h, page, cursors_shown, chrome.topbar_rule); - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - // A notice floats over the panes. - const group_index = if (layer.kind == .notice) groups.notices else 0; - emitTagLayer(g, instances, &cell_next[group_index], layer, win_w, win_h, page, cursors_shown); - } - for (groups.items[0..groups.len], 0..) |group, index| - std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); - // The body's context rows, which its scroll leaves where they are. - const scrolling: ?usize = if (g.glide.follow.offset != 0) g.glide.pane else g.scroll_pane; - const held: u16 = if (scrolling) |id| if (core.panes[id]) |pane| pane.context_rows else 0 else 0; - shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); - @memcpy(instances[cell_total + shifted ..][0..decor_len], g.decor.items); - g.cells.uploadCells(cmd, cell_total + shifted + decor_len, &g.atlas); - } - - build_zone.end(); - building = false; - if (frame_probe) |probe| probe.zone(.gui_build, probe_build); - // Drawn only over a scroll's shifted rows (scrollScissor asks a scroll). - const scroll_clip = if (shifted != 0) scrollScissor(g, layout, sw, sh) else std.mem.zeroes(c.SDL_Rect); - g.cells.record(cmd, target, sw, sh, clear, background_opacity, groups.items[0..groups.len], groups.ink, cell_total, shifted, scroll_clip, overlay_count); - - command_consumed = true; - return finishFrame(g, gpa, cmd, frame_target); -} - -/// Submits the frame: captured, handed to the soft presenter, or presented. -fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Present.Target) !bool { - if (g.present.capture) { - try captureFrame(g, gpa, cmd, target.texture, target.w, target.h); - return true; - } - var took: Present.Timings = .{}; - const presented = try g.present.finishFrame(cmd, target, &captureSeries, &took); - // A soft present's wait for the GPU, its upload of the frame and its flip. - if (g.present.soft_present) if (frame_probe) |probe| { - const now = monoNs(); - probe.zone(.gui_wait, now -| took.wait_ns); - probe.zone(.gui_upload, now -| took.upload_ns); - probe.zone(.gui_flip, now -| took.flip_ns); - }; - return presented; -} - -const ResolvedCell = struct { - slot: Slot, - fg: [3]u8, - bg: [3]u8, - role: pardes.FontRole, -}; - -const taglineBandOffset = pardes.Layer.taglineBandOffset; - -/// The colours and atlas slot of `line[at]`. `cursor` is where the cursor sits -/// in `line`, block or bar: shaping breaks around it. -fn resolveCell(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole, is_cursor: bool, page: [3]u8) ResolvedCell { - const cell = &line[at]; - var fg = fg_default; - var bg = page; - var reverse = is_cursor; - if (!cell.default) { - const st = cell.style; - fg = switch (st.fg) { - .default => fg_default, - .index => |i| pardes.colors.xterm[i], - .rgb => |rgb| rgb, - }; - switch (st.bg) { - .default => {}, - .index => |i| bg = pardes.colors.xterm[i], - .rgb => |rgb| bg = rgb, - } - if (st.reverse) reverse = !reverse; - if (st.invisible) { - fg = bg; - // With a translucent background, painting bg-colored glyphs at - // full opacity would expose text that the terminal concealed, so - // cellSlot draws a concealed cell blank. - } - if (st.dim) for (&fg) |*ch| { - ch.* = @intCast(@as(u16, ch.*) * 6 / 10); - }; - } - if (reverse) std.mem.swap([3]u8, &fg, &bg); - - return .{ - .slot = cellSlot(g, line, at, cursor, role), - .fg = fg, - .bg = bg, - .role = role, - }; -} - -fn cellFontRole(cell: *const pardes.Cell) pardes.FontRole { - return if (cell.default) .body else cell.style.font_role; -} - -fn cellInstanceCount(cell: *const pardes.Cell) u32 { - return if (cellFontRole(cell) == .tagline) 2 else 1; -} - -fn tagLayerCellCount(g: *const Gui, layer: *const pardes.Layer) u32 { - const pixels = @as(u32, layer.viewport.w) * g.cell_w; - return @min(layer.cols, (pixels + g.tagline_width - 1) / g.tagline_width); -} - -fn emitTagLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const pardes.Layer, win_w: f32, win_h: f32, page: [3]u8, show_cursor: bool) void { - const bw: f32 = @floatFromInt(g.cell_w); - const bh: f32 = @floatFromInt(g.cell_h); - const tw: f32 = @floatFromInt(g.tagline_width); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; - const background: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = layer.bg } } }; - // 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; - const faded = (layer.kind == .pane or layer.kind == .notice) and dim.of(layer.id); - // A row to each line, each a grid row with the tagline's glyphs. - for (0..layer.rows) |index| { - const y = layer.viewport.y + @as(u16, @intCast(index)); - emitInstance(g, instances, next.*, 0, y, .{ .w = band_right - left, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, .body, (&background)[0..1], 0, null, false, page); - next.* += 1; - const cells = layer.cells[index * layer.cols ..][0..layer.cols]; - const line_cursor: ?usize = if (layer.cursor) |cu| (if (cu.y == index) cu.x else null) else null; - for (0..tagLayerCellCount(g, layer)) |col| { - const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.x == col and cu.y == index else false; - emitInstance(g, instances, next.*, @intCast(col), y, .{ .w = tw, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, .tagline, cells, col, line_cursor, cursor, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, 1e9 }, win_w, win_h); - if (faded and !cursor) dim.fade(&instances[next.*]); - next.* += 1; - } - } -} - -fn bodyLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { - for (layers) |*layer| { - const r = layer.viewport; - if (layer.rows > 0 and col >= r.x and col - r.x < r.w and row >= r.y and row - r.y < r.h) return layer; - } - return null; -} - -fn emitBodyLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const pardes.Layer, win_w: f32, win_h: f32, page: [3]u8, show_cursor: bool, border_rgb: [3]u8) void { - const bw: f32 = @floatFromInt(g.cell_w); - const bh: f32 = @floatFromInt(g.cell_h); - const tw: f32 = @floatFromInt(g.tagline_width); - const th: f32 = @floatFromInt(g.tagline_height); - const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; - const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * bh; - const faded = dim.of(layer.id); - for (0..layer.rows) |index| { - const row: u16 = @intCast(index); - const top = layer.rowTop(row, bh, th); - if (top >= bottom) break; - const height = layer.rowHeight(row, bh, th); - const header = row < layer.context_rows; - const role: pardes.FontRole = if (header) .tagline else .body; - const width = if (header) tw else bw; - if (header) { - var background: pardes.Cell = .{ .default = false, .style = layer.cells[index * layer.cols].style }; - background.style.font_role = .body; - emitInstance(g, instances, next.*, 0, 0, .{ .w = @as(f32, @floatFromInt(layer.viewport.w)) * bw, .h = height, .x_off = left, .y_off = top }, win_w, win_h, .body, (&background)[0..1], 0, null, false, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); - next.* += 1; - } - const line = layer.cells[index * layer.cols ..][0..layer.cols]; - const line_cursor: ?usize = if (layer.cursor) |cu| if (cu.y == row) cu.x else null else null; - for (0..layer.cols) |col| { - if (left + @as(f32, @floatFromInt(col)) * width >= right) break; - 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); - 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, role, line, col, line_cursor, cursor, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); - if (faded and !cursor) dim.fade(&instances[next.*]); - next.* += 1; - } - if (layer.hasContextBorderAfter(row)) { - const border: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = border_rgb } } }; - emitInstance(g, instances, next.*, 0, 0, .{ - .w = @as(f32, @floatFromInt(layer.viewport.w)) * bw, - .h = 1, - .x_off = left, - .y_off = top + height - 1, - }, win_w, win_h, .body, (&border)[0..1], 0, null, false, page); - clipInstance(&instances[next.*], .{ -1e9, -1e9, right, bottom }, win_w, win_h); - next.* += 1; - } - } -} - -/// acme's Scrollwid column at a pane's or column's left edge, in window -/// pixels: where its button sits over its scrollbar, one width for both -/// (`rail_px` at acme's 17px font, scaled with the tagline, and always -/// short of the cell so the text keeps a gap), right of the column's rule. -fn scrollColumn(g: *const Gui, chrome: *const pardes.Chrome, col: u16, layout: CellLayout) [2]f32 { - const rule: f32 = if (col == 0) 0 else rulePx(chrome); - const x0 = @round(@as(f32, @floatFromInt(col)) * layout.w + rule); - const scaled: f32 = @round(@as(f32, @floatFromInt(@max(1, chrome.rail_px))) * @as(f32, @floatFromInt(g.tagline_height)) / 17); - // The rail and the grip are GUTTER cells wide; the text starts after. - const w = std.math.clamp(scaled, dp(4), @max(dp(4), @floor(layout.w * @as(f32, @floatFromInt(config.GUTTER))) - rule - dp(3))); - return .{ x0, x0 + w }; -} - -/// acme's button for the grip whose first cell is (col, row), in window -/// pixels: the scroll column wide, its tag row tall, from the rule above to -/// the rule below, so button and scrollbar read as one strip. -fn gripButton(g: *const Gui, chrome: *const pardes.Chrome, col: u16, row: u16, layout: CellLayout) [4]f32 { - const x = scrollColumn(g, chrome, col, layout); - const y0 = @round(@as(f32, @floatFromInt(row)) * layout.h); - return .{ x[0], y0, x[1], @round(@as(f32, @floatFromInt(row + 1)) * layout.h) }; -} - -/// A pane's button fill, from its region's state, not the grid's cells -/// (which are drawn for cell shells): dirty, focused, or the tag's ground. -fn gripFill(chrome: *const pardes.Chrome, focus: bool, dirty: bool) [3]u8 { - if (dirty) return chrome.grip_dirty; - return if (focus) chrome.grip_focus_ring else chrome.tag_bg; -} - -fn inkOn(bg: [3]u8) [3]u8 { - const lum = (@as(u16, bg[0]) * 3 + @as(u16, bg[1]) * 6 + @as(u16, bg[2])) / 10; - return if (lum > 140) .{ 0x00, 0x00, 0x00 } else .{ 0xff, 0xff, 0xff }; -} - -/// Cuts an instance's quad to a pixel rectangle (left, top, right, bottom), -/// its atlas window in proportion, so the glyph neither moves nor stretches -/// (a band is a stretched quad); nothing left, an empty quad. -fn clipInstance(instance: *CellInstance, r: [4]f32, win_w: f32, win_h: f32) void { - // In clip space, where y grows up: a quad's y0 is its top. - const left = r[0] / win_w * 2 - 1; - const right = r[2] / win_w * 2 - 1; - const top = 1 - r[1] / win_h * 2; - const bottom = 1 - r[3] / win_h * 2; - if (instance.x1 <= left or instance.x0 >= right or instance.y0 <= bottom or instance.y1 >= top) { - instance.x1 = instance.x0; - instance.y1 = instance.y0; - return; - } - if (instance.x0 < left) { - const fraction = (instance.x1 - left) / (instance.x1 - instance.x0); - instance.u0 = instance.u1 + (instance.u0 - instance.u1) * fraction; - instance.x0 = left; - } - if (instance.x1 > right) { - const fraction = (right - instance.x0) / (instance.x1 - instance.x0); - instance.u1 = instance.u0 + (instance.u1 - instance.u0) * fraction; - instance.x1 = right; - } - if (instance.y0 > top) { - const fraction = (top - instance.y1) / (instance.y0 - instance.y1); - instance.v0 = instance.v1 + (instance.v0 - instance.v1) * fraction; - instance.y0 = top; - } - if (instance.y1 < bottom) { - const fraction = (instance.y0 - bottom) / (instance.y0 - instance.y1); - instance.v1 = instance.v0 + (instance.v1 - instance.v0) * fraction; - instance.y1 = bottom; - } -} - -fn emitSurfaceCell( - g: *Gui, - chrome: *const pardes.Chrome, - instances: [*]CellInstance, - next: *u32, - col: u16, - row: u16, - body_layout: CellLayout, - win_w: f32, - win_h: f32, - line: []const pardes.Cell, - line_cover: []const Cover, - at: usize, - cursor: ?usize, - is_cursor: bool, - page: [3]u8, -) void { - const role = cellFontRole(&line[at]); - if (role == .tagline) { - const here = line_cover[at]; - // The workspace row's underlay is its own ground (a theme's status - // bar), else the focused or plain tag's. - const band_base: pardes.Cell = .{ - .style = .{ .bg = .{ .rgb = if (row < chrome.tagline_rows) chrome.tagline_bg else if (here.focus) chrome.tag_focus_bg else chrome.tag_bg }, .font_role = .tagline }, - .default = false, - }; - // The smaller font changes the ink, not the chrome's coverage. Painting - // this underlay at tagline height leaves page-colored gutters between - // adjacent workspace, column and pane tags at TaglineSize < 100. - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .body, (&band_base)[0..1], 0, null, false, page); - next.* += 1; - // Tag glyphs keep their font size inside a full physical-width grip. - // A pane's grip cells are the cell shells' form (a dirty `*`): the - // button draws its own glyph over a blank of them. - var blank = line[at]; - blank.text[0] = ' '; - blank.len = 1; - if (here.pane_grip) - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .tagline, (&blank)[0..1], 0, null, false, page) - else - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, .tagline, line, at, cursor, is_cursor, page); - // A grip's glyph is the cell at its left edge, and a blank one is - // no glyph: its marks are decor. - const glyph = &line[at - @min(here.grip_offset, at)]; - const grip = here.grip and here.grip_top and !glyph.default and glyph.printableAscii() != ' ' and !glyph.style.invisible; - const offset: u16 = if (grip) @min(here.grip_offset, at) else 0; - // 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 (line_cover[at - offset].anchor) taglineBandOffset(row, win_h, g.cell_h, g.tagline_height) else 0; - // A grip is acme's button: its fill is this cell's ground, cut to - // the button (and a dirty one's inset a pixel inside its ring, so - // the ring reads round it), its glyph centered in it. - const button = if (here.grip and here.grip_top) gripButton(g, chrome, col - @min(here.grip_offset, @as(u16, @intCast(at))), row, body_layout) else null; - if (grip) { - // A grip is one glyph centered across the gutter, not text: it is - // looked up by its codepoint's glyph, never shaped. - const drawn = g.atlas.glyphForCodepoint(cellCodepoint(glyph)); - const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = @bitCast(GlyphDecoration.fromCell(glyph)), .centered = true }); - const slot = cached orelse g.atlas.space_slot; - const b = button.?; - const center = (b[0] + b[2]) / 2 - @as(f32, @floatFromInt(col - offset)) * body_layout.w; - const shift: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, offset) * g.cell_w)) + @as(f32, @floatFromInt(config.GUTTER * g.cell_w)) / 2 - center else 0; - const resolved = resolveCell(g, glyph[0..1], 0, null, .tagline, false, page); - const ink = if (here.pane_grip) inkOn(gripFill(chrome, here.focus, here.dirty)) else resolved.fg; - instances[next.*].fr = @as(f32, @floatFromInt(ink[0])) / 255; - instances[next.*].fg = @as(f32, @floatFromInt(ink[1])) / 255; - instances[next.*].fb = @as(f32, @floatFromInt(ink[2])) / 255; - instances[next.*].u0 = (@as(f32, @floatFromInt(slot.u)) + shift) / 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 (button) |b| { - // acme's button fills its tag row from the rule above to the rule - // below: the underlay is its fill, cut to its columns; a pane's - // from its region's state, not the grid's cell form (whose dirty - // `*` is the cell shells'), a column's its cell's own ground. - const base = &instances[next.* - 1]; - const own: [3]f32 = .{ instances[next.*].br, instances[next.*].bg, instances[next.*].bb }; - if (here.pane_grip) { - const fill = gripFill(chrome, here.focus, here.dirty); - base.br = @as(f32, @floatFromInt(fill[0])) / 255; - base.bg = @as(f32, @floatFromInt(fill[1])) / 255; - base.bb = @as(f32, @floatFromInt(fill[2])) / 255; - } else { - base.br = own[0]; - base.bg = own[1]; - base.bb = own[2]; - } - clipInstance(base, .{ b[0], -1e9, b[2], 1e9 }, win_w, win_h); - // Over it, only its own glyph; the band round it and the ring - // are decor (gripDecor). - if (here.pane_grip and !grip) { - instances[next.*].u0 = @as(f32, @floatFromInt(g.atlas.space_slot.u)) / atlas_w; - instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; - instances[next.*].v0 = @as(f32, @floatFromInt(g.atlas.space_slot.v)) / atlas_h; - instances[next.*].v1 = @as(f32, @floatFromInt(g.atlas.space_slot.v + g.tagline_height)) / atlas_h; - } - // Its ground is the fill again. - instances[next.*].br = base.br; - instances[next.*].bg = base.bg; - instances[next.*].bb = base.bb; - clipInstance(&instances[next.*], b, win_w, win_h); - } else if (inset > 0) { - instances[next.*].x0 += @as(f32, @floatFromInt(inset)) / win_w * 2; - instances[next.*].u0 += @as(f32, @floatFromInt(inset)) / atlas_w; - } - if (here.dim and !is_cursor) dim.fade(&instances[next.*]); - next.* += 1; - return; - } - emitInstance(g, instances, next.*, col, row, body_layout, win_w, win_h, role, line, at, cursor, is_cursor, page); - if (line_cover[at].dim and !is_cursor) dim.fade(&instances[next.*]); - next.* += 1; -} - -fn emitInstance( - g: *Gui, - instances: [*]CellInstance, - idx: u32, - col: u16, - row: u16, - layout: CellLayout, - win_w: f32, - win_h: f32, - role: pardes.FontRole, - line: []const pardes.Cell, - at: usize, - cursor: ?usize, - is_cursor: bool, - page: [3]u8, -) void { - const resolved = resolveCell(g, line, at, cursor, role, is_cursor, page); - - const px0 = layout.x_off + @as(f32, @floatFromInt(col)) * layout.w; - const visual_h: f32 = if (resolved.role == .tagline) - @floatFromInt(g.tagline_height) - else - layout.h; - const band_offset: f32 = if (resolved.role == .tagline) - @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; - const x0 = (px0 / win_w) * 2.0 - 1.0; - const x1 = ((px0 + layout.w) / win_w) * 2.0 - 1.0; - const y0 = 1.0 - (py0 / win_h) * 2.0; - const y1 = 1.0 - ((py0 + visual_h) / win_h) * 2.0; - const aw_f: f32 = @floatFromInt(atlas_w); - const ah_f: f32 = @floatFromInt(atlas_h); - const uv_w: u32 = if (resolved.role == .tagline) g.tagline_width else g.cell_w; - const uv_h: u32 = if (resolved.role == .tagline) g.tagline_height else g.cell_h; - - instances[idx] = .{ - .x0 = x0, - .y0 = y0, - .x1 = x1, - .y1 = y1, - .u0 = @as(f32, @floatFromInt(resolved.slot.u)) / aw_f, - .v0 = @as(f32, @floatFromInt(resolved.slot.v)) / ah_f, - .u1 = @as(f32, @floatFromInt(resolved.slot.u + uv_w)) / aw_f, - .v1 = @as(f32, @floatFromInt(resolved.slot.v + uv_h)) / ah_f, - .fr = @as(f32, @floatFromInt(resolved.fg[0])) / 255.0, - .fg = @as(f32, @floatFromInt(resolved.fg[1])) / 255.0, - .fb = @as(f32, @floatFromInt(resolved.fg[2])) / 255.0, - .br = @as(f32, @floatFromInt(resolved.bg[0])) / 255.0, - .bg = @as(f32, @floatFromInt(resolved.bg[1])) / 255.0, - .bb = @as(f32, @floatFromInt(resolved.bg[2])) / 255.0, - }; - // A block cursor is foreground UI ink, even though its color is carried - // in the reversed cell background. Keep it visible at WindowOpacity 0. - if (is_cursor) instances[idx].effect |= opaque_bg_bit; -} - -fn cellCodepoint(cell: *const pardes.Cell) u32 { - const grapheme = cell.grapheme(); - return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); -} - -fn firstCp(s: []const u8) u32 { - if (s.len == 0) return ' '; - const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return ' '; - if (n > s.len) return ' '; - return std.unicode.utf8Decode(s[0..n]) catch ' '; -} - -fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { - var cw: c_int = 10; - var chh: c_int = 20; - var asc: c_int = 16; - g.atlas.cellMetrics(g.px, &cw, &chh, &asc); - g.cell_w = @intCast(@max(cw, 1)); - g.cell_h = @intCast(@max(chh, 1)); - g.ascent = @intCast(@max(asc, 1)); - const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, g.tagline_percent); - g.tagline_px = tagline.px; - g.tagline_width = tagline.width; - g.tagline_baseline = tagline.baseline; - g.tagline_height = tagline.height; - - resetGlyphAtlas(g); - - if (core) |p| { - const geom = windowCells(g); - _ = updateCoreResize(p, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); - } - - resetScroll(g); -} - -// The first cell of the cleared atlas stays blank: the space slot. -fn resetGlyphAtlas(g: *Gui) void { - g.atlas.reset(g.cell_w); - g.words.clear(); -} - -fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { - if (!fitTaglineFont(g, core.settings.font.tagline_percent)) return; - const geom = windowCells(g); - _ = updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height); -} - -/// The tagline's face at `percent` of the body's: whether it changed. -fn fitTaglineFont(g: *Gui, percent: u8) bool { - if (percent == g.tagline_percent) return false; - g.tagline_percent = percent; - const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, percent); - g.tagline_px = tagline.px; - g.tagline_width = tagline.width; - g.tagline_baseline = tagline.baseline; - g.tagline_height = tagline.height; - resetGlyphAtlas(g); - return true; -} - -/// What text draws, so a frame does not work it out again. `cells` is the -/// atlas slot of a codepoint no ligature can touch (`shape_slot` for one that -/// is shaped with its word); `map` is the atlas slot of every cell of a word -/// holding one, found by the word's text. Bounded: past `max_cells` word cells -/// it starts over, and the next frames look up what they show again (the -/// glyphs stay in the atlas). -const Words = struct { - cells: std.AutoHashMapUnmanaged(CellKey, Slot) = .empty, - map: std.AutoHashMapUnmanaged(u64, Word) = .empty, - /// Every word's codepoints and slots, end to end; a Word indexes both. - text: std.ArrayListUnmanaged(u32) = .empty, - slots: std.ArrayListUnmanaged(Slot) = .empty, - shaped: std.ArrayListUnmanaged(c.UIShapedCell) = .empty, - /// The word the last cell was in, so the rest of it costs a compare. It - /// is positional, so every frame forgets it: the cells change under it. - memo: Memo = .{}, - - const max_cells = 1 << 17; - const CellKey = packed struct(u64) { cp: u21, role: pardes.FontRole, decoration: GlyphDecoration, _: u30 = 0 }; - const shape_slot: Slot = .{ .u = std.math.maxInt(u32), .v = std.math.maxInt(u32) }; - const Word = struct { start: u32, len: u32, decoration: GlyphDecoration }; - const Memo = struct { - line: ?[*]const pardes.Cell = null, - len: usize = 0, - start: usize = 0, - end: usize = 0, - cursor: ?usize = null, - slots: usize = 0, - }; - - fn clear(w: *Words) void { - w.cells.clearRetainingCapacity(); - w.map.clearRetainingCapacity(); - w.text.clearRetainingCapacity(); - w.slots.clearRetainingCapacity(); - w.memo = .{}; - } - - fn deinit(w: *Words, gpa: std.mem.Allocator) void { - w.cells.deinit(gpa); - w.map.deinit(gpa); - w.text.deinit(gpa); - w.slots.deinit(gpa); - w.shaped.deinit(gpa); - } -}; - -/// What decides where a word ends, for one cell. A concealed cell is a space. -const WordCell = struct { cp: u32, decoration: GlyphDecoration, role: pardes.FontRole }; - -fn wordCell(cell: *const pardes.Cell) WordCell { - return .{ - .cp = if (!cell.default and cell.style.invisible) ' ' else cellCodepoint(cell), - .decoration = GlyphDecoration.fromCell(cell), - .role = cellFontRole(cell), - }; -} - -/// Whether a word ends between `a`, cell `i`, and `b`, cell `i + 1`: at a -/// space, a decoration or role change, either side of the cursor (Ghostty's -/// rule: the cell being edited shows its own glyph, so a ligature under the -/// cursor comes apart), and inside f|i, f|l and s|t, whose typographic -/// ligatures do not belong on a grid (Ghostty again). Colours never end a -/// word: a ligature spans a syntax colour change or a selection edge, and each -/// cell tints its own slice. -fn wordBreak(a: WordCell, b: WordCell, i: usize, cursor: ?usize) bool { - if (a.cp == ' ' or b.cp == ' ') return true; - // A rule is drawn by hand (ruleArms), never a slice of a shaped word. - if (ruleArms(a.cp) != null or ruleArms(b.cp) != null) return true; - if (cursor) |at| if (at == i or at == i + 1) return true; - if (a.role != b.role or !std.meta.eql(a.decoration, b.decoration)) return true; - return (a.cp == 'f' and (b.cp == 'i' or b.cp == 'l')) or (a.cp == 's' and b.cp == 't'); -} - -/// The atlas slot `line[at]` draws: blank for a plain space (or concealed -/// text), its own glyph when no ligature could replace that glyph (every -/// cell, in a font without ligatures), else its slice -/// of the word around it, shaped once and cached by the word's text. The -/// cells of a word being walked cost a compare. Taglines are not shaped: they are drawn at two pitches -/// (tagline_width in a tag layer, a whole cell in the grid), and a strip would -/// not line up in one of them. -fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: pardes.FontRole) Slot { - const words = &g.words; - const memo = words.memo; - if (memo.line == line.ptr and memo.len == line.len and memo.cursor == cursor and at >= memo.start and at < memo.end and role == .body) - return words.slots.items[memo.slots + at - memo.start]; - var here = wordCell(&line[at]); - // An underlined or struck-out space is a glyph of its own: it draws its line. - if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot; - if (ruleArms(here.cp) != null) - return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @fromBackingInt(@intCast(@backingInt(role))), .rule = true }) orelse g.atlas.space_slot; - const gpa = g.atlas.glyphs.allocator; - const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; - const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot; - if (!known.found_existing) { - const drawn = g.atlas.glyphForCodepoint(here.cp); - known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph)) - Words.shape_slot - else - cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @fromBackingInt(@intCast(@backingInt(role))), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot; - } - const plain = known.value_ptr.*; - if (!std.meta.eql(plain, Words.shape_slot)) return plain; - - if (words.text.items.len > Words.max_cells) words.clear(); - var start = at; - while (start > 0) { - const before = wordCell(&line[start - 1]); - if (wordBreak(before, here, start - 1, cursor)) break; - start -= 1; - here = before; - } - // The word's text goes on the end of `text`: a new word keeps it there, - // a known one gives it back. - const text_start = words.text.items.len; - var end = start; - while (true) { - words.text.append(gpa, here.cp) catch return g.atlas.space_slot; - end += 1; - if (end == line.len) break; - const next = wordCell(&line[end]); - if (wordBreak(here, next, end - 1, cursor)) break; - here = next; - } - const text = words.text.items[text_start..]; - const decoration = here.decoration; - const hash = std.hash.Wyhash.hash(@as(u5, @bitCast(decoration)), std.mem.sliceAsBytes(text)); - if (words.map.get(hash)) |word| { - if (word.len == text.len and std.meta.eql(word.decoration, decoration) and - std.mem.eql(u32, words.text.items[word.start..][0..word.len], text)) - { - words.text.shrinkRetainingCapacity(text_start); - words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = word.start }; - return words.slots.items[word.start + at - start]; - } - } - - // A new word (a hash collision takes the map entry over). Runs of one - // face are shaped in that face; fallback faces shape like the primary. - const probe_shape = monoNs(); - defer if (frame_probe) |probe| { - probe.zone(.gui_shape, probe_shape); - probe.shaped +|= 1; - }; - const n = text.len; - words.slots.ensureUnusedCapacity(gpa, n) catch { - words.text.shrinkRetainingCapacity(text_start); - return g.atlas.space_slot; - }; - words.shaped.resize(gpa, n) catch { - words.text.shrinkRetainingCapacity(text_start); - return g.atlas.space_slot; - }; - const shaped = words.shaped.items; - var run_start: usize = 0; - var face = g.atlas.glyphForCodepoint(text[0]).face; - while (run_start < n) { - var run_end = run_start + 1; - var next_face = face; - while (run_end < n) : (run_end += 1) { - next_face = g.atlas.glyphForCodepoint(text[run_end]).face; - if (next_face != face) break; - } - g.atlas.shape(face, g.px, g.cell_w, text[run_start..run_end], shaped[run_start..]); - for (shaped[run_start..run_end]) |cell| { - const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = @bitCast(decoration), .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; - const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.atlas.space_slot; - words.slots.appendAssumeCapacity(slot); - } - run_start = run_end; - face = next_face; - } - words.map.put(gpa, hash, .{ .start = @intCast(text_start), .len = @intCast(n), .decoration = decoration }) catch {}; - words.memo = .{ .line = line.ptr, .len = line.len, .start = start, .end = end, .cursor = cursor, .slots = text_start }; - return words.slots.items[text_start + at - start]; -} - -/// A Gui for the tests that build cells, decor or a scroll without a -/// window: these metrics, every other field its default. What needs SDL, a -/// font or the atlas is undefined (textTestGui adds a font and an atlas). -fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui { - return .{ - .window = undefined, - .present = undefined, - .cells = undefined, - .overlay_vertices = &.{}, - .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined }, - .px = 0, - .tagline_px = 0, - .tagline_percent = 0, - .tagline_width = tagline_width, - .tagline_height = tagline_height, - .cell_w = cell_w, - .cell_h = cell_h, - .ascent = 0, - .tagline_baseline = 0, - }; -} - -/// The atlas slot of `key` (Atlas.cachedGlyph), rasterized on first use at -/// the window's sizes, a grip glyph GUTTER cells wide, its rules and -/// decorations a logical pixel thick (dp): a raster is the frame probe's. -/// Null when the atlas is full. -fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { - if (g.atlas.glyphs.get(key)) |s| return s; - const probe_raster = monoNs(); - const body: Atlas.Size = .{ .px = g.px, .cell_w = g.cell_w, .height = g.cell_h, .baseline = g.ascent }; - const tagline: Atlas.Size = .{ .px = g.tagline_px, .cell_w = g.tagline_width, .height = g.tagline_height, .baseline = g.tagline_baseline }; - const s = g.atlas.cachedGlyph(key, body, tagline, config.GUTTER, @intFromFloat(dp(1))) orelse return null; - if (frame_probe) |probe| { - probe.zone(.gui_raster, probe_raster); - probe.rastered +|= 1; - } - return s; -} - -fn backgroundOpacity(percent: u8) f32 { - std.debug.assert(percent <= 100); - return @as(f32, @floatFromInt(percent)) / 100; -} - -/// PARDES_TEST_LATENCY trace for an external driver, CLOCK_MONOTONIC ns: -/// `R t` when stdin input is read, `F start fence submit` per captured frame -/// (present entry, the GPU fence of that frame, and its submission: submit - -/// start is the frame's CPU cost). Nothing is written without it. -var latency_fd: c_int = -1; -var frame_started_ns: u64 = 0; - -fn monoNs() u64 { - var ts: libc.timespec = undefined; - if (libc.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); -} - -fn latencyNote(comptime fmt: []const u8, args: anytype) void { - if (latency_fd < 0) return; - var buf: [64]u8 = undefined; - const line = std.fmt.bufPrint(&buf, fmt, args) catch return; - _ = libc.write(latency_fd, line.ptr, line.len); -} - -/// Writes the frame to latest.ppm in the capture directory, and in a -/// series to frame-<n>.ppm too. -fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { - const frame = try g.present.readFrame(cmd, target, sw, sh); - defer g.present.releaseFrame(frame); - latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, frame.fence_ns, frame.submit_ns }); - - try writeCapturePpm(g, gpa, frame.pixels, sw, sh, "latest", false); - var name: [24]u8 = undefined; - // unreachable below: "frame-" and a u32 fit 24 - if (g.capture_series) try writeCapturePpm(g, gpa, frame.pixels, sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable, true); - g.captured +%= 1; -} - -/// A test window's state for a harness (test/process/window.zig), in the -/// capture directory's `status`: "<loop step> <frames captured> <idle>". -/// Idle is 1 once the frame last captured is the one that stays: nothing -/// owes a frame, nothing moves, nothing waits on a clock. A harness that -/// sees a step past the one it acted on, idle, has its frame, however slow -/// the machine is. -var test_status_step: u64 = 0; -fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) void { - test_status_step +%= 1; - if (g.capture_dir.len == 0) return; - const idle = presented and !core.needs_frame and !frontendMoving(g) and core.nextWake() == null and - !g.glide.moving() and g.scroll_lag == 0 and g.scroll_delta == 0 and g.scroll_notch == 0; - var line_buf: [64]u8 = undefined; - // What keeps it busy, after: owes a frame, moves, waits, not shown. - const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(frontendMoving(g)), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch unreachable; // seven numbers fit 64 - var tmp_buf: [4096]u8 = undefined; - var final_buf: [4096]u8 = undefined; - const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/status.tmp", .{g.capture_dir}, 0) catch return; - const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/status", .{g.capture_dir}, 0) catch return; - const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - _ = libc.rename(tmp_path, final_path); -} - -/// `<name>.ppm`, RGB; with `alpha`, `<name>.pam` (P7 RGB_ALPHA) instead: a -/// series keeps the alpha a blend writes, which the window's transparency -/// shows and an RGB capture cannot. -fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8, alpha: bool) !void { - // A latency trace times frames, and an 8 MB file write per frame would - // stall the loop it is timing. - if (g.capture_dir.len == 0 or latency_fd >= 0) return; - const bgr = try g.present.bgr(); - - var tmp_buf: [4096]u8 = undefined; - var final_buf: [4096]u8 = undefined; - const ext = if (alpha) "pam" else "ppm"; - const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.{s}.tmp", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong; - const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.{s}", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong; - - const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return error.CaptureWriteFailed; - defer _ = libc.close(fd); - - var header: [96]u8 = undefined; - const hdr = if (alpha) - std.fmt.bufPrint(&header, "P7\nWIDTH {d}\nHEIGHT {d}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", .{ width, height }) catch unreachable // two u32s fit 96 - else - std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 96 - _ = host_io.writeFd(fd, hdr); - - const depth: usize = if (alpha) 4 else 3; - const row_rgb = try gpa.alloc(u8, @as(usize, width) * depth); - defer gpa.free(row_rgb); - for (0..height) |row| { - const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4]; - for (0..width) |x| { - const si = x * 4; - const di = x * depth; - row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0]; - row_rgb[di + 1] = src[si + 1]; - row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2]; - if (alpha) row_rgb[di + 3] = src[si + 3]; - } - _ = host_io.writeFd(fd, row_rgb); - } - if (libc.rename(tmp_path, final_path) != 0) return error.CaptureWriteFailed; -} - -/// One flat, hard-edged rectangle of decor, in window pixels: clipped to the -/// window and dropped when empty, as the triangle overlay drew it. -fn addDecor(g: *Gui, gpa: std.mem.Allocator, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, rgb: [3]u8, alpha: f32, win_w: f32, win_h: f32) !void { - const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, win_w); - const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, win_w); - const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, win_h); - const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, win_h); - if (x1 <= x0 or y1 <= y0) return; - // decor.frag.glsl reads the colour from the ground and the coverage - // from the ink's red. - try g.decor.append(gpa, .{ - .x0 = (x0 / win_w) * 2.0 - 1.0, - .y0 = 1.0 - (y0 / win_h) * 2.0, - .x1 = (x1 / win_w) * 2.0 - 1.0, - .y1 = 1.0 - (y1 / win_h) * 2.0, - .u0 = 0, - .v0 = 0, - .u1 = 0, - .v1 = 0, - .fr = alpha, - .fg = 0, - .fb = 0, - .br = @as(f32, @floatFromInt(rgb[0])) / 255.0, - .bg = @as(f32, @floatFromInt(rgb[1])) / 255.0, - .bb = @as(f32, @floatFromInt(rgb[2])) / 255.0, - }); -} - -/// A body region in window pixels. -fn bodyPixels(region: pardes.Region, layout: CellLayout) [4]f32 { - return .{ - @as(f32, @floatFromInt(region.rect.x)) * layout.w, - @as(f32, @floatFromInt(region.rect.y)) * layout.h, - @as(f32, @floatFromInt(region.rect.x + region.rect.w)) * layout.w, - @as(f32, @floatFromInt(region.rect.y + region.rect.h)) * layout.h, - }; -} - -/// The frame's decor, group by group (docs/render-pipeline.md), all of it -/// read from the regions and the palette: the page's rules and the panes' -/// rails, rules and grip marks with the page, notice rules with the -/// notices, bar cursors with the ink. -fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, groups: *Groups, layout: CellLayout, win_w: f32, win_h: f32, cursors_shown: bool) !void { - g.decor.clearRetainingCapacity(); - const chrome = &surface.chrome; - const regions = surface.regionList(); - for (groups.items[0..groups.len], 0..) |*group, index| { - group.decor_start = @intCast(g.decor.items.len); - defer group.decor_count = @as(u32, @intCast(g.decor.items.len)) - group.decor_start; - if (index == 0) { - // The grips' buttons before any rule: the rules over their rows - // cut them, and the band round them never covers a rule. - try gripDecor(g, gpa, regions, surface.cells, chrome, layout, surface.cols, surface.rows, win_w, win_h); - const top = for (regions) |region| { - if (region.kind == .workspace_tag) break region.rect.h; - } else 0; - // The workspace tag is ruled off from the tags right under it. - const tag_under = for (regions) |region| switch (region.kind) { - .grip, .tag, .column_grip, .column_tag => if (region.rect.y == top) break true, - else => {}, - } else false; - // As wide as the other rules, where the tagline leaves the room. - const height: u32 = @intFromFloat(@max(1, @min(rulePx(chrome), @as(f32, @floatFromInt((g.cell_h -| g.tagline_height) * 2))))); - if (top != 0 and top < surface.rows and tag_under and height != 0) { - const y0: f32 = @floatFromInt(top * g.cell_h - height / 2); - try addDecor(g, gpa, 0, y0, win_w, y0 + @as(f32, @floatFromInt(height)), chrome.topbar_rule, 1, win_w, win_h); - } - // The column bar is ruled off from the panes under it. - for (regions) |bar| { - if (bar.kind != .column_grip) continue; - const y = @as(f32, @floatFromInt(bar.rect.y + bar.rect.h)) * layout.h; - try addDecor(g, gpa, 0, y - rulePx(chrome), win_w, y, chrome.border, 1, win_w, win_h); - break; - } - // A tag on the last row runs on through the pixels under the grid. - const grid_bottom = @as(f32, @floatFromInt(surface.rows)) * layout.h; - const tag_last = for (regions) |region| switch (region.kind) { - .grip, .tag, .column_grip, .column_tag, .workspace_tag => if (region.rect.h != 0 and region.rect.y + region.rect.h == surface.rows) break true, - else => {}, - } else false; - if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); - try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h); - // A single spine runs down each column, through every tag and body. - for (regions) |column| { - if (column.kind != .column) continue; - const x = @as(f32, @floatFromInt(column.rect.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(column.rect.y)) * layout.h; - const grid_y1 = @as(f32, @floatFromInt(surface.rows)) * layout.h; - const y1 = if (win_h - grid_y1 < layout.h) @max(grid_y1, win_h) else grid_y1; - // None at the window's edge: nothing to rule apart there. - if (column.rect.x == 0) continue; - if (y1 > y0) try addDecor(g, gpa, x, y0, x + rulePx(chrome), y1, chrome.border, 1, win_w, win_h); - } - } - // A notice chip is tagline hung over the body's top rows, so it is - // ruled off from the text beneath it the way a tag is: the same - // colour and thickness along its bottom, running to the window's - // edge when it does. - if (index == groups.notices) for (surface.tagLayers()) |*layer| { - if (layer.rows == 0 or layer.kind != .notice) continue; - const x0 = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; - const x1 = x0 + @as(f32, @floatFromInt(layer.viewport.w)) * layout.w; - const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; - const top = @as(f32, @floatFromInt(layer.viewport.y)) * layout.h; - const rule_y = top + layout.h; - try addDecor(g, gpa, x0, rule_y - dp(1), rule_x1, rule_y, chrome.border, 1, win_w, win_h); - }; - if (index == groups.ink and cursors_shown) try cursorDecor(g, gpa, surface, layout, win_w, win_h); - } -} - -/// Each pane's rule between its tag and body, and its scroll rail: a page -/// coloured gutter with a thin track and its thumb, running down through the -/// pixels past the last whole row. -fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - const page = chrome.page orelse bg_default; - for (regions) |rail| { - if (rail.kind != .rail or rail.rect.h == 0) continue; - const tag = for (regions) |region| { - if (region.kind == .tag and region.owner == rail.owner) break region; - } else continue; - if (@as(u32, tag.rect.x) + tag.rect.w > cols or @as(u32, tag.rect.y) + tag.rect.h > rows or - @as(u32, rail.rect.y) + rail.rect.h > rows) continue; - const x0 = @as(f32, @floatFromInt(rail.rect.x)) * layout.w; - const x1 = @as(f32, @floatFromInt(tag.rect.x + tag.rect.w)) * layout.w; - // Like the band above it, the rule of a pane at the right edge runs - // on through the pixels past the last whole cell. Under a tag on - // top, over one below its body. - const rule_x1 = if (win_w - x1 < layout.w) @max(x1, win_w) else x1; - const tag_bottom = tag.rect.y > rail.rect.y; - const rule_y = @as(f32, @floatFromInt(if (tag_bottom) tag.rect.y else tag.rect.y + tag.rect.h)) * layout.h; - try addDecor(g, gpa, x0, if (tag_bottom) rule_y else rule_y - dp(1), rule_x1, if (tag_bottom) rule_y + dp(1) else rule_y, chrome.tag_rule orelse mixRgb(chrome.tag_bg, page), 1, win_w, win_h); - // Stacked panes are ruled apart as columns are, where one pane's - // body meets the next one's tag (acme's Border). - { - const pane_top = @min(tag.rect.y, rail.rect.y); - const stacked = for (regions) |other| { - if ((other.kind == .body or other.kind == .tag) and other.owner != rail.owner and other.rect.y + other.rect.h == pane_top and - other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; - } else false; - // Inside the tag band's slack, never over its glyphs: the top - // slack of a tag on top, the bottom slack of the one above when - // tags are at the bottom; a pixel at least. - const y = @as(f32, @floatFromInt(pane_top)) * layout.h; - const spare = g.cell_h -| g.tagline_height; - if (stacked and !tag_bottom) { - const room = taglineBandOffset(pane_top, win_h, g.cell_h, g.tagline_height); - try addDecor(g, gpa, x0, y, rule_x1, y + @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), chrome.border, 1, win_w, win_h); - } else if (stacked and pane_top > 0) { - const room = spare - taglineBandOffset(pane_top - 1, win_h, g.cell_h, g.tagline_height); - try addDecor(g, gpa, x0, y - @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(room)))), rule_x1, y, chrome.border, 1, win_w, win_h); - } - } - - const y0 = @as(f32, @floatFromInt(rail.rect.y)) * layout.h; - const body_end = rail.rect.y + rail.rect.h; - const body_y1 = @as(f32, @floatFromInt(body_end)) * layout.h; - const y1 = if (body_end == rows and win_h - body_y1 < layout.h) @max(body_y1, win_h) else body_y1; - // A theme's own track fills its width, the thumb one pixel short - // of it so the track edges it (acme's scrollbar); else a thin rail. - // acme's scrollbar: the track fills the scroll column, under the - // grip's button; the thumb is a pixel short of its right edge, so - // the track edges it. - const column = scrollColumn(g, chrome, rail.rect.x, layout); - try addDecor(g, gpa, x0, y0, x0 + layout.w, y1, page, 1, win_w, win_h); - try addDecor(g, gpa, column[0], y0, column[1], y1, chrome.scroll_track, 1, win_w, win_h); - if (rail.thumb_h != 0 and rail.thumb_span > 0) { - // In pixels, not rows, and with the picture while it glides - // or lags behind the core's rows (both in rows of the body). - const lag: f32 = if (g.glide.follow.offset != 0 and g.glide.pane == rail.owner) - g.glide.lagLines() - else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; - const track_px = body_y1 - y0; - const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); - const at = rail.thumb_at + lag * rail.thumb_span / @as(f32, @floatFromInt(rail.rect.h)); - const thumb_y0 = y0 + std.math.clamp(at * track_px, 0, track_px - size); - const thumb_y1 = if (thumb_y0 + size >= body_y1 - 0.5) y1 else thumb_y0 + size; - try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); - } else if (rail.thumb_h != 0) { - const thumb_y0 = @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y)) * layout.h; - const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; - try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, win_w, win_h); - } - // A query's places' ticks over the track and thumb, where its matches - // are in the file (Places.addTicks); the current one last, on top. - const track_px = body_y1 - y0; - for (0..2) |pass| for (ticks) |tick| { - if (tick.owner != rail.owner or tick.current != (pass == 1)) continue; - const at = @as(f32, @floatFromInt(tick.at)) / @as(f32, @floatFromInt(pardes.panes.Places.tick_scale)); - const h = if (tick.current) dp(3) else dp(2); - const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h); - try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, win_w, win_h); - }; - } -} - -/// Halfway between two colours. -const mixRgb = pardes.colors.mix; - -/// A rule's width: the theme's own, or one pixel. -fn rulePx(chrome: *const pardes.Chrome) f32 { - return dp(@floatFromInt(@max(1, chrome.rule_px))); -} - -/// The display's density (SDL's window display scale: 2 on a 2x screen), -/// by which every size given in logical pixels is drawn, as acme scales its -/// Border, ButtonBorder and Scrollgap (scalesize). Cells, glyphs and what is -/// measured in them are already the display's pixels and are not scaled. -/// One per process, as its window is. -var display_scale: f32 = 1; - -/// The window's display scale, or PARDES_TEST_SCALE (a harness forcing 2x); -/// a test window is 1x unless forced, whatever display it lands on, so its -/// captures are the same on any machine. -fn updateDisplayScale(window: *c.SDL_Window) void { - if (std.c.getenv("PARDES_TEST_SCALE")) |forced| { - display_scale = std.fmt.parseFloat(f32, std.mem.span(forced)) catch 1; - } else if (std.c.getenv("PARDES_TEST") != null) { - display_scale = 1; - } else { - const scale = c.SDL_GetWindowDisplayScale(window); - display_scale = if (scale > 0 and std.math.isFinite(scale)) scale else 1; - } - display_scale = std.math.clamp(display_scale, 1, 4); -} - -/// InactiveDim: the unfocused panes' text faded toward its ground by the -/// setting's percent, never below the pair's own contrast or 4.5, whichever -/// is lower. The window's alone, from the regions' focus: renderFrame -/// begins it each frame. ponytail: one window per process, as display_scale. -var dim: Dim = .{}; - -const Dim = struct { - amount: f32 = 0, - /// The pane with the keyboard, from its regions. - focused: u16 = pardes.Region.none, - /// The few ink and paper pairs a frame has, each faded once. - keys: [32]?[6]u8 = @splat(null), - values: [32][3]u8 = undefined, - - fn begin(d: *Dim, percent: u8, regions: []const pardes.Region) void { - d.* = .{ .amount = @as(f32, @floatFromInt(@min(percent, 100))) / 100 }; - for (regions) |region| if (region.active and (region.kind == .grip or region.kind == .tag or region.kind == .body)) { - d.focused = region.owner; - break; - }; - if (d.focused == pardes.Region.none) d.amount = 0; - } - - /// Whether pane `owner`'s text fades this frame. - fn of(d: *const Dim, owner: u16) bool { - return d.amount > 0 and owner != d.focused; - } - - /// A cell instance's ink faded toward its ground. - fn fade(d: *Dim, instance: *CellInstance) void { - const ink = d.faded(byteRgb(.{ instance.fr, instance.fg, instance.fb }), byteRgb(.{ instance.br, instance.bg, instance.bb })); - instance.fr = @as(f32, @floatFromInt(ink[0])) / 255.0; - instance.fg = @as(f32, @floatFromInt(ink[1])) / 255.0; - instance.fb = @as(f32, @floatFromInt(ink[2])) / 255.0; - } - - fn faded(d: *Dim, ink: [3]u8, paper: [3]u8) [3]u8 { - const key = ink ++ paper; - const slot = (@as(usize, ink[0]) *% 31 +% @as(usize, ink[1]) *% 7 +% ink[2] +% @as(usize, paper[0]) *% 13 +% @as(usize, paper[1]) *% 3 +% paper[2]) % d.keys.len; - if (d.keys[slot]) |held| if (std.mem.eql(u8, &held, &key)) return d.values[slot]; - // Contrast falls as the ink nears its paper: the most of `amount` - // that keeps the pair at its own contrast or 4.5, whichever is lower. - const floor = @min(pardes.colors.contrast(ink, paper), 4.5); - var t = d.amount; - if (pardes.colors.contrast(blendLinear(ink, paper, t), paper) < floor) { - var lo: f32 = 0; - var hi: f32 = t; - for (0..8) |_| { - const mid = (lo + hi) / 2; - if (pardes.colors.contrast(blendLinear(ink, paper, mid), paper) >= floor) lo = mid else hi = mid; - } - t = lo; - } - d.keys[slot] = key; - d.values[slot] = blendLinear(ink, paper, t); - return d.values[slot]; - } - - fn byteRgb(rgb: [3]f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, rgb) |*o, v| o.* = @intFromFloat(@round(std.math.clamp(v, 0, 1) * 255)); - return out; - } -}; - -/// `t` of the way from one colour to the other in linear light, so a -/// coloured ink does not muddy on its way to the paper. -fn blendLinear(from: [3]u8, to: [3]u8, t: f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, from, to) |*o, a, b| { - const l = pardes.colors.to_linear[a] * (1 - t) + pardes.colors.to_linear[b] * t; - o.* = encoded[@intFromFloat(@round(std.math.clamp(l, 0, 1) * (encoded.len - 1)))]; - } - return out; -} - -/// Linear light back to an sRGB channel, in 4096 steps. -const encoded: [4096]u8 = blk: { - @setEvalBranchQuota(1_000_000); - var table: [4096]u8 = undefined; - for (&table, 0..) |*out, i| { - const l = @as(f64, @floatFromInt(i)) / 4095; - const v = if (l <= 0.0031308) l * 12.92 else 1.055 * std.math.pow(f64, l, 1.0 / 2.4) - 0.055; - out.* = @intFromFloat(@round(v * 255)); - } - break :blk table; -}; - -/// A logical pixel size in the display's pixels: rounded, at least one. -fn dp(logical: f32) f32 { - return @max(1, @round(logical * display_scale)); -} - -/// The two short bars on each row of a grip with no mode glyph there, -/// centered in its anchor. -fn gripDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, cells: []const pardes.Cell, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32) !void { - if (g.tagline_height < 6 or g.tagline_width < 3) return; - for (regions) |grip| { - if (grip.kind != .grip and grip.kind != .column_grip) continue; - if (grip.rect.h == 0 or grip.rect.y >= rows) continue; - const button = gripButton(g, chrome, grip.rect.x, grip.rect.y, layout); - // Round the button, its first row is the tag's band: nothing of the - // cells under it shows there. - const band = if (grip.active) chrome.tag_focus_bg else chrome.tag_bg; - const left = @as(f32, @floatFromInt(grip.rect.x)) * layout.w; - const right = @as(f32, @floatFromInt(grip.rect.x + grip.rect.w)) * layout.w; - try addDecor(g, gpa, left, button[1], button[0], button[3], band, 1, win_w, win_h); - try addDecor(g, gpa, button[2], button[1], right, button[3], band, 1, win_w, win_h); - if (grip.kind != .grip) continue; - // acme's button ring, two pixels (ButtonBorder) inside the button: - // the focused one's in its own fill. An unfocused dirty one keeps a - // pixel of band inside its ring, so the four states differ in shape - // whatever a theme's colours (a focused dirty one is acme's - // modbutton, filled up to its ring). - { - // The rules drawn over the row (paneDecor, after this) cut into - // it: the ring runs inside them, from rule to rule. - const tag = for (regions) |part| { - if (part.kind == .tag and part.owner == grip.owner) break part; - } else grip; - const tag_bottom = for (regions) |part| { - if (part.kind == .rail and part.owner == grip.owner) break part.rect.y < tag.rect.y; - } else false; - const stacked = !tag_bottom and for (regions) |other| { - if ((other.kind == .body or other.kind == .tag) and other.owner != grip.owner and other.rect.y + other.rect.h == grip.rect.y and - other.rect.x < tag.rect.x + tag.rect.w and tag.rect.x < other.rect.x + other.rect.w) break true; - } else false; - const top_rule: f32 = if (tag_bottom) dp(1) else if (stacked) @max(1, @min(rulePx(chrome), @as(f32, @floatFromInt(taglineBandOffset(grip.rect.y, win_h, g.cell_h, g.tagline_height))))) else 0; - const bottom_rule: f32 = if (!tag_bottom and grip.rect.h == 1) dp(1) else 0; - const x0 = button[0]; - const x1 = button[2]; - const y0 = button[1] + top_rule; - const y1 = button[3] - bottom_rule; - const ring = if (grip.active) chrome.grip_focus_ring else chrome.grip_border; - // acme's ButtonBorder: two logical pixels. - const b = dp(2); - try addDecor(g, gpa, x0, y0, x1, y0 + b, ring, 1, win_w, win_h); - try addDecor(g, gpa, x0, y1 - b, x1, y1, ring, 1, win_w, win_h); - try addDecor(g, gpa, x0, y0 + b, x0 + b, y1 - b, ring, 1, win_w, win_h); - try addDecor(g, gpa, x1 - b, y0 + b, x1, y1 - b, ring, 1, win_w, win_h); - if (grip.dirty and !grip.active) { - const gap = b + dp(1); - try addDecor(g, gpa, x0 + b, y0 + b, x1 - b, y0 + gap, band, 1, win_w, win_h); - try addDecor(g, gpa, x0 + b, y1 - gap, x1 - b, y1 - b, band, 1, win_w, win_h); - try addDecor(g, gpa, x0 + b, y0 + gap, x0 + gap, y1 - gap, band, 1, win_w, win_h); - try addDecor(g, gpa, x1 - gap, y0 + gap, x1 - b, y1 - gap, band, 1, win_w, win_h); - } - } - // The marks are the first row's alone, where its cell is blank (no - // mode glyph), centered in the button, in its ink from the region's - // state. - const x = grip.rect.x; - const y = grip.rect.y; - if (x >= cols) continue; - const cell = &cells[@as(usize, y) * cols + x]; - if (cell.default or cell.printableAscii() != ' ') continue; - const rgb = inkOn(gripFill(chrome, grip.active, grip.dirty)); - const center_x = @floor((button[0] + button[2]) / 2); - const center_y = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))) + @as(f32, @floatFromInt(g.tagline_height)) / 2; - const half_w = @max(dp(1), @min(dp(3), @floor((button[2] - button[0] - 2 * dp(3)) / 2))); - // The mode's two bars: a logical pixel thick, a pixel either side of - // the middle. - const bar = dp(1); - try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y - bar - dp(1)), @floor(center_x + half_w), @floor(center_y - dp(1)), rgb, 1, win_w, win_h); - try addDecor(g, gpa, @floor(center_x - half_w), @floor(center_y + dp(1)), @floor(center_x + half_w), @floor(center_y + dp(1) + bar), rgb, 1, win_w, win_h); - } -} - -const CursorBox = struct { x0: f32, y0: f32, x1: f32, y1: f32, rgb: [3]u8, bar: bool }; -const max_cursors = 1 + pardes.MAX_PANES + pardes.MAX_TAG_LAYERS; - -/// Where the frame draws the focused caret, its top in grid rows: from its -/// own springs (the quad's, while it moves or while a glide moves the text) -/// or its cell; carried by the text's glide when its line rode it. The probe -/// records it and the glide tests hold its invariants. -fn caretRow(g: *const Gui, surface: *const pardes.Surface, now_ns: u64) ?f32 { - const cursor = surface.cursor orelse return null; - const quad = g.caret.placed and (g.caret.moving() or g.glide.follow.offset != 0); - return if (quad) g.caret.sample(now_ns)[0][1] - caretRide(g, surface) else @floatFromInt(cursor.y); -} - -/// What the caret's ease sees in the frame about to be drawn (Caret.see): -/// the focused cursor's box in cells (its own cell's, or the layer's that -/// draws it), and the focused body's pane, first line and place. -fn seeCaret(g: *Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, now_ns: u64) void { - const box: ?Caret.Box = if (surface.cursor) |cursor| box: { - var boxes: [max_cursors]CursorBox = undefined; - const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; - if (all.len == 0) break :box null; - const cx = (@as(f32, @floatFromInt(cursor.x)) + 0.5) * layout.w; - const cy = (@as(f32, @floatFromInt(cursor.y)) + 0.5) * layout.h; - var best = all[0]; - var nearest = std.math.inf(f32); - for (all) |b| { - const dx = (b.x0 + b.x1) / 2 - cx; - const dy = (b.y0 + b.y1) / 2 - cy; - if (dx * dx + dy * dy < nearest) { - nearest = dx * dx + dy * dy; - best = b; - } - } - break :box .{ .x = best.x0 / layout.w, .y = best.y0 / layout.h, .w = (best.x1 - best.x0) / layout.w, .h = (best.y1 - best.y0) / layout.h }; - } else null; - for (surface.regionList()) |region| if (region.kind == .body and region.active) - return g.caret.see(box, region.owner, region.line, region.rect.x, region.rect.y, now_ns); - g.caret.see(box, pardes.Region.none, 0, 0, 0, now_ns); -} - -/// The caret's ease (G3), the window's own: the focused cursor's quad on -/// critically damped springs at its box's corners, in grid cells, on the -/// window's clock, from the cursor the Surface shows. A jump glides, its -/// leading corners first, bowing a little on a long one; a step eases, and -/// a stream of them (typing, a held key) keeps up; a scroll or a pane's move -/// carries it with its text; a focus change glides from where it was drawn. -/// The quad is drawn only while it moves: at rest the cells draw the cursor. -const Caret = struct { - /// Top left, top right, bottom right, bottom left; x then y. - corners: [4][2]Spring = @splat(@splat(.{})), - target: Box = .{}, - from_centre: [2]f32 = .{ 0, 0 }, - placed: bool = false, - /// When the last step (a move of a cell or less) came. - step_ns: u64 = 0, - /// The focused body as the last frame showed it: its pane, its first - /// line and its top left, to tell a scroll and a pane's move from the - /// caret's own. - seen: struct { owner: u8 = pardes.Region.none, line: i32 = 0, x: u16 = 0, y: u16 = 0 } = .{}, - - /// The default flavour's spring, as fast again as the caret follows - /// input (it settles in 90-150 ms). - const omega: f32 = 34 * 2.4; - /// The trailing corners of a jump, a little behind the leading ones. - const follow: f32 = 0.85; - /// A step's spring, stiffer than a jump's. - const step_pace: f32 = 1.5; - /// A jump longer than this, in cells, bows, by this much of its length. - const arc_from: f32 = 8; - const arc: f32 = 0.04; - /// Steps this close are a stream: each lands. - const stream_ns: u64 = 150 * std.time.ns_per_ms; - - const Box = struct { x: f32 = 0, y: f32 = 0, w: f32 = 0, h: f32 = 0 }; - - /// One axis on a critically damped spring, closed form: a new target - /// keeps the value and its speed; settled, it is its target. - const Spring = struct { - omega: f32 = omega, - target: f32 = 0, - from: f32 = 0, - velocity: f32 = 0, - from_ns: u64 = 0, - settled: bool = true, - - fn at(s: *const Spring, now_ns: u64) [2]f32 { - if (s.settled) return .{ s.target, 0 }; - const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| s.from_ns)) / std.time.ns_per_s); - const x0 = s.from - s.target; - const k = s.velocity + s.omega * x0; - const decay = @exp(-s.omega * t); - return .{ s.target + (x0 + k * t) * decay, (s.velocity - s.omega * t * k) * decay }; - } - - fn value(s: *const Spring, now_ns: u64) f32 { - return s.at(now_ns)[0]; - } - - fn retarget(s: *Spring, target: f32, now_ns: u64, w: f32) void { - if (target == s.target) return; - const state = s.at(now_ns); - s.* = .{ .omega = w, .target = target, .from = state[0], .velocity = state[1], .from_ns = now_ns, .settled = false }; - } - - /// Settles within half a percent of a cell, barely moving; true - /// while it still moves. - fn step(s: *Spring, now_ns: u64) bool { - if (s.settled) return false; - const state = s.at(now_ns); - if (@abs(state[0] - s.target) < 5e-3 and @abs(state[1]) < 5e-2) s.settled = true; - return !s.settled; - } - }; - - fn cornersOf(box: Box) [4][2]f32 { - return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; - } - - fn centre(box: Box) [2]f32 { - return .{ box.x + box.w / 2, box.y + box.h / 2 }; - } - - /// Heads for `box`: eased, or landed at once (`land`: a scroll moved - /// the text under it, not the caret). - fn aim(caret: *Caret, box: Box, now_ns: u64, land_it: bool) void { - if (caret.placed and std.meta.eql(box, caret.target) and !(land_it and caret.moving())) return; - const to = cornersOf(box); - const from_c = if (caret.placed) caret.centreAt(now_ns) else centre(box); - const to_c = centre(box); - const dx = to_c[0] - from_c[0]; - const dy = to_c[1] - from_c[1]; - const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; - // A step is measured mark to mark, not from where an ease under way - // has got to (a held key's steps would read as jumps from there). - const last = centre(caret.target); - const one_step = caret.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; - const streaming = one_step and caret.step_ns != 0 and now_ns -| caret.step_ns < stream_ns; - if (one_step) caret.step_ns = now_ns; - const land = !caret.placed or land_it or streaming; - caret.from_centre = from_c; - caret.target = box; - caret.placed = true; - for (&caret.corners, to) |*corner, point| { - // Leading: the corner ahead of the move, on the side it goes. - const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; - const w = if (jump) omega * (if (ahead > 0) 1 else follow) else omega * step_pace; - for (corner, point) |*axis, v| { - if (land) axis.* = .{ .omega = w, .target = v, .from = v } else axis.retarget(v, now_ns, w); - } - } - } - - fn centreAt(caret: *const Caret, now_ns: u64) [2]f32 { - var sum: [2]f32 = .{ 0, 0 }; - for (caret.corners) |corner| for (&sum, corner) |*s, axis| { - s.* += axis.value(now_ns) / 4; - }; - return sum; - } - - /// The text under it moved by (dx, dy) cells: so does the quad. - fn shift(caret: *Caret, dx: f32, dy: f32) void { - for (&caret.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| { - axis.from += d; - axis.target += d; - }; - caret.from_centre = .{ caret.from_centre[0] + dx, caret.from_centre[1] + dy }; - caret.target.x += dx; - caret.target.y += dy; - } - - /// The quad at `now_ns`, bowed on a long jump. - fn sample(caret: *const Caret, now_ns: u64) [4][2]f32 { - var out: [4][2]f32 = undefined; - for (&out, caret.corners) |*point, corner| for (point, corner) |*v, axis| { - v.* = axis.value(now_ns); - }; - const to_c = centre(caret.target); - const dx = to_c[0] - caret.from_centre[0]; - const dy = to_c[1] - caret.from_centre[1]; - const length = @sqrt(dx * dx + dy * dy); - if (length < arc_from) return out; - const now_c = caret.centreAt(now_ns); - const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1])); - const travelled = std.math.clamp(1 - left / length, 0, 1); - const bow = arc * length * 4 * travelled * (1 - travelled); - for (&out) |*point| { - point[0] += -dy / length * bow; - point[1] += dx / length * bow; - } - return out; - } - - /// Steps the springs to `now_ns`; true while the quad still moves. - fn step(caret: *Caret, now_ns: u64) bool { - var any = false; - for (&caret.corners) |*corner| for (corner) |*axis| { - if (axis.step(now_ns)) any = true; - }; - return any; - } - - /// How far, in cells, the furthest corner still is from its mark. - fn remaining(caret: *const Caret, now_ns: u64) f32 { - var most: f32 = 0; - for (caret.corners) |corner| for (corner) |axis| { - most = @max(most, @abs(axis.value(now_ns) - axis.target)); - }; - return most; - } - - fn moving(caret: *const Caret) bool { - for (caret.corners) |corner| for (corner) |axis| { - if (!axis.settled) return true; - }; - return false; - } - - /// The frame about to be drawn shows the focused cursor at `box` (grid - /// cells; null: none) in pane `owner`'s body, whose first line is - /// `line` and top left (x, y): carried with that body when it moved or - /// scrolled, eased to its box otherwise. - fn see(caret: *Caret, box: ?Box, owner: u8, line: i32, x: u16, y: u16, now_ns: u64) void { - const b = box orelse { - // Nowhere to land: a glide under way stops; the next cursor - // lands where it is. - caret.* = .{}; - return; - }; - var land = false; - const was = caret.seen; - if (was.owner == owner and owner != pardes.Region.none) { - // The pane moved in the layout: its caret moves with it. - caret.shift(@as(f32, @floatFromInt(x)) - @as(f32, @floatFromInt(was.x)), @as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(was.y))); - // Scrolled: the text moved, not the caret; it lands on its - // cell (the glide draws it with the text, caretRide). - land = line != was.line; - } - caret.seen = .{ .owner = owner, .line = line, .x = x, .y = y }; - caret.aim(b, now_ns, land); - _ = caret.step(now_ns); - } -}; - -/// The rows a caret whose line rode the wheel's glide is drawn above its -/// cell: the text's own offset, so it moves with its line as a glyph does -/// (its springs landed on the cell, Caret.see). -fn caretRide(g: *const Gui, surface: *const pardes.Surface) f32 { - const glide = &g.glide; - const cu = surface.cursor orelse return 0; - if (glide.follow.offset != 0) { - if (!glide.caret_rides) return 0; - const x0 = glide.rect.x + config.GUTTER; - if (cu.x < x0 or cu.x >= x0 + glide.bw() or cu.y < glide.body_y or cu.y >= glide.body_y + glide.body_h) return 0; - return glide.follow.offset; - } - // A fine wheel's or a touchpad's fraction (scroll_lag) holds the whole - // body off its cells, the caret's row with the rest, at rest too. - if (g.scroll_lag == 0 or g.scroll_pane == null) return 0; - const r = g.scroll_rect; - if (cu.x < r.x + config.GUTTER or cu.x >= r.x + r.w or cu.y < g.scroll_body_y or cu.y >= g.scroll_body_y + g.scroll_body_h) return 0; - return g.scroll_lag; -} - -/// The bar cursors as decor; a block cursor is its cell's own colours. -fn cursorDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32) !void { - var boxes: [max_cursors]CursorBox = undefined; - // The focused one is drawn with its line where a wheel's fraction holds - // the text off its cells (a block is a cell of the shifted rows). - // The focused box is the one nearest its cell (a body layer's is lifted - // off the grid), as seeCaret finds it. - const ride = caretRide(g, surface) * layout.h; - const all = boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]; - var focused: usize = all.len; - if (surface.cursor) |cu| { - const cx = (@as(f32, @floatFromInt(cu.x)) + 0.5) * layout.w; - const cy = (@as(f32, @floatFromInt(cu.y)) + 0.5) * layout.h; - var nearest = std.math.inf(f32); - for (all, 0..) |b, i| { - const d = ((b.x0 + b.x1) / 2 - cx) * ((b.x0 + b.x1) / 2 - cx) + ((b.y0 + b.y1) / 2 - cy) * ((b.y0 + b.y1) / 2 - cy); - if (d < nearest) { - nearest = d; - focused = i; - } - } - } - for (all, 0..) |box, i| if (box.bar) { - const shift = if (i == focused) ride else 0; - try addDecor(g, gpa, box.x0, box.y0 - shift, box.x1, box.y1 - shift, box.rgb, 1, win_w, win_h); - }; -} - -/// The triangle overlay: the cursor's glide, over everything. -fn buildOverlay( - g: *Gui, - which: pardes.config.Runtime.Pet, - trail_on: bool, - surface: *const pardes.Surface, - now_ns: u64, - sw: u32, - sh: u32, -) u32 { - if (g.overlay_vertices.len == 0 or sw == 0 or sh == 0) return 0; - var builder = OverlayBuilder{ .vertices = g.overlay_vertices, .win_w = @floatFromInt(sw), .win_h = @floatFromInt(sh) }; - appendWorkspacePet(g, which, surface, &builder); - appendJumpTrail(g, trail_on, surface, now_ns, &builder); - appendCursorGlide(g, surface, now_ns, &builder); - return @intCast(builder.len); -} - -/// A jump's trail (jump_trail.zig): the cells behind the cursor in its -/// body, on the page's own ground, drawn over toward the text's colour. -fn appendJumpTrail(g: *Gui, on: bool, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { - var at: [5]JumpTrail.Cell = undefined; - const lit = g.trail.see(if (surface.cursor) |cu| .{ cu.x, cu.y } else null, on, now_ns, &at); - if (lit.len == 0) return; - const cursor = surface.cursor.?; - const body = for (surface.regionList()) |region| { - if (region.kind == .body and cursor.x >= region.rect.x and cursor.x < @as(u32, region.rect.x) + region.rect.w and - cursor.y >= region.rect.y and cursor.y < @as(u32, region.rect.y) + region.rect.h) break region.rect; - } else return; - const page = surface.chrome.page orelse bg_default; - const w: f32 = @floatFromInt(g.cell_w); - const h: f32 = @floatFromInt(g.cell_h); - for (lit) |cell| { - if (cell.x < body.x or cell.y < body.y or cell.x >= @as(i32, body.x) + body.w or cell.y >= @as(i32, body.y) + body.h) continue; - const under = &surface.cells[@as(usize, @intCast(cell.y)) * surface.cols + @as(usize, @intCast(cell.x))]; - // On the page's own ground alone: never a selection or a match. - const ground: [3]u8 = if (under.default) page else switch (under.style.bg) { - .rgb => |rgb| rgb, - else => page, - }; - if (!std.mem.eql(u8, &ground, &page)) continue; - var color = overlayRgb(surface.chrome.fg orelse fg_default); - color.a = cell.strength; - const x0 = @as(f32, @floatFromInt(cell.x)) * w; - const y0 = @as(f32, @floatFromInt(cell.y)) * h; - builder.addRect(x0, y0, x0 + w, y0 + h, color); - } -} - -/// The workspace tag's pet (the Pet setting, gui/pet.zig): in the blank -/// end of the grid's first row, past the tag's text, in the tag's colours, -/// on the window's own clock. Nothing of it reaches the core. -fn appendWorkspacePet(g: *Gui, which: pardes.config.Runtime.Pet, surface: *const pardes.Surface, builder: *OverlayBuilder) void { - const kind: pet.Kind = @fromBackingInt(@backingInt(which)); - if (kind == .off or surface.rows == 0 or surface.cols == 0) { - g.pet_state = .{}; - return; - } - var occupied: usize = 0; - for (surface.cells[0..surface.cols], 0..) |*cell, i| { - if (cellCodepoint(cell) != ' ') occupied = i + 1; - } - 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), - builder.win_w, - band_top, - @floatFromInt(g.tagline_height), - ); - // ponytail: it moves when the window draws; a wake of its own for an - // idle window if a still pet ever matters. - const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; - const ink = overlayRgb(surface.chrome.tag_fg); - const eye = overlayRgb(surface.chrome.tag_bg); - // Behind the cursor: the overlay is over the cells, so the pixels a - // cursor covers are left out. - var boxes: [max_cursors]CursorBox = undefined; - const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; - for (0..pet.height) |y| for (0..pet.width) |x| { - const color = pet.pixel(kind, pose, x, y); - if (color == 0) continue; - const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; - const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; - const covered = for (cursors) |box| { - if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; - } else false; - if (covered) continue; - builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); - }; -} - -fn overlayRgb(rgb: [3]u8) OverlayColor { - return .{ - .r = @as(f32, @floatFromInt(rgb[0])) / 255.0, - .g = @as(f32, @floatFromInt(rgb[1])) / 255.0, - .b = @as(f32, @floatFromInt(rgb[2])) / 255.0, - .a = 1, - }; -} - -/// G3: the focused cursor while it glides or blinks, its quad from the -/// window's caret (Caret, grid cells) in its cursor colour; a little less -/// than solid, so the glyphs it passes over stay legible. -fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, builder: *OverlayBuilder) void { - const chrome = &surface.chrome; - if (g.cursor_quad_alpha <= 0.001) return; - const layout = fixedCellLayout(g); - const ride = caretRide(g, surface); - // Never off the grid, however a long jump bows. - var quad = g.caret.sample(now_ns); - for (&quad) |*point| point.* = .{ std.math.clamp(point[0], 0, @as(f32, @floatFromInt(surface.cols))), std.math.clamp(point[1], 0, @as(f32, @floatFromInt(surface.rows))) }; - if (ride != 0) { - // Carried past the body's edge with its line: clipped as the text is. - const mid = quad[0][1] - ride + 0.5; - const top: f32 = @floatFromInt(g.glide.body_y); - if (mid < top or mid > top + @as(f32, @floatFromInt(g.glide.body_h))) return; - } - var px: [4][2]f32 = undefined; - var centre: [2]f32 = .{ 0, 0 }; - for (&px, 0..) |*point, i| { - point.* = .{ quad[i][0] * layout.w, (quad[i][1] - ride) * layout.h }; - centre[0] += point[0] / 4; - centre[1] += point[1] / 4; - } - // Its colour: the cursor the cells would draw nearest the quad. - var boxes: [max_cursors]CursorBox = undefined; - var rgb: [3]u8 = chrome.fg orelse fg_default; - var nearest: f32 = std.math.inf(f32); - for (boxes[0..cursorBoxes(g, surface, layout, builder.win_h, &boxes)]) |box| { - const dx = (box.x0 + box.x1) / 2 - centre[0]; - const dy = (box.y0 + box.y1) / 2 - centre[1]; - if (dx * dx + dy * dy < nearest) { - nearest = dx * dx + dy * dy; - rgb = box.rgb; - } - } - const color: OverlayColor = .{ .r = @as(f32, @floatFromInt(rgb[0])) / 255, .g = @as(f32, @floatFromInt(rgb[1])) / 255, .b = @as(f32, @floatFromInt(rgb[2])) / 255, .a = g.cursor_quad_alpha }; - builder.addTri(px[0][0], px[0][1], px[1][0], px[1][1], px[2][0], px[2][1], color); - builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color); -} - -const OverlayBuilder = struct { - vertices: []OverlayVertex, - len: usize = 0, - win_w: f32, - win_h: f32, - - fn addVertex(b: *OverlayBuilder, px: f32, py: f32, color: OverlayColor) void { - if (b.len >= b.vertices.len) return; - b.vertices[b.len] = .{ - .x = (px / b.win_w) * 2.0 - 1.0, - .y = 1.0 - (py / b.win_h) * 2.0, - .r = color.r, - .g = color.g, - .b = color.b, - .a = color.a, - }; - b.len += 1; - } - - fn addTri(b: *OverlayBuilder, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, color: OverlayColor) void { - if (b.len + 3 > b.vertices.len) return; - b.addVertex(x0, y0, color); - b.addVertex(x1, y1, color); - b.addVertex(x2, y2, color); - } - - fn addRect(b: *OverlayBuilder, x0_in: f32, y0_in: f32, x1_in: f32, y1_in: f32, color: OverlayColor) void { - if (b.len + 6 > b.vertices.len) return; - const x0 = std.math.clamp(@min(x0_in, x1_in), 0.0, b.win_w); - const x1 = std.math.clamp(@max(x0_in, x1_in), 0.0, b.win_w); - const y0 = std.math.clamp(@min(y0_in, y1_in), 0.0, b.win_h); - const y1 = std.math.clamp(@max(y0_in, y1_in), 0.0, b.win_h); - if (x1 <= x0 or y1 <= y0) return; - b.addTri(x0, y0, x1, y0, x1, y1, color); - b.addTri(x0, y0, x1, y1, x0, y1, color); - } -}; - -fn envU16(env: *std.process.Environ.Map, name: []const u8) ?u16 { - const raw = env.get(name) orelse return null; - return std.fmt.parseInt(u16, raw, 10) catch null; -} - -fn pixelCell(px: f32, cell: u32) u16 { - const idx = @floor(@max(px, 0) / @as(f32, @floatFromInt(@max(cell, 1)))); - return @intFromFloat(@min(idx, 10_000)); -} - -fn wheelRunFile(gpa: std.mem.Allocator) !*pardes.Pardes { - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - errdefer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..400) |i| try text.print(gpa, "{d:0>4} a line of the file\n", .{i}); - _ = try core.setTestFile(text.items); - for ("200G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); - return core; -} - -fn tagLayerIn(layers: []const pardes.Layer, col: u16, row: u16) ?*const pardes.Layer { - for (layers) |*layer| { - const r = layer.viewport; - if (layer.rows > 0 and row >= r.y and row - r.y < layer.rows and col >= r.x and col - r.x < r.w) return layer; - } - return null; -} - -fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []const pardes.Layer, tag_layers: []const pardes.Layer) !void { - for (0..rows) |row| for (0..cols) |col| { - const scan = bodyLayerIn(body_layers, @intCast(col), @intCast(row)) != null or tagLayerIn(tag_layers, @intCast(col), @intCast(row)) != null; - try std.testing.expectEqual(scan, cover[row * cols + col].layer); - }; -} - -/// A Gui that can shape and rasterize the face in `bytes` at `px`, and -/// nothing else. From here on the fonts allocate from std.testing.allocator -/// (the caller puts font_allocator back), so the test counts what they leak. -fn textTestGui(bytes: []const u8, px: f32) !Gui { - var atlas = try Atlas.init(std.testing.allocator, bytes); - atlas.prime(); - font_allocator = std.testing.allocator; - var cw: c_int = 0; - var ch: c_int = 0; - var ascent: c_int = 0; - atlas.cellMetrics(px, &cw, &ch, &ascent); - const tag = taglineRaster(&atlas, px, @intCast(cw), @intCast(ch), 82); - var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); - g.atlas = atlas; - g.px = px; - g.ascent = ascent; - g.tagline_px = tag.px; - g.tagline_baseline = tag.baseline; - resetGlyphAtlas(&g); - return g; -} - -fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell { - var line: [text.len]pardes.Cell = @splat(.{ .default = false }); - for (&line, text) |*cell, byte| cell.text[0] = byte; - return line; -} - -fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { - var it = g.atlas.glyphs.iterator(); - while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; - return error.NoGlyph; -} - -/// Every cursor on the frame where it is drawn, in window pixels: the grid's -/// where no layer has its cell, and each layer's at that layer's pitch. A bar -/// is an eighth of its cell wide, a block the whole cell. -fn cursorBoxes(g: *const Gui, surface: *const pardes.Surface, layout: CellLayout, win_h: f32, out: *[max_cursors]CursorBox) usize { - const chrome = &surface.chrome; - var n: usize = 0; - if (surface.cursor) |cursor| { - if (cursor.x < surface.cols and cursor.y < surface.rows and bodyLayerIn(surface.bodyLayers(), cursor.x, cursor.y) == null and tagLayerIn(surface.tagLayers(), cursor.x, cursor.y) == null) { - const cell = &surface.cells[@as(usize, cursor.y) * surface.cols + cursor.x]; - const role = cellFontRole(cell); - const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; - const height = std.math.clamp(if (role == .tagline) @as(f32, @floatFromInt(g.tagline_height)) else layout.h, 1.0, layout.h); - const x0 = @as(f32, @floatFromInt(cursor.x)) * layout.w; - const y0 = @as(f32, @floatFromInt(cursor.y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(cursor.y, win_h, @intFromFloat(layout.h), @intFromFloat(height)))); - out[n] = .{ .x0 = x0, .y0 = y0, .x1 = x0 + if (cursor.bar) @max(dp(1), width / 8.0) else width, .y1 = y0 + height, .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; - n += 1; - } - } - for (surface.bodyLayers()) |*layer| { - if (layer.rows == 0) continue; - const cursor = layer.cursor orelse continue; - if (cursor.y >= layer.rows or cursor.x >= layer.cols) continue; - const left = @as(f32, @floatFromInt(layer.viewport.x)) * layout.w; - const bottom = @as(f32, @floatFromInt(layer.viewport.y + layer.viewport.h)) * layout.h; - const top = layer.rowTop(cursor.y, layout.h, @floatFromInt(g.tagline_height)); - if (top >= bottom) continue; - const height = layer.rowHeight(cursor.y, layout.h, @floatFromInt(g.tagline_height)); - const role: pardes.FontRole = if (cursor.y < layer.context_rows) .tagline else .body; - const width: f32 = if (role == .tagline) @floatFromInt(g.tagline_width) else layout.w; - const x = left + @as(f32, @floatFromInt(cursor.x)) * width; - const cell = &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x]; - out[n] = .{ .x0 = x, .y0 = top, .x1 = x + if (cursor.bar) @max(dp(1), width / 8) else width, .y1 = @min(bottom, top + height), .rgb = cursorColor(chrome, cell, role), .bar = cursor.bar }; - n += 1; - } - for (surface.tagLayers()) |*layer| { - if (layer.rows == 0) continue; - const cursor = layer.cursor orelse continue; - if (cursor.x >= layer.cols or cursor.y >= layer.rows) continue; - const width: f32 = @floatFromInt(g.tagline_width); - const span = layer.caretSpan(cursor.x, layout.w, width, if (cursor.bar) @max(dp(1), width / 8) else width); - const y = layer.viewport.y + cursor.y; - const top = @as(f32, @floatFromInt(y)) * layout.h + @as(f32, @floatFromInt(taglineBandOffset(y, win_h, g.cell_h, g.tagline_height))); - out[n] = .{ .x0 = span[0], .y0 = top, .x1 = span[1], .y1 = top + @as(f32, @floatFromInt(g.tagline_height)), .rgb = cursorColor(chrome, &layer.cells[@as(usize, cursor.y) * layer.cols + cursor.x], .tagline), .bar = cursor.bar }; - n += 1; - } - return n; -} - -fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { - return if (role == .tagline) switch (cell.style.fg) { - .rgb => |rgb| rgb, - else => chrome.tag_fg, - } else chrome.fg orelse fg_default; -} - -test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { - // HarfBuzz's process-wide objects come from the default heap, as in runNative. - var primer = try Atlas.init(std.testing.allocator, font_ttf); - primer.prime(); - primer.deinit(std.testing.allocator); - font_allocator = std.testing.allocator; - defer font_allocator = std.heap.smp_allocator; - - var atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer atlas.deinit(std.testing.allocator); - atlas.reset(32); - const size: Atlas.Size = .{ .px = 27, .cell_w = 32, .height = 48, .baseline = 30 }; - const g_slot = atlas.cachedGlyph(.{ .face = 0, .glyph = atlas.glyphForCodepoint('g').glyph, .role = .body, .decoration = .{ .bold = true } }, size, size, config.GUTTER, 1).?; - try std.testing.expect(Atlas.inkBounds(atlas.atlas_stage[@as(usize, g_slot.v) * atlas_w + g_slot.u ..], atlas_w, 32, 48) != null); - try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph)); - - // A font with ligatures runs the whole HarfBuzz pass. - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(bytes); - var maple = try Atlas.init(std.testing.allocator, bytes); - defer maple.deinit(std.testing.allocator); - var cell_w: c_int = 0; - var cell_h: c_int = 0; - var ascent: c_int = 0; - maple.cellMetrics(27, &cell_w, &cell_h, &ascent); - const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; - var shaped: [text.len]c.UIShapedCell = undefined; - maple.shape(0, 27, @intCast(cell_w), &text, &shaped); - try std.testing.expectEqual(@as(u8, 2), shaped[1].span); - try std.testing.expectEqual(@as(u8, 2), shaped[4].span); -} - -test "every font size step moves the cell, and the ends are reachable exactly" { - var atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer atlas.deinit(std.testing.allocator); - var px = font_px_min + font_px_step; - while (px <= font_px_max) : (px += 1.0) { - var cw: c_int = 0; - var ch: c_int = 0; - var asc: c_int = 0; - var pw: c_int = 0; - var ph: c_int = 0; - atlas.cellMetrics(px, &cw, &ch, &asc); - atlas.cellMetrics(px - font_px_step, &pw, &ph, &asc); - try std.testing.expect(cw > pw and ch > ph); - } - try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max)); - try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max)); -} - -test "tagline glyph shrinks into its own cell and stays vertically centered" { - const body_px: f32 = 27.0; - var g = try textTestGui(font_ttf, body_px); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - _ = fitTaglineFont(&g, config.gui_tagline_font_percent); - const cell_w: c_int = @intCast(g.cell_w); - const cell_h: c_int = @intCast(g.cell_h); - const tag = taglineRaster(&g.atlas, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); - try std.testing.expect(tag.px < body_px); - try std.testing.expect(tag.width < @as(u32, @intCast(cell_w))); - - // Each at its role's size, as a frame draws it. - const h = g.atlas.glyphForCodepoint('H').glyph; - const body = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .body }).?; - const tagline = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .tagline }).?; - const b = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, body.v) * atlas_w + body.u ..], atlas_w, @intCast(cell_w), @intCast(cell_h)).?; - const t = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, tagline.v) * atlas_w + tagline.u ..], atlas_w, @intCast(tag.width), @intCast(tag.height)).?; - try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x); - try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y); - const body_center_x: isize = @intCast(b.min_x + b.max_x); - const tag_center_x: isize = @intCast(t.min_x + t.max_x); - const body_center_y: isize = @intCast(b.min_y + b.max_y); - const centered_top: isize = @intCast((@as(u32, @intCast(cell_h)) - tag.height) / 2); - const tag_center_y: isize = @as(isize, @intCast(t.min_y + t.max_y)) + centered_top * 2; - const body_slot_center: isize = @intCast(@as(u32, @intCast(cell_w)) - 1); - const tag_slot_center: isize = @intCast(tag.width - 1); - try std.testing.expect(@abs((tag_center_x - tag_slot_center) - (body_center_x - body_slot_center)) <= 2); - try std.testing.expect(@abs(tag_center_y - body_center_y) <= 4); - try std.testing.expect(tag.height < @as(u32, @intCast(cell_h))); -} - -test "tagline percentage changes measured band height without body metrics" { - var atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer atlas.deinit(std.testing.allocator); - var cell_w: c_int = 1; - var cell_h: c_int = 1; - var ascent: c_int = 1; - atlas.cellMetrics(27.0, &cell_w, &cell_h, &ascent); - const small = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 40); - const configured = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 82); - const full = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 100); - try std.testing.expect(small.width < configured.width); - try std.testing.expect(configured.width <= full.width); - try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width); - try std.testing.expect(small.height < configured.height); - try std.testing.expect(configured.height <= full.height); - try std.testing.expect(full.height <= @as(u32, @intCast(cell_h))); -} - -test "installed Nerd Symbols fallback covers Yazi directory icons" { - try std.testing.expectEqualStrings("SymbolsNerdFont-Regular", fonts.fallback_names[2]); - - var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena_state.deinit(); - const candidate = for (fonts.fallbacks(arena_state.allocator())) |font| { - if (std.mem.eql(u8, font.name, "SymbolsNerdFont-Regular")) break font; - } else return; - - const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); - defer std.testing.allocator.free(bytes); - var atlas = try Atlas.init(std.testing.allocator, bytes); - defer atlas.deinit(std.testing.allocator); - try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); -} - -test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf '\\120\\101\\122\\104\\105\\123\\055\\124\\101\\111\\114'; exit\n")); - var bytes: std.ArrayList(u8) = .empty; - defer bytes.deinit(gpa); - var eof = false; - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (!eof and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - for (batch.slice()) |msg| switch (msg) { - .output => |o| { - try std.testing.expect(!eof); - try bytes.appendSlice(gpa, o.bytes); - }, - .eof => |e| { - try std.testing.expect(e.failure == null); - eof = true; - }, - else => return error.UnexpectedMessage, - }; - if (!eof) try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expect(eof); - try std.testing.expect(std.mem.indexOf(u8, bytes.items, "PARDES-TAIL") != null); - shell.closePty(0); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expect(ptys[0] == null or ptys[0].?.reader == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); -} - -test "GUI PTY Restore joins a real reader waiting for queue space" { - const gpa = std.testing.allocator; - var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - try dump.dumpState(core); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - queue.acceptReader(1, 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); - try host_io.PtyTests.waitBlocked(&queue); - const old_serial = core.panes[0].?.serial; - const replacement = try dump.restore(core, core.dump_out.?, "test"); - shell.stopPtys(); - core.deinit(); - core = replacement; - shell.core = replacement; - // The dump's pane, its serial too; its old shell stopped all the same. - try std.testing.expectEqual(old_serial, core.panes[0].?.serial); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - queue.cancelReader(1, 1); - queue.acceptReader(0, gens[0]); - queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - try std.testing.expect(queue.pushOutput(0, gens[0], try gpa.dupe(u8, "fresh"))); - var batch = queue.take(); - defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqualStrings("fresh", batch.items[0].output.bytes); -} - -test "GUI PTY deletion joins an idle reader and its shell is reaped by exit" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var shell: Shell = undefined; - shell.core = core; - shell.gpa = gpa; - shell.ptys = &ptys; - shell.gens = &gens; - shell.queue = &queue; - defer shell.shutdownPtys(); - const rcs: host_io.Shell.PromptFiles = .{}; - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - ptys[0].?.reader = try queue.startReader(.{ .handle = ptys[0].?.fd, .flags = .{ .nonblocking = false } }, 0, 1); - try core.removePane(0, null); - shell.reconcilePtys(); - try std.testing.expect(queue.readers[0] == null); - try std.testing.expectEqual(@as(usize, 0), queue.waiting); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); - try std.testing.expectEqual(@as(c_int, -1), libc.fcntl(child.file.handle, libc.F.GETFD)); - shell.shutdownPtys(); - try std.testing.expectEqual(@as(libc.pid_t, -1), libc.waitpid(child.pid, null, libc.W.NOHANG)); - try std.testing.expectEqual(libc.E.CHILD, libc.errno(-1)); -} - -test "GUI PTY file watcher stops and joins without closing its watched descriptor" { - if (!file_watch.supported) return error.SkipZigTest; - const gpa = std.testing.allocator; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - const fd = file_watch.init(true); - if (fd < 0) return error.WatchInitFailed; - defer _ = libc.close(fd); - const stop = try stopPipe(); - defer for (stop) |pipe_fd| { - _ = libc.close(pipe_fd); - }; - const thread = try std.Thread.spawn(.{}, watchThread, .{ fd, stop[0], &queue }); - _ = host_io.writeFd(stop[1], "x"); - thread.join(); - try std.testing.expect(libc.fcntl(fd, libc.F.GETFD) >= 0); - try std.testing.expectEqual(@as(usize, 0), queue.take().len); -} - -test "GUI completion failure survives backlog and leaves the document unchanged" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - pane.body.cur_col = 1; - core.lspRequest(core.view().active, .completion, ""); - const id = core.lsp_ask.wait.?.id; - var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = id }; - defer queue.deinit(); - queue.acceptReader(0, 1); - for (0..output_capacity) |_| queue.push(.{ .output = .{ - .pane = 0, - .gen = 1, - .bytes = try gpa.dupe(u8, "output"), - } }); - queue.push(.{ .lsp = .{ .id = id, .rows = null } }); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var shell: Shell = undefined; - shell.core = core; - shell.queue = &queue; - shell.gpa = gpa; - shell.lsp_allocator = gpa; - shell.gens = &gens; - shell.ptys = &ptys; - shell.drainQueue(); - try std.testing.expect(core.lsp_ask.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); -} - -test "GUI worker setup failures finish matching LSP and pipe requests" { - const gpa = std.testing.allocator; - var failing_vtable = std.testing.io.vtable.*; - failing_vtable.concurrent = std.Io.failingConcurrent; - const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; - for (0..2) |failure| { - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - const pane = try core.setTestFile("abc"); - var failing = std.testing.FailingAllocator.init(gpa, .{ - .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), - }); - var queue: Queue = .{ - .io = std.testing.io, - .gpa = gpa, - .lsp_allocator = failing.allocator(), - }; - defer queue.deinit(); - var tasks: PipeTasks = .{}; - core.lspRequest(core.view().active, .status, ""); - const req: host_io.Lsp.Request = .{ - .id = core.lsp_ask.wait.?.id, - .kind = .status, - .pane = @intCast(core.view().active), - .offset = 0, - .arg = "", - }; - if (failure == 0) { - queue.lsp_id = req.id -% 1; - queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); - queue.startLsp(core, req); - try std.testing.expectEqual(req.id, queue.lsp_id.?); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - } else { - var shell: Shell = undefined; - shell.core = core; - shell.threads_ok = false; - lsp(&shell, req); - } - try std.testing.expect(core.lsp_ask.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - - pane.body.cur_col = 2; - pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - core.update(.{ .key = .{ .cp = '|' } }); - core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); - core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe.wait.?.id; - selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe); - try std.testing.expect(core.pipe.wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expect(queue.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), tasks.len); - try std.testing.expectEqual(@as(usize, 0), queue.len); - } -} - -test "high-density window coordinates map once to render pixels" { - const geometry: WindowGeometry = .{ - .window_w = 560, - .window_h = 360, - .pixel_w = 1120, - .pixel_h = 720, - }; - try std.testing.expectEqual(Point{ .x = 700, .y = 240 }, windowPointToPixels(geometry, 350, 120)); -} - -test "the GUI's stdin keys reach a terminal pane as the tty's do: F5, Insert and the keypad's Up" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - var in: Input = .{ .core = core }; - var parser: vaxis.Parser = .{}; - var bytes: []const u8 = "\x1b[15~\x1b[2~\x1b[57419u"; - while (bytes.len > 0) { - const result = try parser.parse(bytes, gpa); - bytes = bytes[result.n..]; - if (result.event) |event| switch (event) { - .key_press => |key| postKey(&in, key, key.text orelse ""), - else => {}, - }; - } - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings("\x1b[15~\x1b[2~\x1b[A", written.written()); -} - -test "the window's function and editing keys reach a terminal as its cursor keys' mode and keyboard flags say" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.body.mode = .tty; - while (core.nextEffect()) |_| {} - var in: Input = .{ .core = core }; - var written: std.Io.Writer.Allocating = .init(gpa); - defer written.deinit(); - const Case = struct { modes: []const u8, sym: c.SDL_Keycode, mod: c.SDL_Keymod = 0, sent: []const u8 }; - const cases = [_]Case{ - .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[A" }, - .{ .modes = "", .sym = c.SDLK_HOME, .sent = "\x1b[H" }, - .{ .modes = "", .sym = c.SDLK_F1, .sent = "\x1bOP" }, - .{ .modes = "", .sym = c.SDLK_F5, .sent = "\x1b[15~" }, - .{ .modes = "", .sym = c.SDLK_F12, .mod = c.SDL_KMOD_LSHIFT, .sent = "\x1b[24;2~" }, - .{ .modes = "", .sym = c.SDLK_INSERT, .sent = "\x1b[2~" }, - // DECCKM: less, vim, htop. - .{ .modes = "\x1b[?1h", .sym = c.SDLK_UP, .sent = "\x1bOA" }, - .{ .modes = "", .sym = c.SDLK_END, .sent = "\x1bOF" }, - .{ .modes = "", .sym = c.SDLK_LEFT, .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[1;5D" }, - // codex's kitty flags (>7u): Ctrl-C and Alt-a are unambiguous. - // (A bare Escape at a shell prompt is pardes's way out of raw input.) - .{ .modes = "\x1b[?1l\x1b[>7u", .sym = 'c', .mod = c.SDL_KMOD_LCTRL, .sent = "\x1b[99;5u" }, - .{ .modes = "", .sym = 'a', .mod = c.SDL_KMOD_LALT, .sent = "\x1b[97;3u" }, - // With event types asked for (2), an arrow says it is a press, as - // the emulator's encoder says it. - .{ .modes = "", .sym = c.SDLK_UP, .sent = "\x1b[1;1:1A" }, - }; - for (cases) |case| { - core.update(.{ .output = .{ .pane = 0, .bytes = case.modes } }); - while (core.nextEffect()) |_| {} - keyDown(&in, case.sym, case.mod); - written.clearRetainingCapacity(); - while (core.nextEffect()) |effect| { - if (effect == .write) try written.writer.writeAll(effect.write.bytes.slice()); - } - try std.testing.expectEqualStrings(case.sent, written.written()); - } -} - -test "tagline pointer mapping retains physical grips and carries logical text coordinates" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); - core.update(.{ .command = "Newcol" }); - core.view().row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 12 }; - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - _ = try core.render(arena.allocator()); - - const r = core.view().rects[core.view().active]; - const body_w: f32 = 10; - const body_h: f32 = 20; - const tag_w: f32 = 8; - const tag_y = r.y; - const x = @as(f32, @floatFromInt(r.x + pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; - - const tag = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x, 10), tag.col); - try std.testing.expectEqual(tag_y, tag.row); - try std.testing.expectEqual(@as(u16, 3), tag.tag_hit.?.col); - try std.testing.expectEqual(pardes.TagKind.pane, tag.tag_hit.?.kind); - const grip = gridCellAtDimensions(core, @as(f32, @floatFromInt(r.x + config.GUTTER)) * body_w - 0.1, (@as(f32, @floatFromInt(tag_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expect(grip.tag_hit == null); - try std.testing.expectEqual(r.x + config.GUTTER - 1, grip.col); - - const body_y = tag_y + core.panes[core.view().active].?.tag_rows; // a long tag wraps - const body = gridCellAtDimensions(core, x, (@as(f32, @floatFromInt(body_y)) + 0.5) * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x, 10), body.col); - try std.testing.expectEqual(body_y, body.row); - try std.testing.expect(body.tag_hit == null); - - // The workspace tag's text starts TAG_TEXT_INSET cells in, as a pane's. - const x_top = @as(f32, @floatFromInt(pardes.TAG_TEXT_INSET)) * body_w + 3.5 * tag_w; - const topbar = gridCellAtDimensions(core, x_top, 0.5 * body_h, body_w, body_h, tag_w); - try std.testing.expectEqual(pixelCell(x_top, 10), topbar.col); - try std.testing.expectEqual(@as(u16, 3), topbar.tag_hit.?.col); - try std.testing.expectEqual(pardes.TagKind.workspace, topbar.tag_hit.?.kind); -} - -test "a click at the window's corner lands in the corner cell" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - var g = testGui(10, 20, 6, 12); - const geometry: WindowGeometry = .{ .window_w = 400, .window_h = 240, .pixel_w = 800, .pixel_h = 480 }; - const last = mouseCellWithGeometry(&g, core, 399.9, 239.9, geometry); - try std.testing.expectEqual(@as(u16, 79), last.col); - try std.testing.expectEqual(@as(u16, 23), last.row); - const first = mouseCellWithGeometry(&g, core, 0, 0, geometry); - try std.testing.expectEqual(@as(u16, 0), first.col); - try std.testing.expectEqual(@as(u16, 0), first.row); -} - -test "a blink holds while typing, eases at its edges and stops when idle" { - const ms = std.time.ns_per_ms; - try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); - const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); - try std.testing.expectEqual(@as(f32, 0), out.alpha); - const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); - try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); - try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); - try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); -} - -test "background opacity acknowledges success and rolls back unsupported surfaces" { - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - var applied: u8 = 100; - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 70")); - try std.testing.expect(core.settings.window_opacity_pending); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 70), applied); - try std.testing.expect(!core.settings.window_opacity_pending); - - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); - finishWindowOpacity(core, &applied, "background transparency requires an alpha-capable SDL window"); - try std.testing.expectEqual(@as(u8, 70), applied); - try std.testing.expectEqual(applied, core.settings.window_opacity); - try std.testing.expect(!core.settings.window_opacity_pending); - const pane = core.panes[0].?; - try std.testing.expectEqualStrings("WindowOpacity: background transparency requires an alpha-capable SDL window", pane.msg[0..pane.msg_len]); - - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 40")); - try std.testing.expect(core.settings.window_opacity_pending); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 40), applied); - try std.testing.expect(core.executeBuiltinLine(0, "WindowOpacity 100")); - finishWindowOpacity(core, &applied, null); - try std.testing.expectEqual(@as(u8, 100), applied); -} - -test "the clipboard pasted into a terminal reaches its pty as xterm pastes: bracketed when asked, no ESC[201~ smuggled through" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var shell: Shell = undefined; - shell.core = core; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const take = struct { - fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }.f; - _ = try take(core, &sent); - // The clipboard is SDL's own with no display to hold one. - _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "dummy"); - defer _ = c.SDL_ResetHint(c.SDL_HINT_VIDEO_DRIVER); - if (!c.SDL_InitSubSystem(c.SDL_INIT_VIDEO)) return error.SkipZigTest; - defer c.SDL_QuitSubSystem(c.SDL_INIT_VIDEO); - putClipboard(gpa, "ls\x1b[201~; rm -rf ~\nx"); - readClipboard(&shell); - try std.testing.expectEqualStrings("ls [201~; rm -rf ~\rx", try take(core, &sent)); - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - _ = try take(core, &sent); - readClipboard(&shell); - try std.testing.expectEqualStrings("\x1b[200~ls [201~; rm -rf ~\nx\x1b[201~", try take(core, &sent)); -} - -test "fractional wheel delta moves the picture by the same fraction" { - const delta = accumulateWheelDelta(0, -0.125); - const s = applyScrollDelta(0, delta); - const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; - try std.testing.expectEqual(@as(f32, 0.125), delta); - try std.testing.expectEqual(@as(f32, 0.125), picture); - try std.testing.expectEqual(@as(i32, 1), s.rows); - try std.testing.expectEqual(@as(f32, -0.875), s.lag); -} - -test "repeated fractional deltas cross exactly one core row" { - var core_row: i32 = 0; - var lag: f32 = 0; - var crossed: u32 = 0; - for (0..8) |_| { - const s = applyScrollDelta(lag, 0.125); - core_row += s.rows; - crossed += @intCast(@abs(s.rows)); - lag = s.lag; - } - try std.testing.expectEqual(@as(u32, 1), crossed); - try std.testing.expectEqual(@as(i32, 1), core_row); - try std.testing.expectEqual(@as(f32, 0), lag); -} - -test "wheel magnitude is preserved without quantization" { - const delta = accumulateWheelDelta(0, -2.75); - const s = applyScrollDelta(0, delta); - const picture = @as(f32, @floatFromInt(s.rows)) + s.lag; - try std.testing.expectEqual(@as(f32, 2.75), delta); - try std.testing.expectEqual(@as(f32, 2.75), picture); - try std.testing.expectEqual(@as(i32, 3), s.rows); - try std.testing.expectEqual(@as(f32, -0.25), s.lag); - try std.testing.expectEqual(@as(f32, 0), accumulateWheelDelta(0, std.math.inf(f32))); - - const bounded = boundScrollDelta(0, 3.0e38, 24); - const safe = applyScrollDelta(0, bounded); - try std.testing.expectEqual(@as(f32, 24), bounded); - try std.testing.expectEqual(@as(i32, 24), safe.rows); -} - -test "fractional scroll reversals preserve signed distance" { - var core_row: i32 = 0; - const forward = applyScrollDelta(0, 0.375); - core_row += forward.rows; - try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(core_row)) + forward.lag); - - const reverse = applyScrollDelta(forward.lag, -0.125); - core_row += reverse.rows; - try std.testing.expectEqual(@as(i32, -1), reverse.rows); - try std.testing.expectEqual(@as(f32, 0.25), @as(f32, @floatFromInt(core_row)) + reverse.lag); - try std.testing.expect(reverse.lag >= 0 and reverse.lag < 1); -} - -test "a wheel's notch is whole lines, a touchpad's fraction is not" { - try std.testing.expectEqual(@as(?i32, 1), notchOf(-1, -1)); - try std.testing.expectEqual(@as(?i32, -3), notchOf(3, 3)); - try std.testing.expectEqual(@as(?i32, null), notchOf(-0.25, 0)); - try std.testing.expectEqual(@as(?i32, null), notchOf(-1.5, -1)); - try std.testing.expectEqual(@as(?i32, null), notchOf(std.math.nan(f32), 1)); -} - -test "a click over codex in a terminal reaches its pty with its modifiers; Shift swaps B1 to pardes and B2 to the program" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try core.render(frame.allocator()); - var in: Input = .{ .core = core }; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const take = struct { - fn f(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }.f; - _ = try take(core, &sent); - const pane = core.panes[0].?; - const r = core.view().rects[0]; - const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; - const next: MouseCell = .{ .col = mc.col + 1, .row = mc.row }; - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); - _ = try take(core, &sent); - in.post(.{ .mouse = pointerMouse(.none, .motion, mc, .{}) }); - try std.testing.expectEqualStrings("\x1b[<35;6;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .ctrl = true }) }); - try std.testing.expectEqualStrings("\x1b[<16;6;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .drag, next, .{}) }); - try std.testing.expectEqualStrings("\x1b[<32;7;4M", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.left, .release, next, .{}) }); - try std.testing.expectEqualStrings("\x1b[<0;7;4m", try take(core, &sent)); - // Shift-B1 is pardes's select; B2 is pardes's execute and Shift-B2 - // the program's, reported without the Shift. - in.post(.{ .mouse = pointerMouse(.left, .press, mc, .{ .shift = true }) }); - in.post(.{ .mouse = pointerMouse(.left, .release, mc, .{ .shift = true }) }); - try std.testing.expectEqualStrings("", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{}) }); - in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{}) }); - try std.testing.expectEqualStrings("", try take(core, &sent)); - in.post(.{ .mouse = pointerMouse(.middle, .press, mc, .{ .shift = true }) }); - in.post(.{ .mouse = pointerMouse(.middle, .release, mc, .{ .shift = true }) }); - try std.testing.expectEqualStrings("\x1b[<1;6;4M\x1b[<1;6;4m", try take(core, &sent)); -} - -test "a wheel over codex in a terminal reaches its pty as the mouse reports it asked for" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); - defer core.deinit(); - var frame: std.heap.ArenaAllocator = .init(gpa); - defer frame.deinit(); - _ = try core.render(frame.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - var in: Input = .{ .core = core }; - var sent: std.ArrayList(u8) = .empty; - defer sent.deinit(gpa); - const Sent = struct { - fn take(core_: *pardes.Pardes, out: *std.ArrayList(u8)) ![]const u8 { - out.clearRetainingCapacity(); - while (core_.nextEffect()) |effect| { - if (effect == .write and effect.write.pane == 0) try out.appendSlice(std.testing.allocator, effect.write.bytes.slice()); - } - return out.items; - } - }; - _ = try Sent.take(core, &sent); - const pane = core.panes[0].?; - const r = core.view().rects[0]; - const mc: MouseCell = .{ .col = r.x + config.GUTTER + 5, .row = core.bodyTop(pane, r) + 3 }; - // What codex 0.159's chat sets on start. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h\x1b[>7u\x1b[?1004h\x1b[?1049h\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h" } }); - _ = try Sent.take(core, &sent); - // A notch up, then a fast turn of three down: each its report, none - // left behind for a glide. - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); - try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = -3, .integer_y = -3 }, mc); - try std.testing.expectEqualStrings(std.mem.asBytes(&@as([3][10]u8, @splat("\x1b[<65;6;4M".*))), try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, 0), g.scroll_notch); - try std.testing.expect(g.scroll_pane == null); - // A touchpad's fractions add up to a turn. - wheelAt(&g, &in, .{ .y = 0.5 }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = 0.5 }, mc); - try std.testing.expectEqualStrings("\x1b[<64;6;4M", try Sent.take(core, &sent)); - // Alt is meta, 8; Shift keeps the turn pardes's own, a glide. - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .alt = true } }, mc); - try std.testing.expectEqualStrings("\x1b[<72;6;4M", try Sent.take(core, &sent)); - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1, .mods = .{ .shift = true } }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); - stepGlide(&g, core); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - resetScroll(&g); - // Its sign-in screen: mouse off, alternate scroll on, so arrow keys. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1007h" } }); - _ = try Sent.take(core, &sent); - wheelAt(&g, &in, .{ .y = -1, .integer_y = -1 }, mc); - try std.testing.expectEqualStrings("\x1b[B", try Sent.take(core, &sent)); - // Back on the main screen a shell's wheel is ours: a notch to glide, - // nothing to the pty. - core.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049l" } }); - _ = try Sent.take(core, &sent); - wheelAt(&g, &in, .{ .y = 1, .integer_y = 1 }, mc); - try std.testing.expectEqualStrings("", try Sent.take(core, &sent)); - try std.testing.expectEqual(@as(i32, -1), g.scroll_notch); -} - -test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - // Lines of two rows each at this width, numbered so no two rows match. - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..60) |i| { - try text.print(gpa, "{d:0>4} ", .{i}); - try text.appendNTimes(gpa, 'a' + @as(u8, @intCast(i % 26)), 100); - try text.append(gpa, '\n'); - } - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const ms = std.time.ns_per_ms; - var now: u64 = std.time.ns_per_s; - core.advance(now); - var s = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const r = core.view().rects[core.view().active]; - g.scroll_pane = core.view().active; - g.scroll_col = r.x + 10; - g.scroll_row = r.y + r.h - 2; - const body_y = core.bodyTop(core.panes[core.view().active].?, r); - const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); - defer gpa.free(row_before); - // The window has drawn the view once (Glide.frame finds a view that moved). - g.now_ns = now; - glideFrame(&g, gpa, s); - // One notch down: the core is a line on at once. - g.scroll_notch = 1; - const scrolled = core.panes[core.view().active].?.scroll(); - stepGlide(&g, core); - try std.testing.expectEqual(scrolled + 1, core.panes[core.view().active].?.scroll()); - _ = arena.reset(.retain_capacity); - s = try core.render(arena.allocator()); - glideFrame(&g, gpa, s); - // The window's own motion: it draws its frames while it moves. - try std.testing.expect(frontendMoving(&g)); - // Its two rows: the picture two rows behind, the rows that left kept, - // nearest first. - try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); - try std.testing.expectEqual(@as(u16, 2), g.glide.nabove); - try std.testing.expect(pardes.glide.sameRow(g.glide.above[0 .. r.w - config.GUTTER], row_before)); - // Frame by frame it comes back, never past, and settles. - var frames: usize = 0; - while (g.glide.moving()) : (frames += 1) { - now += 7 * ms; - core.advance(now); - stepGlide(&g, core); - g.now_ns = now; - glideFrame(&g, gpa, s); - try std.testing.expect(g.glide.follow.offset <= 1e-4); - if (frames > 200) return error.NeverSettled; - } - try std.testing.expect(frames > 5); - try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); - try std.testing.expect(!frontendMoving(&g)); -} - -test "a fractional wheel turn that brings the picture back onto the core's row is drawn: the window never rests on a frame half a row off" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - // A high-resolution wheel's half notches (SDL's y, up positive), a - // frame each: the first scrolls the core a line and leaves the picture - // half a row behind it; the second takes the picture onto it. - for (0..2) |_| { - try wr.frame(gpa, &.{-0.5}); - try std.testing.expectEqual(wr.picture(), wr.drawn); - } - try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); -} - -test "a wheel turned down then up never draws the picture moving against the turn" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - // Two half notches down (the picture back on the core's row), then - // quarter notches up, a frame each and frames between: each frame's - // picture is where the last left it or on the way the wheel turns, - // never back against it. - for ([_]struct { f32, usize }{ .{ -0.5, 2 }, .{ 0.25, 4 } }) |phase| { - const turn, const turns = phase; - for (0..turns + 4) |k| { - const was = wr.drawn; - try wr.frame(gpa, if (k < turns) &.{turn} else &.{}); - const moved = wr.drawn - was; - try std.testing.expect(moved * -turn >= -1e-4); - } - } -} - -test "a fine wheel's turns that stop at a fraction leave the text on a whole row, and a turn mid-settle is not lost" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - const line = struct { - fn of(p: *pardes.Pardes) i64 { - return @intCast(p.panes[p.view().active].?.scroll()); - } - }.of; - const first = line(core); - // Three quarter notches down, a frame each: the core a line on, the - // picture a quarter row behind it. Then nothing: it eases onto the - // core's row (never back against the turns) and rests there, drawn. - for (0..3) |_| try wr.frame(gpa, &.{-0.25}); - try std.testing.expect(wr.g.scroll_lag != 0); - var frames: usize = 0; - while (wr.g.scroll_lag != 0) : (frames += 1) { - const was = wr.drawn; - try wr.frame(gpa, &.{}); - try std.testing.expect(wr.drawn >= was); - try std.testing.expect(frames < 20); - } - try std.testing.expectEqual(first + 1, line(core)); - try std.testing.expectEqual(wr.picture(), wr.drawn); - try std.testing.expectEqual(@as(f32, @floatFromInt(first + 1)), wr.drawn); - // Again, and a quarter notch more arrives mid-settle: it counts, and - // the settle ends on the row after it. - for (0..3) |_| try wr.frame(gpa, &.{-0.25}); - for (0..4) |_| try wr.frame(gpa, &.{}); - try std.testing.expect(wr.g.scroll_lag != 0); - try wr.frame(gpa, &.{-0.25}); - for (0..20) |_| try wr.frame(gpa, &.{}); - try std.testing.expectEqual(@as(f32, 0), wr.g.scroll_lag); - try std.testing.expectEqual(first + 3, line(core)); - try std.testing.expectEqual(@as(f32, @floatFromInt(first + 3)), wr.drawn); -} - -test "a bar cursor is drawn on its line while a wheel's fraction holds the text off its row, as a block is" { - const gpa = std.testing.allocator; - const core = try wheelRunFile(gpa); - defer core.deinit(); - core.settings.cursor_blink = false; - core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); - var wr = try WheelRun.init(gpa, core); - defer wr.deinit(gpa); - defer wr.g.decor.deinit(gpa); - // Half a notch down: the core a line on, the text drawn half a row - // below its cells until the settle. - try wr.frame(gpa, &.{-0.5}); - try std.testing.expectEqual(@as(f32, -0.5), wr.g.scroll_lag); - _ = wr.arena.reset(.retain_capacity); - const s = try core.render(wr.arena.allocator()); - const cu = s.cursor.?; - try std.testing.expect(cu.bar); - const layout = fixedCellLayout(&wr.g); - const win_w: f32 = @floatFromInt(@as(u32, s.cols) * wr.g.cell_w); - const win_h: f32 = @floatFromInt(@as(u32, s.rows) * wr.g.cell_h); - wr.g.decor.clearRetainingCapacity(); - try cursorDecor(&wr.g, gpa, s, layout, win_w, win_h); - try std.testing.expectEqual(@as(usize, 1), wr.g.decor.items.len); - // Its top where its line's top is drawn (emitScrollRows: the row less - // the lag), not on its cell. - const top = (1 - wr.g.decor.items[0].y0) * win_h / 2; - try std.testing.expectApproxEqAbs((@as(f32, @floatFromInt(cu.y)) - wr.g.scroll_lag) * layout.h, top, 0.01); -} - -test "a wheel's caret rides with its line, the text's own glide, never a spring of its own" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); - _ = try core.setTestFile(text.items); - core.settings.cursor_blink = false; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var now: u64 = std.time.ns_per_s; - core.advance(now); - for ("10G") |ch| core.update(.{ .key = .{ .cp = ch, .text = &.{ch} } }); - _ = try core.render(arena.allocator()); - now += std.time.ns_per_s; - core.advance(now); - _ = arena.reset(.retain_capacity); - var s = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const r = core.view().rects[core.view().active]; - g.scroll_pane = core.view().active; - g.scroll_col = r.x + 10; - g.scroll_row = r.y + r.h - 2; - stepGlide(&g, core); - // The window has drawn the view once (Glide.frame finds a view that moved). - g.now_ns = now; - glideFrame(&g, gpa, s); - const before: f32 = @floatFromInt(s.cursor.?.y); - g.scroll_notch = 1; - stepGlide(&g, core); - var frames: usize = 0; - while (true) : (frames += 1) { - now += 7 * std.time.ns_per_ms; - core.advance(now); - _ = arena.reset(.retain_capacity); - s = try core.render(arena.allocator()); - g.now_ns = now; - glideFrame(&g, gpa, s); - seeCaret(&g, s, fixedCellLayout(&g), 480, now); - if (frames == 0) { - try std.testing.expect(g.glide.caret_rides); - // Where its line is drawn: on the row it was on, the cell a row up. - try std.testing.expectApproxEqAbs(before, caretRow(&g, s, now).?, 1e-3); - } - // Always exactly with its line, the cell less the text's offset. - try std.testing.expectApproxEqAbs(@as(f32, @floatFromInt(s.cursor.?.y)) - g.glide.follow.offset, caretRow(&g, s, now).?, 1e-3); - if (!g.glide.moving()) break; - stepGlide(&g, core); - if (frames > 200) return error.NeverSettled; - } - try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); -} - -test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - // Numbered lines no two alike, short enough never to wrap. - for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - core.advance(std.time.ns_per_s); - _ = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - const body_h: f32 = @floatFromInt(core.view().rects[core.view().active].h - core.panes[core.view().active].?.tag_rows); - const ctrl = struct { - fn key(cp: u21) pardes.Key { - return .{ .cp = cp, .ctrl = true }; - } - }; - const script = [_]GlideRun.Step{ - .{ .frame = 2, .key = ctrl.key('d') }, - .{ .frame = 40, .key = ctrl.key('f') }, - .{ .frame = 80, .key = .{ .cp = 'g', .text = "g" } }, - .{ .frame = 80, .key = .{ .cp = 'e', .text = "e" } }, - .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, - .{ .frame = 120, .key = .{ .cp = 'g', .text = "g" } }, - // Faster than they settle: each adds to the glide under way. - .{ .frame = 160, .key = ctrl.key('d') }, - .{ .frame = 165, .key = ctrl.key('d') }, - .{ .frame = 170, .key = ctrl.key('d') }, - .{ .frame = 175, .key = ctrl.key('d') }, - }; - var seq: GlideRun = .{}; - try seq.play(&g, core, gpa, &arena, &script, 240); - try seq.checkCaret(); - // Every one moves the picture on the frame it is drawn in, and the - // picture lags by what the core moved (a far jump, by one body). - var longest: usize = 0; - var shortest: usize = std.math.maxInt(usize); - for ([_]usize{ 2, 40, 80, 120 }) |at| { - const moved: f32 = @floatFromInt(@abs(seq.lines[at] - seq.lines[at - 1])); - try std.testing.expect(moved >= 1); - const lag = @abs(seq.offsets[at]); - try std.testing.expect(lag > 0.5 * @min(moved, body_h)); - try std.testing.expect(lag <= @min(moved, body_h) + 1e-3); - // Settles on the same law whatever the distance: a few frames for - // a half page, not many more for a jump of 3000 lines. - const frames = seq.settle(at); - longest = @max(longest, frames); - shortest = @min(shortest, frames); - try std.testing.expect(frames >= 8 and frames <= 24); - } - try std.testing.expect(longest - shortest <= 5); - // Readable: never more than a quarter of a body a frame once it moves. - for (1..seq.frames) |k| { - if (seq.lines[k] != seq.lines[k - 1]) continue; - try std.testing.expect(@abs(seq.offsets[k] - seq.offsets[k - 1]) <= body_h / 4 + 1e-3); - } - // The seq of half pages: one glide, never at rest between them, and - // done as soon after the last as one half page alone takes. - for (160..180) |k| try std.testing.expect(seq.offsets[k] != 0); - try std.testing.expect(seq.settle(175) <= seq.settle(2) + 4); -} - -test "a held key moves the view at the stream's own rate, never a bounce a line, and settles once it stops" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); - defer core.deinit(); - var text: std.ArrayList(u8) = .empty; - defer text.deinit(gpa); - for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); - _ = try core.setTestFile(text.items); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - core.advance(std.time.ns_per_s); - _ = try core.render(arena.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.glide.deinit(gpa); - // j held from the top: a repeat every second frame, the view following - // a line a repeat once the caret is at its last rows. - var script: [48]GlideRun.Step = undefined; - for (&script, 0..) |*step, i| step.* = .{ .frame = 20 + 2 * i, .key = .{ .cp = 'j', .text = "j" } }; - var seq: GlideRun = .{}; - try seq.play(&g, core, gpa, &arena, &script, 200); - // Inside the stream the picture moves every frame by about the same - // step: an input's rows over its spacing, not a spring's ease to each. - var least: f32 = std.math.inf(f32); - var most: f32 = 0; - for (90..110) |k| { - const step = (@as(f32, @floatFromInt(seq.lines[k])) + seq.offsets[k]) - (@as(f32, @floatFromInt(seq.lines[k - 1])) + seq.offsets[k - 1]); - least = @min(least, step); - most = @max(most, step); - } - try std.testing.expect(seq.lines[89] > 0 and least > 0.4 and most < 0.6); - // The caret stays on its row, the text moving under it: not a pixel's - // wobble (the glide's fractional lag never reaches it). - for (90..110) |k| try std.testing.expectEqual(seq.carets[89], seq.carets[k]); - // It comes to rest once the keys stop, never past its mark. - for (110..200) |k| try std.testing.expect(seq.offsets[k] <= 0); - try std.testing.expectEqual(@as(f32, 0), seq.offsets[199]); - // Ctrl-d held, then PageDown held: the caret keeps its row the whole - // way, the pages moving under it. - var pages: [40]GlideRun.Step = undefined; - for (&pages, 0..) |*step, i| step.* = .{ .frame = 10 + 2 * i, .key = if (i < 20) .{ .cp = 'd', .ctrl = true } else .{ .cp = pardes.Key.page_down } }; - var held: GlideRun = .{}; - try held.play(&g, core, gpa, &arena, &pages, 100); - try held.checkCaret(); - try seq.checkCaret(); - // (The first of each may move it, one ease: from the last row to where - // a half page keeps it, and from there to a page's.) - for (30..50) |k| try std.testing.expectEqual(held.carets[30], held.carets[k]); - for (70..90) |k| try std.testing.expectEqual(held.carets[70], held.carets[k]); -} - -test "a scroll's shifted rows start under the context rows, and its scissor below their band" { - var surface: pardes.Surface = .{}; - var g = testGui(10, 20, 6, 12); - g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; - g.scroll_body_y = 1; - g.scroll_body_h = 19; - const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; - // On the grid, three body-high rows are held, and nothing moves up. - const grid = holdContext(&g, &surface, 0, 3, 19, layout); - try std.testing.expectEqual(@as(u16, 3), grid.rows); - try std.testing.expectEqual(@as(f32, 0), grid.lift); - const clip = scrollScissor(&g, layout, 400, 400); - try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); - try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); - // In a body layer they are tagline-high: the rows under them move up - // by what each is shorter, to where the layer draws them. - surface.body_layers[0].rows = 30; - surface.body_layers[0].context_rows = 3; - const layered = holdContext(&g, &surface, 0, 3, 19, layout); - try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); - try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); - // None held: the whole body moves. - surface.body_layers[0].rows = 0; - try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); - try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); -} - -test "concealed terminal text emits no ink on its ground" { - var g = testGui(10, 20, 6, 12); - var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - cell.text[0] = 'X'; - const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot); - try std.testing.expectEqual(bg_default, resolved.bg); -} - -test "a block cursor's cell is drawn reversed: the cell's ink its ground, its ground its ink" { - var g = testGui(10, 20, 6, 12); - // A blank, so no glyph is looked up in this atlas-less Gui. - const cell: pardes.Cell = .{ - .text = .{ ' ', ' ', ' ', ' ', ' ', ' ', ' ' }, - .len = 1, - .default = false, - .style = .{ .fg = .{ .rgb = .{ 10, 20, 30 } }, .bg = .{ .rgb = .{ 200, 210, 220 } } }, - }; - const plain = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - const cursor = resolveCell(&g, (&cell)[0..1], 0, 0, .body, true, bg_default); - try std.testing.expectEqual([3]u8{ 10, 20, 30 }, plain.fg); - try std.testing.expectEqual(plain.fg, cursor.bg); - try std.testing.expectEqual(plain.bg, cursor.fg); -} - -test "the layer cover is the per-cell layer scan, over a core's layouts and random layers" { - // A gui-shaped core: its tagline is narrower and shorter than the body, - // so tags and notices are layers. - const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 97, .rows = 31 }); - defer core.deinit(); - core.update(.{ .resize = .{ .cols = 97, .rows = 31, .row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 7, .tagline_h = 13 } } }); - for (1..4) |id| _ = try core.newShell(id, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - pardes.layout.insert(core, 1, 1, 2); - pardes.layout.insert(core, 0, 1, 3); - var cover: [97 * 31]Cover = undefined; - var notices = false; - for (0..32) |step| { - if (step & 3 == 0) try std.testing.expect(core.executeBuiltinLine(2, "Collapse")); - core.view().prefix = if (step & 4 != 0) .leader else .none; - if (step & 8 != 0) { - try std.testing.expect(core.executeBuiltinLine(0, "Msg a message chip over the body")); - try std.testing.expect(core.executeBuiltinLine(3, "Msg another")); - } - const s = try core.render(core.scratch.allocator()); - try std.testing.expectEqual(@as(usize, cover.len), @as(usize, s.cols) * s.rows); - @memset(&cover, .{ .layer = true, .floating = true, .grip = true, .focus = true }); // what an earlier frame left - coverFrame(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); - try expectCoverIsScan(&cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers()); - // A grip's cells know their way to its glyph, and the focused - // pane's tag rows are the focused ones. - for (s.regionList()) |region| { - if (region.kind != .grip) continue; - for (0..region.rect.w) |offset| { - const cell = cover[@as(usize, region.rect.y) * s.cols + region.rect.x + offset]; - try std.testing.expect(cell.grip); - try std.testing.expectEqual(offset, cell.grip_offset); - try std.testing.expectEqual(region.owner == core.view().active, cell.focus); - } - } - for (s.tagLayers()) |layer| notices = notices or (layer.rows != 0 and layer.kind == .notice); - } - try std.testing.expect(notices); - - // Random layers: overlapping, empty, past the grid's right and bottom - // edges, and at the top of u16, where x + w overflows it. - const gen = struct { - fn coordinate(random: std.Random, limit: u16) u16 { - if (random.uintLessThan(u8, 12) == 0) return std.math.maxInt(u16) - random.uintLessThan(u16, 3); - return random.uintAtMost(u16, limit + 3); - } - fn rect(random: std.Random, cols: u16, rows: u16) pardes.Rect { - return .{ .x = coordinate(random, cols), .y = coordinate(random, rows), .w = coordinate(random, cols), .h = coordinate(random, rows / 2) }; - } - }; - var prng = std.Random.DefaultPrng.init(0x6c61796572); - const random = prng.random(); - var body: [pardes.MAX_PANES]pardes.Layer = undefined; - var tag: [pardes.MAX_TAG_LAYERS]pardes.Layer = undefined; - var grid: [64 * 40]Cover = undefined; - for (0..3000) |_| { - const cols = random.intRangeAtMost(u16, 1, 64); - const rows = random.intRangeAtMost(u16, 1, 40); - const empty = random.intRangeAtMost(u8, 2, 5); // about one layer in `empty` is empty - for (&body) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; - for (&tag) |*layer| layer.* = .{ .rows = @intFromBool(random.uintLessThan(u8, empty) != 0), .viewport = gen.rect(random, cols, rows) }; - const bodies = body[0..random.uintAtMost(usize, body.len)]; - const tags = tag[0..random.uintAtMost(usize, tag.len)]; - const cells = grid[0 .. @as(usize, cols) * rows]; - @memset(cells, .{ .layer = random.boolean() }); - coverFrame(cells, cols, rows, bodies, tags, &.{}); - try expectCoverIsScan(cells, cols, rows, bodies, tags); - } -} - -test "every pixel of a grip column is band, button or ring, and the button sits over the scrollbar" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 20 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([60][5]u8, @splat("text\n".*)))); - pane.tag.own = try gpa.dupe(u8, "second\nthird"); - core.newScratchBelow(0); - for ([_]struct { w: u32, h: u32, tag: u32 }{ .{ .w = 10, .h = 20, .tag = 12 }, .{ .w = 17, .h = 35, .tag = 30 }, .{ .w = 9, .h = 19, .tag = 15 }, .{ .w = 12, .h = 24, .tag = 24 } }) |m| for ([_]usize{ 0, 1 }) |focus| for ([_]bool{ false, true }) |dirty| { - core.view().active = focus; - pane.file.?.revision = pane.file.?.saved_revision + @intFromBool(dirty); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var g = testGui(m.w, m.h, m.w, m.tag); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - const win_w: f32 = @floatFromInt(60 * m.w); - const win_h: f32 = @floatFromInt(20 * m.h); - const cover = try gpa.alloc(Cover, @as(usize, s.cols) * s.rows); - defer gpa.free(cover); - coverFrame(cover, s.cols, s.rows, s.bodyLayers(), s.tagLayers(), s.regionList()); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, win_w, win_h, true); - const grip = s.region(.grip, 0).?; - // The grip column's pixels, band first, then its cells, then decor. - const x_px: u32 = grip.rect.x * m.w; - const w_px: u32 = config.GUTTER * m.w; - const y_px: u32 = grip.rect.y * m.h; - const h_px: u32 = grip.rect.h * m.h; - const pixels = try gpa.alloc(?[3]f32, w_px * h_px); - defer gpa.free(pixels); - @memset(pixels, null); - const paint = struct { - fn quad(into: []?[3]f32, x0n: f32, y0n: f32, x1n: f32, y1n: f32, rgb: [3]f32, ww: f32, wh: f32, ox: u32, oy: u32, pw: u32, ph: u32) void { - const px0: i64 = @intFromFloat(@round((x0n + 1) / 2 * ww)); - const px1: i64 = @intFromFloat(@round((x1n + 1) / 2 * ww)); - const py0: i64 = @intFromFloat(@round((1 - y0n) / 2 * wh)); - const py1: i64 = @intFromFloat(@round((1 - y1n) / 2 * wh)); - var y = @max(py0, oy); - while (y < @min(py1, oy + ph)) : (y += 1) { - var x = @max(px0, ox); - while (x < @min(px1, ox + pw)) : (x += 1) into[@intCast((y - oy) * pw + (x - ox))] = rgb; - } - } - }; - var instances: [4]CellInstance = undefined; - for (0..grip.rect.h) |line| for (0..config.GUTTER) |dx| { - const col: u16 = grip.rect.x + @as(u16, @intCast(dx)); - const row: u16 = grip.rect.y + @as(u16, @intCast(line)); - const at = @as(usize, row) * s.cols; - var next: u32 = 0; - emitSurfaceCell(&g, &s.chrome, &instances, &next, col, row, layout, win_w, win_h, s.cells[at..][0..s.cols], cover[at..][0..s.cols], col, null, false, bg_default); - for (instances[0..next]) |i| paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); - }; - for (g.decor.items) |i| if (i.fr >= 1 and i.clip_x1 < i.clip_x0) paint.quad(pixels, i.x0, i.y0, i.x1, i.y1, .{ i.br, i.bg, i.bb }, win_w, win_h, x_px, y_px, w_px, h_px); - const rgb = struct { - fn of(v: [3]u8) [3]f32 { - return .{ @as(f32, @floatFromInt(v[0])) / 255, @as(f32, @floatFromInt(v[1])) / 255, @as(f32, @floatFromInt(v[2])) / 255 }; - } - }.of; - const chrome = &s.chrome; - const band = if (focus == 0) chrome.tag_focus_bg else chrome.tag_bg; - // Band, fills, rings, the rules between stacked panes and under the - // tag, and the mode marks' ink (the grip's first cell's). - const ink = inkOn(gripFill(chrome, grip.active, grip.dirty)); - const allowed = [_][3]f32{ rgb(band), rgb(core.chromeTheme().box), rgb(pardes.draw.boxDirty(core)), rgb(chrome.grip_border), rgb(chrome.grip_focus_ring), rgb(chrome.border), rgb(ink), rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)) }; - for (pixels, 0..) |pixel, n| { - const got = pixel orelse return error.TestUnpaintedGripPixel; - const known = for (allowed) |a| { - if (std.meta.eql(a, got)) break true; - } else false; - // Under the first row there is no button: band and rules only. - if (n / w_px >= m.h and n / w_px < h_px - 1 and !std.meta.eql(got, rgb(band)) and !std.meta.eql(got, rgb(chrome.border))) - return error.TestButtonUnderFirstRow; - if (!known) std.debug.print("sliver {any} at {d},{d} of {d}x{d} (metrics {d}x{d}/{d}, focus {d}, dirty {}) page {any}\n", .{ got, n % w_px, n / w_px, w_px, h_px, m.w, m.h, m.tag, focus, dirty, s.chrome.page }); - try std.testing.expect(known); - } - // The rule under the tag runs unbroken across the grip column. - for (pixels[(h_px - 1) * w_px ..][0..w_px]) |pixel| - try std.testing.expectEqual(rgb(chrome.tag_rule orelse mixRgb(chrome.tag_bg, chrome.page orelse bg_default)), pixel.?); - // The button's edges are the scrollbar's. - const button = gripButton(&g, chrome, grip.rect.x, grip.rect.y, layout); - const column = scrollColumn(&g, chrome, s.region(.rail, 0).?.rect.x, layout); - try std.testing.expectEqual(column[0], button[0]); - try std.testing.expectEqual(column[1], button[2]); - }; - pane.file.?.revision = pane.file.?.saved_revision; -} - -test "small tagline fonts leave no background gutters between adjacent tags" { - const chrome: pardes.Chrome = .{}; - var g = testGui(10, 20, 8, 16); - const cell: pardes.Cell = .{ .default = false, .style = .{ .font_role = .tagline } }; - var instances: [6]CellInstance = undefined; - var next: u32 = 0; - for (0..3) |row| { - // Column 1: past the anchor's inset edge at the column's left. - emitSurfaceCell(&g, &chrome, &instances, &next, 1, @intCast(row), fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{}}, 0, null, false, 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); - try std.testing.expectApproxEqAbs(@as(f32, 16.0 / 480.0 * 2), ink.y0 - ink.y1, 0.0001); - try std.testing.expect(ink.y0 <= base.y0 and ink.y1 >= base.y1); - try std.testing.expectApproxEqAbs(@as(f32, 10.0 / 800.0 * 2), ink.x1 - ink.x0, 0.0001); - 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, &chrome, &instances, &next, 0, 1, fixedCellLayout(&g), 800, 480, (&cell)[0..1], &.{.{ .anchor = true }}, 0, null, false, 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); -} - -test "block cursor alone overrides transparent cell background" { - var g = testGui(10, 20, 6, 12); - const cell: pardes.Cell = .{}; - var instances: [2]CellInstance = undefined; - for ([_]bool{ false, true }, 0..) |cursor, i| { - emitInstance(&g, &instances, @intCast(i), 0, 0, fixedCellLayout(&g), 800, 480, .body, (&cell)[0..1], 0, null, cursor, bg_default); - try std.testing.expectEqual(cursor, instances[i].effect & opaque_bg_bit != 0); - } -} - -test "insert cursor overlays without replacing the character beneath it" { - const cell: pardes.Cell = .{ - .text = .{ 'x', ' ', ' ', ' ', ' ', ' ', ' ' }, - .len = 1, - .default = false, - }; - try std.testing.expectEqual(@as(u32, 'x'), cellCodepoint(&cell)); - - // A bar at a tag cell: tagline-tall, centered in its row, in the - // cell's ink, drawn as decor over it. - var cells: [25]pardes.Cell = @splat(.{}); - cells[3 * 5 + 2] = .{ .default = false, .style = .{ .fg = .{ .rgb = .{ 32, 48, 64 } }, .font_role = .tagline } }; - const surface: pardes.Surface = .{ .cols = 5, .rows = 5, .cells = &cells, .cursor = .{ .x = 2, .y = 3, .bar = true } }; - var g = testGui(10, 20, 8, 8); - defer g.decor.deinit(std.testing.allocator); - try cursorDecor(&g, std.testing.allocator, &surface, fixedCellLayout(&g), 100, 100); - try std.testing.expectEqual(@as(usize, 1), g.decor.items.len); - const bar = g.decor.items[0]; - try std.testing.expectApproxEqAbs(@as(f32, -0.32), bar.y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, -0.48), bar.y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 32.0 / 255.0), bar.br, 0.0001); - try std.testing.expectEqual(@as(f32, 1), bar.fr); -} - -test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { - const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(bytes); - var g = try textTestGui(bytes, 27); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - - const line = textTestLine("a->b"); - var slots: [4]Slot = undefined; - for (&slots, 0..) |*slot, i| slot.* = cellSlot(&g, &line, i, null, .body); - // `->` is one glyph strip two cells wide: each cell samples its own half. - try std.testing.expectEqual(slots[1].v, slots[2].v); - try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u); - var strips: usize = 0; - var it = g.atlas.glyphs.iterator(); - while (it.next()) |entry| if (entry.key_ptr.span == 2) { - strips += 1; - try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead); - try std.testing.expectEqual(slots[1], entry.value_ptr.*); - }; - try std.testing.expectEqual(@as(usize, 1), strips); - // The arrow runs through the seam: both halves carry ink at it. - const seam = g.atlas.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; - var left_ink: usize = 0; - var right_ink: usize = 0; - for (0..g.cell_h) |y| { - left_ink += seam[y * atlas_w + slots[2].u - 1]; - right_ink += seam[y * atlas_w + slots[2].u]; - } - try std.testing.expect(left_ink > 0 and right_ink > 0); - // `a` and `b` are their plain glyphs. - try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('a').glyph, .role = .body }).?, slots[0]); - try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('b').glyph, .role = .body }).?, slots[3]); - - // A second line with the same word reuses the shaped slots. - const again = textTestLine("a->b"); - const text_len = g.words.text.items.len; - for (0..4) |i| try std.testing.expectEqual(slots[i], cellSlot(&g, &again, i, null, .body)); - try std.testing.expectEqual(text_len, g.words.text.items.len); - - // The cursor on either half shows plain `-` and `>`. - const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('-').glyph, .role = .body }).?; - const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('>').glyph, .role = .body }).?; - for ([_]usize{ 1, 2 }) |cursor| { - try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body)); - try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body)); - } - // A tagline is never shaped. - try std.testing.expectEqual(g.atlas.glyphForCodepoint('-').glyph, (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); -} - -test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { - var g = try textTestGui(font_ttf, 18); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - // Each glyph as it is drawn unshaped, in an atlas of its own. - var plain = try textTestGui(font_ttf, 18); - defer plain.atlas.deinit(std.testing.allocator); - defer plain.words.deinit(std.testing.allocator); - const text = "a->b != c => d <= e |> www == :: 0x1F"; - var line = textTestLine(text); - line[3].style.bold = true; // a style change inside a word - for (line, 0..) |cell, i| { - if (text[i] == ' ') continue; - const slot = cellSlot(&g, &line, i, null, .body); - const key = try glyphKeyAt(&g, slot); - try std.testing.expectEqual(g.atlas.glyphForCodepoint(text[i]).glyph, key.glyph); - try std.testing.expectEqual(@as(u4, 1), key.span); - const expected = cachedGlyph(&plain, .{ .face = 0, .glyph = key.glyph, .role = .body, .decoration = .{ .bold = cell.style.bold } }).?; - for (0..g.cell_h) |y| - try std.testing.expectEqualSlices(u8, plain.atlas.atlas_stage[(expected.v + y) * atlas_w + expected.u ..][0..g.cell_w], g.atlas.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); - } -} - -test "pane indicator cached ink centers bearings styles and sizes" { - var g = testGui(10, 20, 6, 12); - g.atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer g.atlas.deinit(std.testing.allocator); - for ([_]f32{ 13, 27, 40 }) |px| { - g.px = px; - var cw: c_int = 0; - var ch: c_int = 0; - g.atlas.cellMetrics(px, &cw, &ch, &g.ascent); - g.cell_w = @intCast(cw); - g.cell_h = @intCast(ch); - for ([_]u8{ 40, 82, 100 }) |percent| { - const tag = taglineRaster(&g.atlas, px, g.cell_w, g.cell_h, percent); - g.tagline_width = tag.width; - g.tagline_height = tag.height; - g.tagline_px = tag.px; - g.tagline_baseline = tag.baseline; - resetGlyphAtlas(&g); - try std.testing.expectEqual(@as(usize, 0), g.atlas.glyphs.count()); - for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const key: GlyphKey = .{ .face = 0, .glyph = g.atlas.glyphForCodepoint(cp).glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; - const slot = cachedGlyph(&g, key).?; - const bounds = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; - const center_x: isize = @intCast(bounds.min_x + bounds.max_x); - const center_y: isize = @intCast(bounds.min_y + bounds.max_y); - try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1); - try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1); - const count = g.atlas.glyphs.count(); - const pen = g.atlas.pen_x; - try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); - try std.testing.expectEqual(count, g.atlas.glyphs.count()); - try std.testing.expectEqual(pen, g.atlas.pen_x); - }; - } - } - resetGlyphAtlas(&g); - g.atlas.pen_y = atlas_h; - try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('^').glyph, .role = .tagline, .centered = true })); -} - -test "pane indicator halves are safe on an exhausted atlas" { - var cells: [12]pardes.Cell = @splat(.{ .default = false, .style = .{ .font_role = .tagline } }); - cells[0].text[0] = '$'; - // A grip two cells wide at the top left. - const grip = [_]pardes.Region{.{ .kind = .grip, .serial = 1, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}; - var cover: [12]Cover = undefined; - coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); - try std.testing.expect(cover[0].grip and cover[1].grip and !cover[2].grip); - // A column's grip is a button too, cut the same way (it has no glyph). - coverFrame(&cover, 6, 2, &.{}, &.{}, &.{.{ .kind = .column_grip, .rect = .{ .x = 0, .y = 0, .w = 2, .h = 1 } }}); - try std.testing.expect(cover[0].grip); - coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); - const chrome: pardes.Chrome = .{}; - - var g = testGui(10, 20, 8, 16); - g.atlas = try Atlas.init(std.testing.allocator, font_ttf); - defer g.atlas.deinit(std.testing.allocator); - g.px = 20; - g.tagline_px = 16; - g.atlas.pen_y = atlas_h; - defer g.words.deinit(std.testing.allocator); - var instances: [4]CellInstance = undefined; - var next: u32 = 0; - for (0..2) |col| { - emitSurfaceCell(&g, &chrome, &instances, &next, @intCast(col), 0, fixedCellLayout(&g), 100, 100, cells[0..6], cover[0..6], col, null, false, bg_default); - try std.testing.expectEqual(@as(f32, 0), instances[col * 2 + 1].u0); - } - try std.testing.expectEqual(@as(u32, 4), next); -} - -test "a concealed cell's underline draws nothing of its own" { - const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; - try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); -} - -test "overlapping background layers keep one uniform opacity" { - const blend = Cells.backgroundLayerBlend(); - try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); - try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor); - for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| { - var alpha = opacity; - for ([_]f32{ 1, 0.5, 0.88, 0, 1 }) |coverage| { - alpha = opacity * coverage + alpha * (1 - coverage); - try std.testing.expectApproxEqAbs(opacity, alpha, 0.00001); - } - } -} - -test "background opacity retains exact endpoints and percentage precision" { - try std.testing.expectEqual(@as(f32, 0), backgroundOpacity(0)); - try std.testing.expectEqual(@as(f32, 0.7), backgroundOpacity(70)); - try std.testing.expectEqual(@as(f32, 1), backgroundOpacity(100)); - for (0..100) |percent| { - try std.testing.expect(backgroundOpacity(@intCast(percent)) < backgroundOpacity(@intCast(percent + 1))); - } -} - -test "InactiveDim fades the unfocused panes' rows alone, never below the text's floor" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.sync(); - const s = try core.render(core.scratch.allocator()); - defer dim = .{}; - dim.begin(60, s.regionList()); - try std.testing.expect(dim.focused != pardes.Region.none); - var cover: [80 * 24]Cover = undefined; - coverFrame(&cover, 80, 24, &.{}, &.{}, s.regionList()); - var seen: [2]bool = .{ false, false }; - for (s.regionList()) |region| if (region.kind == .body or region.kind == .tag) { - const unfocused = region.owner != dim.focused; - try std.testing.expectEqual(unfocused, cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); - seen[@intFromBool(unfocused)] = true; - } else if (region.kind == .grip) try std.testing.expect(!cover[@as(usize, region.rect.y) * 80 + region.rect.x].dim); - try std.testing.expect(seen[0] and seen[1]); - // Toward the ground, a pair already near its floor no further. - var instance: CellInstance = std.mem.zeroes(CellInstance); - instance.fr = 0.9; - instance.fg = 0.9; - instance.fb = 0.9; - dim.fade(&instance); - try std.testing.expect(instance.fr < 0.9 and instance.fr > 0); - try std.testing.expect(pardes.colors.contrast(Dim.byteRgb(.{ instance.fr, instance.fg, instance.fb }), .{ 0, 0, 0 }) >= 4.5 - 1e-3); - // Off, nothing fades. - dim.begin(0, s.regionList()); - try std.testing.expect(!dim.of(0) and !dim.of(1)); -} - -test "a theme's own rules and scrollbar are drawn at its widths: acme's 2px black rules and 12px track" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); - for (0..40) |_| core.update(.tick); - core.sync(); - const s = try core.render(core.scratch.allocator()); - try std.testing.expectEqual(@as(u8, 2), s.chrome.rule_px); - // acme's 12px, at GripWidth's 150% default. - try std.testing.expectEqual(@as(u8, 18), s.chrome.rail_px); - var g = testGui(16, 20, 10, 12); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 480, true); - const px = struct { - fn w(item: CellInstance) f32 { - return (item.x1 - item.x0) / 2 * 1280; - } - }; - var spines: usize = 0; - var tracks: usize = 0; - for (g.decor.items) |item| { - const black = item.br == 0 and item.bg == 0 and item.bb == 0; - // No rule at the window's left edge; one 2px spine where columns meet. - if (black and @abs(px.w(item) - 2) < 0.01 and item.y1 < -0.9) { - try std.testing.expect(item.x0 > -1); - spines += 1; - } - const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - if (@abs(item.br - @as(f32, 0x99) / 255) < 1e-3 and @abs(item.bb - @as(f32, 0x4c) / 255) < 1e-3 and @abs(px.w(item) - (column[1] - column[0])) < 0.01) tracks += 1; - } - try std.testing.expectEqual(@as(usize, 1), spines); - try std.testing.expect(tracks >= 2); -} - -test "the scrollbar thumb moves by the pixel and follows a glide" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const thumb = struct { - // The thumb's top, in window pixels. - fn top(gui: *Gui, p: *pardes.Pardes) !f32 { - gui.decor.clearRetainingCapacity(); - p.sync(); - const s = try p.render(p.scratch.allocator()); - var groups: Groups = .{}; - try buildDecor(gui, std.testing.allocator, s, &groups, fixedCellLayout(gui), 800, 480, true); - const ink = s.chrome.scroll_thumb; - for (gui.decor.items) |item| if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and - @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and - @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) return (1 - item.y0) / 2 * 480; - return error.TestExpectedThumb; - } - }; - pane.file.?.scroll = 10; - const at10 = try thumb.top(&g, core); - pane.file.?.scroll = 11; - const at11 = try thumb.top(&g, core); - // A line of a thousand moves it a fraction of a row, not 0 or 20 px. - try std.testing.expect(at11 > at10 and at11 - at10 < 1); - g.glide.pane = core.view().active; - g.glide.follow.offset = -1; - try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); - // A wrapped line: the picture moved two rows for the one line, and the - // thumb lags the line, not two. - g.glide.lines_moved = 1; - g.glide.rows_moved = 2; - g.glide.follow.offset = -2; - try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); -} - -test "the scrollbar thumb lies in its scroll column, a pixel short of the column's right edge, so the track edges it" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.setTestFile(std.mem.asBytes(&@as([1000][5]u8, @splat("line\n".*)))); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const ink = s.chrome.scroll_thumb; - const thumb = for (g.decor.items) |item| { - if (@abs(item.br - @as(f32, @floatFromInt(ink[0])) / 255) < 1e-3 and - @abs(item.bg - @as(f32, @floatFromInt(ink[1])) / 255) < 1e-3 and - @abs(item.bb - @as(f32, @floatFromInt(ink[2])) / 255) < 1e-3) break item; - } else return error.TestExpectedThumb; - // The pane is the window's first: its scroll column is at cell 0. - const column = scrollColumn(&g, &s.chrome, 0, fixedCellLayout(&g)); - try std.testing.expectApproxEqAbs(column[0], (thumb.x0 + 1) / 2 * 800, 1e-3); - try std.testing.expectApproxEqAbs(column[1] - 1, (thumb.x1 + 1) / 2 * 800, 1e-3); -} - -test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - core.newScratchBelow(0); - core.sync(); - const s = try core.render(core.scratch.allocator()); - const lower = for (s.regionList()) |region| { - if (region.kind == .tag and region.rect.y > 2) break region; - } else return error.TestExpectedStackedTag; - for ([_]u32{ 12, 20 }) |tagline_h| { - var g = testGui(10, 20, 6, tagline_h); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 800, 480, true); - const top = @as(f32, @floatFromInt(lower.rect.y)) * 20; - const slack: f32 = @floatFromInt(@max(1, pardes.Layer.taglineBandOffset(lower.rect.y, 480, 20, tagline_h))); - var found = false; - for (g.decor.items) |item| { - const y0 = (1 - item.y0) / 2 * 480; - const y1 = (1 - item.y1) / 2 * 480; - if (@abs(y0 - top) > 0.01 or @abs(item.br - @as(f32, @floatFromInt(s.chrome.border[0])) / 255) > 1e-3) continue; - found = true; - try std.testing.expect(y1 - y0 <= slack + 0.01); - } - try std.testing.expect(found); - } -} - -test "an empty column is ruled on both sides, as between two filled ones" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - // Newcol from the left pane: an empty column between the two filled ones. - pardes.layout.newColumn(core, 0); - core.sync(); - try std.testing.expectEqual(@as(usize, 3), core.view().ncol); - try std.testing.expectEqual(@as(usize, 0), core.view().cols[1].n); - const s = try core.render(core.scratch.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); - const border = [3]f32{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 }; - // Its left edge and its right edge (the next column's left): each a - // rule `rule_px` wide in the border colour, down to the window's foot. - for ([_]usize{ 1, 2 }) |column| { - const px: f32 = @floatFromInt(@as(u32, core.view().col_x[column]) * 10); - const rule = for (g.decor.items) |item| { - if (@abs(item.x0 - (px / 800 * 2 - 1)) < 1e-4 and @abs(item.x1 - ((px + @as(f32, @floatFromInt(s.chrome.rule_px))) / 800 * 2 - 1)) < 1e-4 and - std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &border)) break item; - } else return error.TestExpectedColumnRule; - try std.testing.expectEqual(@as(f32, -1), rule.y1); - } -} - -test "at a 2x display every logical pixel is two: rules, the tag rule, the grip's ring, the rail's edge" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - try std.testing.expect(core.executeBuiltinLine(0, "Theme acme")); - for (0..40) |_| core.update(.tick); - core.sync(); - const s = try core.render(core.scratch.allocator()); - for ([_]f32{ 1, 2 }) |scale| { - display_scale = scale; - defer display_scale = 1; - var g = testGui(16, 32, 12, 24); - defer g.decor.deinit(gpa); - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, fixedCellLayout(&g), 1280, 768, true); - const w = struct { - fn of(item: CellInstance) f32 { - return (item.x1 - item.x0) / 2 * 1280; - } - fn h(item: CellInstance) f32 { - return (item.y0 - item.y1) / 2 * 768; - } - }; - var spine: ?f32 = null; - var tag_rule: ?f32 = null; - var ring: ?f32 = null; - for (g.decor.items) |item| { - const rgb: [3]u8 = .{ @intFromFloat(@round(item.br * 255)), @intFromFloat(@round(item.bg * 255)), @intFromFloat(@round(item.bb * 255)) }; - // The spine between the columns: black, tall. - if (std.mem.eql(u8, &rgb, &.{ 0, 0, 0 }) and w.h(item) > 300) spine = @round(w.of(item)); - // The tag rule: #8888cc, wide and thin. - if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.of(item) > 200) tag_rule = @round(w.h(item)); - // The ring's left side: #8888cc, a tag row tall. - if (std.mem.eql(u8, &rgb, &.{ 0x88, 0x88, 0xcc }) and w.h(item) > 10 and w.of(item) < 8) ring = @round(w.of(item)); - } - try std.testing.expectEqual(@as(?f32, 2 * scale), spine); - try std.testing.expectEqual(@as(?f32, 1 * scale), tag_rule); - try std.testing.expectEqual(@as(?f32, 2 * scale), ring); - // The rail starts after the rule, a logical 2 in, and keeps a - // logical 3 clear of the text when the cell is narrow. - const column = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - try std.testing.expectEqual(40 * 16 + 2 * scale, column[0]); - g.cell_w = 12; - defer g.cell_w = 16; - const narrow = scrollColumn(&g, &s.chrome, 40, fixedCellLayout(&g)); - try std.testing.expectEqual(@as(f32, 40 * 12 + 2 * scale), narrow[0]); - try std.testing.expectEqual(@as(f32, 40 * 12) + 12 * @as(f32, @floatFromInt(config.GUTTER)) - 3 * scale, narrow[1]); - g.cell_w = 8; - // A bar cursor is an eighth of its cell, never under a logical pixel - // (an 8 px cell: one pixel, two at 2x). - const saved = s.cursor; - defer s.cursor = saved; - s.cursor = .{ .x = 60, .y = 10, .bar = true }; - var boxes: [max_cursors]CursorBox = undefined; - const n = cursorBoxes(&g, s, fixedCellLayout(&g), 768, &boxes); - const bar = for (boxes[0..n]) |box| { - if (box.bar and box.x0 == 60 * 8) break box; - } else return error.NoBarCursor; - try std.testing.expectEqual(scale, bar.x1 - bar.x0); - } -} - -test "decor is read from the regions" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - _ = try core.newShell(1, ""); - try std.testing.expect(pardes.layout.splitColumn(core, 0, 1, false)); - core.sync(); - const s = try core.render(core.scratch.allocator()); - var g = testGui(10, 20, 6, 12); - defer g.decor.deinit(gpa); - const layout = fixedCellLayout(&g); - const ndc = struct { - fn x(px: f32) f32 { - return px / 800 * 2 - 1; - } - }; - var groups: Groups = .{}; - try buildDecor(&g, gpa, s, &groups, layout, 800, 480, true); - // A spine one pixel wide at each column's left edge, down from under the - // workspace tag; a rail two pixels wide at each pane's. - for (core.view().col_x[0..core.view().ncol]) |x| { - const left = ndc.x(@as(f32, @floatFromInt(x)) * 10); - // Two pixels (rule_px), and none at the window's own edge. - const spine = for (g.decor.items) |item| { - if (item.x0 == left and @abs(item.x1 - ndc.x(@as(f32, @floatFromInt(x)) * 10 + 2)) < 0.0001 and - @abs(item.y0 - (1 - 20.0 / 480.0 * 2)) < 0.0001 and std.mem.eql(f32, &.{ item.br, item.bg, item.bb }, &.{ @as(f32, @floatFromInt(s.chrome.border[0])) / 255, @as(f32, @floatFromInt(s.chrome.border[1])) / 255, @as(f32, @floatFromInt(s.chrome.border[2])) / 255 })) break item; - } else null; - try std.testing.expectEqual(x == 0, spine == null); - if (spine) |rule| { - try std.testing.expectApproxEqAbs(@as(f32, 1 - 20.0 / 480.0 * 2), rule.y0, 0.0001); - try std.testing.expectEqual(@as(f32, -1), rule.y1); - } - // The scrollbar fills the scroll column right of the rule. - const column = scrollColumn(&g, &s.chrome, x, layout); - const rail = for (g.decor.items) |item| { - if (@abs(item.x0 - ndc.x(column[0])) < 0.0001 and @abs(item.x1 - ndc.x(column[1])) < 0.0001 and - @abs(item.br - @as(f32, @floatFromInt(s.chrome.scroll_track[0])) / 255) < 0.0001) break item; - } else return error.TestExpectedRail; - _ = rail; - } - try std.testing.expectEqual(@as(u32, 0), groups.items[groups.notices].decor_count); -} - -test "a body tells its first line" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 80, .rows = 24 }); - defer core.deinit(); - const pane = try core.setTestFile(std.mem.asBytes(&@as([80][5]u8, @splat("line\n".*)))); - pane.scrollBy(8); - core.sync(); - const s = try core.render(core.scratch.allocator()); - const body = for (s.regionList()) |region| { - if (region.kind == .body) break region; - } else return error.NoBody; - try std.testing.expectEqual(@as(i32, 8), body.line); -} - -test "a caret eases a cell at a time, keeps up with typing, and glides a jump, landing exactly" { - const ms = std.time.ns_per_ms; - var caret: Caret = .{}; - caret.aim(.{ .x = 3, .y = 4, .w = 1, .h = 1 }, 0, false); - // The first mark lands at once. - try std.testing.expect(!caret.moving()); - // A step eases, a stream of them keeps up. - caret.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, 1000 * ms, false); - try std.testing.expect(caret.moving()); - caret.aim(.{ .x = 5, .y = 4, .w = 1, .h = 1 }, 1050 * ms, false); - try std.testing.expect(!caret.moving()); - // A jump glides, the leading corner ahead, and lands exactly. - caret.aim(.{ .x = 30, .y = 10, .w = 1, .h = 1 }, 2000 * ms, false); - try std.testing.expect(caret.moving()); - const mid = caret.sample(2040 * ms); - try std.testing.expect(mid[1][0] > mid[0][0] - 1 and mid[0][0] > 5 and mid[0][0] < 30); - var t: u64 = 2040 * ms; - while (caret.step(t)) t += 16 * ms; - try std.testing.expect(t < 2400 * ms); - try std.testing.expectEqual([2]f32{ 30, 10 }, caret.sample(t)[0]); - // A scroll lands it with its text. - caret.see(.{ .x = 30, .y = 8, .w = 1, .h = 1 }, 0, 10, 2, 1, t); - caret.see(.{ .x = 30, .y = 6, .w = 1, .h = 1 }, 0, 12, 2, 1, t + 16 * ms); - try std.testing.expect(!caret.moving()); -} - -test "a jump's trail is drawn behind the cursor in its body, and gone by 120 ms" { - var cells: [80 * 4]pardes.Cell = @splat(.{}); - var surface: pardes.Surface = .{ .cols = 80, .rows = 4, .cells = &cells }; - surface.regions[0] = .{ .kind = .body, .rect = .{ .x = 2, .y = 0, .w = 78, .h = 4 } }; - surface.nregions = 1; - var g = testGui(10, 20, 8, 16); - var vertices: [5 * 6]OverlayVertex = undefined; - var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 80 }; - const ms = std.time.ns_per_ms; - surface.cursor = .{ .x = 4, .y = 1 }; - appendJumpTrail(&g, true, &surface, 1000 * ms, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - surface.cursor = .{ .x = 14, .y = 1 }; - appendJumpTrail(&g, true, &surface, 1016 * ms, &builder); - try std.testing.expect(builder.len >= 3 * 6 and builder.len <= 5 * 6); - // On the cursor's row, behind it, never its own cell. - for (vertices[0..builder.len]) |v| { - const x = (v.x + 1) * 400; - const y = (1 - v.y) * 40; - try std.testing.expect(y >= 20 - 0.01 and y <= 40 + 0.01); - try std.testing.expect(x >= 50 - 0.01 and x <= 140 + 0.01); - } - try std.testing.expect(g.trail.active); - builder.len = 0; - appendJumpTrail(&g, true, &surface, 1150 * ms, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - try std.testing.expect(!g.trail.active); -} - -test "a pet stays past the workspace tag's text, and off it is gone" { - std.testing.refAllDecls(pet); - var cells: [80]pardes.Cell = @splat(.{}); - const surface: pardes.Surface = .{ .cols = 80, .rows = 1, .cells = &cells }; - for ("Workspace Commands", 0..) |ch, i| { - cells[i].text[0] = ch; - cells[i].len = 1; - cells[i].default = false; - } - var g = testGui(10, 20, 8, 16); - var vertices: [pet.max_vertices]OverlayVertex = undefined; - var builder: OverlayBuilder = .{ .vertices = &vertices, .win_w = 800, .win_h = 480 }; - appendWorkspacePet(&g, .cat, &surface, &builder); - try std.testing.expect(builder.len > 0); - for (vertices[0..builder.len]) |v| { - const x = (v.x + 1) * 400; - const y = (1 - v.y) * 240; - try std.testing.expect(x >= 20 * 8 - 0.01); - try std.testing.expect(y >= 0 and y < 20); - } - builder.len = 0; - appendWorkspacePet(&g, .off, &surface, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); - try std.testing.expectEqual(@as(?u64, null), g.pet_state.tick); -} - -test "compact body layer rendering fills recovered rows and clips the final glyph" { - var g = testGui(10, 20, 6, 12); - var cells: [24]pardes.Cell = @splat(.{}); - var layer: pardes.Layer = .{ - .viewport = .{ .x = 3, .y = 2, .w = 2, .h = 5 }, - .cols = 2, - .rows = 12, - .context_rows = 4, - .cells = &cells, - }; - layer.setContextLines(&.{ 0, 4, 5, 6 }); - var instances: [32]CellInstance = undefined; - var next: u32 = 0; - emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); - // Four compact header rows (48px), then three body rows: two complete - // and a third clipped to the remaining12px of the100px viewport. - try std.testing.expectEqual(@as(u32, 20), next); - try std.testing.expectApproxEqAbs(@as(f32, 0.49), instances[3].y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0.48), instances[3].y1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 80.0 / 255.0), instances[3].br, 0.0001); - try std.testing.expectApproxEqAbs(instances[3].br, instances[13].br, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0.6), instances[0].y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0.12), instances[14].y0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, -0.4), instances[19].y1, 0.0001); - try std.testing.expectApproxEqAbs(instances[19].v0 + @as(f32, 12) / atlas_h, instances[19].v1, 0.0001); - // A drag preview reserves the last physical column without changing cells. - layer.viewport.w = 1; - next = 0; - emitBodyLayer(&g, &instances, &next, &layer, 200, 200, bg_default, false, .{ 80, 90, 100 }); - for (instances[0..next]) |instance| try std.testing.expect(instance.x1 <= -0.6 + 0.0001); -} - -test "compact tag layers fill available width and clip at their physical edge" { - var g = testGui(10, 20, 6, 12); - var cells: [6]pardes.Cell = @splat(.{}); - const layer: pardes.Layer = .{ .kind = .pane, .id = 0, .serial = 7, .viewport = .{ .x = 2, .y = 3, .w = 3, .h = 1 }, .cols = 6, .rows = 1, .cells = &cells, .bg = .{ 20, 30, 40 } }; - var instances: [8]CellInstance = undefined; - var next: u32 = 0; - emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); - // Five six-pixel cells fit in the three body-column viewport. - try std.testing.expectEqual(@as(u32, 6), next); - try std.testing.expectApproxEqAbs(@as(f32, -0.6), instances[1].x0, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 0), instances[5].x1, 0.0001); - g.tagline_width = 8; - next = 0; - emitTagLayer(&g, &instances, &next, &layer, 100, 100, bg_default, false); - try std.testing.expectEqual(@as(u32, 5), next); - try std.testing.expectApproxEqAbs(@as(f32, 0), instances[4].x1, 0.0001); - try std.testing.expectApproxEqAbs(@as(f32, 6) / atlas_w, instances[4].u1 - instances[4].u0, 0.0001); -} - -test "trackpad rotation never types search keys into an insert-mode file or raw terminal" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); - defer core.deinit(); - _ = try core.setTestFile("unchanged\n"); - var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; - defer client.deinit(); - var in: Input = .{ .core = core, .client = &client }; - var g: Gui = undefined; - g.trackpad = .{}; - var ev: c.UITrackpadEvent = std.mem.zeroes(c.UITrackpadEvent); - ev.kind = c.UI_TRACKPAD_ROTATE; - ev.a = 20; - const pane = core.panes[core.view().active].?; - pane.body.mode = .insert; - dispatchTrackpad(&g, &in, &ev); - pane.body.mode = .tty; - dispatchTrackpad(&g, &in, &ev); - try std.testing.expectEqual(@as(usize, 0), client.pending.items.len); - ev.kind = c.UI_TRACKPAD_HISTORY; - ev.a = -1; - dispatchTrackpad(&g, &in, &ev); - ev.a = 1; - dispatchTrackpad(&g, &in, &ev); - try std.testing.expectEqual(@as(usize, 2), client.pending.items.len); - try std.testing.expectEqualStrings("Back", client.pending.items[0].command); - try std.testing.expectEqualStrings("Forward", client.pending.items[1].command); -} - -test "a detached GUI authority follows terminal directory changes with no window" { - const gpa = std.testing.allocator; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "child"); - var start_buf: [4096]u8 = undefined; - const start = start_buf[0..try tmp.dir.realPath(io, &start_buf)]; - var cwd_buf: [4096]u8 = undefined; - const expected = cwd_buf[0..try tmp.dir.realPathFile(io, "child", &cwd_buf)]; - const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer core.deinit(); - core.panes[0].?.shell_spoke = true; - _ = core.settings.shell.effective.set("/bin/sh"); - var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; - defer queue.deinit(); - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(1); - const rcs: host_io.Shell.PromptFiles = .{}; - var pipes: PipeTasks = .{}; - var watches: file_watch.Table = @splat(null); - var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches }; - defer shell.shutdownPtys(); - const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; - try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); - const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000; - var actual: [4096]u8 = undefined; - while (std.Io.Clock.awake.now(io).toMilliseconds() < until) { - if (host_io.shellCwd(child.pid, &actual)) |cwd| if (std.mem.eql(u8, cwd, expected)) break; - try io.sleep(.fromMilliseconds(1), .awake); - } - try std.testing.expectEqualStrings(expected, host_io.shellCwd(child.pid, &actual) orelse return error.MissingCwd); - pollFrame(&shell); - try std.testing.expectEqualStrings(expected, core.panes[0].?.cwd.owned); -} - -test "detached trackpad scrolling keeps fractions local and queues whole rows for replication" { - const gpa = std.testing.allocator; - const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); - defer core.deinit(); - _ = try core.setTestFile("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\nsixteen\nseventeen\neighteen\nnineteen\ntwenty\n"); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - _ = try core.render(arena.allocator()); - var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; - defer client.deinit(); - var in: Input = .{ .core = core, .client = &client }; - const id = core.view().active; - const r = core.view().rects[id]; - var g: Gui = undefined; - g.scroll_pane = id; - g.scroll_delta = 0.375; - g.scroll_lag = 0; - g.scroll_idle = 0; - g.scroll_notch = 0; - g.scroll_edge = &.{}; - g.scroll_edge_len = 0; - g.glide = .{}; - g.scroll_col = r.x + config.GUTTER + 2; - g.scroll_row = core.bodyTop(core.panes[id].?, r) + 2; - defer gpa.free(g.scroll_edge); - const before = core.panes[id].?.scroll(); - try std.testing.expect(scrollRows(&g, &in, gpa)); - try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); - // The next row is fetched early; its inverse raster offset keeps the - // exact fraction under the finger until that row is fully shown. - try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(client.pending.items.len)) + g.scroll_lag); - try std.testing.expectEqual(before, core.panes[id].?.scroll()); - core.update(client.pending.items[0]); - client.pending.clearRetainingCapacity(); - g.scroll_delta = 0.75; - try std.testing.expect(scrollRows(&g, &in, gpa)); - try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); - try std.testing.expectEqual(before + 1, core.panes[id].?.scroll()); - try std.testing.expect(client.pending.items[0].mouse.shift); - core.update(client.pending.items[0]); - try std.testing.expectEqual(@as(f32, 1.125), @as(f32, @floatFromInt(core.panes[id].?.scroll() - before)) + g.scroll_lag); -} - -/// Render addon scenes to textures on this device, before the page's pass. -/// The fallback cells remain visible if decoding or pipeline creation fails. -fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, surface: *const pardes.Surface) void { - for (surface.gpu_frames, 0..) |maybe, id| { - const scratch: GpuScene.abi.Image = @fromBackingInt(@intCast(pardes.MAX_PANES + id + 1)); - const frame = maybe orelse { - if (g.addon_gpu) |*gpu| { - gpu.forget(@fromBackingInt(@intCast(id + 1))); - gpu.forget(scratch); - } - g.addon_hash[id] = 0; - g.addon_serial[id] = 0; - g.addon_failed[id] = 0; - continue; - }; - const hash = std.hash.Wyhash.hash(frame.serial, frame.bytes); - if (g.addon_failed[id] == hash) continue; - if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.cells.device); - const gpu = &g.addon_gpu.?; - const target: GpuScene.abi.Image = @fromBackingInt(@intCast(id + 1)); - if (g.addon_hash[id] != hash or g.addon_serial[id] != frame.serial) { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var scene = GpuScene.decodeFrame(arena.allocator(), frame.bytes) catch |err| { - log.warn("addon GPU scene: {t}", .{err}); - g.addon_failed[id] = hash; - continue; - }; - scene.pass.image = if (scene.post != null) scratch else target; - gpu.record(cmd, scene.pass) catch |err| { - log.warn("addon GPU render: {t}", .{err}); - g.addon_failed[id] = hash; - continue; - }; - if (scene.post) |post| { - gpu.postProcess(cmd, scratch, target, post) catch |err| { - log.warn("addon GPU postprocess: {t}", .{err}); - g.addon_failed[id] = hash; - continue; - }; - } else gpu.forget(scratch); - g.addon_hash[id] = hash; - g.addon_serial[id] = frame.serial; - } - const out = gpu.output(target) orelse continue; - g.cells.makeAddonPipeline() catch continue; - g.prepared_images.append(gpa, .{ - .premultiplied = true, - .texture = out.texture, - .place = .{ .pane = @intCast(id), .raster = .{ .ptr = undefined, .w = out.width, .h = out.height, .stride = out.width * 4 }, .src = .{ .x = 0, .y = 0, .w = out.width, .h = out.height }, .dst = frame.dst, .key = hash }, - }) catch {}; - } - if (g.addon_gpu) |*gpu| gpu.endFrame(); -} - -test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes to the recorded stage and slots" { - // The glyph atlas the frames sample, byte for byte and on any machine: - // FreeType and HarfBuzz are the build's, the faces the repo's (the - // embedded Adwaita Mono, assets/MapleMono-NF for ligatures and Nerd - // icons). CJK has no face of the repo's and no fallback of pardes's - // list: the frame corpus draws its .notdef. Recorded before the GPU - // move (.scratch/sketch/briefs/gpu-s0.md); a change here is a change - // to every frame. - const want = [2][2]u64{ .{ 0xa03053f14e2c5472, 0x9029886b638b07d5 }, .{ 0xcbaa53a0103aaff5, 0x7563d69768f7d867 } }; - const maple = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); - defer std.testing.allocator.free(maple); - defer display_scale = 1; - var got: [2][2]u64 = undefined; - for ([_]f32{ 27, 54 }, [_]f32{ 1, 2 }, &got) |px, scale, *hashes| { - display_scale = scale; - var stage_hash = std.hash.Wyhash.init(0); - var slots_hash = std.hash.Wyhash.init(0); - // 0: Adwaita Mono, Maple its fallback; 1: Maple, whose ligatures shape. - for ([_][]const u8{ font_ttf, maple }) |primary| { - var g = try textTestGui(primary, px); - defer font_allocator = std.heap.smp_allocator; - defer g.atlas.deinit(std.testing.allocator); - defer g.words.deinit(std.testing.allocator); - try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false)); - try std.testing.expect(fitTaglineFont(&g, 80)); - const decorations = [_]Atlas.Decoration{ - .{}, - .{ .bold = true }, - .{ .underline = .single }, - .{ .underline = .double }, - .{ .underline = .curly }, - .{ .underline = .dotted }, - .{ .underline = .dashed }, - .{ .strikethrough = true }, - }; - for (0x21..0x7f) |cp| { - const drawn = g.atlas.glyphForCodepoint(@intCast(cp)); - for (decorations) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body, .decoration = decoration }) orelse return error.AtlasFull; - for (decorations[0..2]) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = decoration }) orelse return error.AtlasFull; - } - const space = g.atlas.glyphForCodepoint(' '); - _ = cachedGlyph(&g, .{ .face = space.face, .glyph = space.glyph, .role = .body, .decoration = .{ .underline = .single } }) orelse return error.AtlasFull; - for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]Atlas.Role{ .body, .tagline }) |role| { - _ = cachedGlyph(&g, .{ .face = 0, .glyph = cp, .role = role, .rule = true }) orelse return error.AtlasFull; - }; - for ([_]u32{ '$', '^', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const drawn = g.atlas.glyphForCodepoint(cp); - _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }) orelse return error.AtlasFull; - }; - // Nerd icons (Yazi's folder, a file, powerline's arrow): Maple's, - // the primary's or the fallback's. - for ([_]u32{ 0xe5ff, 0xf07b, 0xe0b0 }) |cp| { - const drawn = g.atlas.glyphForCodepoint(cp); - try std.testing.expect(drawn.glyph != 0); - _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body }) orelse return error.AtlasFull; - } - // Ligature strips, shaped by the words' cache as a frame shapes them. - const line = textTestLine("a->b => != <= >= == === !== |> <| :: ++ -- www office"); - for (0..line.len) |i| _ = cellSlot(&g, &line, i, null, .body); - stage_hash.update(g.atlas.atlas_stage); - const Entry = struct { key: u64, u: u32, v: u32 }; - var entries: std.ArrayList(Entry) = .empty; - defer entries.deinit(std.testing.allocator); - var it = g.atlas.glyphs.iterator(); - while (it.next()) |e| try entries.append(std.testing.allocator, .{ .key = @bitCast(e.key_ptr.*), .u = e.value_ptr.u, .v = e.value_ptr.v }); - std.mem.sort(Entry, entries.items, {}, struct { - fn less(_: void, x: Entry, y: Entry) bool { - return x.key < y.key; - } - }.less); - for (entries.items) |e| slots_hash.update(std.mem.asBytes(&e)); - } - hashes.* = .{ stage_hash.final(), slots_hash.final() }; - } - if (!std.meta.eql(want, got)) std.debug.print("atlas hashes: .{{ .{{ 0x{x}, 0x{x} }}, .{{ 0x{x}, 0x{x} }} }}\n", .{ got[0][0], got[0][1], got[1][0], got[1][1] }); - try std.testing.expectEqual(want, got); -} diff --git a/src/gui/macos_trackpad.h b/src/gui/macos_trackpad.h deleted file mode 100644 index f5266084..00000000 --- a/src/gui/macos_trackpad.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef PARDES_MACOS_TRACKPAD_H -#define PARDES_MACOS_TRACKPAD_H -#include <SDL3/SDL.h> - -enum { UI_TRACKPAD_FINGERS = 1, UI_TRACKPAD_PRESSURE, UI_TRACKPAD_ROTATE, - UI_TRACKPAD_PINCH, UI_TRACKPAD_SCROLL, UI_TRACKPAD_HISTORY }; -/* Same prefix as SDL_UserEvent; the rest lives inside SDL_Event's storage. */ -typedef struct { - Uint32 type, reserved; - Uint64 timestamp; - SDL_WindowID windowID; - int kind; - float x, y, a, b; - Uint32 phase; - int fingers; -} UITrackpadEvent; - -Uint32 ui_macos_trackpad_event_type(void); -void ui_macos_trackpad_attach(SDL_Window *window); -void ui_macos_trackpad_haptic(void); -#endif diff --git a/src/gui/macos_trackpad.m b/src/gui/macos_trackpad.m deleted file mode 100644 index 64806b9e..00000000 --- a/src/gui/macos_trackpad.m +++ /dev/null @@ -1,176 +0,0 @@ -/* AppKit input missing from SDL's public event stream. The SDL view keeps its - * drawing, keyboard and mouse responder chain; only trackpad methods change. */ -#import <Cocoa/Cocoa.h> -#import <objc/runtime.h> -#include "macos_trackpad.h" -#include <string.h> -#include <math.h> - -static char window_key; -static char swipe_key, axis_key, suppress_momentum_key; -static Uint32 gesture_type; -static Class trackpad_class; -_Static_assert(sizeof(UITrackpadEvent) <= sizeof(SDL_Event), "trackpad event fits SDL"); - -Uint32 ui_macos_trackpad_event_type(void) { return gesture_type; } - -void ui_macos_trackpad_haptic(void) -{ - [[NSHapticFeedbackManager defaultPerformer] - performFeedbackPattern:NSHapticFeedbackPatternAlignment - performanceTime:NSHapticFeedbackPerformanceTimeNow]; -} - -static void send_gesture(NSView *view, NSEvent *event, int kind, float a, float b, int fingers) -{ - SDL_Window *window = (SDL_Window *)[objc_getAssociatedObject(view, &window_key) pointerValue]; - if (!window) return; - NSPoint point = [view convertPoint:event.locationInWindow fromView:nil]; - SDL_Event packet = {0}; - UITrackpadEvent decoded = {0}; - UITrackpadEvent *out = &decoded; - out->type = gesture_type; - out->timestamp = SDL_GetTicksNS(); - out->windowID = SDL_GetWindowID(window); - out->kind = kind; - out->x = point.x; - out->y = view.isFlipped ? point.y : NSHeight(view.bounds) - point.y; - out->a = a; - out->b = b; - out->fingers = fingers; - /* Stable decoded phases, independent of NSEventPhase's bit values. */ - if (kind == UI_TRACKPAD_ROTATE || kind == UI_TRACKPAD_PINCH || kind == UI_TRACKPAD_SCROLL) - out->phase = event.phase == NSEventPhaseBegan ? 1 : - event.phase == NSEventPhaseEnded ? 2 : - event.phase == NSEventPhaseCancelled ? 3 : 0; - memcpy(&packet, &decoded, sizeof(decoded)); - SDL_PushEvent(&packet); -} - -static void touches(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_FINGERS, 0, 0, - (int)[event touchesMatchingPhase:NSTouchPhaseTouching inView:nil].count); - /* Do not also emit SDL's absolute finger coordinates: those describe the - * trackpad surface, not a position inside this window. Scroll comes from - * scrollWheel:, including the system's momentum events. */ -} - -static void pressure(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_PRESSURE, event.stage, 0, 0); -} - -static void rotate(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_ROTATE, event.rotation, 0, 0); -} - -static void magnify(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - send_gesture(view, event, UI_TRACKPAD_PINCH, 1 + event.magnification, 0, 0); -} - -static void swipe(NSView *view, SEL selector, NSEvent *event) -{ - (void)selector; - /* NSEvent swipe deltaX: negative is right/back, positive left/forward. */ - if (event.deltaX != 0) - send_gesture(view, event, UI_TRACKPAD_HISTORY, event.deltaX, 0, 0); -} - -static void scroll(NSView *view, SEL selector, NSEvent *event) -{ - if (event.hasPreciseScrollingDeltas) { - if (event.phase == NSEventPhaseBegan) { - objc_setAssociatedObject(view, &axis_key, @0, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - objc_setAssociatedObject(view, &suppress_momentum_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } - if ([objc_getAssociatedObject(view, &swipe_key) boolValue]) return; - if ([objc_getAssociatedObject(view, &suppress_momentum_key) boolValue]) return; - NSInteger axis = [objc_getAssociatedObject(view, &axis_key) integerValue]; - CGFloat x = fabs(event.scrollingDeltaX), y = fabs(event.scrollingDeltaY); - if (!axis && x + y >= 3) { - if (x > y * 1.5) axis = 1; - else if (y > x * 1.5) axis = 2; - objc_setAssociatedObject(view, &axis_key, @(axis), OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } - if (axis == 1 && (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseChanged) && - !(event.modifierFlags & (NSEventModifierFlagShift | NSEventModifierFlagOption)) && - [NSEvent isSwipeTrackingFromScrollEventsEnabled]) { - // AppKit supplies Safari-style completion/cancellation and honours - // the user's Swipe Between Pages preference. No guessed velocity. - objc_setAssociatedObject(view, &swipe_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - __weak NSView *weak_view = view; - __block BOOL cancelled = NO; - __block BOOL previewed = NO; - [event trackSwipeEventWithOptions:NSEventSwipeTrackingLockDirection | NSEventSwipeTrackingClampGestureAmount - dampenAmountThresholdMin:-1 max:1 - usingHandler:^(CGFloat amount, NSEventPhase phase, BOOL complete, BOOL *stop) { - NSView *target = weak_view; - if (!target) { *stop = YES; return; } - if (phase == NSEventPhaseCancelled) cancelled = YES; - // An early notch says the swipe is approaching the - // shorter commit distance, while the fingers still move. - if (!cancelled && !complete && !previewed && fabs(amount) >= 0.12) { - previewed = YES; - ui_macos_trackpad_haptic(); - } - const BOOL commit = !cancelled && phase != NSEventPhaseNone && fabs(amount) >= 0.25; - if (!commit && !cancelled && phase != NSEventPhaseEnded && !complete) return; - objc_setAssociatedObject(target, &swipe_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - objc_setAssociatedObject(target, &suppress_momentum_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - // Commit during the physical swipe. AppKit's later - // animation to +/-1 must not set our trigger distance. - *stop = YES; - if (commit) - send_gesture(target, event, UI_TRACKPAD_HISTORY, amount > 0 ? 1 : -1, 0, 0); - }]; - return; - } - send_gesture(view, event, UI_TRACKPAD_SCROLL, - event.scrollingDeltaX, event.scrollingDeltaY, 0); - } else { - /* An ordinary mouse wheel retains SDL's discrete-notch handling. */ - [[view nextResponder] scrollWheel:event]; - } - (void)selector; -} - -void ui_macos_trackpad_attach(SDL_Window *window) -{ - NSWindow *native = (__bridge NSWindow *)SDL_GetPointerProperty( - SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); - NSView *view = native.contentView; - if (!view) return; - if (!gesture_type) { - /* SDL_EVENT_USER is already the shell's queue wake. */ - Uint32 first = SDL_RegisterEvents(2); - if (!first) return; - gesture_type = first + 1; - } - if (!trackpad_class) { - trackpad_class = objc_allocateClassPair(object_getClass(view), "PardesSDLTrackpadView", 0); - if (!trackpad_class) return; - SEL touch_selectors[] = { @selector(touchesBeganWithEvent:), @selector(touchesMovedWithEvent:), - @selector(touchesEndedWithEvent:), @selector(touchesCancelledWithEvent:) }; - for (unsigned i = 0; i < 4; ++i) - class_addMethod(trackpad_class, touch_selectors[i], (IMP)touches, "v@:@"); - class_addMethod(trackpad_class, @selector(pressureChangeWithEvent:), (IMP)pressure, "v@:@"); - class_addMethod(trackpad_class, @selector(rotateWithEvent:), (IMP)rotate, "v@:@"); - class_addMethod(trackpad_class, @selector(magnifyWithEvent:), (IMP)magnify, "v@:@"); - class_addMethod(trackpad_class, @selector(swipeWithEvent:), (IMP)swipe, "v@:@"); - class_addMethod(trackpad_class, @selector(scrollWheel:), (IMP)scroll, "v@:@"); - objc_registerClassPair(trackpad_class); - } - objc_setAssociatedObject(view, &window_key, [NSValue valueWithPointer:window], OBJC_ASSOCIATION_RETAIN_NONATOMIC); - object_setClass(view, trackpad_class); - view.allowedTouchTypes = NSTouchTypeMaskIndirect; - view.wantsRestingTouches = YES; - view.pressureConfiguration = [[NSPressureConfiguration alloc] - initWithPressureBehavior:NSPressureBehaviorPrimaryDeepClick]; -} diff --git a/src/gui/pet.zig b/src/gui/pet.zig deleted file mode 100644 index 7a13ca91..00000000 --- a/src/gui/pet.zig +++ /dev/null @@ -1,215 +0,0 @@ -//! Original code-native pixel companions. Pure, bounded geometry and a 10 Hz -//! animation clock: no textures, allocation, input handling or editor state. -const std = @import("std"); - -pub const Kind = enum { off, cat, frog }; -pub const width = 12; -pub const height = 9; -pub const max_vertices = width * height * 6; -pub const Lane = struct { left: f32, right: f32, top: f32, scale: f32 }; -pub const Pose = struct { x: f32, y: f32, scale: f32, left: bool, walking: bool, frame: u8 }; -/// The frog's hop: sits two ticks, takes off, peaks for two, comes down, lands. -const hop_ticks = 8; - -/// Only the trailing blank part of the global tag is eligible. The caller -/// supplies its last occupied cell, including any wide-grapheme continuation. -pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32) ?Lane { - if (cell_w <= 0 or band_h < height + 2) return null; - const scale = @min(3, @floor((band_h - 2) / height)); - const left = @as(f32, @floatFromInt(occupied + 2)) * cell_w; - const right = screen_w - 2 * cell_w - width * scale; - if (right - left < 4 * scale) return null; - return .{ .left = left, .right = right, .top = top + band_h - height * scale - 1, .scale = scale }; -} - -pub const State = struct { - kind: Kind = .off, - tick: ?u64 = null, - x: f32 = 0, - target: f32 = 0, - left: bool = false, - idle: u8 = 12, - frame: u8 = 0, - rng: std.Random.DefaultPrng = undefined, - - /// No lane (the tag's text has filled it) hides the pet but keeps - /// where it was and what it was doing. - pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { - const region = area orelse return null; - if (kind == .off) { - s.* = .{}; - return null; - } - const tick = now_ms / 100; - if (s.kind != kind or s.tick == null) { - s.* = .{ .kind = kind, .tick = tick, .x = region.left, .target = region.left, .rng = .init(now_ms) }; - } - s.x = std.math.clamp(s.x, region.left, region.right); - s.target = std.math.clamp(s.target, region.left, region.right); - // Coming back from suspension never launches the pet across the tag. - const steps = @min(tick -| s.tick.?, 2); - s.tick = tick; - for (0..steps) |_| { - s.frame +%= 1; - if (s.idle > 0) { - s.idle -= 1; - if (s.idle == 0) { - // Wander to a random spot of the lane; one too close - // would be a shuffle in place, so take the far end. - s.target = region.left + s.rng.random().float(f32) * (region.right - region.left); - if (@abs(s.target - s.x) < 8 * region.scale) - s.target = if (s.x - region.left > region.right - s.x) region.left else region.right; - s.left = s.target < s.x; - s.frame = 255; // the walk starts at frame 0 - } - continue; - } - // The cat walks steadily; the frog travels only while airborne. - const phase = s.frame % hop_ticks; - if (kind == .cat or (phase >= 2 and phase < 6)) { - const step = (if (kind == .cat) @as(f32, 1.8) else 2.6) * region.scale; - s.x = if (s.left) @max(s.target, s.x - step) else @min(s.target, s.x + step); - } - if (s.x == s.target and (kind == .cat or phase == hop_ticks - 1)) - s.idle = s.rng.random().intRangeAtMost(u8, 20, 60); - } - return .{ .x = @floor(s.x), .y = region.top, .scale = region.scale, .left = s.left, .walking = s.idle == 0, .frame = s.frame }; - } -}; - -const cat = [_][]const u8{ - " # # ", - " #####", - " ##o##", - " # ######", - " # ######## ", - " ######### ", - " ######## ", - " ## ## ", - " # # ", -}; -const frog = [_][]const u8{ - " ", - " ", - " ", - " ## ", - " #o## ", - " #########", - " ######### ", - " ##### ## ", - "###### ### ", -}; -const frog_leap = [_][]const u8{ - " ## ", - " #o## ", - " #######", - " ######## ", - " ####### ", - " ### ## ", - "## # ", - "# ", - " ", -}; - -/// 0 transparent, 1 theme ink, 2 eye cutout. Walk legs and idle blinks are -/// generated in this fixed 12x9 tile; neither can spill into an adjacent row. -pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { - if (x_in >= width or y >= height or kind == .off) return 0; - const x = if (pose.left) width - 1 - x_in else x_in; - const alternate = (pose.frame / 2) % 2 == 1; - // An idle companion still looks alive during its first pause: a slow - // two-pixel tail-tip flick, or the frog's throat gently inflating. These - // remain inside the tile and mirror with the rest of the animal. - const breathing = (pose.frame / 4) % 2 == 1; - if (!pose.walking and breathing) { - if (kind == .cat and y == 3 and x <= 1) - return @intFromBool(x == 0); - if (kind == .frog and ((y == 6 and x == 11) or (y == 7 and x == 10))) return 1; - } - if (kind == .cat and pose.walking and alternate and y >= 7) - return @intFromBool((y == 7 and (x == 3 or x == 7)) or (y == 8 and (x == 2 or x == 8))); - // A hopping frog leaps two rows low at take-off and one on the way down. - const phase = pose.frame % hop_ticks; - const leaping = kind == .frog and pose.walking and phase >= 2 and phase < 6; - const sink: usize = if (!leaping) 0 else if (phase == 2) 2 else if (phase == 5) 1 else 0; - if (y < sink) return 0; - const ch = (if (kind == .cat) cat else if (leaping) frog_leap else frog)[y - sink][x]; - return switch (ch) { - '#' => 1, - 'o' => if (!pose.walking and pose.frame % 30 >= 27) 1 else 2, - else => 0, - }; -} - -test "pet stays in trailing workspace blanks, and a lost lane hides it without a reset" { - try std.testing.expect(lane(20, 8, 200, 0, 16) == null); - try std.testing.expect(lane(3, 8, 200, 0, 10) == null); - const region = lane(3, 8, 200, 2, 20).?; - try std.testing.expect(region.left >= 5 * 8); - var state: State = .{}; - var moved = false; - var reversed = false; - for (0..2000) |i| { - const pose = state.sample(.cat, i * 100, region).?; - try std.testing.expect(pose.x >= region.left and pose.x + width * pose.scale <= 200 - 16); - try std.testing.expect(pose.y >= 2 and pose.y + height * pose.scale < 22); - moved = moved or pose.walking; - reversed = reversed or pose.left; - } - try std.testing.expect(moved and reversed); - const kept = state; - try std.testing.expect(state.sample(.cat, 300000, null) == null); - try std.testing.expectEqual(kept.x, state.x); - try std.testing.expectEqual(kept.tick, state.tick); - try std.testing.expect(state.sample(.off, 300100, region) == null); -} - -test "pet clock is fixed rate and sprites bounded in both directions" { - const region = lane(1, 8, 400, 0, 16).?; - var state: State = .{}; - const start = state.sample(.frog, 1000, region).?; - try std.testing.expectEqualDeep(start, state.sample(.frog, 1099, region).?); - for ([_]Kind{ .cat, .frog }) |kind| for ([_]bool{ false, true }) |left| { - const pose: Pose = .{ .x = 0, .y = 0, .scale = 1, .left = left, .walking = true, .frame = 3 }; - var count: usize = 0; - for (0..height) |y| for (0..width) |x| { - count += @intFromBool(pixel(kind, pose, x, y) != 0); - }; - try std.testing.expect(count > 20 and count <= width * height); - try std.testing.expectEqual(@as(u2, 0), pixel(kind, pose, width, height)); - }; -} - -test "pet rests at random spots and the frog travels only in the air" { - const region = lane(1, 8, 800, 0, 16).?; - var state: State = .{}; - var last = state.sample(.frog, 0, region).?; - var rested_midway = false; - for (1..3000) |i| { - const pose = state.sample(.frog, i * 100, region).?; - const phase = pose.frame % hop_ticks; - if (pose.x != last.x) try std.testing.expect(pose.walking and phase >= 2 and phase < 6); - rested_midway = rested_midway or (last.walking and !pose.walking and pose.x > region.left and pose.x < @floor(region.right)); - last = pose; - } - try std.testing.expect(rested_midway); -} - -test "pet initial idle visibly animates without walking or leaving its tile" { - const region = lane(1, 8, 400, 0, 16).?; - for ([_]Kind{ .cat, .frog }) |kind| { - var state: State = .{}; - const initial = state.sample(kind, 0, region).?; - var later = initial; - for (1..5) |tick| later = state.sample(kind, tick * 100, region).?; - try std.testing.expect(!initial.walking and !later.walking); - try std.testing.expectEqual(initial.x, later.x); - try std.testing.expectEqual(initial.y, later.y); - var changes: usize = 0; - for (0..height) |y| for (0..width) |x| { - changes += @intFromBool(pixel(kind, initial, x, y) != pixel(kind, later, x, y)); - }; - try std.testing.expectEqual(@as(usize, 2), changes); - try std.testing.expectEqual(@as(u2, 0), pixel(kind, later, width, height)); - } -} |
