//! The canonical screen every shell draws: cells, their styles and diffs, //! the image placements laid over them, and the Surface that holds a frame. const pardes = @import("pardes.zig"); const std = @import("std"); const layout = @import("layout.zig"); const uucode = @import("uucode"); const vaxis = @import("vaxis"); const panes = @import("panes.zig"); const config = @import("config.zig"); const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const MAX_TAG_LAYERS = pardes.MAX_TAG_LAYERS; pub const Color = union(enum) { default, index: u8, rgb: [3]u8 }; pub const FontRole = enum(u8) { body, tagline }; pub const CellStyle = struct { fg: Color = .default, bg: Color = .default, bold: bool = false, dim: bool = false, italic: bool = false, blink: bool = false, reverse: bool = false, invisible: bool = false, strikethrough: bool = false, ul: enum(u3) { off, single, double, curly, dotted, dashed } = .off, font_role: FontRole = .body, }; pub const Cell = struct { text: [7]u8 = @splat(' '), len: u8 = 1, style: CellStyle = .{}, default: bool = true, pub fn grapheme(c: *const Cell) []const u8 { return c.text[0..c.len]; } pub fn visuallyEqual(a: *const Cell, b: *const Cell) bool { if (a.default or b.default) return a.default and b.default; return a.len == b.len and std.mem.eql(u8, a.grapheme(), b.grapheme()) and std.meta.eql(a.style, b.style); } pub fn printableAscii(c: *const Cell) ?u8 { if (c.default) return ' '; if (c.len != 1) return null; const byte = c.text[0]; return if (byte >= ' ' and byte <= '~') byte else null; } }; test "cell visual equality ignores dead grapheme tail bytes" { var a: Cell = .{ .default = false }; var b = a; a.text[0] = 'x'; b.text[0] = 'x'; a.text[4] = 'a'; b.text[4] = 'b'; try std.testing.expect(a.visuallyEqual(&b)); b.style.bold = true; try std.testing.expect(!a.visuallyEqual(&b)); a.default = true; b.default = true; try std.testing.expect(a.visuallyEqual(&b)); } /// A rectangle in pixels. pub const RectPx = struct { x: u32 = 0, y: u32 = 0, w: u32 = 0, h: u32 = 0, }; pub const PixelPoint = struct { x: u32, y: u32 }; /// Source pixels and their destination inside a pane body's pixel rectangle. /// Both rectangles are half-open. Rounding is always toward the inside, so a /// backend can draw this result without a backend-specific overflow clip. pub const NativeGeometry = struct { src: RectPx, dst: RectPx, /// Map a destination pixel back into the retained source crop. This is the /// same integer transform the texture rectangle describes; points in a /// letterbox return null. pub fn sourcePoint(self: NativeGeometry, x: u32, y: u32) ?PixelPoint { if (self.src.w == 0 or self.src.h == 0 or self.dst.w == 0 or self.dst.h == 0) return null; if (x < self.dst.x or y < self.dst.y) return null; const dx = x - self.dst.x; const dy = y - self.dst.y; if (dx >= self.dst.w or dy >= self.dst.h) return null; return .{ .x = self.src.x + @as(u32, @intCast(@as(u64, dx) * self.src.w / self.dst.w)), .y = self.src.y + @as(u32, @intCast(@as(u64, dy) * self.src.h / self.dst.h)), }; } }; /// Where a fitted placement (`at` null) goes: shrunk only when it must be, /// at the top left. The scale ratios are compared without floating point: /// the tighter bound is exact, the other rounded inward. pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeometry { if (iw == 0 or ih == 0 or max_w == 0 or max_h == 0 or iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null; const src_w: u32 = @intCast(iw); const src_h: u32 = @intCast(ih); if (src_w <= max_w and src_h <= max_h) return .{ .src = .{ .w = src_w, .h = src_h }, .dst = .{ .w = src_w, .h = src_h }, }; const dst: RectPx = if (@as(u64, max_w) * src_h <= @as(u64, max_h) * src_w) .{ .w = max_w, .h = @intCast(@max(1, @as(u64, src_h) * max_w / src_w)), } else .{ .w = @intCast(@max(1, @as(u64, src_w) * max_h / src_h)), .h = max_h, }; return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst }; } test "native image contain keeps aspect, bounds, top-left, and small-image size" { try std.testing.expectEqual(RectPx{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst); try std.testing.expectEqual(RectPx{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst); try std.testing.expectEqual(RectPx{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst); try std.testing.expect(containGeometry(17, 9, 0, 40) == null); const odd = containGeometry(403, 211, 101, 47).?; try std.testing.expectEqual(RectPx{ .w = 89, .h = 47 }, odd.dst); try std.testing.expectEqual(RectPx{ .w = 403, .h = 211 }, odd.src); // Nothing its backend contract cannot represent. try std.testing.expect(containGeometry(0, 10, 20, 20) == null); if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null); } /// A rectangle in the frame's cells. pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; /// The pixels a placement shows: RGBA, straight alpha, `stride` bytes a /// row. They are the pane's, and stay put until its next frame. pub const Raster = struct { ptr: [*]const u8, w: u32, h: u32, stride: u32, pub fn of(rgba: []const u8, w: usize, h: usize) Raster { return .{ .ptr = rgba.ptr, .w = @intCast(w), .h = @intCast(h), .stride = @intCast(w * 4) }; } pub fn bytes(r: Raster) []const u8 { return r.ptr[0 .. @as(usize, r.stride) * r.h]; } }; /// A picture over the frame's cells, which a frontend realises: the window /// as a texture kept by `key`, the tty as a kitty image, or either as glyph /// art in `dst`'s cells (Art.zig, the frontends' own) where it cannot show /// pixels or the pane asks for art. The frame lists them a pane at a time, /// lowest first. pub const Placement = struct { pane: u8, raster: Raster, /// The part of `raster` shown. src: RectPx, /// The cells it lies over, which clip it. dst: RectCell, /// Where it goes in `dst`, in pixels from `dst`'s top left corner; /// null: the frontend fits `src` there, no larger than it is, at the /// top left (as glyph art, centred). at: ?RectPx = null, /// The pixels' identity (`keyOf`): one key is one picture, so a /// frontend keeps what it uploaded under it. key: u64, /// A terminal program's kitty `z=`: below 0 it is under the text, /// which a tty passes on to the terminal outside. z: i32 = 0, /// Rows of `raster` that alone differ from the picture under the key /// `from`: a frontend still holding that one updates those rows. dirty: ?Dirty = null, art: Art = .{}, pub const Dirty = struct { from: u64, y: u32, h: u32 }; /// How the pane wants it drawn as glyph art: the Petscii, Palette and /// Ascii words on an image pane, Petscii and TermImages on a terminal. pub const Art = struct { /// Glyph art even where pixels could be shown (Petscii on). glyph: bool = false, palette: Palette = .commodore, /// Letters and signs among the glyphs, not only blocks and lines. ascii: bool = true, pub const Palette = enum { commodore, terminal }; }; /// A pane's picture `page` (a PDF's page, a terminal's image id; 0 for /// an image) as of `revision`. pub fn keyOf(serial: u32, page: u32, revision: u32) u64 { return std.hash.Wyhash.hash(0, std.mem.asBytes(&[3]u32{ serial, page, revision })); } }; test "a placement's key follows its pane, its page and the revision of its pixels, and nothing of where it goes" { const first = Placement.keyOf(41, 7, 3); try std.testing.expectEqual(first, Placement.keyOf(41, 7, 3)); try std.testing.expect(first != Placement.keyOf(41, 8, 3)); try std.testing.expect(first != Placement.keyOf(41, 7, 4)); try std.testing.expect(first != Placement.keyOf(42, 7, 3)); } /// One part of the frame and where it is, placed once by `draw.place` /// before anything is painted: every painter and every shell reads the /// geometry here instead of working it out again. `rect` is in grid cells /// and is the hit-test geometry. pub const Region = struct { pub const Kind = enum(u8) { /// The frame-wide border fill every other part is painted over. page, /// A pane's grip: the mode mark at the head of its tag rows. grip, /// A pane's tag rows, right of its grip. tag, /// A pane's body, right of its rail: absent while it is collapsed. body, /// The scroll rail down a pane's left edge, beside its body. rail, /// A transient band over the body's top rows (a message, a prompt). notice, column_grip, column_tag, workspace_tag, /// A column below the workspace tag, its bar and panes: its left /// edge is the spine a pixel shell rules down it. column, /// A drag's guide or a seam's hover hint, drawn over the panes. guide, /// The debug stats box, drawn over the panes. debug, }; pub const none = std.math.maxInt(u8); kind: Kind, /// The pane slot, or the column, the part belongs to; `none` for the /// page and the workspace tag. owner: u8 = none, serial: u32 = 0, rect: layout.Rect, /// The pane or column has the keyboard's focus. active: bool = false, /// A grip's pane has changes it has not saved. dirty: bool = false, /// A rail's thumb: rows from the rail's top, and how many. Zero rows is /// a rail with no thumb (an image). A native PDF's thumb is measured in /// document pixels and filled in by Pdf.draw while it paints, so read /// regions once render has returned. thumb_y: u16 = 0, thumb_h: u16 = 0, /// The same thumb unrounded, for a pixel shell: its top and its length /// as fractions of the track (the length before any minimum, so one /// row of the content is `thumb_span / rect.h`). Zero when unmeasured. thumb_at: f32 = 0, thumb_span: f32 = 0, /// A notice's index in its pane's `notices`. notice: u8 = 0, /// A body's view: the first line it shows (a file's scroll, a /// terminal's grid offset), and the text it shows (`draw.place`'s doc: /// 0 for a terminal or a picture), which a frontend's glide follows. line: i32 = 0, doc: u64 = 0, /// A body drawn as a strip of pictures (a PDF): how far down the strip /// it shows, in pixels. Its placements are laid at the whole pixel; a /// pixel frontend draws them the fraction higher. scroll_px: f64 = 0, /// Cells the column-move rail takes off the right edge while it runs /// there: layers and pixel shells stop short of them, the grid does not. clip: u16 = 0, }; /// Guides a frame can draw: a run of a column-move rail per pane it skips /// the tags of, and a handful of border and hover dashes. pub const MAX_GUIDES = MAX_PANES + 4; pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + MAX_GUIDES + 1; /// The colours a pixel shell draws its chrome in (rules, rails, grips, the /// tag underlay), resolved by the core each frame, so a frontend attached /// to a detached session draws them from the frame alone. pub const RailTick = struct { owner: u8, at: u16, current: bool }; pub const max_rail_ticks = 4096; pub const rail_tick_scale = 1024; pub const Chrome = struct { /// The theme's ground and ink; null where it leaves them to the shell. page: ?[3]u8 = null, fg: ?[3]u8 = null, /// Rules and column spines. border: [3]u8 = .{ 0, 0, 0 }, /// The rule under the workspace tag. topbar_rule: [3]u8 = .{ 0, 0, 0 }, tag_bg: [3]u8 = .{ 0, 0, 0 }, /// The focused pane's and column's tag underlay. tag_focus_bg: [3]u8 = .{ 0, 0, 0 }, tag_fg: [3]u8 = .{ 0, 0, 0 }, scroll_track: [3]u8 = .{ 0, 0, 0 }, scroll_thumb: [3]u8 = .{ 0, 0, 0 }, /// A pane's places' ticks on its rail, and its current one's. match_tick: [3]u8 = .{ 0, 0, 0 }, match_current: [3]u8 = .{ 0, 0, 0 }, /// Rule width in pixels (colors.Theme.rule_px). rule_px: u8 = 2, /// The ring round a grip, acme's button: unfocused, and focused. grip_border: [3]u8 = .{ 0, 0, 0 }, grip_focus_ring: [3]u8 = .{ 0, 0, 0 }, /// A dirty pane's button fill. grip_dirty: [3]u8 = .{ 0, 0, 0 }, /// The rule between a pane's tag and its body; null is halfway between /// the tag's ground and the page the shell actually draws. tag_rule: ?[3]u8 = null, /// The scroll column's width, button and scrollbar alike, in pixels at /// a 17px tagline (acme's 12 at its font); a pixel shell scales it. rail_px: u8 = 12, }; /// The canonical interface: what a frame of pardes IS. The tui shell writes /// these cells to vaxis one-to-one; the SDL shells rasterize them. pub const Surface = struct { /// `box` is acme's boxcursor, shown while a pane or a column is carried /// by its grip (cols.c:485, rows.c:151). pub const PointerShape = enum(u8) { arrow, link, target, box }; pointer_shape: PointerShape = .arrow, body_layers: [MAX_PANES]Layer = @splat(.{}), tag_layers: [MAX_TAG_LAYERS]Layer = @splat(.{}), cols: u16 = 0, rows: u16 = 0, regions: [MAX_REGIONS]Region = undefined, nregions: u16 = 0, /// The panes' places' ticks on their rails (Places.addTicks), /// placed with the regions: each at `at` 1/`rail_tick_scale`s down its /// rail's track, the pane's current match's marked. rail_ticks: [max_rail_ticks]RailTick = undefined, nrail_ticks: u16 = 0, chrome: Chrome = .{}, cells: []Cell = &.{}, /// bar: draw an insert-style thin cursor instead of the block cursor: ?struct { x: u16, y: u16, bar: bool = false } = null, placements: std.ArrayList(Placement) = .empty, pub fn tagLayers(s: *const Surface) []const Layer { return &s.tag_layers; } pub fn bodyLayers(s: *const Surface) []const Layer { return &s.body_layers; } pub fn regionList(s: *const Surface) []const Region { return s.regions[0..s.nregions]; } pub fn addRegion(s: *Surface, r: Region) void { std.debug.assert(s.nregions < s.regions.len); s.regions[s.nregions] = r; s.nregions += 1; } /// The first part of `kind` that `owner` has: its tag, its rail. pub fn region(s: *Surface, kind: Region.Kind, owner: usize) ?*Region { for (s.regions[0..s.nregions]) |*r| if (r.kind == kind and r.owner == owner) return r; return null; } pub fn at(s: *Surface, x: u16, y: u16) *Cell { std.debug.assert(x < s.cols and y < s.rows); return &s.cells[@as(usize, y) * s.cols + x]; } pub fn set(s: *Surface, x: u16, y: u16, text: []const u8, style: CellStyle) void { const c = s.at(x, y); std.debug.assert(text.len <= c.text.len); @memcpy(c.text[0..text.len], text); c.len = @intCast(text.len); c.style = style; c.default = false; } pub fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { var col = x; const end = x + w; var i: usize = 0; while (i < text.len) { if (col >= end) break; { const b = text[i]; if (b >= 0x20 and b < 0x7f and (i + 1 == text.len or text[i + 1] < 0x80)) { s.set(col, y, text[i .. i + 1], style); i += 1; col += 1; continue; } } col = s.printGeneral(col, end, y, text, &i, style) orelse break; } return col; } /// `print`'s general arm: the grapheme at `i.*`, painted at `col`. /// Advances `i.*` past it and returns the column after it, or null /// when a wide glyph does not fit before `end`. fn printGeneral(s: *Surface, col: u16, end: u16, y: u16, text: []const u8, i: *usize, style: CellStyle) ?u16 { const start = i.*; // n == 0: not a start byte at all. A short tail or a bad // continuation decodes to null the same way — one U+FFFD, one byte. const n = std.unicode.utf8ByteSequenceLength(text[start]) catch 0; const decoded: ?u21 = if (n > 0 and start + n <= text.len) (std.unicode.utf8Decode(text[start .. start + n]) catch null) else null; var cp_slice: []const u8 = "\u{FFFD}"; var consumed: usize = 1; if (decoded != null) { var git = uucode.grapheme.utf8Iterator(text[start..]); if (git.nextGrapheme()) |g| { const candidate = text[start .. start + g.end]; if (std.unicode.utf8ValidateSlice(candidate)) { cp_slice = candidate; consumed = candidate.len; } else { cp_slice = text[start .. start + n]; consumed = n; } } } i.* += consumed; var cp = decoded orelse 0xFFFD; if (cp == '\r') return col; if (cp == '\t') { const spaces = @min(config.tab_now, end - col); s.fill(col, y, spaces, 1, style); return col + spaces; } // No other C0/C1 control or DEL reaches a font fallback either. if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { cp = 0xFFFD; cp_slice = "\u{FFFD}"; } const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) 1 else @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); if (width == 2 and col + 1 >= end) return null; var shown = cp_slice; if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { const cap = @typeInfo(@FieldType(Cell, "text")).array.len; var prefix: usize = 0; while (prefix < shown.len) { const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; if (prefix + cp_len > cap) break; prefix += cp_len; } shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; } s.set(col, y, shown, style); if (width == 2 and col + 1 < end) { // spacer: empty cell under the wide glyph's tail s.set(col + 1, y, "", style); } return col + width; } pub fn fill(s: *Surface, x: u16, y: u16, w: u16, h: u16, style: CellStyle) void { var yy = y; while (yy < y + h) : (yy += 1) { var xx = x; while (xx < x + w) : (xx += 1) s.set(xx, yy, " ", style); } } /// Recolour `n` cells from (x, y), keeping their glyphs: a selection's /// ground, and its ink when `fg` is given. pub fn tint(s: *Surface, x: u16, y: u16, n: u16, bg: [3]u8, fg: ?[3]u8) void { for (x..x + n) |col| { const cell = s.at(@intCast(col), y); cell.default = false; cell.style.bg = .{ .rgb = bg }; if (fg) |ink| cell.style.fg = .{ .rgb = ink }; } } pub fn clearRect(s: *Surface, x: u16, y: u16, w: u16, h: u16) void { var yy = y; while (yy < y + h) : (yy += 1) { var xx = x; while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{}; } } /// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint pub fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void { const c = s.at(x, y); @memcpy(c.text[0..glyph.len], glyph); c.len = @intCast(glyph.len); c.default = false; } }; test "surface print expands configured tabs and normalizes other controls" { const tab_cells: usize = @as(usize, config.tab_width) * 2; const replacement_cells = 5; const cell_count = tab_cells + replacement_cells + 1; var cells: [cell_count]Cell = @splat(.{}); var surface = Surface{ .cols = cells.len, .rows = 1, .cells = &cells }; const end = surface.print(0, 0, cells.len, "\t\t\x00\x0b\x0c\r\x7f\xc2\x85A", .{}); try std.testing.expectEqual(@as(u16, cells.len), end); for (cells[0..tab_cells]) |cell| try std.testing.expectEqualStrings(" ", cell.grapheme()); for (cells[tab_cells .. tab_cells + replacement_cells]) |cell| try std.testing.expectEqualStrings("\u{FFFD}", cell.grapheme()); try std.testing.expectEqualStrings("A", cells[cell_count - 1].grapheme()); } test "surface print keeps combining and wide graphemes in their display cells" { var cells: [8]Cell = @splat(.{}); var surface = Surface{ .cols = cells.len, .rows = 1, .cells = &cells }; const end = surface.print(0, 0, cells.len, "e\u{301}界👩🏽\u{200d}🚀1\u{fe0f}\u{20e3}A", .{}); try std.testing.expectEqual(@as(u16, 8), end); try std.testing.expectEqualStrings("e\u{301}", cells[0].grapheme()); try std.testing.expectEqualStrings("界", cells[1].grapheme()); try std.testing.expectEqualStrings("", cells[2].grapheme()); try std.testing.expectEqualStrings("👩", cells[3].grapheme()); try std.testing.expectEqualStrings("", cells[4].grapheme()); try std.testing.expectEqualStrings("1\u{fe0f}\u{20e3}", cells[5].grapheme()); try std.testing.expectEqualStrings("", cells[6].grapheme()); try std.testing.expectEqualStrings("A", cells[7].grapheme()); } test "the ASCII fast path in surface print paints what the general arm paints" { // The general arm alone, every grapheme through it. const ref = struct { fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { var col = x; var i: usize = 0; while (i < text.len and col < x + w) col = s.printGeneral(col, x + w, y, text, &i, style) orelse break; return col; } }.print; const H = struct { fn check(text: []const u8) !void { // Every width from 0 past the end, because clipping interacts with the fast path: the // wide-glyph bail at the right edge is only reachable from the general arm. var w: u16 = 0; while (w <= text.len + 4) : (w += 1) { var fast_cells: [64]Cell = @splat(.{}); var slow_cells: [64]Cell = @splat(.{}); var fast = Surface{ .cols = fast_cells.len, .rows = 1, .cells = &fast_cells }; var slow = Surface{ .cols = slow_cells.len, .rows = 1, .cells = &slow_cells }; const got = fast.print(0, 0, w, text, .{}); const want = ref(&slow, 0, 0, w, text, .{}); std.testing.expectEqual(want, got) catch |e| { std.debug.print("print end column: {any} w={d}\n", .{ text, w }); return e; }; for (fast_cells, slow_cells, 0..) |f, sc, col| { std.testing.expectEqualStrings(sc.grapheme(), f.grapheme()) catch |e| { std.debug.print("print cell {d}: {any} w={d}\n", .{ col, text, w }); return e; }; try std.testing.expectEqual(sc.default, f.default); } } } }; const neighbours = [_][]const u8{ "", "x", "\u{301}", "\u{200d}\u{1f680}", "\u{903}", "\u{fe0f}", "\u{20e3}", "\u{4e16}", "\u{1f642}", "\xff", "\xe4\xb8", "\xe4\x28\xb8", "\u{1f1e6}\u{1f1e7}", }; // Every byte 0x20..0x7e takes the fast path; \t, \r, the rest of the C0 controls and DEL are // excluded by its range test and must keep the general arm's tab expansion and U+FFFD. var buf: [16]u8 = undefined; var b: u8 = 0; while (b < 0x80) : (b += 1) { buf[0] = b; for (neighbours) |tail| { @memcpy(buf[1..][0..tail.len], tail); try H.check(buf[0 .. 1 + tail.len]); @memcpy(buf[0..tail.len], tail); buf[tail.len] = b; try H.check(buf[0 .. tail.len + 1]); } } // Runs long enough that the fast path starts, hands over and restarts inside one call. try H.check("ascii \u{4e16}\u{754c} e\u{301} \xff ok\t\r!"); try H.check("plain"); }