const filesystem = @import("../fs.zig"); const std = @import("std"); const builtin = @import("builtin"); const posix = std.posix; const libc = std.c; const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser const ghostty_vt = @import("ghostty-vt"); // 256-color palette for .index cells 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 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("../9p_io.zig"); const daemon = @import("../daemon.zig"); const upgrade = @import("../upgrade.zig"); 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 vert_spv = @embedFile("ui.vert.spv"); const frag_spv = @embedFile("ui.frag.spv"); const decor_frag_spv = @embedFile("decor.frag.spv"); const overlay_vert_spv = @embedFile("overlay.vert.spv"); const overlay_frag_spv = @embedFile("overlay.frag.spv"); const image_vert_spv = @embedFile("image.vert.spv"); const image_frag_spv = @embedFile("image.frag.spv"); 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: u32 = 2048; const atlas_h: u32 = 2048; const Slot = struct { u: u32, v: u32 }; /// An atlas entry is a glyph of a face (0 the primary font, i the fallback /// i - 1) at a role's size, drawn `span` cells wide with its own cell `lead` /// cells in: a ligature is one strip whose cells sample their own slices. /// Packed, so the atlas map hashes one word instead of walking fields. const GlyphKey = packed struct(u64) { face: u8, glyph: u32, role: pardes.FontRole, decoration: GlyphDecoration = .{}, centered: bool = false, lead: u4 = 0, span: u4 = 1, /// A light box-drawing rule (`ruleArms`), drawn edge to edge rather /// than from the font; `glyph` is its codepoint. rule: bool = false, _: u1 = 0, }; /// The light box-drawing rules drawn by hand, as Ghostty and kitty draw /// them: a logical pixel thick through the cell's middle, out to its edges, /// so a markdown table's `|` (Tables.zig) joins the rows above and below it /// and its delimiter row is one line across, at any line height a font's /// own glyph would leave gaps in. The arms each one has: left, right, up, down. fn ruleArms(cp: u32) ?[4]bool { return switch (cp) { 0x2500 => .{ true, true, false, false }, // ─ 0x2502 => .{ false, false, true, true }, // │ 0x250c => .{ false, true, false, true }, // ┌ 0x2510 => .{ true, false, false, true }, // ┐ 0x2514 => .{ false, true, true, false }, // └ 0x2518 => .{ true, false, true, false }, // ┘ 0x251c => .{ false, true, true, true }, // ├ 0x2524 => .{ true, false, true, true }, // ┤ 0x252c => .{ true, true, false, true }, // ┬ 0x2534 => .{ true, true, true, false }, // ┴ 0x253c => .{ true, true, true, true }, // ┼ else => null, }; } fn drawRule(out: [*]u8, stride: usize, width: usize, height: usize, arms: [4]bool) void { if (width == 0 or height == 0) return; const t: usize = @min(@max(1, @as(usize, @intFromFloat(dp(1)))), @min(width, height)); const mx = (width - t) / 2; const my = (height - t) / 2; for (0..height) |y| @memset(out[y * stride ..][0..width], 0); if (arms[0] or arms[1]) for (0..t) |k| { const from: usize = if (arms[0]) 0 else mx; const to: usize = if (arms[1]) width else mx + t; @memset(out[(my + k) * stride + from ..][0 .. to - from], 255); }; if (arms[2] or arms[3]) { const from: usize = if (arms[2]) 0 else my; const to: usize = if (arms[3]) height else my + t; for (from..to) |y| @memset(out[y * stride + mx ..][0..t], 255); } } 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; } }; const TaglineRaster = struct { px: f32, width: u32, baseline: i32, height: u32, }; fn taglineRaster(font: *c.UIFont, 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; c.ui_font_cell_metrics(font, 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" }); } 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. const primer = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; c.ui_font_prime(primer); c.ui_font_free(primer); font_allocator = std.testing.allocator; defer font_allocator = std.heap.smp_allocator; const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); var mask: [64 * 64]u8 = undefined; try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, 27, c.ui_font_glyph(font, 'g'), 1, &mask, 64, 32, 48, 0, 32, 30)); try std.testing.expectEqual(@as(c_int, 0), c.ui_font_substitutes(font, c.ui_font_glyph(font, '-'))); // 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); const maple = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; defer c.ui_font_free(maple); var cell_w: c_int = 0; var cell_h: c_int = 0; var ascent: c_int = 0; c.ui_font_cell_metrics(maple, 27, &cell_w, &cell_h, &ascent); const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; var shaped: [text.len]c.UIShapedCell = undefined; c.ui_font_shape(maple, 27, cell_w, &text, text.len, &shaped); try std.testing.expectEqual(@as(u8, 2), shaped[1].span); try std.testing.expectEqual(@as(u8, 2), shaped[4].span); } /// 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; const LoadedFallback = struct { face: *c.UIFont, bytes: []u8 = &.{}, }; 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; test "every font size step moves the cell, and the ends are reachable exactly" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); 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; c.ui_font_cell_metrics(font, px, &cw, &ch, &asc); c.ui_font_cell_metrics(font, 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 "FreeType atlas raster is grayscale, bounded, and clears blank cells" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); const h = c.ui_font_glyph(font, 'H'); try std.testing.expect(h != 0); try std.testing.expectEqual(@as(u32, 0), c.ui_font_glyph(font, 0x10ffff)); const size: f32 = 13.0; var cell_w: c_int = 0; var cell_h: c_int = 0; var ascent: c_int = 0; c.ui_font_cell_metrics(font, size, &cell_w, &cell_h, &ascent); try std.testing.expect(cell_w > 0 and cell_w <= 128); try std.testing.expect(cell_h > 0 and cell_h <= 128); const stride: c_int = 128; var bitmap: [128 * 128]u8 = @splat(0xaa); try std.testing.expectEqual( @as(c_int, 1), c.ui_font_raster(font, size, h, 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), ); var ink: usize = 0; var soft: usize = 0; var regular_coverage: usize = 0; for (0..@intCast(cell_h)) |y| { for (0..@intCast(cell_w)) |x| { const coverage = bitmap[y * @as(usize, @intCast(stride)) + x]; if (coverage > 0) ink += 1; if (coverage > 0 and coverage < 255) soft += 1; regular_coverage += coverage; } } try std.testing.expect(ink > 0); try std.testing.expect(soft > 0); // Synthetic bold thickens the outline inside the same cell. try std.testing.expectEqual( @as(c_int, 1), c.ui_font_raster(font, size, h, 1, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), ); var bold_coverage: usize = 0; for (0..@intCast(cell_h)) |y| { for (0..@intCast(cell_w)) |x| bold_coverage += bitmap[y * @as(usize, @intCast(stride)) + x]; for (bitmap[y * @as(usize, @intCast(stride)) + @as(usize, @intCast(cell_w)) ..][0..@intCast(stride - cell_w)]) |guard| try std.testing.expectEqual(@as(u8, 0xaa), guard); } try std.testing.expect(bold_coverage > regular_coverage); try std.testing.expectEqual( @as(c_int, 0), c.ui_font_raster(font, size, c.ui_font_glyph(font, ' '), 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), ); for (0..@intCast(cell_h)) |y| for (0..@intCast(cell_w)) |x| try std.testing.expectEqual( @as(u8, 0), bitmap[y * @as(usize, @intCast(stride)) + x], ); } const InkBounds = struct { min_x: usize, min_y: usize, max_x: usize, max_y: usize }; fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds { var bounds: ?InkBounds = null; for (0..h) |y| for (0..w) |x| { if (bitmap[y * stride + x] == 0) continue; if (bounds) |*b| { b.min_x = @min(b.min_x, x); b.min_y = @min(b.min_y, y); b.max_x = @max(b.max_x, x); b.max_y = @max(b.max_y, y); } else bounds = .{ .min_x = x, .min_y = y, .max_x = x, .max_y = y }; }; return bounds; } test "tagline glyph shrinks into its own cell and stays vertically centered" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); const body_px: f32 = 27.0; var cell_w: c_int = 1; var cell_h: c_int = 1; var body_ascent: c_int = 1; c.ui_font_cell_metrics(font, body_px, &cell_w, &cell_h, &body_ascent); const tag = taglineRaster(font, 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))); const stride: c_int = 128; var body: [128 * 128]u8 = @splat(0); var tagline: [128 * 128]u8 = @splat(0); const h = c.ui_font_glyph(font, 'H'); try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, body_px, h, 0, &body, stride, cell_w, cell_h, 0, cell_w, body_ascent)); try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, tag.px, h, 0, &tagline, stride, @intCast(tag.width), @intCast(tag.height), 0, @intCast(tag.width), tag.baseline)); const b = inkBounds(&body, @intCast(stride), @intCast(cell_w), @intCast(cell_h)).?; const t = inkBounds(&tagline, @intCast(stride), @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" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); var cell_w: c_int = 1; var cell_h: c_int = 1; var ascent: c_int = 1; c.ui_font_cell_metrics(font, 27.0, &cell_w, &cell_h, &ascent); const small = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 40); const configured = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 82); const full = taglineRaster(font, 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); const face = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; defer c.ui_font_free(face); try std.testing.expect(c.ui_font_glyph(face, 0xe5ff) != 0); } const CellInstance = extern struct { x0: f32, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, fr: f32, fg: f32, fb: f32, br: f32, bg: f32, bb: f32, /// The flags (the high bits, ui.vert.glsl). effect: u32 = 0, /// A clip rectangle in target pixels; x1 < x0 is none (ui.vert.glsl). clip_x0: f32 = 0, clip_y0: f32 = 0, clip_x1: f32 = -1, clip_y1: f32 = -1, }; const OverlayVertex = extern struct { x: f32, y: f32, r: f32, g: f32, b: f32, a: f32, }; const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 }; const ImageInstance = extern struct { x0: f32, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, }; const opaque_bg_bit: u32 = 0x2000_0000; const PreparedImage = struct { place: pardes.Placement, texture: *c.SDL_GPUTexture, }; test "the shader instance ABI: the flags after the colours, the clip after them" { try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance)); try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect")); try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0")); try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance)); } 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; 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); } 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); } } 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); } } const Gui = struct { window: *c.SDL_Window, device: *c.SDL_GPUDevice, swapchain_format: c.SDL_GPUTextureFormat, pipeline: *c.SDL_GPUGraphicsPipeline, decor_pipeline: *c.SDL_GPUGraphicsPipeline, overlay_pipeline: *c.SDL_GPUGraphicsPipeline, image_pipeline: *c.SDL_GPUGraphicsPipeline, atlas_tex: *c.SDL_GPUTexture, atlas_sampler: *c.SDL_GPUSampler, linear_sampler: *c.SDL_GPUSampler, atlas_xfer: *c.SDL_GPUTransferBuffer, vbuf: ?*c.SDL_GPUBuffer = null, vxfer: ?*c.SDL_GPUTransferBuffer = null, vbuf_cells: u32 = 0, overlay_vbuf: *c.SDL_GPUBuffer, overlay_vxfer: *c.SDL_GPUTransferBuffer, overlay_vertices: []OverlayVertex, image_vbuf: ?*c.SDL_GPUBuffer = null, image_vxfer: ?*c.SDL_GPUTransferBuffer = null, image_capacity: u32 = 0, /// The textures of the placements shown, by key. native_images: std.AutoHashMapUnmanaged(u64, *c.SDL_GPUTexture) = .empty, 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, font: *c.UIFont, font_bytes: []u8 = &.{}, font_name: [255]u8 = @splat(0), font_name_len: u8 = 0, fallbacks: [max_fallback_fonts]?LoadedFallback = @splat(null), fallback_count: usize = 0, 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, atlas_stage: []u8, glyphs: std.AutoHashMap(GlyphKey, Slot), pen_x: u32 = 0, pen_y: u32 = 0, /// The atlas rows drawn into since the last upload, [top, bottom): the /// whole atlas at first, since the texture starts undefined. atlas_dirty_top: u32 = 0, atlas_dirty_bottom: u32 = atlas_h, space_slot: Slot = .{ .u = 0, .v = 0 }, words: Words = .{}, touch: Touch = .{}, /// 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, /// 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 (terminal.ownsWheel). program_wheel: 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, capture: bool = false, /// 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, capture_tex: ?*c.SDL_GPUTexture = null, capture_tex_w: u32 = 0, capture_tex_h: u32 = 0, capture_xfer: ?*c.SDL_GPUTransferBuffer = null, capture_xfer_size: u32 = 0, soft_present: bool = false, surface_opacity: bool = false, applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, soft_texture: ?*c.SDL_Texture = null, /// What a window is opened again with (reopenWindow): the flags (not /// hidden), the present mode, its size when it was closed. win_flags: c.SDL_WindowFlags = 0, present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC, 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, soft_tex_w: u32 = 0, soft_tex_h: u32 = 0, gamepad: ?*c.SDL_Gamepad = null, 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 { if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); 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 (c.ui_font_name(g.font)) |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); } fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { if (c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len))) |face| { g.fallbacks[0] = .{ .face = face }; g.fallback_count = 1; } var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); for (fonts.fallbacks(arena_state.allocator())) |candidate| { if (g.fallback_count == g.fallbacks.len) break; const bytes = filesystem.readFile(gpa, candidate.path) catch continue; const len = std.math.cast(c_int, bytes.len) orelse { gpa.free(bytes); continue; }; const face = c.ui_font_new(bytes.ptr, len) orelse { gpa.free(bytes); continue; }; g.fallbacks[g.fallback_count] = .{ .face = face, .bytes = bytes }; g.fallback_count += 1; } } fn deinitFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { for (g.fallbacks[0..g.fallback_count]) |loaded| { const fallback = loaded.?; c.ui_font_free(fallback.face); if (fallback.bytes.len != 0) gpa.free(fallback.bytes); } } const FaceGlyph = struct { face: u8, glyph: u32 }; /// The face and glyph that draw `cp`, the face as a GlyphKey face: 0 is the /// primary font and i the fallback i - 1. A codepoint no face has draws the /// primary's .notdef. fn glyphForCodepoint(g: *const Gui, cp: u32) FaceGlyph { const primary = c.ui_font_glyph(g.font, @intCast(cp)); if (primary != 0) return .{ .face = 0, .glyph = primary }; for (g.fallbacks[0..g.fallback_count], 1..) |loaded, face| { const glyph = c.ui_font_glyph(loaded.?.face, @intCast(cp)); if (glyph != 0) return .{ .face = @intCast(face), .glyph = glyph }; } return .{ .face = 0, .glyph = 0 }; } 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, }; } 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)); } fn fixedCellLayout(g: *const Gui) CellLayout { return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; } /// What one group draws, in this order: its cells, its images, then its /// decor. const Group = struct { cell_start: u32 = 0, cell_count: u32 = 0, image_start: u32 = 0, image_count: u32 = 0, decor_start: u32 = 0, decor_count: u32 = 0, }; /// The frame's draw groups, bottom to top: the page and the panes, the /// notices floating over them, the guides and 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, guides: 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 a guide or 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); }, .guide, .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), else => {}, }; } pub fn run(init: std.process.Init, opts: pardes.Options, headless: bool) !void { return runNative(init, opts, headless, null); } /// `pardes-gui --attach=:` (and `:`, /// through ssh, main.zig): this window a replica client of a session /// elsewhere, as the tty's `remote` is a terminal's (`remoteSession`). pub fn remote(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, headless: 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 (!c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_GAMEPAD)) { 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; const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); // Background-only opacity needs per-pixel alpha; whole-window compositor // opacity would dim the text as well. SDL requires this flag at creation. const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; const reopen_flags = win_flags; // `--detach`: a window never shown, closed once the session is up. if (headless) 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; defer if (window_slot) |open| c.SDL_DestroyWindow(open); if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); updateDisplayScale(window); if (native_wayland) log.info("Wayland opacity: background-only transparent surface", .{}); // 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()}); const device = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, true, null) orelse { log.err("SDL_CreateGPUDevice: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; defer c.SDL_DestroyGPUDevice(device); var soft_present = false; var soft_renderer: ?*c.SDL_Renderer = null; if (surface_opacity or !c.SDL_ClaimWindowForGPUDevice(device, window)) { if (surface_opacity) log.info("transparent window: the GPU API will not claim one, presenting through SDL_Renderer", .{}) else log.warn("ClaimWindowForGPUDevice: {s}; presenting in software", .{c.SDL_GetError()}); soft_renderer = c.SDL_CreateRenderer(window, null) orelse { log.err("SDL_CreateRenderer: {s}", .{c.SDL_GetError()}); return error.SdlInit; }; soft_present = true; } const present_mode: c.SDL_GPUPresentMode = blk: { if (soft_present) break :blk c.SDL_GPU_PRESENTMODE_VSYNC; for ([_]c.SDL_GPUPresentMode{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }) |mode| { if (c.SDL_WindowSupportsGPUPresentMode(device, window, mode)) break :blk mode; } break :blk c.SDL_GPU_PRESENTMODE_VSYNC; }; if (!test_mode) _ = c.SDL_SetGPUAllowedFramesInFlight(device, 1); if (!soft_present) { _ = c.SDL_SetGPUSwapchainParameters(device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, present_mode); } const swapchain_format = if (soft_present) softTargetFormat(device) else c.SDL_GetGPUSwapchainTextureFormat(device, window); font_allocator = gpa; const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)) orelse { log.err("ui_font_new failed", .{}); return error.FontInit; }; // 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; c.ui_font_prime(font); 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; c.ui_font_cell_metrics(font, px, &cw, &chh, &asc); const cell_w: u32 = @intCast(@max(cw, 1)); const cell_h: u32 = @intCast(@max(chh, 1)); const tagline = taglineRaster(font, 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); } const atlas_tex = texture2d(device, c.SDL_GPU_TEXTUREFORMAT_R8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, atlas_w, atlas_h) orelse return error.GpuCreate; var samp_info = std.mem.zeroes(c.SDL_GPUSamplerCreateInfo); samp_info.min_filter = c.SDL_GPU_FILTER_NEAREST; samp_info.mag_filter = c.SDL_GPU_FILTER_NEAREST; samp_info.mipmap_mode = c.SDL_GPU_FILTER_NEAREST; samp_info.address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; samp_info.address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; samp_info.address_mode_w = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; const atlas_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate; samp_info.min_filter = c.SDL_GPU_FILTER_LINEAR; samp_info.mag_filter = c.SDL_GPU_FILTER_LINEAR; samp_info.mipmap_mode = c.SDL_GPU_FILTER_LINEAR; const linear_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate; var ax_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = atlas_w * atlas_h, .props = 0 }; const atlas_xfer = c.SDL_CreateGPUTransferBuffer(device, &ax_info) orelse return error.GpuCreate; const pipeline = try makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState)); const decor_pipeline = try makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, cell_input, backgroundLayerBlend()); const overlay_pipeline = try makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, overlay_input, backgroundLayerBlend()); const image_pipeline = try makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, backgroundLayerBlend()); const overlay_buffer_size: u32 = @intCast(max_overlay_vertices * @sizeOf(OverlayVertex)); var ovb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = overlay_buffer_size, .props = 0 }; const overlay_vbuf = c.SDL_CreateGPUBuffer(device, &ovb_info) orelse return error.GpuCreate; var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 }; const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate; const atlas_stage = try gpa.alloc(u8, atlas_w * atlas_h); defer gpa.free(atlas_stage); @memset(atlas_stage, 0); 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, .device = device, .swapchain_format = swapchain_format, .pipeline = pipeline, .decor_pipeline = decor_pipeline, .overlay_pipeline = overlay_pipeline, .image_pipeline = image_pipeline, .atlas_tex = atlas_tex, .atlas_sampler = atlas_sampler, .linear_sampler = linear_sampler, .atlas_xfer = atlas_xfer, .overlay_vbuf = overlay_vbuf, .overlay_vxfer = overlay_vxfer, .overlay_vertices = overlay_vertices, .font = font, .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, .atlas_stage = atlas_stage, .glyphs = std.AutoHashMap(GlyphKey, Slot).init(gpa), .capture = test_mode, .capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0, .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, .capture_dir = capture_dir orelse "", .soft_present = soft_present, .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, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, .win_flags = reopen_flags, .present_mode = present_mode, .window_w = want_w, .window_h = want_h, .window_slot = &window_slot, }; // The pipelines, textures and buffers the Gui holds, whatever they were // regrown to; the image ones are released below. defer { c.SDL_ReleaseGPUGraphicsPipeline(device, g.pipeline); c.SDL_ReleaseGPUGraphicsPipeline(device, g.decor_pipeline); c.SDL_ReleaseGPUGraphicsPipeline(device, g.overlay_pipeline); c.SDL_ReleaseGPUTexture(device, g.atlas_tex); c.SDL_ReleaseGPUSampler(device, g.atlas_sampler); c.SDL_ReleaseGPUSampler(device, g.linear_sampler); c.SDL_ReleaseGPUTransferBuffer(device, g.atlas_xfer); c.SDL_ReleaseGPUBuffer(device, g.overlay_vbuf); c.SDL_ReleaseGPUTransferBuffer(device, g.overlay_vxfer); if (g.vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer); if (g.vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer); if (g.image_vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer); if (g.image_vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer); if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(device, texture); if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer); if (g.gamepad) |pad| c.SDL_CloseGamepad(pad); } setGuiFontName(&g, "Adwaita Mono"); loadFallbackFonts(&g, gpa); defer deinitFallbackFonts(&g, gpa); defer g.glyphs.deinit(); defer g.words.deinit(gpa); defer { clearNativeImages(&g); g.native_images.deinit(gpa); 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 c.SDL_ReleaseGPUGraphicsPipeline(device, image_pipeline); defer if (g.font_bytes.len != 0) gpa.free(g.font_bytes); // set by Font, if it ran defer c.ui_font_free(g.font); 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 remoteSession(init, &g, opts_in, test_mode, to); try localSession(init, &g, opts_in, test_mode, headless); } /// 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); if (g.soft_renderer) |renderer| { if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture); g.soft_texture = null; g.soft_tex_w = 0; g.soft_tex_h = 0; c.SDL_DestroyRenderer(renderer); g.soft_renderer = null; } else c.SDL_ReleaseWindowFromGPUDevice(g.device, 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 (g.soft_present) { g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse { c.SDL_DestroyWindow(window); return false; }; } else { if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) { c.SDL_DestroyWindow(window); return false; } _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode); } 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.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, headless: bool, ) !void { const io = init.io; const gpa = init.gpa; const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); host_io.startWorkers(io, 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; shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .alone_unattended = headless }; 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 !headless) 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 (headless) { 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(); clearNativeImages(g); 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 (`remoteSession`): 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, 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 `Remote.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(), 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.remote`): 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 (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.remote.?.link.dirty = true; const geom = windowCells(g); if (resizeOf(core.view(), geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| v.in.post(ev); 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=:`: 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 `remote`, with /// a window for a terminal. fn remoteSession(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.TerminalImages.start(io, allocs.image); pardes.Kind.heap = allocs.addon; pardes.syntax.start(allocs.tree_sitter); defer { pardes.TerminalImages.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 }; 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, .remote = &client, }; 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(); shell.core = core; shell.gview = joined.view; shell.surface = null; g.hit_core = core; frame_probe = &core.frames; link.reset(r, &joined); 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, .remote = &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; 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; } const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; var ms: c_int = 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); 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) r.ready(); var sev = std.mem.zeroes(c.SDL_Event); g.input_seen = false; var got = c.SDL_WaitEventTimeout(&sev, ms); 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(); r.settle(); 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 (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 => |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;;BEL, the driver's own: // mouse;;;;[;] // mouse;wheel;;;[;]: 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;;;;; // 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); if (std.mem.eql(u8, kind, "wheel")) { // ESC]777;mouse;wheel;;;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; } else if (std.mem.eql(u8, kind, "focus")) { // ESC]777;mouse;focus;<1 gained, 0 lost>;0;0BEL sev.type = if (button != 0) c.SDL_EVENT_WINDOW_FOCUS_GAINED else c.SDL_EVENT_WINDOW_FOCUS_LOST; } else if (std.mem.eql(u8, kind, "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); } else { sev.type = if (std.mem.eql(u8, kind, "down")) c.SDL_EVENT_MOUSE_BUTTON_DOWN else c.SDL_EVENT_MOUSE_BUTTON_UP; sev.button.button = button; sev.button.down = std.mem.eql(u8, kind, "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 kind: @FieldType(Finger, "kind") = if (std.mem.eql(u8, type_name, "SDL_EVENT_FINGER_DOWN") or std.mem.eql(u8, type_name, "down")) .down else if (std.mem.eql(u8, type_name, "SDL_EVENT_FINGER_MOTION") or std.mem.eql(u8, type_name, "motion")) .motion else if (std.mem.eql(u8, type_name, "SDL_EVENT_FINGER_UP") or std.mem.eql(u8, type_name, "up")) .up else if (std.mem.eql(u8, type_name, "SDL_EVENT_FINGER_CANCELED") or std.mem.eql(u8, type_name, "cancel")) .cancel else return null; 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); } 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 // ghostty 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()); } } 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 (`remote`): its inputs go to its link, never /// straight to the core, which only reads here. remote: ?*Client = null, quit: bool = false, fn post(in: *Input, ev: pardes.Event) void { if (in.remote) |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.remote) |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 { // 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.remote) |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.remote == 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) { const want = std.math.clamp(g.px + step, font_px_min, font_px_max); if (want != g.px) { g.px = want; // A client's view is sized by its next loop, as its input. if (in.remote) |r| { refitFont(g, null); r.link.dirty = true; } else { refitFont(g, in.core); observeGuiFont(g, in.core); } } return; } 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 button: pardes.Mouse.Button = switch (b.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 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; 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; 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)); }, 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 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 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; } 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); } /// 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.panes.terminal.ownsWheel(pane)) { // 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.remote != null) { // ponytail: a replica client's wheel moves the view a // whole row a turn, with no glide and no touchpad's // fraction: its core's clock is the session's, which // moves only as its units come. if (notchOf(w.y, w.integer_y)) |lines| { g.program_wheel = @floatFromInt(lines); } else 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, .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); } } } if (w.x != 0) in.post(.{ .mouse = .{ .button = if (w.x > 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, } }); } const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, mods: PointerMods = .{} }; /// The modifiers held with a pointer event, as the core's Mouse carries them. const PointerMods = struct { ctrl: bool = false, shift: bool = false, alt: bool = false, 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 (`parked` has /// it). gui: ?*Gui = null, parked: ?*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 (`remote`). remote: ?*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 keeps 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; 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.parked = g; s.gui = null; s.presented = false; s.surface = null; // Its clients look at it still (Peers keeps it attended). s.peers.alone_unattended = true; s.core.unattended = s.peers.count() == 0; daemon.setState(true); } fn openTheWindow(s: *Shell) void { const g = s.parked orelse return; if (!reopenWindow(g)) { log.err("--attach: no window: {s}", .{c.SDL_GetError()}); return daemon.setState(true); } s.gui = g; s.parked = null; s.peers.alone_unattended = 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, .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)); } 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| { 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); 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; }; const nf = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse { log.err("ui_font_new failed: {s}", .{path}); s.gpa.free(bytes); core.rejectFont(); break :blk; }; c.ui_font_free(g.font); if (g.font_bytes.len != 0) s.gpa.free(g.font_bytes); g.font = nf; g.font_bytes = bytes; // FreeType borrows them for the face lifetime 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); } pollCwds(core, s.ptys); 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(dir: []const u8, pixels: []const u8, w: u32, h: u32) void { 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); } }; 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); } 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; // 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.surface_opacity or g.capture or core.settings.window_opacity == 100) null else "background transparency requires a native Wayland or alpha-capable SDL window"); } 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); } 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.remote != 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; } 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 }); } 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)); } 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); } 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) } }); const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); const written = fd >= 0 and host_io.writeFd(fd, bytes); if (fd >= 0) _ = libc.close(fd); if (!written) { _ = libc.unlink(path); s.gpa.free(path); return s.core.update(.{ .handed = .{ .seq = seq, .failure = "cannot write its dump" } }); } const job = s.gpa.create(Handover.Job) catch { _ = libc.unlink(path); 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| { _ = libc.unlink(path); 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 }; } 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); } /// 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)); } 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, gpa); 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); } 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, gpa: std.mem.Allocator) void { _ = gpa; 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; } 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, gpa); 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, gpa); 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 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, gpa); // 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, gpa); 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, gpa); if (frames > 200) return error.NeverSettled; } try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.y)), caretRow(&g, s, now).?); } /// 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, gpa); _ = 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; } }; 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]); } fn resetScroll(g: *Gui) void { g.scroll_pane = null; g.scroll_delta = 0; g.scroll_lag = 0; g.scroll_edge_len = 0; g.scroll_notch = 0; g.glide.stop(); } fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { stepGlide(g, core, gpa); const id = g.scroll_pane orelse return; const pane = core.panes[id] orelse { resetScroll(g); return; }; 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; } const r = core.view().rects[id]; if (r.h <= pane.tag_rows) { resetScroll(g); return; } 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(); core.update(.{ .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 }, }); if (pane.scroll() == was) { resetScroll(g); return; } } 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 srow = body_y + (if (st.rows > 0) 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); } /// 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; } } if (!gliding) { // A touchpad's fraction opens one row, the one that left. if (g.scroll_edge_len >= bw) { const erow: u16 = if (lag > 0) y0 + bh else y0 - 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 body, or bh + i below it, in grid rows. const at_row: i32 = if (lag < 0) @as(i32, y0) - 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) }; } 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); } 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 }; } fn releaseNativeImage(g: *Gui, key: u64) void { if (g.native_images.fetchRemove(key)) |removed| c.SDL_ReleaseGPUTexture(g.device, removed.value); } fn clearNativeImages(g: *Gui) void { var iterator = g.native_images.valueIterator(); while (iterator.next()) |texture| c.SDL_ReleaseGPUTexture(g.device, texture.*); g.native_images.clearRetainingCapacity(); } /// 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 key = place.key; if (g.native_images.contains(key)) return; const r = place.raster; const row = r.stride; if (place.dirty) |dirty| dirty: { // The core changed only these rows since a picture we still hold: // write them into that texture rather than sending the whole page. if (dirty.y + dirty.h > r.h) break :dirty; const texture = g.native_images.get(dirty.from) orelse break :dirty; try uploadTextureRows(g, cmd, texture, r.bytes()[dirty.y * row ..][0 .. dirty.h * row], r.w, dirty.y, dirty.h); try g.native_images.put(gpa, key, texture); _ = g.native_images.remove(dirty.from); return; } const texture = texture2d(g.device, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, r.w, r.h) orelse return error.GpuCreate; errdefer c.SDL_ReleaseGPUTexture(g.device, texture); try uploadTextureRows(g, cmd, texture, r.bytes()[0..byte_len], r.w, 0, r.h); try g.native_images.put(gpa, key, texture); } /// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`. fn uploadTextureRows( g: *Gui, cmd: *c.SDL_GPUCommandBuffer, texture: *c.SDL_GPUTexture, rgba: []const u8, width: usize, y: usize, rows: usize, ) !void { var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = @intCast(rgba.len), .props = 0, }; const transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate; defer c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer, false) orelse return error.GpuMap); @memcpy(mapped[0..rgba.len], rgba); c.SDL_UnmapGPUTransferBuffer(g.device, transfer); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = transfer, .offset = 0, .pixels_per_row = @intCast(width), .rows_per_layer = @intCast(rows), }; const dst = c.SDL_GPUTextureRegion{ .texture = texture, .mip_level = 0, .layer = 0, .x = 0, .y = @intCast(y), .z = 0, .w = @intCast(width), .h = @intCast(rows), .d = 1, }; c.SDL_UploadToGPUTexture(copy, &src, &dst, false); c.SDL_EndGPUCopyPass(copy); } fn appendPreparedImage(g: *Gui, gpa: std.mem.Allocator, place: pardes.Placement) void { const texture = g.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.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| releaseNativeImage(g, 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); 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; growInstances(g, &g.image_vbuf, &g.image_vxfer, &g.image_capacity, capacity, @sizeOf(ImageInstance)) catch return false; const ptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.image_vxfer.?, false) orelse return false); const instances: [*]ImageInstance = @ptrCast(@alignCast(ptr)); const win_w: f32 = @floatFromInt(sw); const win_h: f32 = @floatFromInt(sh); var idx: u32 = 0; for (g.prepared_images.items) |prepared| { if (!emitPreparedImage(g, surface, &instances[idx], prepared, win_w, win_h)) continue; idx += 1; } c.SDL_UnmapGPUTransferBuffer(g.device, g.image_vxfer.?); std.debug.assert(idx == capacity); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.image_vxfer.?, .offset = 0 }; const dst = c.SDL_GPUBufferRegion{ .buffer = g.image_vbuf.?, .offset = 0, .size = idx * @sizeOf(ImageInstance) }; c.SDL_UploadToGPUBuffer(copy, &src, &dst, false); c.SDL_EndGPUCopyPass(copy); 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 drawNativeImagesGpu( g: *Gui, rp: ?*c.SDL_GPURenderPass, batch: Group, whole: c.SDL_Rect, ) void { const pass = rp orelse return; c.SDL_BindGPUGraphicsPipeline(pass, g.image_pipeline); var idx = batch.image_start; const end = batch.image_start + batch.image_count; for (g.prepared_images.items[batch.image_start..end]) |prepared| { const clip = imageScissor(g, prepared.place); if (clip.w > 0 and clip.h > 0) { c.SDL_SetGPUScissor(pass, &clip); const sampler = c.SDL_GPUTextureSamplerBinding{ .texture = prepared.texture, .sampler = g.linear_sampler }; c.SDL_BindGPUFragmentSamplers(pass, 0, &sampler, 1); const binding = c.SDL_GPUBufferBinding{ .buffer = g.image_vbuf.?, .offset = idx * @sizeOf(ImageInstance) }; c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1); c.SDL_DrawGPUPrimitives(pass, 6, 1, 0, 0); } idx += 1; } std.debug.assert(idx == batch.image_start + batch.image_count); // Back to the whole target: what draws after a picture may run on past // the grid, as a rule and a band do. c.SDL_SetGPUScissor(pass, &whole); } 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 = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return false; var command_consumed = false; defer if (!command_consumed) { _ = c.SDL_SubmitGPUCommandBuffer(cmd); }; const frame_target = try acquireTarget(g, cmd, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse { command_consumed = true; _ = c.SDL_SubmitGPUCommandBuffer(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). 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 !uploadOverlayGpu(g, cmd, 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); var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo); color_target.texture = target; color_target.clear_color = .{ .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, }; color_target.load_op = c.SDL_GPU_LOADOP_CLEAR; color_target.store_op = c.SDL_GPU_STOREOP_STORE; 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.guides 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, and a glide's rows past it. const capacity = std.math.add(u32, cell_total, 2 * cells + decor_len) catch return error.GpuCapacity; try growInstances(g, &g.vbuf, &g.vxfer, &g.vbuf_cells, capacity, @sizeOf(CellInstance)); const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.vxfer.?, false) orelse { command_consumed = true; _ = c.SDL_SubmitGPUCommandBuffer(cmd); return false; }); const instances: [*]CellInstance = @ptrCast(@alignCast(vptr)); 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.guides 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); c.SDL_UnmapGPUTransferBuffer(g.device, g.vxfer.?); if (g.atlas_dirty_top < g.atlas_dirty_bottom) uploadAtlas(g, cmd); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.vxfer.?, .offset = 0 }; const dst = c.SDL_GPUBufferRegion{ .buffer = g.vbuf.?, .offset = 0, .size = (cell_total + shifted + decor_len) * @sizeOf(CellInstance) }; c.SDL_UploadToGPUBuffer(copy, &src, &dst, false); c.SDL_EndGPUCopyPass(copy); } build_zone.end(); building = false; if (frame_probe) |probe| probe.zone(.gui_build, probe_build); const rp = c.SDL_BeginGPURenderPass(cmd, &color_target, 1, null); pushLayerOpacity(cmd, rp, background_opacity); const whole = c.SDL_Rect{ .x = 0, .y = 0, .w = @intCast(sw), .h = @intCast(sh) }; const decor_base = cell_total + shifted; for (groups.items[0..groups.len], 0..) |group, index| { const has_shifted = index == 0 and shifted != 0; if ((group.cell_count != 0 or has_shifted) and g.vbuf != null) { c.SDL_BindGPUGraphicsPipeline(rp, g.pipeline); const samp_binding = c.SDL_GPUTextureSamplerBinding{ .texture = g.atlas_tex, .sampler = g.atlas_sampler }; c.SDL_BindGPUFragmentSamplers(rp, 0, &samp_binding, 1); if (group.cell_count != 0) { const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = group.cell_start * @sizeOf(CellInstance) }; c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1); c.SDL_DrawGPUPrimitives(rp, 6, group.cell_count, 0, 0); } if (has_shifted) { const clip = scrollScissor(g, layout, sw, sh); c.SDL_SetGPUScissor(rp, &clip); const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = cell_total * @sizeOf(CellInstance) }; c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1); c.SDL_DrawGPUPrimitives(rp, 6, shifted, 0, 0); c.SDL_SetGPUScissor(rp, &whole); } } if (group.image_count != 0) drawNativeImagesGpu(g, rp, group, whole); if (group.decor_count != 0 and g.vbuf != null) { c.SDL_BindGPUGraphicsPipeline(rp, g.decor_pipeline); // Ink keeps its colour at any WindowOpacity. pushLayerOpacity(cmd, rp, if (index == groups.ink) 1 else background_opacity); const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = (decor_base + group.decor_start) * @sizeOf(CellInstance) }; c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1); c.SDL_DrawGPUPrimitives(rp, 6, group.decor_count, 0, 0); } } drawOverlayGpu(g, cmd, rp, overlay_count); c.SDL_EndGPURenderPass(rp); command_consumed = true; return finishFrame(g, gpa, cmd, frame_target); } const Target = struct { texture: *c.SDL_GPUTexture, w: u32, h: u32 }; /// What this frame draws into: the capture texture in test mode (the grid's /// size plus PARDES_TEST_PAD) or with a soft presenter, else the swapchain's /// image; null when there is none to be had this time. fn acquireTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, capture_w: u32, capture_h: u32) !?Target { if (g.capture) { if (capture_w == 0 or capture_h == 0) return null; try ensureCaptureTexture(g, capture_w, capture_h); return .{ .texture = g.capture_tex.?, .w = capture_w, .h = capture_h }; } if (g.soft_present) { var pw: c_int = 0; var ph: c_int = 0; if (!c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph) or pw <= 0 or ph <= 0) return null; try ensureCaptureTexture(g, @intCast(pw), @intCast(ph)); return .{ .texture = g.capture_tex.?, .w = @intCast(pw), .h = @intCast(ph) }; } var swap_tex: ?*c.SDL_GPUTexture = null; var sw: u32 = 0; var sh: u32 = 0; if (!c.SDL_AcquireGPUSwapchainTexture(cmd, g.window, &swap_tex, &sw, &sh)) return null; // A busy swapchain skips the frame. return .{ .texture = swap_tex orelse return null, .w = sw, .h = sh }; } /// Submits the frame: captured, handed to the soft presenter, or presented. fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Target) !bool { if (g.capture) { try captureFrame(g, gpa, cmd, target.texture, target.w, target.h); return true; } if (g.soft_present) { try softPresentFrame(g, cmd, target.texture, target.w, target.h); return true; } return c.SDL_SubmitGPUCommandBuffer(cmd); } 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| palColor(i), .rgb => |rgb| rgb, }; switch (st.bg) { .default => {}, .index => |i| bg = palColor(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; } 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.space_slot, resolved.slot); try std.testing.expectEqual(bg_default, resolved.bg); } fn cellInstanceCount(cell: *const pardes.Cell) u32 { return if (cellFontRole(cell) == .tagline) 2 else 1; } 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); }; } 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); } } 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]; const band_base: pardes.Cell = .{ .style = .{ .bg = .{ .rgb = 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 = glyphForCodepoint(g, cellCodepoint(glyph)); const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = GlyphDecoration.fromCell(glyph), .centered = true }); const slot = cached orelse g.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.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.space_slot.v)) / atlas_h; instances[next.*].v1 = @as(f32, @floatFromInt(g.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; } 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); } 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; } 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); } } fn cellCodepoint(cell: *const pardes.Cell) u32 { const grapheme = cell.grapheme(); return if (cell.default or grapheme.len == 0) ' ' else firstCp(grapheme); } 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); } fn palColor(idx: u8) [3]u8 { const p = ghostty_vt.color.default[idx]; return .{ p.r, p.g, p.b }; } 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; c.ui_font_cell_metrics(g.font, 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.font, 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.glyphs.clearRetainingCapacity(); g.words.clear(); @memset(g.atlas_stage, 0); g.space_slot = .{ .u = 0, .v = 0 }; g.pen_x = g.cell_w; g.pen_y = 0; g.atlas_dirty_top = 0; g.atlas_dirty_bottom = atlas_h; } 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.font, 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.space_slot; if (ruleArms(here.cp) != null) return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot; const gpa = g.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.space_slot; if (!known.found_existing) { const drawn = glyphForCodepoint(g, here.cp); const font = if (drawn.face == 0) g.font else g.fallbacks[drawn.face - 1].?.face; known.value_ptr.* = if (role == .body and c.ui_font_substitutes(font, drawn.glyph) != 0) Words.shape_slot else cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = role, .decoration = here.decoration }) orelse g.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.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.space_slot; }; words.shaped.resize(gpa, n) catch { words.text.shrinkRetainingCapacity(text_start); return g.space_slot; }; const shaped = words.shaped.items; var run_start: usize = 0; var face = glyphForCodepoint(g, 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 = glyphForCodepoint(g, text[run_end]).face; if (next_face != face) break; } const run_font = if (face == 0) g.font else g.fallbacks[face - 1].?.face; c.ui_font_shape(run_font, g.px, @intCast(g.cell_w), text[run_start..].ptr, @intCast(run_end - run_start), shaped[run_start..].ptr); for (shaped[run_start..run_end]) |cell| { const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = 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.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, .device = undefined, .swapchain_format = undefined, .pipeline = undefined, .decor_pipeline = undefined, .overlay_pipeline = undefined, .image_pipeline = undefined, .atlas_tex = undefined, .atlas_sampler = undefined, .linear_sampler = undefined, .atlas_xfer = undefined, .overlay_vbuf = undefined, .overlay_vxfer = undefined, .overlay_vertices = &.{}, .font = 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, .atlas_stage = &.{}, .glyphs = undefined, }; } /// A Gui that can shape and rasterize `font` 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(font: *c.UIFont, px: f32) !Gui { c.ui_font_prime(font); font_allocator = std.testing.allocator; var cw: c_int = 0; var ch: c_int = 0; var ascent: c_int = 0; c.ui_font_cell_metrics(font, px, &cw, &ch, &ascent); const tag = taglineRaster(font, px, @intCast(cw), @intCast(ch), 82); var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); g.font = font; g.px = px; g.ascent = ascent; g.tagline_px = tag.px; g.tagline_baseline = tag.baseline; g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); 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; } 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); const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; defer c.ui_font_free(font); var g = try textTestGui(font, 27); defer font_allocator = std.heap.smp_allocator; defer std.testing.allocator.free(g.atlas_stage); defer g.glyphs.deinit(); 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.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_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.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'a'), .role = .body }).?, slots[0]); try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'b'), .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 = c.ui_font_glyph(font, '-'), .role = .body }).?; const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '>'), .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(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); } fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { var it = g.glyphs.iterator(); while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; return error.NoGlyph; } test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); var g = try textTestGui(font, 18); defer font_allocator = std.heap.smp_allocator; defer std.testing.allocator.free(g.atlas_stage); defer g.glyphs.deinit(); defer g.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 var expected: [64 * 64]u8 = undefined; 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(c.ui_font_glyph(font, text[i]), key.glyph); try std.testing.expectEqual(@as(u4, 1), key.span); _ = c.ui_font_raster(font, 18, key.glyph, @intFromBool(cell.style.bold), &expected, 64, @intCast(g.cell_w), @intCast(g.cell_h), 0, @intCast(g.cell_w), g.ascent); for (0..g.cell_h) |y| try std.testing.expectEqualSlices(u8, expected[y * 64 ..][0..g.cell_w], g.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); } } /// The atlas slot of `key`, rasterized on first use. A strip is `span` cells /// wide (a grip glyph GUTTER cells, centered); a cell samples its slice of it. /// Null when the atlas is full. fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { if (g.glyphs.get(key)) |s| return s; const slot_w = g.cell_w * @as(u32, if (key.centered) config.GUTTER else key.span); if (g.pen_x + slot_w > atlas_w) { g.pen_x = 0; g.pen_y += g.cell_h; } if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back const probe_raster = monoNs(); defer if (frame_probe) |probe| { probe.zone(.gui_raster, probe_raster); probe.rastered +|= 1; }; const s = Slot{ .u = g.pen_x, .v = g.pen_y }; const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u; const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face; const px = if (key.role == .tagline) g.tagline_px else g.px; const baseline = if (key.role == .tagline) g.tagline_baseline else g.ascent; const cell_w = if (key.role == .tagline) g.tagline_width else g.cell_w; const raster_w = if (key.centered) slot_w else cell_w * key.span; const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h; const bold = @intFromBool(key.decoration.bold); if (key.rule) { drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?); } else if (key.centered) { _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h)); } else { _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline); } decorateLine(out, atlas_w, raster_w, raster_h, baseline, key.decoration); if (key.centered) centerGlyphInk(out, raster_w, raster_h); g.atlas_dirty_top = @min(g.atlas_dirty_top, s.v); g.atlas_dirty_bottom = @max(g.atlas_dirty_bottom, s.v + raster_h); g.glyphs.put(key, s) catch return null; g.pen_x += slot_w; return s; } // Run once when a grip glyph enters the atlas, after decorations. Copy only // visible ink so bearings, empty bitmap margins and bold all share one center. fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void { const b = inkBounds(out[0 .. (height - 1) * atlas_w + width], atlas_w, width, height) orelse return; const w = b.max_x - b.min_x + 1; const h = b.max_y - b.min_y + 1; const left = (width - w) / 2; const top = (height - h) / 2; var scratch: [atlas_w]u8 = undefined; for (0..h) |step| { const row = if (top > b.min_y) h - 1 - step else step; const source = (b.min_y + row) * atlas_w + b.min_x; const target = (top + row) * atlas_w; @memcpy(scratch[0..w], out[source..][0..w]); @memset(out[target..][0..width], 0); @memcpy(out[target + left ..][0..w], scratch[0..w]); } for (0..height) |row| { if (row < top or row >= top + h) @memset(out[row * atlas_w ..][0..width], 0); } } test "pane indicator cached ink centers bearings styles and sizes" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); var g = testGui(10, 20, 6, 12); g.font = font; g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); defer std.testing.allocator.free(g.atlas_stage); g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); defer g.glyphs.deinit(); for ([_]f32{ 13, 27, 40 }) |px| { g.px = px; var cw: c_int = 0; var ch: c_int = 0; c.ui_font_cell_metrics(font, px, &cw, &ch, &g.ascent); g.cell_w = @intCast(cw); g.cell_h = @intCast(ch); for ([_]u8{ 40, 82, 100 }) |percent| { const tag = taglineRaster(font, 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.glyphs.count()); for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { const key: GlyphKey = .{ .face = 0, .glyph = c.ui_font_glyph(font, @intCast(cp)), .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; const slot = cachedGlyph(&g, key).?; const bounds = inkBounds(g.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.glyphs.count(); const pen = g.pen_x; try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); try std.testing.expectEqual(count, g.glyphs.count()); try std.testing.expectEqual(pen, g.pen_x); }; } } resetGlyphAtlas(&g); g.pen_y = atlas_h; try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '^'), .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 = .{}; const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); var g = testGui(10, 20, 8, 16); g.font = font; g.px = 20; g.tagline_px = 16; g.pen_y = atlas_h; g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); defer g.glyphs.deinit(); 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); } // Underline and strikethrough stay inside the existing atlas slot, so text // advance, caret and selection geometry are identical to the regular glyph. // The cached mask keeps this work out of steady-state rendering and also // decorates terminal spaces. Bold is not drawn here: the rasterizer emboldens // the outline. fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline: i32, decoration: GlyphDecoration) void { if (width == 0 or height == 0) return; // A line is a logical pixel thick, its dots and waves as long: the same // weight at any density (dp). const t: usize = @intFromFloat(dp(1)); if (decoration.underline != .off) { const base: usize = @intCast(@max(0, baseline)); const row = @min(base + 1, height -| t); for (0..width) |x| { const top = switch (decoration.underline) { .off => unreachable, .single => row, .double => { const upper = @min(base + 1, height -| 3 * t); for (0..t) |k| { out[@min(upper + k, height - 1) * stride + x] = 255; out[@min(upper + 2 * t + k, height - 1) * stride + x] = 255; } continue; }, .curly => row -| @as(usize, if (x % (4 * t) < 2 * t) t else 0), .dotted => if (x % (3 * t) < t) row else continue, .dashed => if (x % (6 * t) < 4 * t) row else continue, }; for (0..t) |k| out[@min(top + k, height - 1) * stride + x] = 255; } } if (decoration.strikethrough) { const row = @min(height -| t, @as(usize, @intCast(@max(0, baseline))) * 2 / 3); for (0..t) |k| @memset(out[@min(row + k, height - 1) * stride ..][0..width], 255); } } test "a box-drawing rule reaches its cell's edges, and only its arms do" { const stride = 12; const width = 9; const height = 15; var mask: [stride * height]u8 = @splat(0xa5); drawRule(&mask, stride, width, height, ruleArms(0x253c).?); // ┼: ink on all four edges, none in the corners, nothing past the slot. try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]); try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]); try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]); try std.testing.expectEqual(@as(u8, 0), mask[0]); for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); drawRule(&mask, stride, width, height, ruleArms(0x2502).?); try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]); try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); try std.testing.expect(ruleArms('|') == null); } test "glyph decorations render spaces and stay inside their atlas slot" { const stride = 9; const width = 5; const height = 7; for ([_]GlyphDecoration{ .{ .underline = .single }, .{ .underline = .double }, .{ .underline = .curly }, .{ .underline = .dotted }, .{ .underline = .dashed }, .{ .strikethrough = true }, }) |decoration| { var mask: [stride * (height + 1)]u8 = @splat(0xa5); for (0..height) |y| @memset(mask[y * stride ..][0..width], 0); decorateLine(&mask, stride, width, height, 5, decoration); try std.testing.expect(inkBounds(&mask, stride, width, height) != null); for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); for (mask[stride * height ..]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); } const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); } /// Uploads only the atlas rows drawn into since the last upload. Glyphs fill /// the atlas pen-style, a band of rows at a time, so new glyphs are a band a /// cell or two tall, not the whole 4 MB texture. The band sits at the same /// offset in the transfer buffer as in the stage, and the texture keeps the /// rows outside it. fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { const top = g.atlas_dirty_top; const rows = g.atlas_dirty_bottom - top; const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.atlas_xfer, false) orelse return; const dst: [*]u8 = @ptrCast(ptr); @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = g.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows }; const dstregion = c.SDL_GPUTextureRegion{ .texture = g.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 }; c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false); c.SDL_EndGPUCopyPass(copy); g.atlas_dirty_top = atlas_h; g.atlas_dirty_bottom = 0; } test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" { const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); var g = try textTestGui(font, 18); defer font_allocator = std.heap.smp_allocator; defer std.testing.allocator.free(g.atlas_stage); defer g.glyphs.deinit(); defer g.words.deinit(std.testing.allocator); // The texture as uploadAtlas leaves it, which starts undefined. const texture = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); defer std.testing.allocator.free(texture); @memset(texture, 0xa5); var glyph: u32 = 0; for (0..40) |frame| { if (frame == 30) resetGlyphAtlas(&g); // a font change // Plain glyphs, strips, taglines, grip glyphs and decorations. for (0..25) |_| { glyph += 1; const span: u4 = @intCast(1 + glyph % 3); _ = cachedGlyph(&g, .{ .face = 0, .glyph = glyph, .role = if (glyph % 4 == 0) .tagline else .body, .decoration = .{ .bold = glyph % 2 == 0, .underline = if (glyph % 5 == 0) .curly else .off, .strikethrough = glyph % 11 == 0 }, .centered = glyph % 13 == 0, .lead = @intCast(glyph % span), .span = span, }) orelse return error.AtlasFull; } for (0..atlas_h) |row| { const stage = g.atlas_stage[row * atlas_w ..][0..atlas_w]; const uploaded = texture[row * atlas_w ..][0..atlas_w]; if (row >= g.atlas_dirty_top and row < g.atlas_dirty_bottom) @memcpy(uploaded, stage) else try std.testing.expect(std.mem.eql(u8, stage, uploaded)); } g.atlas_dirty_top = atlas_h; g.atlas_dirty_bottom = 0; } try std.testing.expect(g.pen_y >= 2 * g.cell_h); } /// A vertex buffer and its upload buffer holding at least `needed` /// elements of `stride` bytes: those there when they do, else twice as /// many again until they would (the old ones let go). fn growInstances(g: *Gui, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void { if (needed <= capacity.* and buffer.* != null and transfer.* != null) return; var grown = @max(@as(u32, 1), capacity.*); while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity; const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity; var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 }; const next_buffer = c.SDL_CreateGPUBuffer(g.device, &vb_info) orelse return error.GpuCreate; errdefer c.SDL_ReleaseGPUBuffer(g.device, next_buffer); var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 }; const next_transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate; if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(g.device, old); if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(g.device, old); buffer.* = next_buffer; transfer.* = next_transfer; capacity.* = grown; } /// One vertex buffer of a pipeline: `pitch` bytes an element, read per /// vertex or per instance through `attrs`. const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute }; /// The cells' and the decor's instances (ui.vert.glsl). const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") }, .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") }, .{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") }, .{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") }, .{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") }, .{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") }, } }; const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{ .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") }, .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") }, } }; const image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{ .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") }, .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") }, } }; /// A pipeline drawing triangles into `color_format`: `vert`, and `frag` /// with its samplers and uniform buffers, over one vertex buffer of /// `input` (none: the post chain's triangle over the whole frame). pub fn makePipeline( device: *c.SDL_GPUDevice, color_format: c.SDL_GPUTextureFormat, vert: []const u8, frag: []const u8, samplers: u32, uniforms: u32, input: ?VertexInput, blend: c.SDL_GPUColorTargetBlendState, ) !*c.SDL_GPUGraphicsPipeline { const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0); defer c.SDL_ReleaseGPUShader(device, vs); const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms); defer c.SDL_ReleaseGPUShader(device, fs); var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend }; var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined; var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); info.vertex_shader = vs; info.fragment_shader = fs; info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; if (input) |in| { vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 }; info.vertex_input_state = .{ .vertex_buffer_descriptions = &vbuf_desc, .num_vertex_buffers = 1, .vertex_attributes = in.attrs.ptr, .num_vertex_attributes = @intCast(in.attrs.len), }; } info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1; info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 }; return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate; } fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState { var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA; blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR; blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; blend.enable_blend = true; return blend; } test "overlapping background layers keep one uniform opacity" { const blend = 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); } } } fn makeShader(device: *c.SDL_GPUDevice, code: []const u8, stage: c.SDL_GPUShaderStage, n_samplers: u32, n_uniform_buffers: u32) !*c.SDL_GPUShader { var info = std.mem.zeroes(c.SDL_GPUShaderCreateInfo); info.code = code.ptr; info.code_size = code.len; info.entrypoint = "main"; info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; info.stage = stage; info.num_samplers = n_samplers; info.num_uniform_buffers = n_uniform_buffers; return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate; } /// A 2D texture of one level, one layer and one sample. pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture { var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); info.type = c.SDL_GPU_TEXTURETYPE_2D; info.format = format; info.usage = usage; info.width = width; info.height = height; info.layer_count_or_depth = 1; info.num_levels = 1; info.sample_count = c.SDL_GPU_SAMPLECOUNT_1; return c.SDL_CreateGPUTexture(device, &info); } fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void { if (g.capture_tex != null and g.capture_tex_w == width and g.capture_tex_h == height) return; const next = texture2d(g.device, g.swapchain_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, width, height) orelse return error.GpuCreate; if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture); g.capture_tex = next; g.capture_tex_w = width; g.capture_tex_h = height; } fn softTargetFormat(device: *c.SDL_GPUDevice) c.SDL_GPUTextureFormat { const candidates = [_]c.SDL_GPUTextureFormat{ c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, }; for (candidates) |format| { if (c.SDL_GPUTextureSupportsFormat( device, format, c.SDL_GPU_TEXTURETYPE_2D, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, )) return format; } return c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM; } fn softPixelFormat(format: c.SDL_GPUTextureFormat) ?c.SDL_PixelFormat { return switch (format) { c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB, => c.SDL_PIXELFORMAT_ARGB8888, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB, => c.SDL_PIXELFORMAT_ABGR8888, else => null, }; } fn ensureSoftTexture(g: *Gui, width: u32, height: u32) !*c.SDL_Texture { if (g.soft_texture) |texture| { if (g.soft_tex_w == width and g.soft_tex_h == height) return texture; c.SDL_DestroyTexture(texture); g.soft_texture = null; } const renderer = g.soft_renderer orelse return error.GpuCreate; const pixel_format = softPixelFormat(g.swapchain_format) orelse return error.UnsupportedCaptureFormat; const next = c.SDL_CreateTexture( renderer, pixel_format, c.SDL_TEXTUREACCESS_STREAMING, @intCast(width), @intCast(height), ) orelse return error.GpuCreate; _ = c.SDL_SetTextureScaleMode(next, c.SDL_SCALEMODE_NEAREST); _ = c.SDL_SetTextureBlendMode(next, c.SDL_BLENDMODE_NONE); g.soft_texture = next; g.soft_tex_w = width; g.soft_tex_h = height; return next; } /// The frame in `target`, `size` bytes, copied down into `capture_xfer` /// (grown to it first) by `cmd`, which the caller submits and waits for. /// With no buffer to be had the command buffer is submitted as it is. fn downloadTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, size: u32) !*c.SDL_GPUTransferBuffer { if (g.capture_xfer == null or g.capture_xfer_size < size) { var info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 }; const next = c.SDL_CreateGPUTransferBuffer(g.device, &info) orelse { _ = c.SDL_SubmitGPUCommandBuffer(cmd); return error.GpuCreate; }; if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); g.capture_xfer = next; g.capture_xfer_size = size; } const xfer = g.capture_xfer.?; const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTextureRegion{ .texture = target, .mip_level = 0, .layer = 0, .x = 0, .y = 0, .z = 0, .w = sw, .h = sh, .d = 1 }; const dst = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = xfer, .offset = 0, .pixels_per_row = sw, .rows_per_layer = sh }; c.SDL_DownloadFromGPUTexture(copy, &src, &dst); c.SDL_EndGPUCopyPass(copy); return xfer; } fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1); if (size == 0 or bpp != 4) { _ = c.SDL_SubmitGPUCommandBuffer(cmd); return error.UnsupportedCaptureFormat; } const xfer = try downloadTarget(g, cmd, target, sw, sh, size); const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; defer c.SDL_ReleaseGPUFence(g.device, fence); var fences = [_]*c.SDL_GPUFence{fence}; const probe_wait = monoNs(); if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; if (frame_probe) |probe| probe.zone(.gui_wait, probe_wait); const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); const texture = try ensureSoftTexture(g, sw, sh); const renderer = g.soft_renderer orelse return error.GpuCreate; const probe_upload = monoNs(); defer if (frame_probe) |probe| probe.zone(.gui_upload, probe_upload); if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap; // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went // out, and when, for a recording at the frames' own times. One write a // frame; nothing else. if (frame_capture_dir) |dir| captureSeries(dir, @as([*]const u8, @ptrCast(mapped))[0..size], sw, sh); // The cell shader already produced premultiplied backgrounds with opaque // foreground ink. Copy that alpha unchanged; never modulate the full frame. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); _ = c.SDL_RenderClear(renderer); _ = c.SDL_RenderTexture(renderer, texture, null, null); const probe_flip = monoNs(); _ = c.SDL_RenderPresent(renderer); if (frame_probe) |probe| probe.zone(.gui_flip, probe_flip); } fn backgroundOpacity(percent: u8) f32 { std.debug.assert(percent <= 100); return @as(f32, @floatFromInt(percent)) / 100; } 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))); } } /// 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-.ppm too. fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void { const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1); if (size == 0) { _ = c.SDL_SubmitGPUCommandBuffer(cmd); return error.UnsupportedCaptureFormat; } const xfer = try downloadTarget(g, cmd, target, sw, sh, size); const submit_ns = monoNs(); const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; defer c.SDL_ReleaseGPUFence(g.device, fence); var fences = [_]*c.SDL_GPUFence{fence}; if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit; latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, monoNs(), submit_ns }); const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap; defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer); const pixels: [*]const u8 = @ptrCast(mapped); try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, "latest"); var name: [24]u8 = undefined; // unreachable below: "frame-" and a u32 fit 24 if (g.capture_series) try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable); g.captured +%= 1; } /// A test window's state for a harness (test/process/window.zig), in the /// capture directory's `status`: " ". /// 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 return; 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); } fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8) !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 bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); if (bpp != 4) return error.UnsupportedCaptureFormat; const bgr = switch (g.swapchain_format) { c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB => false, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB => true, else => return error.UnsupportedCaptureFormat, }; var tmp_buf: [4096]u8 = undefined; var final_buf: [4096]u8 = undefined; const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.ppm.tmp", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong; const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.ppm", .{ g.capture_dir, name }, 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: [64]u8 = undefined; const hdr = std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch return error.CaptureWriteFailed; _ = host_io.writeFd(fd, hdr); const row_rgb = try gpa.alloc(u8, @as(usize, width) * 3); 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 * 3; 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]; } _ = 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; }; 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)); } /// 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); } } 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 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); } 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); } }; 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()); } /// 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; if (!glide.caret_rides or glide.follow.offset == 0) return 0; const cu = surface.cursor orelse 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; } /// 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; } /// 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; for (boxes[0..cursorBoxes(g, surface, layout, win_h, &boxes)]) |box| if (box.bar) try addDecor(g, gpa, box.x0, box.y0, box.x1, box.y1, 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); } } 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); } /// 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); }; } 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); } 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); } 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; } fn uploadOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, vertex_count: u32) bool { const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex); const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.overlay_vxfer, false) orelse return false; const dst: [*]u8 = @ptrCast(ptr); const src: [*]const u8 = @ptrCast(g.overlay_vertices.ptr); @memcpy(dst[0..byte_len], src[0..byte_len]); c.SDL_UnmapGPUTransferBuffer(g.device, g.overlay_vxfer); const copy = c.SDL_BeginGPUCopyPass(cmd); const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.overlay_vxfer, .offset = 0 }; const dst_region = c.SDL_GPUBufferRegion{ .buffer = g.overlay_vbuf, .offset = 0, .size = byte_len }; c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false); c.SDL_EndGPUCopyPass(copy); return true; } fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void { const uniforms = [4]f32{ opacity, 0, 0, 0 }; c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms))); // The source alpha is geometric/image coverage, not window opacity. Its // alpha contribution is multiplied by this constant separately, so a // rail repainted over a gutter still has alpha p, not p + p*(1-p). c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity }); } fn drawOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32) void { if (vertex_count == 0) return; const pass = rp orelse return; c.SDL_BindGPUGraphicsPipeline(pass, g.overlay_pipeline); const binding = c.SDL_GPUBufferBinding{ .buffer = g.overlay_vbuf, .offset = 0 }; c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1); pushLayerOpacity(cmd, pass, backgroundOpacity(g.applied_window_opacity)); c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0); } 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; } 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); }