From 41dd733ca7123c9ac4bfc6c781697a660e95b052 Mon Sep 17 00:00:00 2001 From: Can Celik Date: Sat, 4 Apr 2026 19:22:04 +0300 Subject: feat: finish ghostty pane backend integration --- vendor/libghostty-vt/src/terminal/PageList.zig | 14645 +++++++++++++++++++ vendor/libghostty-vt/src/terminal/Parser.zig | 1099 ++ vendor/libghostty-vt/src/terminal/Screen.zig | 10354 +++++++++++++ vendor/libghostty-vt/src/terminal/ScreenSet.zig | 107 + vendor/libghostty-vt/src/terminal/Selection.zig | 1598 ++ vendor/libghostty-vt/src/terminal/StringMap.zig | 298 + vendor/libghostty-vt/src/terminal/Tabstops.zig | 271 + vendor/libghostty-vt/src/terminal/Terminal.zig | 13089 +++++++++++++++++ vendor/libghostty-vt/src/terminal/UTF8Decoder.zig | 142 + vendor/libghostty-vt/src/terminal/ansi.zig | 106 + vendor/libghostty-vt/src/terminal/apc.zig | 186 + .../src/terminal/bitmap_allocator.zig | 1021 ++ .../libghostty-vt/src/terminal/build_options.zig | 80 + vendor/libghostty-vt/src/terminal/c/AGENTS.md | 22 + vendor/libghostty-vt/src/terminal/c/allocator.zig | 67 + vendor/libghostty-vt/src/terminal/c/build_info.zig | 162 + vendor/libghostty-vt/src/terminal/c/cell.zig | 178 + vendor/libghostty-vt/src/terminal/c/color.zig | 13 + vendor/libghostty-vt/src/terminal/c/focus.zig | 55 + vendor/libghostty-vt/src/terminal/c/formatter.zig | 417 + vendor/libghostty-vt/src/terminal/c/grid_ref.zig | 156 + vendor/libghostty-vt/src/terminal/c/key_encode.zig | 356 + vendor/libghostty-vt/src/terminal/c/key_event.zig | 268 + vendor/libghostty-vt/src/terminal/c/main.zig | 178 + vendor/libghostty-vt/src/terminal/c/modes.zig | 104 + .../libghostty-vt/src/terminal/c/mouse_encode.zig | 530 + .../libghostty-vt/src/terminal/c/mouse_event.zig | 155 + vendor/libghostty-vt/src/terminal/c/osc.zig | 140 + vendor/libghostty-vt/src/terminal/c/paste.zig | 129 + vendor/libghostty-vt/src/terminal/c/render.zig | 1382 ++ vendor/libghostty-vt/src/terminal/c/result.zig | 8 + vendor/libghostty-vt/src/terminal/c/row.zig | 132 + vendor/libghostty-vt/src/terminal/c/sgr.zig | 179 + .../libghostty-vt/src/terminal/c/size_report.zig | 82 + vendor/libghostty-vt/src/terminal/c/style.zig | 134 + vendor/libghostty-vt/src/terminal/c/terminal.zig | 2358 +++ vendor/libghostty-vt/src/terminal/c/types.zig | 215 + vendor/libghostty-vt/src/terminal/charsets.zig | 115 + vendor/libghostty-vt/src/terminal/color.zig | 1146 ++ vendor/libghostty-vt/src/terminal/csi.zig | 55 + vendor/libghostty-vt/src/terminal/cursor.zig | 15 + vendor/libghostty-vt/src/terminal/dcs.zig | 430 + .../src/terminal/device_attributes.zig | 227 + .../libghostty-vt/src/terminal/device_status.zig | 74 + vendor/libghostty-vt/src/terminal/focus.zig | 39 + vendor/libghostty-vt/src/terminal/formatter.zig | 6279 ++++++++ vendor/libghostty-vt/src/terminal/hash_map.zig | 1540 ++ vendor/libghostty-vt/src/terminal/highlight.zig | 213 + vendor/libghostty-vt/src/terminal/hyperlink.zig | 240 + vendor/libghostty-vt/src/terminal/kitty.zig | 15 + vendor/libghostty-vt/src/terminal/kitty/color.zig | 77 + .../libghostty-vt/src/terminal/kitty/graphics.zig | 36 + .../src/terminal/kitty/graphics_command.zig | 1325 ++ .../src/terminal/kitty/graphics_exec.zig | 570 + .../src/terminal/kitty/graphics_image.zig | 835 ++ .../src/terminal/kitty/graphics_render.zig | 27 + .../src/terminal/kitty/graphics_storage.zig | 1359 ++ .../src/terminal/kitty/graphics_unicode.zig | 1347 ++ vendor/libghostty-vt/src/terminal/kitty/key.zig | 169 + .../src/terminal/kitty/testdata/dog.png | Bin 0 -> 237387 bytes .../image-png-none-50x76-2147483647-raw.data | Bin 0 -> 86 bytes .../image-rgb-none-20x15-2147483647-raw.data | Bin 0 -> 900 bytes ...age-rgb-zlib_deflate-128x96-2147483647-raw.data | Bin 0 -> 30455 bytes vendor/libghostty-vt/src/terminal/lib.zig | 22 + vendor/libghostty-vt/src/terminal/main.zig | 87 + vendor/libghostty-vt/src/terminal/modes.zig | 381 + vendor/libghostty-vt/src/terminal/mouse.zig | 168 + vendor/libghostty-vt/src/terminal/osc.zig | 826 ++ vendor/libghostty-vt/src/terminal/osc/encoding.zig | 38 + vendor/libghostty-vt/src/terminal/osc/parsers.zig | 21 + .../terminal/osc/parsers/change_window_icon.zig | 33 + .../terminal/osc/parsers/change_window_title.zig | 119 + .../terminal/osc/parsers/clipboard_operation.zig | 106 + .../src/terminal/osc/parsers/color.zig | 780 + .../src/terminal/osc/parsers/context_signal.zig | 541 + .../src/terminal/osc/parsers/hyperlink.zig | 164 + .../src/terminal/osc/parsers/iterm2.zig | 435 + .../osc/parsers/kitty_clipboard_protocol.zig | 702 + .../src/terminal/osc/parsers/kitty_color.zig | 212 + .../src/terminal/osc/parsers/kitty_text_sizing.zig | 255 + .../src/terminal/osc/parsers/mouse_shape.zig | 39 + .../src/terminal/osc/parsers/osc9.zig | 1141 ++ .../src/terminal/osc/parsers/report_pwd.zig | 48 + .../src/terminal/osc/parsers/rxvt_extension.zig | 59 + .../src/terminal/osc/parsers/semantic_prompt.zig | 1264 ++ vendor/libghostty-vt/src/terminal/page.zig | 3918 +++++ vendor/libghostty-vt/src/terminal/parse_table.zig | 388 + vendor/libghostty-vt/src/terminal/point.zig | 94 + .../libghostty-vt/src/terminal/ref_counted_set.zig | 714 + vendor/libghostty-vt/src/terminal/render.zig | 1465 ++ vendor/libghostty-vt/src/terminal/res/glitch.txt | 1 + vendor/libghostty-vt/src/terminal/res/rgb.txt | 782 + vendor/libghostty-vt/src/terminal/search.zig | 22 + .../libghostty-vt/src/terminal/search/Thread.zig | 905 ++ .../libghostty-vt/src/terminal/search/active.zig | 175 + .../libghostty-vt/src/terminal/search/pagelist.zig | 441 + .../libghostty-vt/src/terminal/search/screen.zig | 1552 ++ .../src/terminal/search/sliding_window.zig | 1676 +++ .../libghostty-vt/src/terminal/search/viewport.zig | 384 + vendor/libghostty-vt/src/terminal/sgr.zig | 1103 ++ vendor/libghostty-vt/src/terminal/size.zig | 227 + vendor/libghostty-vt/src/terminal/size_report.zig | 160 + vendor/libghostty-vt/src/terminal/stream.zig | 3449 +++++ .../libghostty-vt/src/terminal/stream_terminal.zig | 2071 +++ vendor/libghostty-vt/src/terminal/style.zig | 1078 ++ vendor/libghostty-vt/src/terminal/tmux.zig | 13 + vendor/libghostty-vt/src/terminal/tmux/control.zig | 839 ++ vendor/libghostty-vt/src/terminal/tmux/layout.zig | 638 + vendor/libghostty-vt/src/terminal/tmux/output.zig | 590 + vendor/libghostty-vt/src/terminal/tmux/viewer.zig | 2283 +++ vendor/libghostty-vt/src/terminal/x11_color.zig | 69 + 111 files changed, 99027 insertions(+) create mode 100644 vendor/libghostty-vt/src/terminal/PageList.zig create mode 100644 vendor/libghostty-vt/src/terminal/Parser.zig create mode 100644 vendor/libghostty-vt/src/terminal/Screen.zig create mode 100644 vendor/libghostty-vt/src/terminal/ScreenSet.zig create mode 100644 vendor/libghostty-vt/src/terminal/Selection.zig create mode 100644 vendor/libghostty-vt/src/terminal/StringMap.zig create mode 100644 vendor/libghostty-vt/src/terminal/Tabstops.zig create mode 100644 vendor/libghostty-vt/src/terminal/Terminal.zig create mode 100644 vendor/libghostty-vt/src/terminal/UTF8Decoder.zig create mode 100644 vendor/libghostty-vt/src/terminal/ansi.zig create mode 100644 vendor/libghostty-vt/src/terminal/apc.zig create mode 100644 vendor/libghostty-vt/src/terminal/bitmap_allocator.zig create mode 100644 vendor/libghostty-vt/src/terminal/build_options.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/AGENTS.md create mode 100644 vendor/libghostty-vt/src/terminal/c/allocator.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/build_info.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/cell.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/color.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/focus.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/formatter.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/grid_ref.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/key_encode.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/key_event.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/main.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/modes.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/mouse_encode.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/mouse_event.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/osc.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/paste.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/render.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/result.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/row.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/sgr.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/size_report.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/style.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/terminal.zig create mode 100644 vendor/libghostty-vt/src/terminal/c/types.zig create mode 100644 vendor/libghostty-vt/src/terminal/charsets.zig create mode 100644 vendor/libghostty-vt/src/terminal/color.zig create mode 100644 vendor/libghostty-vt/src/terminal/csi.zig create mode 100644 vendor/libghostty-vt/src/terminal/cursor.zig create mode 100644 vendor/libghostty-vt/src/terminal/dcs.zig create mode 100644 vendor/libghostty-vt/src/terminal/device_attributes.zig create mode 100644 vendor/libghostty-vt/src/terminal/device_status.zig create mode 100644 vendor/libghostty-vt/src/terminal/focus.zig create mode 100644 vendor/libghostty-vt/src/terminal/formatter.zig create mode 100644 vendor/libghostty-vt/src/terminal/hash_map.zig create mode 100644 vendor/libghostty-vt/src/terminal/highlight.zig create mode 100644 vendor/libghostty-vt/src/terminal/hyperlink.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/color.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics_render.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/key.zig create mode 100644 vendor/libghostty-vt/src/terminal/kitty/testdata/dog.png create mode 100644 vendor/libghostty-vt/src/terminal/kitty/testdata/image-png-none-50x76-2147483647-raw.data create mode 100644 vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-none-20x15-2147483647-raw.data create mode 100644 vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data create mode 100644 vendor/libghostty-vt/src/terminal/lib.zig create mode 100644 vendor/libghostty-vt/src/terminal/main.zig create mode 100644 vendor/libghostty-vt/src/terminal/modes.zig create mode 100644 vendor/libghostty-vt/src/terminal/mouse.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/encoding.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/change_window_icon.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/change_window_title.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/clipboard_operation.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/color.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/context_signal.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/hyperlink.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/iterm2.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/kitty_clipboard_protocol.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/kitty_color.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/kitty_text_sizing.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/mouse_shape.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/osc9.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/report_pwd.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/rxvt_extension.zig create mode 100644 vendor/libghostty-vt/src/terminal/osc/parsers/semantic_prompt.zig create mode 100644 vendor/libghostty-vt/src/terminal/page.zig create mode 100644 vendor/libghostty-vt/src/terminal/parse_table.zig create mode 100644 vendor/libghostty-vt/src/terminal/point.zig create mode 100644 vendor/libghostty-vt/src/terminal/ref_counted_set.zig create mode 100644 vendor/libghostty-vt/src/terminal/render.zig create mode 100644 vendor/libghostty-vt/src/terminal/res/glitch.txt create mode 100644 vendor/libghostty-vt/src/terminal/res/rgb.txt create mode 100644 vendor/libghostty-vt/src/terminal/search.zig create mode 100644 vendor/libghostty-vt/src/terminal/search/Thread.zig create mode 100644 vendor/libghostty-vt/src/terminal/search/active.zig create mode 100644 vendor/libghostty-vt/src/terminal/search/pagelist.zig create mode 100644 vendor/libghostty-vt/src/terminal/search/screen.zig create mode 100644 vendor/libghostty-vt/src/terminal/search/sliding_window.zig create mode 100644 vendor/libghostty-vt/src/terminal/search/viewport.zig create mode 100644 vendor/libghostty-vt/src/terminal/sgr.zig create mode 100644 vendor/libghostty-vt/src/terminal/size.zig create mode 100644 vendor/libghostty-vt/src/terminal/size_report.zig create mode 100644 vendor/libghostty-vt/src/terminal/stream.zig create mode 100644 vendor/libghostty-vt/src/terminal/stream_terminal.zig create mode 100644 vendor/libghostty-vt/src/terminal/style.zig create mode 100644 vendor/libghostty-vt/src/terminal/tmux.zig create mode 100644 vendor/libghostty-vt/src/terminal/tmux/control.zig create mode 100644 vendor/libghostty-vt/src/terminal/tmux/layout.zig create mode 100644 vendor/libghostty-vt/src/terminal/tmux/output.zig create mode 100644 vendor/libghostty-vt/src/terminal/tmux/viewer.zig create mode 100644 vendor/libghostty-vt/src/terminal/x11_color.zig (limited to 'vendor/libghostty-vt/src/terminal') diff --git a/vendor/libghostty-vt/src/terminal/PageList.zig b/vendor/libghostty-vt/src/terminal/PageList.zig new file mode 100644 index 00000000..39873374 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/PageList.zig @@ -0,0 +1,14645 @@ +//! Maintains a linked list of pages to make up a terminal screen +//! and provides higher level operations on top of those pages to +//! make it slightly easier to work with. +const PageList = @This(); + +const std = @import("std"); +const builtin = @import("builtin"); +const build_options = @import("terminal_options"); +const Allocator = std.mem.Allocator; +const assert = @import("../quirks.zig").inlineAssert; +const fastmem = @import("../fastmem.zig"); +const tripwire = @import("../tripwire.zig"); +const DoublyLinkedList = @import("../datastruct/main.zig").IntrusiveDoublyLinkedList; +const color = @import("color.zig"); +const highlight = @import("highlight.zig"); +const kitty = @import("kitty.zig"); +const point = @import("point.zig"); +const pagepkg = @import("page.zig"); +const stylepkg = @import("style.zig"); +const size = @import("size.zig"); +const OffsetBuf = size.OffsetBuf; +const Capacity = pagepkg.Capacity; +const Page = pagepkg.Page; +const Row = pagepkg.Row; + +const log = std.log.scoped(.page_list); + +/// The number of PageList.Nodes we preheat the pool with. A node is +/// a very small struct so we can afford to preheat many, but the exact +/// number is uncertain. Any number too large is wasting memory, any number +/// too small will cause the pool to have to allocate more memory later. +/// This should be set to some reasonable minimum that we expect a terminal +/// window to scroll into quickly. +const page_preheat = 4; + +/// The list of pages in the screen. These are expected to be in order +/// where the first page is the topmost page (scrollback) and the last is +/// the bottommost page (the current active page). +pub const List = DoublyLinkedList(Node); + +/// A single node within the PageList linked list. +/// +/// This isn't pub because you can access the type via List.Node. +const Node = struct { + prev: ?*Node = null, + next: ?*Node = null, + data: Page, + serial: u64, +}; + +/// The memory pool we get page nodes from. +const NodePool = std.heap.MemoryPool(List.Node); + +/// The standard page capacity that we use as a starting point for +/// all pages. This is chosen as a sane default that fits most terminal +/// usage to support using our pool. +const std_capacity = pagepkg.std_capacity; + +/// The byte size required for a standard page. +const std_size = Page.layout(std_capacity).total_size; + +/// The memory pool we use for page memory buffers. We use a separate pool +/// so we can allocate these with a page allocator. We have to use a page +/// allocator because we need memory that is zero-initialized and page-aligned. +const PagePool = std.heap.MemoryPoolAligned( + [std_size]u8, + .fromByteUnits(std.heap.page_size_min), +); + +/// List of pins, known as "tracked" pins. These are pins that are kept +/// up to date automatically through page-modifying operations. +const PinSet = std.AutoArrayHashMapUnmanaged(*Pin, void); +const PinPool = std.heap.MemoryPool(Pin); + +/// The pool of memory used for a pagelist. This can be shared between +/// multiple pagelists but it is not threadsafe. +pub const MemoryPool = struct { + alloc: Allocator, + nodes: NodePool, + pages: PagePool, + pins: PinPool, + + pub const ResetMode = std.heap.ArenaAllocator.ResetMode; + + pub fn init( + gen_alloc: Allocator, + page_alloc: Allocator, + preheat: usize, + ) Allocator.Error!MemoryPool { + var node_pool = try NodePool.initPreheated(gen_alloc, preheat); + errdefer node_pool.deinit(); + var page_pool = try PagePool.initPreheated(page_alloc, preheat); + errdefer page_pool.deinit(); + var pin_pool = try PinPool.initPreheated(gen_alloc, 8); + errdefer pin_pool.deinit(); + return .{ + .alloc = gen_alloc, + .nodes = node_pool, + .pages = page_pool, + .pins = pin_pool, + }; + } + + pub fn deinit(self: *MemoryPool) void { + self.pages.deinit(); + self.nodes.deinit(); + self.pins.deinit(); + } + + pub fn reset(self: *MemoryPool, mode: ResetMode) void { + _ = self.pages.reset(mode); + _ = self.nodes.reset(mode); + _ = self.pins.reset(mode); + } +}; + +/// The memory pool we get page nodes, pages from. +pool: MemoryPool, + +/// The list of pages in the screen. +pages: List, + +/// A monotonically increasing serial number that is incremented each +/// time a page is allocated or reused as new. The serial is assigned to +/// the Node. +/// +/// The serial number can be used to detect whether the page is identical +/// to the page that was originally referenced by a pointer. Since we reuse +/// and pool memory, pointer stability is not guaranteed, but the serial +/// will always be different for different allocations. +/// +/// Developer note: we never do overflow checking on this. If we created +/// a new page every second it'd take 584 billion years to overflow. We're +/// going to risk it. +page_serial: u64, + +/// The lowest still valid serial number that could exist. This allows +/// for quick comparisons to find invalid pages in references. +page_serial_min: u64, + +/// Byte size of the total amount of allocated pages. Note this does +/// not include the total allocated amount in the pool which may be more +/// than this due to preheating. +page_size: usize, + +/// Maximum size of the page allocation in bytes. This only includes pages +/// that are used ONLY for scrollback. If the active area is still partially +/// in a page that also includes scrollback, then that page is not included. +explicit_max_size: usize, + +/// This is the minimum max size that we will respect due to the rows/cols +/// of the PageList. We must always be able to fit at least the active area +/// and at least two pages for our algorithms. +min_max_size: usize, + +/// The total number of rows represented by this PageList. This is used +/// specifically for scrollbar information so we can have the total size. +total_rows: usize, + +/// The list of tracked pins. These are kept up to date automatically. +tracked_pins: PinSet, + +/// The top-left of certain parts of the screen that are frequently +/// accessed so we don't have to traverse the linked list to find them. +/// +/// For other tags, don't need this: +/// - screen: pages.first +/// - history: active row minus one +/// +viewport: Viewport, + +/// The pin used for when the viewport scrolls. This is always pre-allocated +/// so that scrolling doesn't have a failable memory allocation. This should +/// never be access directly; use `viewport`. +viewport_pin: *Pin, + +/// The row offset from the top that the viewport pin is at. We +/// store the offset from the top because it doesn't change while more +/// data is printed to the terminal. +/// +/// This is null when it isn't calculated. It is calculated on demand +/// when the viewportRowOffset function is called, because it is only +/// required for certain operations such as rendering the scrollbar. +/// +/// In order to make this more efficient, in many places where the value +/// would be invalidated, we update it in-place instead. This is key to +/// keeping our performance decent in normal cases since recalculating +/// this from scratch, depending on the size of the scrollback and position +/// of the pin, can be very expensive. +/// +/// This is only valid if viewport is `pin`. Every other offset is +/// self-evident or quick to calculate. +viewport_pin_row_offset: ?usize, + +/// The current desired screen dimensions. I say "desired" because individual +/// pages may still be a different size and not yet reflowed since we lazily +/// reflow text. +cols: size.CellCountInt, +rows: size.CellCountInt, + +/// If this is true then verifyIntegrity will do nothing. This is +/// only present with runtime safety enabled. +pause_integrity_checks: if (build_options.slow_runtime_safety) usize else void = + if (build_options.slow_runtime_safety) 0 else {}, + +/// The viewport location. +pub const Viewport = union(enum) { + /// The viewport is pinned to the active area. By using a specific marker + /// for this instead of tracking the row offset, we eliminate a number of + /// memory writes making scrolling faster. + active, + + /// The viewport is pinned to the top of the screen, or the farthest + /// back in the scrollback history. + top, + + /// The viewport is pinned to a tracked pin. The tracked pin is ALWAYS + /// s.viewport_pin hence this has no value. We force that value to prevent + /// allocations. + pin, +}; + +/// Returns the minimum valid "max size" for a given number of rows and cols +/// such that we can fit the active area AND at least two pages. Note we +/// need the two pages for algorithms to work properly (such as grow) but +/// we don't need to fit double the active area. +/// +/// This min size may not be totally correct in the case that a large +/// number of other dimensions makes our row size in a page very small. +/// But this gives us a nice fast heuristic for determining min/max size. +/// Therefore, if the page size is violated you should always also verify +/// that we have enough space for the active area. +fn minMaxSize(cols: size.CellCountInt, rows: size.CellCountInt) usize { + // Invariant required to ensure our divCeil below cannot overflow. + comptime { + const max_rows = std.math.maxInt(size.CellCountInt); + _ = std.math.divCeil(usize, max_rows, 1) catch unreachable; + } + + // Get our capacity to fit our rows. If the cols are too big, it may + // force less rows than we want meaning we need more than one page to + // represent a viewport. + const cap = initialCapacity(cols); + + // Calculate the number of standard sized pages we need to represent + // an active area. + const pages_exact = if (cap.rows >= rows) 1 else std.math.divCeil( + usize, + rows, + cap.rows, + ) catch { + // Not possible: + // - initialCapacity guarantees at least 1 row + // - numerator/denominator can't overflow because of comptime check above + unreachable; + }; + + // We always need at least one page extra so that we + // can fit partial pages to spread our active area across two pages. + // Even for caps that can't fit all rows in a single page, we add one + // because the most extra space we need at any given time is only + // the partial amount of one page. + const pages = pages_exact + 1; + assert(pages >= 2); + + // log.debug("minMaxSize cols={} rows={} cap={} pages={}", .{ + // cols, + // rows, + // cap, + // pages, + // }); + + return PagePool.item_size * pages; +} + +/// Calculates the initial capacity for a new page for a given column +/// count. This will attempt to fit within std_size at all times so we +/// can use our memory pool, but if cols is too big, this will return a +/// larger capacity. +/// +/// The returned capacity is always guaranteed to layout properly (not +/// overflow). We are able to support capacities up to the maximum int +/// value of cols, so this will never overflow. +fn initialCapacity(cols: size.CellCountInt) Capacity { + // This is an important invariant that ensures that this function + // can never return an error. We verify here that our standard capacity + // when increased to maximum possible columns can always support at + // least one row in memory. + // + // IF THIS EVER FAILS: We probably need to modify our logic below + // to reduce other elements of the capacity (styles, graphemes, etc.). + // But, instead, I recommend taking a step back and re-evaluating + // life choices. + comptime { + var cap = std_capacity; + cap.cols = std.math.maxInt(size.CellCountInt); + const layout = Page.layout(cap); + assert(layout.total_size <= size.max_page_size); + } + + if (std_capacity.adjust( + .{ .cols = cols }, + )) |cap| { + // If we can adjust our standard capacity, we fit within the + // standard size and we're good! + return cap; + } else |err| { + // Ensure our error set doesn't change. + comptime assert(@TypeOf(err) == error{OutOfMemory}); + } + + // This code path means that our standard capacity can't even + // accommodate our column count! The only solution is to increase + // our capacity and go non-standard. + var cap: Capacity = std_capacity; + cap.cols = cols; + return cap; +} + +/// This is the page allocator we'll use for all our underlying +/// VM page allocations. +inline fn pageAllocator() Allocator { + // In tests we use our testing allocator so we can detect leaks. + if (builtin.is_test) return std.testing.allocator; + + // On non-macOS we use our standard Zig page allocator. + if (!builtin.target.os.tag.isDarwin()) return std.heap.page_allocator; + + // On macOS we want to tag our memory so we can assign it to our + // core terminal usage. + const mach = @import("../os/mach.zig"); + return mach.taggedPageAllocator(.application_specific_1); +} + +const init_tw = tripwire.module(enum { + init_memory_pool, + init_pages, + viewport_pin, + viewport_pin_track, +}, init); + +/// Initialize the page. The top of the first page in the list is always the +/// top of the active area of the screen (important knowledge for quickly +/// setting up cursors in Screen). +/// +/// max_size is the maximum number of bytes that will be allocated for +/// pages. If this is smaller than the bytes required to show the viewport +/// then max_size will be ignored and the viewport will be shown, but no +/// scrollback will be created. max_size is always rounded down to the nearest +/// terminal page size (not virtual memory page), otherwise we would always +/// slightly exceed max_size in the limits. +/// +/// If max_size is null then there is no defined limit and the screen will +/// grow forever. In reality, the limit is set to the byte limit that your +/// computer can address in memory. If you somehow require more than that +/// (due to disk paging) then please contribute that yourself and perhaps +/// search deep within yourself to find out why you need that. +pub fn init( + alloc: Allocator, + cols: size.CellCountInt, + rows: size.CellCountInt, + max_size: ?usize, +) Allocator.Error!PageList { + const tw = init_tw; + + // The screen starts with a single page that is the entire viewport, + // and we'll split it thereafter if it gets too large and add more as + // necessary. + try tw.check(.init_memory_pool); + var pool = try MemoryPool.init( + alloc, + pageAllocator(), + page_preheat, + ); + errdefer pool.deinit(); + + try tw.check(.init_pages); + var page_serial: u64 = 0; + const page_list, const page_size = try initPages( + &pool, + &page_serial, + cols, + rows, + ); + + // Get our minimum max size, see doc comments for more details. + const min_max_size = minMaxSize(cols, rows); + + // We always track our viewport pin to ensure this is never an allocation + try tw.check(.viewport_pin); + const viewport_pin = try pool.pins.create(); + viewport_pin.* = .{ .node = page_list.first.? }; + var tracked_pins: PinSet = .{}; + errdefer tracked_pins.deinit(pool.alloc); + + try tw.check(.viewport_pin_track); + try tracked_pins.putNoClobber(pool.alloc, viewport_pin, {}); + + errdefer comptime unreachable; + const result: PageList = .{ + .cols = cols, + .rows = rows, + .pool = pool, + .pages = page_list, + .page_serial = page_serial, + .page_serial_min = 0, + .page_size = page_size, + .explicit_max_size = max_size orelse std.math.maxInt(usize), + .min_max_size = min_max_size, + .total_rows = rows, + .tracked_pins = tracked_pins, + .viewport = .{ .active = {} }, + .viewport_pin = viewport_pin, + .viewport_pin_row_offset = null, + }; + result.assertIntegrity(); + return result; +} + +const initPages_tw = tripwire.module(enum { + page_node, + page_buf_std, + page_buf_non_std, +}, initPages); + +fn initPages( + pool: *MemoryPool, + serial: *u64, + cols: size.CellCountInt, + rows: size.CellCountInt, +) Allocator.Error!struct { List, usize } { + const tw = initPages_tw; + + var page_list: List = .{}; + var page_size: usize = 0; + + // Add pages as needed to create our initial viewport. + const cap = initialCapacity(cols); + const layout = Page.layout(cap); + const pooled = layout.total_size <= std_size; + const page_alloc = pool.pages.arena.child_allocator; + + // Guaranteed by comptime checks in initialCapacity but + // redundant here for safety. + assert(layout.total_size <= size.max_page_size); + + // If we have an error, we need to clean up our non-standard pages + // since they're not in the pool. + errdefer { + var it = page_list.first; + while (it) |node| : (it = node.next) { + if (node.data.memory.len > std_size) { + page_alloc.free(node.data.memory); + } + } + } + + var rem = rows; + while (rem > 0) { + try tw.check(.page_node); + const node = try pool.nodes.create(); + errdefer pool.nodes.destroy(node); + + const page_buf = if (pooled) buf: { + try tw.check(.page_buf_std); + break :buf try pool.pages.create(); + } else buf: { + try tw.check(.page_buf_non_std); + break :buf try page_alloc.alignedAlloc( + u8, + .fromByteUnits(std.heap.page_size_min), + layout.total_size, + ); + }; + errdefer if (pooled) + pool.pages.destroy(page_buf) + else + page_alloc.free(page_buf); + + // In runtime safety modes we have to memset because the Zig allocator + // interface will always memset to 0xAA for undefined. On freestanding + // (WASM), the WasmAllocator reuses freed slots without zeroing since + // only fresh memory.grow pages are guaranteed zero by the WASM spec. + // On native, the OS page allocator (mmap) returns zeroed pages. + if (comptime std.debug.runtime_safety or builtin.os.tag == .freestanding) + @memset(page_buf, 0); + + // Initialize the first set of pages to contain our viewport so that + // the top of the first page is always the active area. + node.* = .{ + .data = .initBuf(.init(page_buf), layout), + .serial = serial.*, + }; + node.data.size.rows = @min(rem, node.data.capacity.rows); + rem -= node.data.size.rows; + + // Add the page to the list + page_list.append(node); + page_size += page_buf.len; + errdefer comptime unreachable; + + // Increment our serial + serial.* += 1; + } + + assert(page_list.first != null); + + return .{ page_list, page_size }; +} + +/// Assert that the PageList is in a valid state. This is a no-op in +/// release builds. +pub inline fn assertIntegrity(self: *const PageList) void { + if (comptime !build_options.slow_runtime_safety) return; + + self.verifyIntegrity() catch |err| { + log.err("PageList integrity check failed: {}", .{err}); + @panic("PageList integrity check failed"); + }; +} + +/// Pause or resume integrity checks. This is useful when you're doing +/// a multi-step operation that temporarily leaves the PageList in an +/// inconsistent state. +pub inline fn pauseIntegrityChecks(self: *PageList, pause: bool) void { + if (comptime !build_options.slow_runtime_safety) return; + if (pause) { + self.pause_integrity_checks += 1; + } else { + self.pause_integrity_checks -= 1; + } +} + +const IntegrityError = error{ + PageSerialInvalid, + TotalRowsMismatch, + TrackedPinInvalid, + ViewportPinOffsetMismatch, + ViewportPinInsufficientRows, +}; + +/// Verify the integrity of the PageList. This is expensive and should +/// only be called in debug/test builds. +fn verifyIntegrity(self: *const PageList) IntegrityError!void { + if (comptime !build_options.slow_runtime_safety) return; + if (self.pause_integrity_checks > 0) return; + + // Our viewport pin should never be garbage + assert(!self.viewport_pin.garbage); + + // Grab our total rows + var actual_total: usize = 0; + { + var node_ = self.pages.first; + while (node_) |node| { + actual_total += node.data.size.rows; + node_ = node.next; + + // While doing this traversal, verify no node has a serial + // number lower than our min. + if (node.serial < self.page_serial_min) { + log.warn( + "PageList integrity violation: page serial too low serial={} min={}", + .{ node.serial, self.page_serial_min }, + ); + return IntegrityError.PageSerialInvalid; + } + } + } + + // Verify that our cached total_rows matches the actual row count + if (actual_total != self.total_rows) { + log.warn( + "PageList integrity violation: total_rows mismatch cached={} actual={}", + .{ self.total_rows, actual_total }, + ); + return IntegrityError.TotalRowsMismatch; + } + + // Verify that all our tracked pins point to valid pages. + for (self.tracked_pins.keys()) |p| { + if (!self.pinIsValid(p.*)) return error.TrackedPinInvalid; + } + + if (self.viewport == .pin) { + // Verify that our viewport pin row offset is correct. + const actual_offset: usize = offset: { + var offset: usize = 0; + var node = self.pages.last; + while (node) |n| : (node = n.prev) { + offset += n.data.size.rows; + if (n == self.viewport_pin.node) { + offset -= self.viewport_pin.y; + break :offset self.total_rows - offset; + } + } + + log.warn( + "PageList integrity violation: viewport pin not in list", + .{}, + ); + return error.ViewportPinOffsetMismatch; + }; + + if (self.viewport_pin_row_offset) |cached_offset| { + if (cached_offset != actual_offset) { + log.warn( + "PageList integrity violation: viewport pin offset mismatch cached={} actual={}", + .{ cached_offset, actual_offset }, + ); + return error.ViewportPinOffsetMismatch; + } + } + + // Ensure our viewport has enough rows. + const rows = self.total_rows - actual_offset; + if (rows < self.rows) { + log.warn( + "PageList integrity violation: viewport pin rows too small rows={} needed={}", + .{ rows, self.rows }, + ); + return error.ViewportPinInsufficientRows; + } + } +} + +/// Deinit the pagelist. If you own the memory pool (used clonePool) then +/// this will reset the pool and retain capacity. +pub fn deinit(self: *PageList) void { + // Verify integrity before cleanup + self.assertIntegrity(); + + // Always deallocate our hashmap. + self.tracked_pins.deinit(self.pool.alloc); + + // Go through our linked list and deallocate all pages that are + // not standard size. + const page_alloc = self.pool.pages.arena.child_allocator; + var it = self.pages.first; + while (it) |node| : (it = node.next) { + if (node.data.memory.len > std_size) { + page_alloc.free(node.data.memory); + } + } + + // Deallocate all the pages. We don't need to deallocate the list or + // nodes because they all reside in the pool. + self.pool.deinit(); +} + +/// Reset the PageList back to an empty state. This is similar to +/// deinit and reinit but it importantly preserves the pointer +/// stability of tracked pins (they're moved to the top-left since +/// all contents are cleared). +/// +/// This can't fail because we always retain at least enough allocated +/// memory to fit the active area. +pub fn reset(self: *PageList) void { + defer self.assertIntegrity(); + + // We need enough pages/nodes to keep our active area. This should + // never fail since we by definition have allocated a page already + // that fits our size but I'm not confident to make that assertion. + const cap = initialCapacity(self.cols); + assert(cap.rows > 0); + + // The number of pages we need is the number of rows in the active + // area divided by the row capacity of a page. + const page_count = std.math.divCeil( + usize, + self.rows, + cap.rows, + ) catch unreachable; + + // Before resetting our pools we need to free any pages that + // are non-standard size since those were allocated outside + // the pool. + { + const page_alloc = self.pool.pages.arena.child_allocator; + var it = self.pages.first; + while (it) |node| : (it = node.next) { + if (node.data.memory.len > std_size) { + page_alloc.free(node.data.memory); + } + } + } + + // Reset our pools to free as much memory as possible while retaining + // the capacity for at least the minimum number of pages we need. + // The return value is whether memory was reclaimed or not, but in + // either case the pool is left in a valid state. + _ = self.pool.pages.reset(.{ + .retain_with_limit = page_count * PagePool.item_size, + }); + _ = self.pool.nodes.reset(.{ + .retain_with_limit = page_count * NodePool.item_size, + }); + + // Our page pool relies on mmap to zero our page memory. Since we're + // retaining a certain amount of memory, it won't use mmap and won't + // be zeroed. This block zeroes out all the memory in the pool arena. + { + // Note: we only have to do this for the page pool because the + // nodes are always fully overwritten on each allocation. + const page_arena = &self.pool.pages.arena; + var it = page_arena.state.buffer_list.first; + while (it) |node| : (it = node.next) { + // WARN: Since HeapAllocator's BufNode is not public API, + // we have to hardcode its layout here. We do a comptime assert + // on Zig version to verify we check it on every bump. + const BufNode = struct { + data: usize, + node: std.SinglyLinkedList.Node, + }; + const buf_node: *BufNode = @fieldParentPtr("node", node); + + // The fully allocated buffer + const alloc_buf = @as([*]u8, @ptrCast(buf_node))[0..buf_node.data]; + // The buffer minus our header + const data_buf = alloc_buf[@sizeOf(BufNode)..]; + @memset(data_buf, 0); + } + } + + // Initialize our pages. This should not be able to fail since + // we retained the capacity for the minimum number of pages we need. + self.pages, self.page_size = initPages( + &self.pool, + &self.page_serial, + self.cols, + self.rows, + ) catch @panic("initPages failed"); + + // Our total rows always goes back to the default + self.total_rows = self.rows; + + // Update all our tracked pins to point to our first page top-left + // and mark them as garbage, because it got mangled in a way where + // semantically it really doesn't make sense. + { + var it = self.tracked_pins.iterator(); + while (it.next()) |entry| { + const p: *Pin = entry.key_ptr.*; + p.node = self.pages.first.?; + p.x = 0; + p.y = 0; + p.garbage = true; + } + + // Our viewport pin is never garbage + self.viewport_pin.garbage = false; + } + + // Move our viewport back to the active area since everything is gone. + self.viewport = .active; +} + +pub const Clone = struct { + /// The top and bottom (inclusive) points of the region to clone. + /// The x coordinate is ignored; the full row is always cloned. + top: point.Point, + bot: ?point.Point = null, + + // If this is non-null then cloning will attempt to remap the tracked + // pins into the new cloned area and will keep track of the old to + // new mapping in this map. If this is null, the cloned pagelist will + // not retain any previously tracked pins except those required for + // internal operations. + // + // Any pins not present in the map were not remapped. + tracked_pins: ?*TrackedPinsRemap = null, + + pub const TrackedPinsRemap = std.AutoHashMap(*Pin, *Pin); +}; + +/// Clone this pagelist from the top to bottom (inclusive). +/// +/// The viewport is always moved to the active area. +/// +/// The cloned pagelist must contain at least enough rows for the active +/// area. If the region specified has less rows than the active area then +/// rows will be added to the bottom of the region to make up the difference. +pub fn clone( + self: *const PageList, + alloc: Allocator, + opts: Clone, +) !PageList { + var it = self.pageIterator( + .right_down, + opts.top, + opts.bot, + ); + + // First, count our pages so our preheat is exactly what we need. + var it_copy = it; + const page_count: usize = page_count: { + var count: usize = 0; + while (it_copy.next()) |_| count += 1; + break :page_count count; + }; + + // Setup our pool + var pool: MemoryPool = try .init( + alloc, + pageAllocator(), + page_count, + ); + errdefer pool.deinit(); + + // Create our viewport. In a clone, the viewport always goes + // to the top. + const viewport_pin = try pool.pins.create(); + var tracked_pins: PinSet = .{}; + errdefer tracked_pins.deinit(pool.alloc); + try tracked_pins.putNoClobber(pool.alloc, viewport_pin, {}); + + // Our list of pages + var page_list: List = .{}; + errdefer { + const page_alloc = pool.pages.arena.child_allocator; + var page_it = page_list.first; + while (page_it) |node| : (page_it = node.next) { + if (node.data.memory.len > std_size) { + page_alloc.free(node.data.memory); + } + } + } + + // Copy our pages + var page_serial: u64 = 0; + var total_rows: usize = 0; + var page_size: usize = 0; + while (it.next()) |chunk| { + // Clone the page. We have to use createPageExt here because + // we don't know if the source page has a standard size. + const node = try createPageExt( + &pool, + chunk.node.data.capacity, + &page_serial, + &page_size, + ); + assert(node.data.capacity.rows >= chunk.end - chunk.start); + defer node.data.assertIntegrity(); + node.data.size.rows = chunk.end - chunk.start; + node.data.size.cols = chunk.node.data.size.cols; + try node.data.cloneFrom( + &chunk.node.data, + chunk.start, + chunk.end, + ); + + node.data.dirty = chunk.node.data.dirty; + + page_list.append(node); + + total_rows += node.data.size.rows; + + // Remap our tracked pins by changing the page and + // offsetting the Y position based on the chunk start. + if (opts.tracked_pins) |remap| { + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + // We're only interested in pins that were within the chunk. + if (p.node != chunk.node or + p.y < chunk.start or + p.y >= chunk.end) continue; + const new_p = try pool.pins.create(); + new_p.* = p.*; + new_p.node = node; + new_p.y -= chunk.start; + try remap.putNoClobber(p, new_p); + try tracked_pins.putNoClobber(pool.alloc, new_p, {}); + } + } + } + + // Initialize our viewport pin to point to the first cloned page + // so it points to valid memory. + viewport_pin.* = .{ .node = page_list.first.? }; + + var result: PageList = .{ + .pool = pool, + .pages = page_list, + .page_serial = page_serial, + .page_serial_min = 0, + .page_size = page_size, + .explicit_max_size = self.explicit_max_size, + .min_max_size = self.min_max_size, + .cols = self.cols, + .rows = self.rows, + .total_rows = total_rows, + .tracked_pins = tracked_pins, + .viewport = .{ .active = {} }, + .viewport_pin = viewport_pin, + .viewport_pin_row_offset = null, + }; + + // We always need to have enough rows for our viewport because this is + // a pagelist invariant that other code relies on. + if (total_rows < self.rows) { + const len = self.rows - total_rows; + for (0..len) |_| { + _ = try result.grow(); + + // Clear the row. This is not very fast but in reality right + // now we rarely clone less than the active area and if we do + // the area is by definition very small. + const last = result.pages.last.?; + const row = &last.data.rows.ptr(last.data.memory)[last.data.size.rows - 1]; + last.data.clearCells(row, 0, result.cols); + } + + // Update our total rows to be our row size. + result.total_rows = result.rows; + } + + result.assertIntegrity(); + return result; +} + +/// Resize options +pub const Resize = struct { + /// The new cols/cells of the screen. + cols: ?size.CellCountInt = null, + rows: ?size.CellCountInt = null, + + /// Whether to reflow the text. If this is false then the text will + /// be truncated if the new size is smaller than the old size. + reflow: bool = true, + + /// Set this to the current cursor position in the active area. Some + /// resize/reflow behavior depends on the cursor position. + cursor: ?Cursor = null, + + pub const Cursor = struct { + x: size.CellCountInt, + y: size.CellCountInt, + }; +}; + +/// Resize +/// TODO: docs +pub fn resize(self: *PageList, opts: Resize) Allocator.Error!void { + defer self.assertIntegrity(); + + if (comptime std.debug.runtime_safety) { + // Resize does not work with 0 values, this should be protected + // upstream + if (opts.cols) |v| assert(v > 0); + if (opts.rows) |v| assert(v > 0); + } + + // Resizing (especially with reflow) can cause our row offset to + // become invalid. Rather than do something fancy like we do other + // places and try to update it in place, we just invalidate it because + // its too easy to get the logic wrong in here. + self.viewport_pin_row_offset = null; + + if (!opts.reflow) return try self.resizeWithoutReflow(opts); + + // Recalculate our minimum max size. This allows grow to work properly + // when increasing beyond our initial minimum max size or explicit max + // size to fit the active area. + const old_min_max_size = self.min_max_size; + self.min_max_size = minMaxSize( + opts.cols orelse self.cols, + opts.rows orelse self.rows, + ); + errdefer self.min_max_size = old_min_max_size; + + // On reflow, the main thing that causes reflow is column changes. If + // only rows change, reflow is impossible. So we change our behavior based + // on the change of columns. + const cols = opts.cols orelse self.cols; + switch (std.math.order(cols, self.cols)) { + .eq => try self.resizeWithoutReflow(opts), + + .gt => { + // We grow rows after cols so that we can do our unwrapping/reflow + // before we do a no-reflow grow. + try self.resizeCols(cols, opts.cursor); + try self.resizeWithoutReflow(opts); + }, + + .lt => { + // We first change our row count so that we have the proper amount + // we can use when shrinking our cols. + try self.resizeWithoutReflow(opts: { + var copy = opts; + copy.cols = self.cols; + break :opts copy; + }); + try self.resizeCols(cols, opts.cursor); + }, + } + + // Various resize operations can change our total row count such + // that our viewport pin is now in the active area and has insufficient + // space. We need to check for this case and fix it up. + switch (self.viewport) { + .pin => if (self.pinIsActive(self.viewport_pin.*)) { + self.viewport = .active; + }, + .active, .top => {}, + } +} + +/// Resize the pagelist with reflow by adding or removing columns. +fn resizeCols( + self: *PageList, + cols: size.CellCountInt, + cursor: ?Resize.Cursor, +) Allocator.Error!void { + assert(cols != self.cols); + + // Update our cols. We have to do this early because grow() that we + // may call below relies on this to calculate the proper page size. + self.cols = cols; + + // If we have a cursor position (x,y), then we try under any col resizing + // to keep the same number remaining active rows beneath it. This is a + // very special case if you can imagine clearing the screen (i.e. + // scrollClear), having an empty active area, and then resizing to less + // cols then we don't want the active area to "jump" to the bottom and + // pull down scrollback. + const preserved_cursor: ?struct { + tracked_pin: *Pin, + remaining_rows: usize, + wrapped_rows: usize, + } = if (cursor) |c| cursor: { + const p = self.pin(.{ .active = .{ + .x = c.x, + .y = c.y, + } }) orelse break :cursor null; + + const active_pin = self.pin(.{ .active = .{} }); + + // We count how many wraps the cursor had before it to begin with + // so that we can offset any additional wraps to avoid pushing the + // original row contents in to the scrollback. + const wrapped = wrapped: { + var wrapped: usize = 0; + + var row_it = p.rowIterator(.left_up, active_pin); + while (row_it.next()) |next| { + const row = next.rowAndCell().row; + if (row.wrap_continuation) wrapped += 1; + } + + break :wrapped wrapped; + }; + + break :cursor .{ + .tracked_pin = try self.trackPin(p), + .remaining_rows = self.rows - c.y - 1, + .wrapped_rows = wrapped, + }; + } else null; + defer if (preserved_cursor) |c| self.untrackPin(c.tracked_pin); + + // Create the first node that contains our reflow. + const first_rewritten_node = node: { + const page = &self.pages.first.?.data; + const cap = page.capacity.adjust( + .{ .cols = cols }, + ) catch |err| err: { + comptime assert(@TypeOf(err) == error{OutOfMemory}); + + // We verify all maxed out page layouts work. + var cap = page.capacity; + cap.cols = cols; + + // We're growing columns so we can only get less rows so use + // the lesser of our capacity and size so we minimize wasted + // rows. + cap.rows = @min(page.size.rows, cap.rows); + break :err cap; + }; + + const node = try self.createPage(cap); + node.data.size.rows = 1; + break :node node; + }; + + // We need to grab our rowIterator now before we rewrite our + // linked list below. + var it = self.rowIterator( + .right_down, + .{ .screen = .{} }, + null, + ); + errdefer { + // If an error occurs, we're in a pretty disastrous broken state, + // but we should still try to clean up our leaked memory. Free + // any of the remaining orphaned pages from before. If we reflowed + // successfully this will be null. + var node_: ?*Node = if (it.chunk) |chunk| chunk.node else null; + while (node_) |node| { + node_ = node.next; + self.destroyNode(node); + } + } + + // Set our new page as the only page. This orphans the existing pages + // in the list, but that's fine since we're gonna delete them anyway. + self.pages.first = first_rewritten_node; + self.pages.last = first_rewritten_node; + + // Reflow all our rows. + { + var reflow_cursor: ReflowCursor = .init(first_rewritten_node); + while (it.next()) |row| { + try reflow_cursor.reflowRow(self, row); + + // Once we're done reflowing a page, destroy it immediately. + // This frees memory and makes it more likely in memory + // constrained environments that the next reflow will work. + if (row.y == row.node.data.size.rows - 1) { + self.destroyNode(row.node); + } + } + + // At the end of the reflow, setup our total row cache + // log.warn("total old={} new={}", .{ self.total_rows, reflow_cursor.total_rows }); + self.total_rows = reflow_cursor.total_rows; + } + + // If our total rows is less than our active rows, we need to grow. + // This can happen if you're growing columns such that enough active + // rows unwrap that we no longer have enough. + var node_it = self.pages.first; + var total: usize = 0; + while (node_it) |node| : (node_it = node.next) { + total += node.data.size.rows; + if (total >= self.rows) break; + } else { + for (total..self.rows) |_| _ = try self.grow(); + } + + // See preserved_cursor setup for why. + if (preserved_cursor) |c| cursor: { + const active_pt = self.pointFromPin( + .active, + c.tracked_pin.*, + ) orelse break :cursor; + + const active_pin = self.pin(.{ .active = .{} }); + + // We need to determine how many rows we wrapped from the original + // and subtract that from the remaining rows we expect because if + // we wrap down we don't want to push our original row contents into + // the scrollback. + const wrapped = wrapped: { + var wrapped: usize = 0; + + var row_it = c.tracked_pin.rowIterator(.left_up, active_pin); + while (row_it.next()) |next| { + const row = next.rowAndCell().row; + if (row.wrap_continuation) wrapped += 1; + } + + break :wrapped wrapped; + }; + + const current = self.rows - active_pt.active.y - 1; + + var req_rows = c.remaining_rows; + req_rows -|= wrapped -| c.wrapped_rows; + req_rows -|= current; + + while (req_rows > 0) { + _ = try self.grow(); + req_rows -= 1; + } + } +} + +// We use a cursor to track where we are in the src/dst. This is very +// similar to Screen.Cursor, so see that for docs on individual fields. +// We don't use a Screen because we don't need all the same data and we +// do our best to optimize having direct access to the page memory. +const ReflowCursor = struct { + x: size.CellCountInt, + y: size.CellCountInt, + pending_wrap: bool, + node: *List.Node, + page: *pagepkg.Page, + page_row: *pagepkg.Row, + page_cell: *pagepkg.Cell, + new_rows: usize, + + /// This is the final row count of the reflowed pages. + total_rows: usize, + + fn init(node: *List.Node) ReflowCursor { + const page = &node.data; + const rows = page.rows.ptr(page.memory); + return .{ + .x = 0, + .y = 0, + .pending_wrap = false, + .node = node, + .page = page, + .page_row = &rows[0], + .page_cell = &rows[0].cells.ptr(page.memory)[0], + .new_rows = 0, + + // Initially whatever size our input node is. + .total_rows = node.data.size.rows, + }; + } + + /// Reflow the provided row in to this cursor. + fn reflowRow( + self: *ReflowCursor, + list: *PageList, + row: Pin, + ) Allocator.Error!void { + const src_page: *Page = &row.node.data; + const src_row = row.rowAndCell().row; + const src_y = row.y; + const cells = src_row.cells.ptr(src_page.memory)[0..src_page.size.cols]; + + // Calculate the columns in this row. First up we trim non-semantic + // rightmost blanks. + var cols_len = src_page.size.cols; + if (!src_row.wrap) { + while (cols_len > 0) { + if (!cells[cols_len - 1].isEmpty()) break; + cols_len -= 1; + } + + // If the row has a semantic prompt then the blank row is meaningful + // so we just consider pretend the first cell of the row isn't empty. + if (cols_len == 0 and src_row.semantic_prompt != .none) cols_len = 1; + } + + // Handle tracked pin adjustments. + { + const pin_keys = list.tracked_pins.keys(); + for (pin_keys) |p| { + if (&p.node.data != src_page or + p.y != src_y) continue; + + // If this pin is in the blanks on the right and past the end + // of the dst col width then we move it to the end of the dst + // col width instead. + if (p.x >= cols_len) p.x = @min( + p.x, + self.page.size.cols - 1 - self.x, + ); + + // We increase our col len to at least include this pin. + // This ensures that blank rows with pins are processed, + // so that the pins can be properly remapped. + cols_len = @max(cols_len, p.x + 1); + } + } + + // Defer processing of blank rows so that blank rows + // at the end of the page list are never written. + if (cols_len == 0) { + // If this blank row was a wrap continuation somehow + // then we won't need to write it since it should be + // a part of the previously written row. + if (!src_row.wrap_continuation) self.new_rows += 1; + return; + } + + // Inherit increased styles or grapheme bytes from the src page + // we're reflowing from for new pages. + const cap = src_page.capacity.adjust( + .{ .cols = self.page.size.cols }, + ) catch |err| err: { + comptime assert(@TypeOf(err) == error{OutOfMemory}); + + var cap = src_page.capacity; + cap.cols = self.page.size.cols; + // We're already a non-standard page. We don't want to + // inherit a massive set of rows, so cap it at our std size. + cap.rows = @min(src_page.size.rows, std_capacity.rows); + break :err cap; + }; + + // Our row isn't blank, write any new rows we deferred. + while (self.new_rows > 0) { + try self.cursorScrollOrNewPage(list, cap); + self.new_rows -= 1; + } + + self.copyRowMetadata(src_row); + + var x: usize = 0; + while (x < cols_len) { + if (self.pending_wrap) { + self.page_row.wrap = true; + try self.cursorScrollOrNewPage(list, cap); + self.copyRowMetadata(src_row); + self.page_row.wrap_continuation = true; + } + + // Move any tracked pins from the source. + { + const pin_keys = list.tracked_pins.keys(); + for (pin_keys) |p| { + if (&p.node.data != src_page or + p.y != src_y or + p.x != x) continue; + + p.node = self.node; + p.x = self.x; + p.y = self.y; + } + } + + if (self.writeCell( + list, + &cells[x], + src_page, + )) |result| switch (result) { + // Wrote the cell, move to the next. + .success => x += 1, + + // Wrote the cell but request to skip the next so skip it. + // This is used for things like spacers. + .skip_next => { + // Remap any tracked pins at the skipped position (x+1) + // since we won't process that cell in the loop. + const pin_keys = list.tracked_pins.keys(); + for (pin_keys) |p| { + if (&p.node.data != src_page or + p.y != src_y or + p.x != x + 1) continue; + + p.node = self.node; + p.x = self.x; + p.y = self.y; + } + + x += 2; + }, + + // Didn't write the cell, repeat writing this same cell. + .repeat => {}, + } else |err| switch (err) { + // System out of memory, we can't fix this. + error.OutOfMemory => return error.OutOfMemory, + + // We reached the capacity of a single page and can't + // add any more of some type of managed memory. When this + // happens we split out the current row we're working on + // into a new page and continue from there. + error.OutOfSpace => if (self.y == 0) { + // If we're already on the first-row, we can't split + // any further, so we just ignore bad cells and take + // corrupted (but valid) cell contents. + log.warn("reflowRow OutOfSpace on first row, discarding cell managed memory", .{}); + x += 1; + self.cursorForward(); + } else { + // Move our last row to a new page. + try self.moveLastRowToNewPage(list, cap); + + // Do NOT increment x so that we retry writing + // the same existing cell. + }, + } + } + + // If the source row isn't wrapped then we should scroll afterwards. + if (!src_row.wrap) { + self.new_rows += 1; + } + } + + /// Write a cell. On error, this will not unwrite the cell but + /// the cell may be incomplete (but valid). For example, if the source + /// cell is styled and we failed to allocate space for styles, the + /// written cell may not be styled but it is valid. + /// + /// The key failure to recognize for callers is when we can't increase + /// capacity in our destination page. In this case, the caller may want + /// to split the page at this row, rewrite the row into a new page + /// and continue from there. + /// + /// But this function guarantees the terminal/page will be in a + /// coherent state even on error. + fn writeCell( + self: *ReflowCursor, + list: *PageList, + cell: *const pagepkg.Cell, + src_page: *const Page, + ) IncreaseCapacityError!enum { + success, + repeat, + skip_next, + } { + // Initialize self.page_cell with basic, unmanaged memory contents. + { + // This must not fail because we want to make sure we atomically + // setup our page cell to be valid. + errdefer comptime unreachable; + + // Copy cell contents. + switch (cell.content_tag) { + .codepoint, + .codepoint_grapheme, + => switch (cell.wide) { + .narrow => self.page_cell.* = cell.*, + + .wide => if (self.page.size.cols > 1) { + if (self.x == self.page.size.cols - 1) { + // If there's a wide character in the last column of + // the reflowed page then we need to insert a spacer + // head and wrap before handling it. + self.page_cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + + // Move to the next row (this sets pending wrap + // which will cause us to wrap on the next + // iteration). + self.cursorForward(); + + // Decrement the source position so that when we + // loop we'll process this source cell again, + // since we can't copy it into a spacer head. + return .repeat; + } else { + self.page_cell.* = cell.*; + } + } else { + // Edge case, when resizing to 1 column, wide + // characters are just destroyed and replaced + // with empty narrow cells. + self.page_cell.content.codepoint = 0; + self.page_cell.wide = .narrow; + self.cursorForward(); + + // Skip spacer tail so it doesn't cause a wrap. + return .skip_next; + }, + + .spacer_tail => if (self.page.size.cols > 1) { + self.page_cell.* = cell.*; + } else { + // Edge case, when resizing to 1 column, wide + // characters are just destroyed and replaced + // with empty narrow cells, so we should just + // discard any spacer tails. + return .success; + }, + + .spacer_head => { + // Spacer heads should be ignored. If we need a + // spacer head in our reflowed page, it is added + // when processing the wide cell it belongs to. + return .success; + }, + }, + + .bg_color_palette, + .bg_color_rgb, + => { + // These are guaranteed to have no style or grapheme + // data associated with them so we can fast path them. + self.page_cell.* = cell.*; + self.cursorForward(); + return .success; + }, + } + + // These will create issues by trying to clone managed memory that + // isn't set if the current dst row needs to be moved to a new page. + // They'll be fixed once we do properly copy the relevant memory. + self.page_cell.content_tag = .codepoint; + self.page_cell.hyperlink = false; + self.page_cell.style_id = stylepkg.default_id; + + if (comptime build_options.kitty_graphics) { + // Copy Kitty virtual placeholder status + if (cell.codepoint() == kitty.graphics.unicode.placeholder) { + self.page_row.kitty_virtual_placeholder = true; + } + } + } + + // std.log.warn("\nsrc_y={} src_x={} dst_y={} dst_x={} dst_cols={} cp={X} wide={} page_cell_wide={}", .{ + // src_y, + // x, + // self.y, + // self.x, + // self.page.size.cols, + // cell.content.codepoint, + // cell.wide, + // self.page_cell.wide, + // }); + + // From this point on we're moving on to failable, managed memory. + // If we reach an error, we do the minimal cleanup necessary to + // not leave dangling memory but otherwise we gracefully degrade + // into some functional but not strictly correct cell. + + // Copy grapheme data. + if (cell.content_tag == .codepoint_grapheme) { + // Copy the graphemes + const cps = src_page.lookupGrapheme(cell).?; + + // If our page can't support an additional cell + // with graphemes then we increase capacity. + if (self.page.graphemeCount() >= self.page.graphemeCapacity()) { + try self.increaseCapacity( + list, + .grapheme_bytes, + ); + } + + // Attempt to allocate the space that would be required + // for these graphemes, and if it's not available, then + // increase capacity. Keep trying until we succeed. + while (true) { + if (self.page.grapheme_alloc.alloc( + u21, + self.page.memory, + cps.len, + )) |slice| { + self.page.grapheme_alloc.free( + self.page.memory, + slice, + ); + break; + } else |_| { + // Grow our capacity until we can fit the extra bytes. + try self.increaseCapacity(list, .grapheme_bytes); + } + } + + self.page.setGraphemes( + self.page_row, + self.page_cell, + cps, + ) catch |err| { + // This shouldn't fail since we made sure we have space + // above. There is no reasonable behavior we can take here + // so we have a warn level log. This is ALMOST non-recoverable, + // though we choose to recover by corrupting the cell + // to a non-grapheme codepoint. + log.err("setGraphemes failed after capacity increase err={}", .{err}); + if (comptime std.debug.runtime_safety) { + // Force a crash with safe builds. + unreachable; + } + + // Unsafe builds we throw away grapheme data! + self.page_cell.content_tag = .codepoint; + self.page_cell.content = .{ .codepoint = 0xFFFD }; + }; + } + + // Copy hyperlink data. + if (cell.hyperlink) hyperlink: { + const src_id = src_page.lookupHyperlink(cell).?; + const src_link = src_page.hyperlink_set.get(src_page.memory, src_id); + + // If our page can't support an additional cell + // with a hyperlink then we increase capacity. + if (self.page.hyperlinkCount() >= self.page.hyperlinkCapacity()) { + try self.increaseCapacity(list, .hyperlink_bytes); + } + + // Ensure that the string alloc has sufficient capacity + // to dupe the link (and the ID if it's not implicit). + const additional_required_string_capacity = + src_link.uri.len + + switch (src_link.id) { + .explicit => |v| v.len, + .implicit => 0, + }; + // Keep trying until we have enough capacity. + while (true) { + if (self.page.string_alloc.alloc( + u8, + self.page.memory, + additional_required_string_capacity, + )) |slice| { + // We have enough capacity, free the test alloc. + self.page.string_alloc.free( + self.page.memory, + slice, + ); + break; + } else |_| { + // Grow our capacity until we can fit the extra bytes. + try self.increaseCapacity( + list, + .string_bytes, + ); + } + } + + const dst_link = src_link.dupe( + src_page, + self.page, + ) catch |err| { + // This shouldn't fail since we did a capacity + // check above. + log.err("link dupe failed with capacity check err={}", .{err}); + if (comptime std.debug.runtime_safety) { + // Force a crash with safe builds. + unreachable; + } + + break :hyperlink; + }; + + const dst_id = self.page.hyperlink_set.addWithIdContext( + self.page.memory, + dst_link, + src_id, + .{ .page = self.page }, + ) catch |err| id: { + // Always free our original link in case the increaseCap + // call fails so we aren't leaking memory. + dst_link.free(self.page); + + // If the add failed then either the set needs to grow + // or it needs to be rehashed. Either one of those can + // be accomplished by increasing capacity, either with + // no actual change or with an increased hyperlink cap. + try self.increaseCapacity(list, switch (err) { + error.OutOfMemory => .hyperlink_bytes, + error.NeedsRehash => null, + }); + + // We need to recreate the link into the new page. + const dst_link2 = src_link.dupe( + src_page, + self.page, + ) catch |err2| { + // This shouldn't fail since we did a capacity + // check above. + log.err("link dupe failed with capacity check err={}", .{err2}); + if (comptime std.debug.runtime_safety) { + // Force a crash with safe builds. + unreachable; + } + + break :hyperlink; + }; + + // We assume this one will succeed. We dupe the link + // again, and don't have to worry about the other one + // because increasing the capacity naturally clears up + // any managed memory not associated with a cell yet. + break :id self.page.hyperlink_set.addWithIdContext( + self.page.memory, + dst_link2, + src_id, + .{ .page = self.page }, + ) catch |err2| { + // This shouldn't happen since we increased capacity + // above so we handle it like the other similar + // cases and log it, crash in safe builds, and + // remove the hyperlink in unsafe builds. + log.err( + "addWithIdContext failed after capacity increase err={}", + .{err2}, + ); + if (comptime std.debug.runtime_safety) { + // Force a crash with safe builds. + unreachable; + } + + dst_link2.free(self.page); + break :hyperlink; + }; + } orelse src_id; + + // We expect this to succeed due to the hyperlinkCapacity + // check we did before. If it doesn't succeed let's + // log it, crash (in safe builds), and clear our state. + self.page.setHyperlink( + self.page_row, + self.page_cell, + dst_id, + ) catch |err| { + log.err( + "setHyperlink failed after capacity increase err={}", + .{err}, + ); + if (comptime std.debug.runtime_safety) { + // Force a crash with safe builds. + unreachable; + } + + // Unsafe builds we throw away hyperlink data! + self.page.hyperlink_set.release(self.page.memory, dst_id); + self.page_cell.hyperlink = false; + break :hyperlink; + }; + } + + // Copy style data. + if (cell.hasStyling()) style: { + const style = src_page.styles.get( + src_page.memory, + cell.style_id, + ).*; + + const id = self.page.styles.addWithId( + self.page.memory, + style, + cell.style_id, + ) catch |err| id: { + // If the add failed then either the set needs to grow + // or it needs to be rehashed. Either one of those can + // be accomplished by increasing capacity, either with + // no actual change or with an increased style cap. + try self.increaseCapacity(list, switch (err) { + error.OutOfMemory => .styles, + error.NeedsRehash => null, + }); + + // We assume this one will succeed. + break :id self.page.styles.addWithId( + self.page.memory, + style, + cell.style_id, + ) catch |err2| { + // Should not fail since we just modified capacity + // above. Log it, crash in safe builds, clear style + // in unsafe builds. + log.err( + "addWithId failed after capacity increase err={}", + .{err2}, + ); + if (comptime std.debug.runtime_safety) { + // Force a crash with safe builds. + unreachable; + } + + self.page_cell.style_id = stylepkg.default_id; + break :style; + }; + } orelse cell.style_id; + + self.page_row.styled = true; + self.page_cell.style_id = id; + } + + self.cursorForward(); + return .success; + } + + /// Create a new page in the provided list with the provided + /// capacity then clone the row currently being worked on to + /// it and delete it from the old page. Places cursor in the + /// same position it was in in the old row in the new one. + /// + /// Asserts that the cursor is on the final row of the page. + /// + /// Expects that the provided capacity is sufficient to copy + /// the row. + /// + /// If this is the only row in the page, the page is removed + /// from the list after cloning the row. + fn moveLastRowToNewPage( + self: *ReflowCursor, + list: *PageList, + cap: Capacity, + ) Allocator.Error!void { + assert(self.y == self.page.size.rows - 1); + assert(!self.pending_wrap); + + const old_node = self.node; + const old_page = self.page; + const old_row = self.page_row; + const old_x = self.x; + + // Our total row count never changes, because we're removing one + // row from the last page and moving it into a new page. + const old_total_rows = self.total_rows; + defer self.total_rows = old_total_rows; + + try self.cursorNewPage(list, cap); + assert(self.node != old_node); + assert(self.y == 0); + + // We have no cleanup for our old state from here on out. No failures! + errdefer comptime unreachable; + + // Restore the x position of the cursor. + self.cursorAbsolute(old_x, 0); + + // Copy our old data. This should NOT fail because we have the + // capacity of the old page which already fits the data we requested. + self.page.cloneRowFrom( + old_page, + self.page_row, + old_row, + ) catch |err| { + log.err( + "error cloning single row for moveLastRowToNewPage err={}", + .{err}, + ); + @panic("unexpected copy row failure"); + }; + + // Move any tracked pins from that last row into this new node. + { + const pin_keys = list.tracked_pins.keys(); + for (pin_keys) |p| { + if (&p.node.data != old_page or + p.y != old_page.size.rows - 1) continue; + + p.node = self.node; + p.y = self.y; + // p.x remains the same since we're copying the row as-is + } + } + + // Clear the row from the old page and truncate it. + old_page.clearCells(old_row, 0, old_page.size.cols); + old_page.size.rows -= 1; + + // If that was the last row in that page + // then we should remove it from the list. + if (old_page.size.rows == 0) { + list.pages.remove(old_node); + list.destroyNode(old_node); + } + } + + /// Increase the capacity of the current page. + fn increaseCapacity( + self: *ReflowCursor, + list: *PageList, + adjustment: ?IncreaseCapacity, + ) IncreaseCapacityError!void { + const old_x = self.x; + const old_y = self.y; + const old_total_rows = self.total_rows; + + const node = node: { + // Pause integrity checks because the total row count won't + // be correct during a reflow. + list.pauseIntegrityChecks(true); + defer list.pauseIntegrityChecks(false); + break :node try list.increaseCapacity( + self.node, + adjustment, + ); + }; + // We must not fail after this, we've modified our self.node + // and we need to fix it up. + errdefer comptime unreachable; + + self.* = .init(node); + self.cursorAbsolute(old_x, old_y); + self.total_rows = old_total_rows; + } + + /// True if this cursor is at the bottom of the page by capacity, + /// i.e. we can't scroll anymore. + fn bottom(self: *const ReflowCursor) bool { + return self.y == self.page.capacity.rows - 1; + } + + fn cursorForward(self: *ReflowCursor) void { + if (self.x == self.page.size.cols - 1) { + self.pending_wrap = true; + } else { + const cell: [*]pagepkg.Cell = @ptrCast(self.page_cell); + self.page_cell = @ptrCast(cell + 1); + self.x += 1; + } + } + + /// Create a new row and move the cursor down. + /// + /// Asserts that the cursor is on the bottom row of the + /// page and that there is capacity to add a new one. + fn cursorScroll(self: *ReflowCursor) void { + // Scrolling requires that we're on the bottom of our page. + // We also assert that we have capacity because reflow always + // works within the capacity of the page. + assert(self.y == self.page.size.rows - 1); + assert(self.page.size.rows < self.page.capacity.rows); + + // Increase our page size + self.page.size.rows += 1; + + // With the increased page size, safely move down a row. + const rows: [*]pagepkg.Row = @ptrCast(self.page_row); + const row: *pagepkg.Row = @ptrCast(rows + 1); + self.page_row = row; + self.page_cell = &row.cells.ptr(self.page.memory)[0]; + self.pending_wrap = false; + self.x = 0; + self.y += 1; + } + + /// Create a new page in the provided list with the provided + /// capacity and one row and move the cursor in to it at 0,0 + fn cursorNewPage( + self: *ReflowCursor, + list: *PageList, + cap: Capacity, + ) Allocator.Error!void { + // Remember our new row count so we can restore it + // after reinitializing our cursor on the new page. + const new_rows = self.new_rows; + + const node = try list.createPage(cap); + errdefer comptime unreachable; + node.data.size.rows = 1; + list.pages.insertAfter(self.node, node); + + self.* = .init(node); + self.new_rows = new_rows; + } + + /// Performs `cursorScroll` or `cursorNewPage` as necessary + /// depending on if the cursor is currently at the bottom. + fn cursorScrollOrNewPage( + self: *ReflowCursor, + list: *PageList, + cap: Capacity, + ) Allocator.Error!void { + // The functions below may overwrite self so we need to cache + // our total rows. We add one because no matter what when this + // returns we'll have one more row added. + const new_total_rows: usize = self.total_rows + 1; + defer self.total_rows = new_total_rows; + + if (self.bottom()) { + try self.cursorNewPage(list, cap); + } else { + self.cursorScroll(); + } + } + + fn cursorAbsolute( + self: *ReflowCursor, + x: size.CellCountInt, + y: size.CellCountInt, + ) void { + assert(x < self.page.size.cols); + assert(y < self.page.size.rows); + + const rows: [*]pagepkg.Row = @ptrCast(self.page_row); + const row: *pagepkg.Row = switch (std.math.order(y, self.y)) { + .eq => self.page_row, + .lt => @ptrCast(rows - (self.y - y)), + .gt => @ptrCast(rows + (y - self.y)), + }; + self.page_row = row; + self.page_cell = &row.cells.ptr(self.page.memory)[x]; + self.pending_wrap = false; + self.x = x; + self.y = y; + } + + fn countTrailingEmptyCells(self: *const ReflowCursor) usize { + // If the row is wrapped, all empty cells are meaningful. + if (self.page_row.wrap) return 0; + + const cells: [*]pagepkg.Cell = @ptrCast(self.page_cell); + const len: usize = self.page.size.cols - self.x; + for (0..len) |i| { + const rev_i = len - i - 1; + if (!cells[rev_i].isEmpty()) return i; + } + + // If the row has a semantic prompt then the blank row is meaningful + // so we always return all but one so that the row is drawn. + if (self.page_row.semantic_prompt != .none) return len - 1; + + return len; + } + + fn copyRowMetadata(self: *ReflowCursor, other: *const Row) void { + self.page_row.semantic_prompt = other.semantic_prompt; + } +}; + +fn resizeWithoutReflow(self: *PageList, opts: Resize) Allocator.Error!void { + // We only set the new min_max_size if we're not reflowing. If we are + // reflowing, then resize handles this for us. + const old_min_max_size = self.min_max_size; + self.min_max_size = if (!opts.reflow) minMaxSize( + opts.cols orelse self.cols, + opts.rows orelse self.rows, + ) else old_min_max_size; + errdefer self.min_max_size = old_min_max_size; + + // Important! We have to do cols first because cols may cause us to + // destroy pages if we're increasing cols which will free up page_size + // so that when we call grow() in the row mods, we won't prune. + if (opts.cols) |cols| { + // Any column change without reflow should not result in row counts + // changing. + const old_total_rows = self.total_rows; + defer assert(self.total_rows == old_total_rows); + + switch (std.math.order(cols, self.cols)) { + .eq => {}, + + // Making our columns smaller. We always have space for this + // in existing pages so we need to go through the pages, + // resize the columns, and clear any cells that are beyond + // the new size. + .lt => { + var it = self.pageIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |chunk| { + const page = &chunk.node.data; + defer page.assertIntegrity(); + const rows = page.rows.ptr(page.memory); + for (0..page.size.rows) |i| { + const row = &rows[i]; + page.clearCells(row, cols, self.cols); + } + + page.size.cols = cols; + } + + // Update all our tracked pins. If they have an X + // beyond the edge, clamp it. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.x >= cols) p.x = cols - 1; + } + + self.cols = cols; + }, + + // Make our columns larger. This is a bit more complicated because + // pages may not have the capacity for this. If they don't have + // the capacity we need to allocate a new page and copy the data. + .gt => { + // See the comment in the while loop when setting self.cols + const old_cols = self.cols; + + var it = self.pageIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |chunk| { + // We need to restore our old cols after we resize because + // we have an assertion on this and we want to be able to + // call this method multiple times. + self.cols = old_cols; + try self.resizeWithoutReflowGrowCols(cols, chunk); + } + + self.cols = cols; + }, + } + } + + if (opts.rows) |rows| { + switch (std.math.order(rows, self.rows)) { + .eq => {}, + + // Making rows smaller, we simply change our rows value. Changing + // the row size doesn't affect anything else since max size and + // so on are all byte-based. + .lt => { + // If our rows are shrinking, we prefer to trim trailing + // blank lines from the active area instead of creating + // history if we can. + // + // This matches macOS Terminal.app behavior. I chose to match that + // behavior because it seemed fine in an ocean of differing behavior + // between terminal apps. I'm completely open to changing it as long + // as resize behavior isn't regressed in a user-hostile way. + const trimmed = self.trimTrailingBlankRows(self.rows - rows); + + // Account for our trimmed rows in the total row cache + self.total_rows -= trimmed; + + // If we didn't trim enough, just modify our row count and this + // will create additional history. + self.rows = rows; + }, + + // Making rows larger we adjust our row count, and then grow + // to the row count. + .gt => gt: { + // If our rows increased and our cursor is NOT at the bottom, + // we want to try to preserve the y value of the old cursor. + // In other words, we don't want to "pull down" scrollback. + // This is purely a UX feature. + if (opts.cursor) |cursor| cursor: { + if (cursor.y >= self.rows - 1) break :cursor; + + // Cursor is not at the bottom, so we just grow our + // rows and we're done. Cursor does NOT change for this + // since we're not pulling down scrollback. + const delta = rows - self.rows; + self.rows = rows; + for (0..delta) |_| _ = try self.grow(); + break :gt; + } + + // This must be set BEFORE any calls to grow() so that + // grow() doesn't prune pages that we need for the active + // area. + self.rows = rows; + + // Cursor is at the bottom or we don't care about cursors. + // In this case, if we have enough rows in our pages, we + // just update our rows and we're done. This effectively + // "pulls down" scrollback. + // + // If we don't have enough scrollback, we add the difference, + // to the active area. + var count: usize = 0; + var page = self.pages.first; + while (page) |p| : (page = p.next) { + count += p.data.size.rows; + if (count >= rows) break; + } else { + assert(count < rows); + for (count..rows) |_| _ = try self.grow(); + } + + // Make sure that the viewport pin isn't below the active + // area, since that will lead to all sorts of problems. + switch (self.viewport) { + .pin => if (self.pinIsActive(self.viewport_pin.*)) { + self.viewport = .active; + }, + .active, .top => {}, + } + }, + } + + if (build_options.slow_runtime_safety) { + // We never have less rows than our active screen has. + assert(self.totalRows() >= self.rows); + } + } +} + +fn resizeWithoutReflowGrowCols( + self: *PageList, + cols: size.CellCountInt, + chunk: PageIterator.Chunk, +) Allocator.Error!void { + assert(cols > self.cols); + const page = &chunk.node.data; + + // Update our col count + const old_cols = self.cols; + self.cols = cols; + errdefer self.cols = old_cols; + + // Unlikely fast path: we have capacity in the page. This + // is only true if we resized to less cols earlier. + if (page.capacity.cols >= cols) fast: { + // If any row has a spacer head at the old last column, it will + // be invalid at the new (wider) size. Fall through to the slow + // path which handles spacer heads correctly via cloneRowFrom. + const rows = page.rows.ptr(page.memory)[0..page.size.rows]; + for (rows) |*row| { + const cells = page.getCells(row); + if (cells[old_cols - 1].wide == .spacer_head) break :fast; + } + + page.size.cols = cols; + return; + } + + // Likely slow path: we don't have capacity, so we need + // to allocate a page, and copy the old data into it. + + // Try to fit our new column size into our existing page capacity. + // If that doesn't work then use a non-standard page with the + // given columns. + const cap = page.capacity.adjust( + .{ .cols = cols }, + ) catch |err| err: { + comptime assert(@TypeOf(err) == error{OutOfMemory}); + + // We verify all maxed out page layouts don't overflow, + var cap = page.capacity; + cap.cols = cols; + + // We're growing columns so we can only get less rows so use + // the lesser of our capacity and size so we minimize wasted + // rows. + cap.rows = @min(page.size.rows, cap.rows); + break :err cap; + }; + + // On error, we need to undo all the pages we've added. + const prev = chunk.node.prev; + errdefer { + var current = chunk.node.prev; + while (current) |p| { + if (current == prev) break; + current = p.prev; + self.pages.remove(p); + self.destroyNode(p); + } + } + + // Keeps track of all our copied rows. Assertions at the end is that + // we copied exactly our page size. + var copied: size.CellCountInt = 0; + + // This function has an unfortunate side effect in that it causes memory + // fragmentation on rows if the columns are increasing in a way that + // shrinks capacity rows. If we have pages that don't divide evenly then + // we end up creating a final page that is not using its full capacity. + // If this chunk isn't the last chunk in the page list, then we've created + // a page where we'll never reclaim that capacity. This makes our max size + // calculation incorrect since we'll throw away data even though we have + // excess capacity. To avoid this, we try to fill our previous page + // first if it has capacity. + // + // This can fail for many reasons (can't fit styles/graphemes, etc.) so + // if it fails then we give up and drop back into creating new pages. + if (prev) |prev_node| prev: { + const prev_page = &prev_node.data; + + // We only want scenarios where we have excess capacity. + if (prev_page.size.rows >= prev_page.capacity.rows) break :prev; + + // We can copy as much as we can to fill the capacity or our + // current page size. + const len = @min( + prev_page.capacity.rows - prev_page.size.rows, + page.size.rows, + ); + + const src_rows = page.rows.ptr(page.memory)[0..len]; + const dst_rows = prev_page.rows.ptr(prev_page.memory)[prev_page.size.rows..]; + for (dst_rows, src_rows) |*dst_row, *src_row| { + prev_page.size.rows += 1; + copied += 1; + prev_page.cloneRowFrom( + page, + dst_row, + src_row, + ) catch { + // If an error happens, we undo our row copy and break out + // into creating a new page. + prev_page.size.rows -= 1; + copied -= 1; + break :prev; + }; + } + + assert(copied == len); + assert(prev_page.size.rows <= prev_page.capacity.rows); + + // Remap any tracked pins that pointed to rows we just copied to prev. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != chunk.node or p.y >= len) continue; + p.node = prev_node; + p.y += prev_page.size.rows - len; + } + } + + // If we have an error, we clear the rows we just added to our prev page. + const prev_copied = copied; + errdefer if (prev_copied > 0) { + const prev_page = &prev.?.data; + const prev_size = prev_page.size.rows - prev_copied; + const prev_rows = prev_page.rows.ptr(prev_page.memory)[prev_size..prev_page.size.rows]; + for (prev_rows) |*row| prev_page.clearCells( + row, + 0, + prev_page.size.cols, + ); + prev_page.size.rows = prev_size; + }; + + // We delete any of the nodes we added. + errdefer { + var it = chunk.node.prev; + while (it) |node| { + if (node == prev) break; + it = node.prev; + self.pages.remove(node); + self.destroyNode(node); + } + } + + // We need to loop because our col growth may force us + // to split pages. + while (copied < page.size.rows) { + const new_node = try self.createPage(cap); + defer new_node.data.assertIntegrity(); + + // The length we can copy into the new page is at most the number + // of rows in our cap. But if we can finish our source page we use that. + const len = @min(cap.rows, page.size.rows - copied); + + // Perform the copy + const y_start = copied; + const src_rows = page.rows.ptr(page.memory)[y_start .. copied + len]; + const dst_rows = new_node.data.rows.ptr(new_node.data.memory)[0..len]; + for (dst_rows, src_rows) |*dst_row, *src_row| { + new_node.data.size.rows += 1; + if (new_node.data.cloneRowFrom( + page, + dst_row, + src_row, + )) |_| { + copied += 1; + } else |err| { + // I don't THINK this should be possible, because while our + // row count may diminish due to the adjustment, our + // prior capacity should have been sufficient to hold all the + // managed memory. + log.warn( + "unexpected cloneRowFrom failure during resizeWithoutReflowGrowCols: {}", + .{err}, + ); + + // We can actually safely handle this though by exiting + // this loop early and cutting our copy short. + new_node.data.size.rows -= 1; + break; + } + } + const y_end = copied; + + // Insert our new page + self.pages.insertBefore(chunk.node, new_node); + + // Update our tracked pins that pointed to this previous page. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != chunk.node or + p.y < y_start or + p.y >= y_end) continue; + p.node = new_node; + p.y -= y_start; + } + } + assert(copied == page.size.rows); + + // Our prior errdeferes are invalid after this point so ensure + // we don't have any more errors. + errdefer comptime unreachable; + + // Remove the old page. + // Deallocate the old page. + self.pages.remove(chunk.node); + self.destroyNode(chunk.node); +} + +/// Returns the number of trailing blank lines, not to exceed max. Max +/// is used to limit our traversal in the case of large scrollback. +fn trailingBlankLines( + self: *const PageList, + max: size.CellCountInt, +) size.CellCountInt { + var count: size.CellCountInt = 0; + + // Go through our pages backwards since we're counting trailing blanks. + var it = self.pages.last; + while (it) |page| : (it = page.prev) { + const len = page.data.size.rows; + const rows = page.data.rows.ptr(page.data.memory)[0..len]; + for (0..len) |i| { + const rev_i = len - i - 1; + const cells = rows[rev_i].cells.ptr(page.data.memory)[0..page.data.size.cols]; + + // If the row has any text then we're done. + if (pagepkg.Cell.hasTextAny(cells)) return count; + + // Inc count, if we're beyond max then we're done. + count += 1; + if (count >= max) return count; + } + } + + return count; +} + +/// Trims up to max trailing blank rows from the pagelist and returns the +/// number of rows trimmed. A blank row is any row with no text (but may +/// have styling). +/// +/// IMPORTANT: This function does NOT update `total_rows`. It returns the +/// number of rows trimmed, and the caller is responsible for decrementing +/// `total_rows` by this amount. +fn trimTrailingBlankRows( + self: *PageList, + max: size.CellCountInt, +) size.CellCountInt { + var trimmed: size.CellCountInt = 0; + const bl_pin = self.getBottomRight(.screen).?; + var it = bl_pin.rowIterator(.left_up, null); + while (it.next()) |row_pin| { + const cells = row_pin.cells(.all); + + // If the row has any text then we're done. + if (pagepkg.Cell.hasTextAny(cells)) return trimmed; + + // If our tracked pins are in this row then we cannot trim it + // because it implies some sort of importance. If we trimmed this + // we'd invalidate this pin, as well. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != row_pin.node or + p.y != row_pin.y) continue; + return trimmed; + } + + // No text, we can trim this row. Because it has + // no text we can also be sure it has no styling + // so we don't need to worry about memory. + row_pin.node.data.size.rows -= 1; + if (row_pin.node.data.size.rows == 0) { + self.erasePage(row_pin.node); + } else { + row_pin.node.data.assertIntegrity(); + } + + trimmed += 1; + if (trimmed >= max) return trimmed; + } + + return trimmed; +} + +/// Scroll options. +pub const Scroll = union(enum) { + /// Scroll to the active area. This is also sometimes referred to as + /// the "bottom" of the screen. This makes it so that the end of the + /// screen is fully visible since the active area is the bottom + /// rows/cols of the screen. + active, + + /// Scroll to the top of the screen, which is the farthest back in + /// the scrollback history. + top, + + /// Scroll to the given absolute row from the top. A value of zero + /// is the top row. This row will be the first visible row in the viewport. + /// Scrolling into or below the active area will clamp to the active area. + row: usize, + + /// Scroll up (negative) or down (positive) by the given number of + /// rows. This is clamped to the "top" and "active" top left. + delta_row: isize, + + /// Jump forwards (positive) or backwards (negative) a set number of + /// prompts. If the absolute value is greater than the number of prompts + /// in either direction, jump to the furthest prompt in that direction. + delta_prompt: isize, + + /// Scroll directly to a specific pin in the page. This will be set + /// as the top left of the viewport (ignoring the pin x value). + pin: Pin, +}; + +/// Scroll the viewport. This will never create new scrollback, allocate +/// pages, etc. This can only be used to move the viewport within the +/// previously allocated pages. +pub fn scroll(self: *PageList, behavior: Scroll) void { + defer self.assertIntegrity(); + + // Special case no-scrollback mode to never allow scrolling. + if (self.explicit_max_size == 0) { + self.viewport = .active; + return; + } + + switch (behavior) { + .active => self.viewport = .active, + .top => self.viewport = .top, + .pin => |p| { + if (self.pinIsActive(p)) { + self.viewport = .active; + return; + } else if (self.pinIsTop(p)) { + self.viewport = .top; + return; + } + + self.viewport_pin.* = p; + self.viewport = .pin; + self.viewport_pin_row_offset = null; // invalidate cache + }, + .row => |n| row: { + // If we're at the top, pin the top. + if (n == 0) { + self.viewport = .top; + break :row; + } + + // If we're below the top of the active area, pin the active area. + if (n >= self.total_rows - self.rows) { + self.viewport = .active; + break :row; + } + + // See if there are any other faster paths we can take. + switch (self.viewport) { + .top, .active => {}, + .pin => if (self.viewport_pin_row_offset) |*v| { + // If we have a pin and we already calculated a row offset, + // then we can efficiently calculate the delta and move + // that much from that pin. + const delta: isize = delta: { + const n_isize: isize = @intCast(n); + const v_isize: isize = @intCast(v.*); + break :delta n_isize - v_isize; + }; + self.scroll(.{ .delta_row = delta }); + return; + }, + } + + // We have an accurate row offset so store it to prevent + // calculating this again. + self.viewport_pin_row_offset = n; + self.viewport = .pin; + + // Slow path, we've just got to traverse the linked list and + // get to our row. As a slight speedup, let's pick the traversal + // that's likely faster based on our absolute row and total rows. + const midpoint = self.total_rows / 2; + if (n < midpoint) { + // Iterate forward from the first node. + var node_it = self.pages.first; + var rem: size.CellCountInt = std.math.cast( + size.CellCountInt, + n, + ) orelse { + self.viewport = .active; + break :row; + }; + while (node_it) |node| : (node_it = node.next) { + if (rem < node.data.size.rows) { + self.viewport_pin.* = .{ + .node = node, + .y = rem, + }; + break :row; + } + + rem -= node.data.size.rows; + } + } else { + // Iterate backwards from the last node. + var node_it = self.pages.last; + var rem: size.CellCountInt = std.math.cast( + size.CellCountInt, + self.total_rows - n, + ) orelse { + self.viewport = .active; + break :row; + }; + while (node_it) |node| : (node_it = node.prev) { + if (rem <= node.data.size.rows) { + self.viewport_pin.* = .{ + .node = node, + .y = node.data.size.rows - rem, + }; + break :row; + } + + rem -= node.data.size.rows; + } + } + + // If we reached here, then we couldn't find the offset. + // This feels impossible? Just clamp to active, screw it lol. + self.viewport = .active; + }, + .delta_prompt => |n| self.scrollPrompt(n), + .delta_row => |n| delta_row: { + switch (self.viewport) { + // If we're at the top and we're scrolling backwards, + // we don't have to do anything, because there's nowhere to go. + .top => if (n <= 0) break :delta_row, + + // If we're at active and we're scrolling forwards, we don't + // have to do anything because it'll result in staying in + // the active. + .active => if (n >= 0) break :delta_row, + + // If we're already a pin type, then we can fast-path our + // delta by simply moving the pin. This has the added benefit + // that we can update our row offset cache efficiently, too. + .pin => switch (std.math.order(n, 0)) { + .eq => break :delta_row, + + .lt => switch (self.viewport_pin.upOverflow(@intCast(-n))) { + .offset => |new_pin| { + self.viewport_pin.* = new_pin; + if (self.viewport_pin_row_offset) |*v| { + v.* -= @as(usize, @intCast(-n)); + } + break :delta_row; + }, + + // If we overflow up we're at the top. + .overflow => { + self.viewport = .top; + break :delta_row; + }, + }, + + .gt => switch (self.viewport_pin.downOverflow(@intCast(n))) { + // If we offset its a valid pin but we still have to + // check if we're in the active area. + .offset => |new_pin| { + if (self.pinIsActive(new_pin)) { + self.viewport = .active; + } else { + self.viewport_pin.* = new_pin; + if (self.viewport_pin_row_offset) |*v| { + v.* += @intCast(n); + } + } + break :delta_row; + }, + + // If we overflow down we're at active. + .overflow => { + self.viewport = .active; + break :delta_row; + }, + }, + }, + } + + // Slow path: we have to calculate the new pin by moving + // from our viewport. + const top = self.getTopLeft(.viewport); + const p: Pin = if (n < 0) switch (top.upOverflow(@intCast(-n))) { + .offset => |v| v, + .overflow => |v| v.end, + } else switch (top.downOverflow(@intCast(n))) { + .offset => |v| v, + .overflow => |v| v.end, + }; + + // If we are still within the active area, then we pin the + // viewport to active. This isn't EXACTLY the same behavior as + // other scrolling because normally when you scroll the viewport + // is pinned to _that row_ even if new scrollback is created. + // But in a terminal when you get to the bottom and back into the + // active area, you usually expect that the viewport will now + // follow the active area. + if (self.pinIsActive(p)) { + self.viewport = .active; + return; + } + + // If we're at the top, then just set the top. This is a lot + // more efficient everywhere. We must check this after the + // active check above because we prefer active if they overlap. + if (self.pinIsTop(p)) { + self.viewport = .top; + return; + } + + // Pin is not active so we need to track it. + self.viewport_pin.* = p; + self.viewport = .pin; + self.viewport_pin_row_offset = null; // invalidate cache + }, + } +} + +/// Jump the viewport forwards (positive) or backwards (negative) a set number of +/// prompts (delta). +fn scrollPrompt(self: *PageList, delta: isize) void { + // If we aren't jumping any prompts then we don't need to do anything. + if (delta == 0) return; + const delta_start: usize = @intCast(if (delta > 0) delta else -delta); + var delta_rem: usize = delta_start; + + // We start at the row before or after our viewport depending on the + // delta so that we don't land back on our current viewport. + const start_pin = start: { + const tl = self.getTopLeft(.viewport); + + // If we're moving up we can just move the viewport up because + // promptIterator handles jumpting to the start of prompts. + if (delta <= 0) break :start tl.up(1) orelse return; + + // If we're moving down and we're presently at some kind of + // prompt, we need to skip all the continuation lines because + // promptIterator can't know if we're cutoff or continuing. + var adjusted: Pin = tl.down(1) orelse return; + if (tl.rowAndCell().row.semantic_prompt != .none) skip: { + while (adjusted.rowAndCell().row.semantic_prompt == .prompt_continuation) { + adjusted = adjusted.down(1) orelse break :skip; + } + } + + break :start adjusted; + }; + + // Go through prompts delta times + var it = start_pin.promptIterator( + if (delta > 0) .right_down else .left_up, + null, + ); + var prompt_pin: ?Pin = null; + while (it.next()) |next| { + prompt_pin = next; + delta_rem -= 1; + if (delta_rem == 0) break; + } + + // If we found a prompt, we move to it. If the prompt is in the active + // area we keep our viewport as active because we can't scroll DOWN + // into the active area. Otherwise, we scroll up to the pin. + if (prompt_pin) |p| { + if (self.pinIsActive(p)) { + self.viewport = .active; + } else { + self.viewport_pin.* = p; + self.viewport = .pin; + self.viewport_pin_row_offset = null; // invalidate cache + } + } +} + +/// Clear the screen by scrolling written contents up into the scrollback. +/// This will not update the viewport. +pub fn scrollClear(self: *PageList) Allocator.Error!void { + defer self.assertIntegrity(); + + // Go through the active area backwards to find the first non-empty + // row. We use this to determine how many rows to scroll up. + const non_empty: usize = non_empty: { + var page = self.pages.last.?; + var n: usize = 0; + while (true) { + const rows: [*]Row = page.data.rows.ptr(page.data.memory); + for (0..page.data.size.rows) |i| { + const rev_i = page.data.size.rows - i - 1; + const row = rows[rev_i]; + const cells = row.cells.ptr(page.data.memory)[0..self.cols]; + for (cells) |cell| { + if (!cell.isEmpty()) break :non_empty self.rows - n; + } + + n += 1; + if (n > self.rows) break :non_empty 0; + } + + page = page.prev orelse break :non_empty 0; + } + }; + + // Scroll + for (0..non_empty) |_| _ = try self.grow(); +} + +/// Compact a page to use the minimum required memory for the contents +/// it stores. Returns the new node pointer if compaction occurred, or null +/// if the page was already compact or compaction would not provide meaningful +/// savings. +/// +/// The current design of PageList at the time of writing this doesn't +/// allow for smaller than `std_size` nodes so if the current node's backing +/// page is standard size or smaller, no compaction will occur. In the +/// future we should fix this up. +/// +/// If this returns OOM, the PageList is left unchanged and no dangling +/// memory references exist. It is safe to ignore the error and continue using +/// the uncompacted page. +pub fn compact(self: *PageList, node: *List.Node) Allocator.Error!?*List.Node { + defer self.assertIntegrity(); + const page: *Page = &node.data; + + // We should never have empty rows in our pagelist anyways... + assert(page.size.rows > 0); + + // We never compact standard size or smaller pages because changing + // the capacity to something smaller won't save memory. + if (page.memory.len <= std_size) return null; + + // Compute the minimum capacity required for this page's content + const req_cap = page.exactRowCapacity(0, page.size.rows); + const new_size = Page.layout(req_cap).total_size; + const old_size = page.memory.len; + if (new_size >= old_size) return null; + + // Create the new smaller page + const new_node = try self.createPage(req_cap); + errdefer self.destroyNode(new_node); + const new_page: *Page = &new_node.data; + new_page.size = page.size; + new_page.dirty = page.dirty; + new_page.cloneFrom( + page, + 0, + page.size.rows, + ) catch |err| { + // cloneFrom should not fail when compacting since req_cap is + // computed to exactly fit the source content and our expectation + // of exactRowCapacity ensures it can fit all the requested + // data. + log.err("compact clone failed err={}", .{err}); + + // In this case, let's gracefully degrade by pretending we + // didn't need to compact. + self.destroyNode(new_node); + return null; + }; + + // Fix up all tracked pins to point to the new page + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != node) continue; + p.node = new_node; + } + + // Insert the new page and destroy the old one + self.pages.insertBefore(node, new_node); + self.pages.remove(node); + self.destroyNode(node); + + new_page.assertIntegrity(); + return new_node; +} + +pub const SplitError = error{ + // Allocator OOM + OutOfMemory, + // Page can't be split further because it is already a single row. + OutOfSpace, +}; + +/// Split the given node in the PageList at the given pin. +/// +/// The row at the pin and after will be moved into a new page with +/// the same capacity as the original page. Alternatively, you can "split +/// above" by splitting the row following the desired split row. +/// +/// Since the split happens below the pin, the pin remains valid. +pub fn split( + self: *PageList, + p: Pin, +) SplitError!void { + if (build_options.slow_runtime_safety) assert(self.pinIsValid(p)); + + // Ran into a bug that I can only explain via aliasing. If a tracked + // pin is passed in, its possible Zig will alias the memory and then + // when we modify it later it updates our p here. Copying the node + // fixes this. + const original_node = p.node; + const page: *Page = &original_node.data; + + // A page that is already 1 row can't be split. In the future we can + // theoretically maybe split by soft-wrapping multiple pages but that + // seems crazy and the rest of our PageList can't handle heterogeneously + // sized pages today. + if (page.size.rows <= 1) return error.OutOfSpace; + + // Splitting at row 0 is a no-op since there's nothing before the split point. + if (p.y == 0) return; + + // At this point we're doing actual modification so make sure + // on the return that we're good. + defer self.assertIntegrity(); + + // Create a new node with the same capacity of managed memory. + const target = try self.createPage(page.capacity); + errdefer self.destroyNode(target); + + // Determine how many rows we're copying + const y_start = p.y; + const y_end = page.size.rows; + target.data.size.rows = y_end - y_start; + assert(target.data.size.rows <= target.data.capacity.rows); + + // Copy our old data. This should NOT fail because we have the + // capacity of the old page which already fits the data we requested. + target.data.cloneFrom(page, y_start, y_end) catch |err| { + log.err( + "error cloning rows for split err={}", + .{err}, + ); + + // Rather than crash, we return an OutOfSpace to show that + // we couldn't split and let our callers gracefully handle it. + // Realistically though... this should not happen. + return error.OutOfSpace; + }; + + // From this point forward there is no going back. We have no + // error handling. It is possible but we haven't written it. + errdefer comptime unreachable; + + // Move any tracked pins from the copied rows + for (self.tracked_pins.keys()) |tracked| { + if (&tracked.node.data != page or + tracked.y < p.y) continue; + + tracked.node = target; + tracked.y -= p.y; + // p.x remains the same since we're copying the row as-is + } + + // Clear our rows + for (page.rows.ptr(page.memory)[y_start..y_end]) |*row| { + page.clearCells( + row, + 0, + page.size.cols, + ); + } + page.size.rows -= y_end - y_start; + + self.pages.insertAfter(original_node, target); +} + +/// This represents the state necessary to render a scrollbar for this +/// PageList. It has the total size, the offset, and the size of the viewport. +pub const Scrollbar = struct { + /// Total size of the scrollable area. + total: usize, + + /// The offset into the total area that the viewport is at. This is + /// guaranteed to be less than or equal to total. This includes the + /// visible row. + offset: usize, + + /// The length of the visible area. This is including the offset row. + len: usize, + + /// A zero-sized scrollable region. + pub const zero: Scrollbar = .{ + .total = 0, + .offset = 0, + .len = 0, + }; + + // Sync with: ghostty_action_scrollbar_s + pub const C = extern struct { + total: u64, + offset: u64, + len: u64, + }; + + pub fn cval(self: Scrollbar) C { + return .{ + .total = @intCast(self.total), + .offset = @intCast(self.offset), + .len = @intCast(self.len), + }; + } + + /// Comparison for scrollbars. + pub fn eql(self: Scrollbar, other: Scrollbar) bool { + return self.total == other.total and + self.offset == other.offset and + self.len == other.len; + } +}; + +/// Return the scrollbar state for this PageList. +/// +/// This may be expensive to calculate depending on where the viewport +/// is (arbitrary pins are expensive). The caller should take care to only +/// call this as needed and not too frequently. +pub fn scrollbar(self: *PageList) Scrollbar { + // If we have no scrollback, special case no scrollbar. + // We need to do this because the way PageList works is that + // it always has SOME extra space (due to the way we allocate by page). + // So even with no scrollback we have some growth. It is architecturally + // much simpler to just hide that for no-scrollback cases. + if (self.explicit_max_size == 0) return .{ + .total = self.rows, + .offset = 0, + .len = self.rows, + }; + + return .{ + .total = self.total_rows, + .offset = self.viewportRowOffset(), + .len = self.rows, // Length is always rows + }; +} + +/// Returns the offset of the current viewport from the top of the +/// screen. +/// +/// This is potentially expensive to calculate because if the viewport +/// is a pin and the pin is near the beginning of the scrollback, we +/// will traverse a lot of linked list nodes. +/// +/// The result is cached so repeated calls are cheap. +fn viewportRowOffset(self: *PageList) usize { + return switch (self.viewport) { + .top => 0, + .active => self.total_rows - self.rows, + .pin => pin: { + // We assert integrity on this code path because it verifies + // that the cached value is correct. + defer self.assertIntegrity(); + + // Return cached value if available + if (self.viewport_pin_row_offset) |cached| break :pin cached; + + // Traverse from the end and count rows until we reach the + // viewport pin. We count backwards because most of the time + // a user is scrolling near the active area. + const top_offset: usize = offset: { + var offset: usize = 0; + var node = self.pages.last; + while (node) |n| : (node = n.prev) { + offset += n.data.size.rows; + if (n == self.viewport_pin.node) { + assert(n.data.size.rows > self.viewport_pin.y); + offset -= self.viewport_pin.y; + break :offset self.total_rows - offset; + } + } + + // Invalid pins are not possible. + unreachable; + }; + + // The offset is from the bottom and our cached value and this + // function returns from the top, so we need to invert it. + self.viewport_pin_row_offset = top_offset; + break :pin top_offset; + }, + }; +} + +/// This fixes up the viewport data when rows are removed from the +/// PageList. This will update a viewport to `active` if row removal +/// puts the viewport into the active area, to `top` if the viewport +/// is now at row 0, and updates any row offset caches as necessary. +/// +/// This is unit tested transitively through other tests such as +/// eraseRows. +fn fixupViewport( + self: *PageList, + removed: usize, +) void { + switch (self.viewport) { + .active => {}, + + // For pin, we check if our pin is now in the active area and if so + // we move our viewport back to the active area. + .pin => if (self.pinIsActive(self.viewport_pin.*)) { + self.viewport = .active; + } else if (self.viewport_pin_row_offset) |*v| { + // If we have a cached row offset, we need to update it + // to account for the erased rows. + if (v.* < removed) { + self.viewport = .top; + } else { + v.* -= removed; + } + }, + + // For top, we move back to active if our erasing moved our + // top page into the active area. + .top => if (self.pinIsActive(.{ .node = self.pages.first.? })) { + self.viewport = .active; + }, + } +} + +/// Returns the actual max size. This may be greater than the explicit +/// value if the explicit value is less than the min_max_size. +/// +/// This value is a HEURISTIC. You cannot assert on this value. We may +/// exceed this value if required to fit the active area. This may be +/// required in some cases if the active area has a large number of +/// graphemes, styles, etc. +pub fn maxSize(self: *const PageList) usize { + return @max(self.explicit_max_size, self.min_max_size); +} + +/// Grow the active area by exactly one row. +/// +/// This may allocate, but also may not if our current page has more +/// capacity we can use. This will prune scrollback if necessary to +/// adhere to max_size. +/// +/// This returns the newly allocated page node if there is one. +pub fn grow(self: *PageList) Allocator.Error!?*List.Node { + defer self.assertIntegrity(); + + const last = self.pages.last.?; + if (last.data.capacity.rows > last.data.size.rows) { + // Fast path: we have capacity in the last page. + last.data.size.rows += 1; + last.data.assertIntegrity(); + + // Increase our total rows by one + self.total_rows += 1; + + return null; + } + + // Slower path: we have no space, we need to allocate a new page. + + // Get the layout first so our failable work is done early. + // We'll need this for both paths. + const cap = initialCapacity(self.cols); + + // If allocation would exceed our max size, we prune the first page. + // We don't need to reallocate because we can simply reuse that first + // page. + // + // We only take this path if we have more than one page since pruning + // reuses the popped page. It is possible to have a single page and + // exceed the max size if that page was adjusted to be larger after + // initial allocation. + if (self.pages.first != null and + self.pages.first != self.pages.last and + self.page_size + PagePool.item_size > self.maxSize()) + prune: { + const first = self.pages.popFirst().?; + assert(first != last); + + // Decrease our total row count from the pruned page + self.total_rows -= first.data.size.rows; + + // If our total row count is now less than our required + // rows then we can't prune. The "+ 1" is because we'll add one + // more row below. + if (self.total_rows + 1 < self.rows) { + self.pages.prepend(first); + assert(self.pages.first == first); + self.total_rows += first.data.size.rows; + break :prune; + } + + // If we have a pin viewport cache then we need to update it. + if (self.viewport == .pin) viewport: { + if (self.viewport_pin_row_offset) |*v| { + // If our offset is less than the number of rows in the + // pruned page, then we are now at the top. + if (v.* < first.data.size.rows) { + self.viewport = .top; + break :viewport; + } + + // Otherwise, our viewport pin is below what we pruned + // so we just decrement our offset. + v.* -= first.data.size.rows; + } + } + + // Update any tracked pins that point to this page to point to the + // new first page to the top-left, and mark them as garbage. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != first) continue; + p.node = self.pages.first.?; + p.y = 0; + p.x = 0; + p.garbage = true; + } + self.viewport_pin.garbage = false; + + // Non-standard pages can't be reused, just destroy them. + if (first.data.memory.len > std_size) { + self.destroyNode(first); + break :prune; + } + + // Reset our memory + const buf = first.data.memory; + @memset(buf, 0); + assert(buf.len <= std_size); + + // Initialize our new page and reinsert it as the last + first.data = .initBuf(.init(buf), Page.layout(cap)); + first.data.size.rows = 1; + self.pages.insertAfter(last, first); + self.total_rows += 1; + + // We also need to reset the serial number. Since this is the only + // place we ever reuse a serial number, we also can safely set + // page_serial_min to be one more than the old serial because we + // only ever prune the oldest pages. + self.page_serial_min = first.serial + 1; + first.serial = self.page_serial; + self.page_serial += 1; + + // In this case we do NOT need to update page_size because + // we're reusing an existing page so nothing has changed. + + first.data.assertIntegrity(); + return first; + } + + // We need to allocate a new memory buffer. + const next_node = try self.createPage(cap); + // we don't errdefer this because we've added it to the linked + // list and its fine to have dangling unused pages. + self.pages.append(next_node); + next_node.data.size.rows = 1; + + // We should never be more than our max size here because we've + // verified the case above. + next_node.data.assertIntegrity(); + + // Record the increased row count + self.total_rows += 1; + + return next_node; +} + +/// Possible dimensions to increase capacity for. +pub const IncreaseCapacity = enum { + styles, + grapheme_bytes, + hyperlink_bytes, + string_bytes, +}; + +pub const IncreaseCapacityError = error{ + // An actual system OOM trying to allocate memory. + OutOfMemory, + + // The existing page is already at max capacity for the given + // adjustment. The caller must create a new page, remove data from + // the old page, etc. (up to the caller). + OutOfSpace, +}; + +/// Increase the capacity of the given page node in the given direction. +/// This will always allocate a new node and remove the old node, so the +/// existing node pointer will be invalid after this call. The newly created +/// node on success is returned. +/// +/// The increase amount is at the control of the PageList implementation, +/// but is guaranteed to always increase by at least one unit in the +/// given dimension. Practically, we'll always increase by much more +/// (we currently double every time) but callers shouldn't depend on that. +/// The only guarantee is some amount of growth. +/// +/// Adjustment can be null if you want to recreate, reclone the page +/// with the same capacity. This is a special case used for rehashing since +/// the logic is otherwise the same. In this case, OutOfMemory is the +/// only possible error. +pub fn increaseCapacity( + self: *PageList, + node: *List.Node, + adjustment: ?IncreaseCapacity, +) IncreaseCapacityError!*List.Node { + defer self.assertIntegrity(); + const page: *Page = &node.data; + + // Apply our adjustment + var cap = page.capacity; + if (adjustment) |v| switch (v) { + inline else => |tag| { + const field_name = @tagName(tag); + const Int = @FieldType(Capacity, field_name); + const old = @field(cap, field_name); + + // We use checked math to prevent overflow. If there is an + // overflow it means we're out of space in this dimension, + // since pages can take up to their maxInt capacity in any + // category. + const new = std.math.mul( + Int, + old, + 2, + ) catch |err| overflow: { + comptime assert(@TypeOf(err) == error{Overflow}); + // Our final doubling would overflow since maxInt is + // 2^N - 1 for an unsignged int of N bits. So, if we overflow + // and we haven't used all the bits, use all the bits. + if (old < std.math.maxInt(Int)) break :overflow std.math.maxInt(Int); + return error.OutOfSpace; + }; + @field(cap, field_name) = new; + + // If our capacity exceeds the maximum page size, treat it + // as an OutOfSpace because things like page splitting will + // help. + const layout = Page.layout(cap); + if (layout.total_size > size.max_page_size) { + return error.OutOfSpace; + } + }, + }; + + log.info("adjusting page capacity={}", .{cap}); + + // Create our new page and clone the old page into it. + const new_node = try self.createPage(cap); + errdefer self.destroyNode(new_node); + const new_page: *Page = &new_node.data; + assert(new_page.capacity.rows >= page.capacity.rows); + assert(new_page.capacity.cols >= page.capacity.cols); + new_page.size.rows = page.size.rows; + new_page.size.cols = page.size.cols; + new_page.cloneFrom( + page, + 0, + page.size.rows, + ) catch |err| { + // cloneFrom only errors if there isn't capacity for the data + // from the source page but we're only increasing capacity so + // this should never be possible. If it happens, we should crash + // because we're in no man's land and can't safely recover. + log.err("increaseCapacity clone failed err={}", .{err}); + @panic("unexpected clone failure"); + }; + + // Preserve page-level dirty flag (cloneFrom only copies row data) + new_page.dirty = page.dirty; + + // Must not fail after this because the operations we do after this + // can't be recovered. + errdefer comptime unreachable; + + // Fix up all our tracked pins to point to the new page. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != node) continue; + p.node = new_node; + } + + // Insert this page and destroy the old page + self.pages.insertBefore(node, new_node); + self.pages.remove(node); + self.destroyNode(node); + + new_page.assertIntegrity(); + return new_node; +} + +/// Create a new page node. This does not add it to the list and this +/// does not do any memory size accounting with max_size/page_size. +inline fn createPage( + self: *PageList, + cap: Capacity, +) Allocator.Error!*List.Node { + // log.debug("create page cap={}", .{cap}); + return try createPageExt( + &self.pool, + cap, + &self.page_serial, + &self.page_size, + ); +} + +inline fn createPageExt( + pool: *MemoryPool, + cap: Capacity, + serial: *u64, + total_size: ?*usize, +) Allocator.Error!*List.Node { + var page = try pool.nodes.create(); + errdefer pool.nodes.destroy(page); + + const layout = Page.layout(cap); + const pooled = layout.total_size <= std_size; + const page_alloc = pool.pages.arena.child_allocator; + + // It would be better to encode this into the Zig error handling + // system but that is a big undertaking and we only have a few + // centralized call sites so it is handled on its own currently. + assert(layout.total_size <= size.max_page_size); + + // Our page buffer comes from our standard memory pool if it + // is within our standard size since this is what the pool + // dispenses. Otherwise, we use the heap allocator to allocate. + const page_buf = if (pooled) + try pool.pages.create() + else + try page_alloc.alignedAlloc( + u8, + .fromByteUnits(std.heap.page_size_min), + layout.total_size, + ); + errdefer if (pooled) + pool.pages.destroy(page_buf) + else + page_alloc.free(page_buf); + + // In runtime safety modes, allocators fill with 0xAA. On freestanding + // (WASM), the WasmAllocator reuses freed slots without zeroing. + if (comptime std.debug.runtime_safety or builtin.os.tag == .freestanding) + @memset(page_buf, 0); + + page.* = .{ + .data = .initBuf(.init(page_buf), layout), + .serial = serial.*, + }; + page.data.size.rows = 0; + serial.* += 1; + + if (total_size) |v| { + // Accumulate page size now. We don't assert or check max size + // because we may exceed it here temporarily as we are allocating + // pages before destroy. + v.* += page_buf.len; + } + + return page; +} + +/// Destroy the memory of the given node in the PageList linked list +/// and return it to the pool. The node is assumed to already be removed +/// from the linked list. +/// +/// IMPORTANT: This function does NOT update `total_rows`. The caller is +/// responsible for accounting for the removed rows. This function only +/// updates `page_size` (byte accounting), not row accounting. +fn destroyNode(self: *PageList, node: *List.Node) void { + destroyNodeExt(&self.pool, node, &self.page_size); +} + +fn destroyNodeExt( + pool: *MemoryPool, + node: *List.Node, + total_size: ?*usize, +) void { + const page: *Page = &node.data; + + // Update our accounting for page size + if (total_size) |v| v.* -= page.memory.len; + + if (page.memory.len <= std_size) { + // Reset the memory to zero so it can be reused + @memset(page.memory, 0); + pool.pages.destroy(@ptrCast(page.memory.ptr)); + } else { + const page_alloc = pool.pages.arena.child_allocator; + page_alloc.free(page.memory); + } + + pool.nodes.destroy(node); +} + +/// Fast-path function to erase exactly 1 row. Erasing means that the row +/// is completely REMOVED, not just cleared. All rows following the removed +/// row will be shifted up by 1 to fill the empty space. +/// +/// Unlike eraseRows, eraseRow does not change the size of any pages. The +/// caller is responsible for adjusting the row count of the final page if +/// that behavior is required. +pub fn eraseRow( + self: *PageList, + pt: point.Point, +) !void { + defer self.assertIntegrity(); + const pn = self.pin(pt).?; + + var node = pn.node; + var rows = node.data.rows.ptr(node.data.memory.ptr); + + // In order to move the following rows up we rotate the rows array by 1. + // The rotate operation turns e.g. [ 0 1 2 3 ] in to [ 1 2 3 0 ], which + // works perfectly to move all of our elements where they belong. + fastmem.rotateOnce(Row, rows[pn.y..node.data.size.rows]); + + // We adjust the tracked pins in this page, moving up any that were below + // the removed row. + { + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node == node and p.y > pn.y) p.y -= 1; + } + } + + // If we have a pinned viewport, we need to adjust for active area. + self.fixupViewport(1); + + // Mark the whole page as dirty. + // + // Technically we only need to mark rows from the erased row to the end + // of the page as dirty, but that's slower and this is a hot function. + node.data.dirty = true; + + // We iterate through all of the following pages in order to move their + // rows up by 1 as well. + while (node.next) |next| { + const next_rows = next.data.rows.ptr(next.data.memory.ptr); + + // We take the top row of the page and clone it in to the bottom + // row of the previous page, which gets rid of the top row that was + // rotated down in the previous page, and accounts for the row in + // this page that will be rotated down as well. + // + // rotate -> clone --> rotate -> result + // 0 -. 1 1 1 + // 1 | 2 2 2 + // 2 | 3 3 3 + // 3 <' 0 <. 4 4 + // --- --- | --- --- <- page boundary + // 4 4 -' 4 -. 5 + // 5 5 5 | 6 + // 6 6 6 | 7 + // 7 7 7 <' 4 + try node.data.cloneRowFrom( + &next.data, + &rows[node.data.size.rows - 1], + &next_rows[0], + ); + + node = next; + rows = next_rows; + + fastmem.rotateOnce(Row, rows[0..node.data.size.rows]); + + // Mark the whole page as dirty. + node.data.dirty = true; + + // Our tracked pins for this page need to be updated. + // If the pin is in row 0 that means the corresponding row has + // been moved to the previous page. Otherwise, move it up by 1. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != node) continue; + if (p.y == 0) { + p.node = node.prev.?; + p.y = p.node.data.size.rows - 1; + continue; + } + p.y -= 1; + } + } + + // Clear the final row which was rotated from the top of the page. + node.data.clearCells(&rows[node.data.size.rows - 1], 0, node.data.size.cols); +} + +/// A variant of eraseRow that shifts only a bounded number of following +/// rows up, filling the space they leave behind with blank rows. +/// +/// `limit` is exclusive of the erased row. A limit of 1 will erase the target +/// row and shift the row below in to its position, leaving a blank row below. +pub fn eraseRowBounded( + self: *PageList, + pt: point.Point, + limit: usize, +) !void { + defer self.assertIntegrity(); + + // This function has a lot of repeated code in it because it is a hot path. + // + // To get a better idea of what's happening, read eraseRow first for more + // in-depth explanatory comments. To avoid repetition, the only comments for + // this function are for where it differs from eraseRow. + + const pn = self.pin(pt).?; + + var node: *List.Node = pn.node; + var rows = node.data.rows.ptr(node.data.memory.ptr); + + // If the row limit is less than the remaining rows before the end of the + // page, then we clear the row, rotate it to the end of the boundary limit + // and update our pins. + if (node.data.size.rows - pn.y > limit) { + node.data.clearCells(&rows[pn.y], 0, node.data.size.cols); + fastmem.rotateOnce(Row, rows[pn.y..][0 .. limit + 1]); + + // Mark the whole page as dirty. + // + // Technically we only need to mark from the erased row to the + // limit but this is a hot function, so we want to minimize work. + node.data.dirty = true; + + // If our viewport is a pin and our pin is within the erased + // region we need to maybe shift our cache up. We do this here instead + // of in the pin loop below because its unlikely to be true and we + // don't want to run the conditional N times. + if (self.viewport == .pin) viewport: { + if (self.viewport_pin_row_offset) |*v| { + const p = self.viewport_pin; + if (p.node != node or + p.y < pn.y or + p.y > pn.y + limit or + p.y == 0) break :viewport; + v.* -= 1; + } + } + + // Update pins in the shifted region. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node == node and + p.y >= pn.y and + p.y <= pn.y + limit) + { + if (p.y == 0) { + p.x = 0; + } else { + p.y -= 1; + } + } + } + + return; + } + + fastmem.rotateOnce(Row, rows[pn.y..node.data.size.rows]); + + // Mark the whole page as dirty. + // + // Technically we only need to mark rows from the erased row to the end + // of the page as dirty, but that's slower and this is a hot function. + node.data.dirty = true; + + // We need to keep track of how many rows we've shifted so that we can + // determine at what point we need to do a partial shift on subsequent + // pages. + var shifted: usize = node.data.size.rows - pn.y; + + // Update tracked pins. + { + // See the other places we do something similar in this function + // for a detailed explanation. + if (self.viewport == .pin) viewport: { + if (self.viewport_pin_row_offset) |*v| { + const p = self.viewport_pin; + if (p.node != node or + p.y < pn.y or + p.y == 0) break :viewport; + v.* -= 1; + } + } + + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node == node and p.y >= pn.y) { + if (p.y == 0) { + p.x = 0; + } else { + p.y -= 1; + } + } + } + } + + while (node.next) |next| { + const next_rows = next.data.rows.ptr(next.data.memory.ptr); + + try node.data.cloneRowFrom( + &next.data, + &rows[node.data.size.rows - 1], + &next_rows[0], + ); + + node = next; + rows = next_rows; + + // We check to see if this page contains enough rows to satisfy the + // specified limit, accounting for rows we've already shifted in prior + // pages. + // + // The logic here is very similar to the one before the loop. + const shifted_limit = limit - shifted; + if (node.data.size.rows > shifted_limit) { + node.data.clearCells(&rows[0], 0, node.data.size.cols); + fastmem.rotateOnce(Row, rows[0 .. shifted_limit + 1]); + + // Mark the whole page as dirty. + // + // Technically we only need to mark from the erased row to the + // limit but this is a hot function, so we want to minimize work. + node.data.dirty = true; + + // See the other places we do something similar in this function + // for a detailed explanation. + if (self.viewport == .pin) viewport: { + if (self.viewport_pin_row_offset) |*v| { + const p = self.viewport_pin; + if (p.node != node or + p.y > shifted_limit) break :viewport; + v.* -= 1; + } + } + + // Update pins in the shifted region. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != node or p.y > shifted_limit) continue; + if (p.y == 0) { + p.node = node.prev.?; + p.y = p.node.data.size.rows - 1; + continue; + } + p.y -= 1; + } + + return; + } + + fastmem.rotateOnce(Row, rows[0..node.data.size.rows]); + + // Mark the whole page as dirty. + node.data.dirty = true; + + // Account for the rows shifted in this node. + shifted += node.data.size.rows; + + // See the other places we do something similar in this function + // for a detailed explanation. + if (self.viewport == .pin) viewport: { + if (self.viewport_pin_row_offset) |*v| { + const p = self.viewport_pin; + if (p.node != node) break :viewport; + v.* -= 1; + } + } + + // Update tracked pins. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != node) continue; + if (p.y == 0) { + p.node = node.prev.?; + p.y = p.node.data.size.rows - 1; + continue; + } + p.y -= 1; + } + } + + // We reached the end of the page list before the limit, so we clear + // the final row since it was rotated down from the top of this page. + node.data.clearCells(&rows[node.data.size.rows - 1], 0, node.data.size.cols); +} + +/// Erase all history rows, optionally up to a bottom-left bound. +/// This always starts from the beginning of the history area. +pub fn eraseHistory( + self: *PageList, + bl_pt: ?point.Point, +) void { + self.eraseRows(.{ .history = .{} }, bl_pt); +} + +/// Erase active area rows, from the top of the active area to the +/// given row (inclusive). +pub fn eraseActive( + self: *PageList, + y: size.CellCountInt, +) void { + assert(y < self.rows); + self.eraseRows(.{ .active = .{} }, .{ .active = .{ .y = y } }); +} + +/// Erase rows from tl_pt to bl_pt (inclusive), physically removing +/// them rather than just clearing their contents. If a point falls +/// in the middle of a page, remaining rows in that page are shifted +/// and the page becomes underutilized (size < capacity). +/// +/// Callers must ensure that the erased range only removes pages from +/// the front or back of the linked list, never the middle. Middle-page +/// erasure would create serial gaps that page_serial_min cannot +/// represent, leaving dangling references in consumers such as search. +/// Use the public eraseHistory/eraseActive wrappers which enforce this. +fn eraseRows( + self: *PageList, + tl_pt: point.Point, + bl_pt: ?point.Point, +) void { + defer self.assertIntegrity(); + + // The count of rows that was erased. + var erased: usize = 0; + + // A pageIterator iterates one page at a time from the back forward. + // "back" here is in terms of scrollback, but actually the front of the + // linked list. + var it = self.pageIterator(.right_down, tl_pt, bl_pt); + while (it.next()) |chunk| { + // If the chunk is a full page, deinit thit page and remove it from + // the linked list. + if (chunk.fullPage()) { + // A rare special case is that we're deleting everything + // in our linked list. erasePage requires at least one other + // page so to handle this we reinit this page, set it to zero + // size which will let us grow our active area back. + if (chunk.node.next == null and chunk.node.prev == null) { + const page = &chunk.node.data; + erased += page.size.rows; + page.reinit(); + page.size.rows = 0; + break; + } + + erased += chunk.node.data.size.rows; + self.erasePage(chunk.node); + continue; + } + + // We are modifying our chunk so make sure it is in a good state. + defer chunk.node.data.assertIntegrity(); + + // The chunk is not a full page so we need to move the rows. + // This is a cheap operation because we're just moving cell offsets, + // not the actual cell contents. + assert(chunk.start == 0); + const rows = chunk.node.data.rows.ptr(chunk.node.data.memory); + const scroll_amount = chunk.node.data.size.rows - chunk.end; + for (0..scroll_amount) |i| { + const src: *Row = &rows[i + chunk.end]; + const dst: *Row = &rows[i]; + const old_dst = dst.*; + dst.* = src.*; + src.* = old_dst; + + // Mark the moved row as dirty. + dst.dirty = true; + } + + // Clear our remaining cells that we didn't shift or swapped + // in case we grow back into them. + for (scroll_amount..chunk.node.data.size.rows) |i| { + const row: *Row = &rows[i]; + chunk.node.data.clearCells( + row, + 0, + chunk.node.data.size.cols, + ); + } + + // Update any tracked pins to shift their y. If it was in the erased + // row then we move it to the top of this page. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != chunk.node) continue; + if (p.y >= chunk.end) { + p.y -= chunk.end; + } else { + p.y = 0; + p.x = 0; + } + } + + // Our new size is the amount we scrolled + chunk.node.data.size.rows = @intCast(scroll_amount); + erased += chunk.end; + } + + // Update our total row count + self.total_rows -= erased; + + // If we deleted active, we need to regrow because one of our invariants + // is that we always have full active space. + if (tl_pt == .active) { + for (0..erased) |_| _ = self.grow() catch |err| { + // If this fails its a pretty big issue actually... but I don't + // want to turn this function into an error-returning function + // because erasing active is so rare and even if it happens failing + // is even more rare... + log.err("failed to regrow active area after erase err={}", .{err}); + return; + }; + } + + // If we have a pinned viewport, we need to adjust for active area. + self.fixupViewport(erased); +} + +/// Erase a single page, freeing all its resources. The page must be +/// at the front or back of the linked list (not the middle) and must +/// NOT be the final page in the entire list (i.e. must not make the +/// list empty). +/// +/// IMPORTANT: This function does NOT update `total_rows`. The caller is +/// responsible for accounting for the removed rows before or after calling +/// this function. +fn erasePage(self: *PageList, node: *List.Node) void { + // Must not be the final page. + assert(node.next != null or node.prev != null); + + // We only support erasing from the front or back, never the middle. + // Middle erasure would create serial gaps that page_serial_min can't + // represent. If this ever needs to change, we'll need a more + // sophisticated invalidation mechanism. + assert(node.prev == null or node.next == null); + + // If we're erasing the first page, update page_serial_min so that + // any external references holding this page's serial will know it + // has been invalidated. + if (node.prev == null) self.page_serial_min = node.next.?.serial; + + // Update any tracked pins to move to the previous or next page. + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != node) continue; + p.node = node.prev orelse node.next orelse unreachable; + p.y = 0; + p.x = 0; + + // This doesn't get marked garbage because the tracked pin + // movement is sensical. + } + + // Remove the page from the linked list + self.pages.remove(node); + self.destroyNode(node); +} + +/// Returns the pin for the given point. The pin is NOT tracked so it +/// is only valid as long as the pagelist isn't modified. +/// +/// This will return null if the point is out of bounds. The caller +/// should clamp the point to the bounds of the coordinate space if +/// necessary. +pub fn pin(self: *const PageList, pt: point.Point) ?Pin { + // getTopLeft is much more expensive than checking the cols bounds + // so we do this first. + const x = pt.coord().x; + if (x >= self.cols) return null; + + // Grab the top left and move to the point. + var p = self.getTopLeft(pt).down(pt.coord().y) orelse return null; + p.x = x; + return p; +} + +/// Convert the given pin to a tracked pin. A tracked pin will always be +/// automatically updated as the pagelist is modified. If the point the +/// pin points to is removed completely, the tracked pin will be updated +/// to the top-left of the screen. +pub fn trackPin(self: *PageList, p: Pin) Allocator.Error!*Pin { + if (build_options.slow_runtime_safety) assert(self.pinIsValid(p)); + + // Create our tracked pin + const tracked = try self.pool.pins.create(); + errdefer self.pool.pins.destroy(tracked); + tracked.* = p; + + // Add it to the tracked list + try self.tracked_pins.putNoClobber(self.pool.alloc, tracked, {}); + errdefer _ = self.tracked_pins.remove(tracked); + + return tracked; +} + +/// Untrack a previously tracked pin. This will deallocate the pin. +pub fn untrackPin(self: *PageList, p: *Pin) void { + assert(p != self.viewport_pin); + if (self.tracked_pins.swapRemove(p)) { + self.pool.pins.destroy(p); + } +} + +pub fn countTrackedPins(self: *const PageList) usize { + return self.tracked_pins.count(); +} + +/// Returns the tracked pins for this pagelist. The slice is owned by the +/// pagelist and is only valid until the pagelist is modified. +pub fn trackedPins(self: *const PageList) []const *Pin { + return self.tracked_pins.keys(); +} + +/// Checks if a pin is valid for this pagelist. This is a very slow and +/// expensive operation since we traverse the entire linked list in the +/// worst case. Only for runtime safety/debug. +pub fn pinIsValid(self: *const PageList, p: Pin) bool { + // This is very slow so we want to ensure we only ever + // call this during slow runtime safety builds. + comptime assert(build_options.slow_runtime_safety); + + var it = self.pages.first; + while (it) |node| : (it = node.next) { + if (node != p.node) continue; + return p.y < node.data.size.rows and + p.x < node.data.size.cols; + } + + return false; +} + +/// Returns the viewport for the given pin, preferring to pin to +/// "active" if the pin is within the active area. +fn pinIsActive(self: *const PageList, p: Pin) bool { + // If the pin is in the active page, then we can quickly determine + // if we're beyond the end. + const active = self.getTopLeft(.active); + if (p.node == active.node) return p.y >= active.y; + + var node_ = active.node.next; + while (node_) |node| { + // This loop is pretty fast because the active area is + // never that large so this is at most one, two nodes for + // reasonable terminals (including very large real world + // ones). + + // A node forward in the active area is our node, so we're + // definitely in the active area. + if (node == p.node) return true; + node_ = node.next; + } + + return false; +} + +/// Returns true if the pin is at the top of the scrollback area. +fn pinIsTop(self: *const PageList, p: Pin) bool { + return p.y == 0 and p.node == self.pages.first.?; +} + +/// Convert a pin to a point in the given context. If the pin can't fit +/// within the given tag (i.e. its in the history but you requested active), +/// then this will return null. +/// +/// Note that this can be a very expensive operation depending on the tag and +/// the location of the pin. This works by traversing the linked list of pages +/// in the tagged region. +/// +/// Therefore, this is recommended only very rarely. +pub fn pointFromPin(self: *const PageList, tag: point.Tag, p: Pin) ?point.Point { + const tl = self.getTopLeft(tag); + + // Count our first page which is special because it may be partial. + var coord: point.Coordinate = .{ .x = p.x }; + if (p.node == tl.node) { + // If our top-left is after our y then we're outside the range. + if (tl.y > p.y) return null; + coord.y = p.y - tl.y; + } else { + coord.y += tl.node.data.size.rows - tl.y; + var node_ = tl.node.next; + while (node_) |node| : (node_ = node.next) { + if (node == p.node) { + coord.y += p.y; + break; + } + + coord.y += node.data.size.rows; + } else { + // We never saw our node, meaning we're outside the range. + return null; + } + } + + return switch (tag) { + inline else => |comptime_tag| @unionInit( + point.Point, + @tagName(comptime_tag), + coord, + ), + }; +} + +/// Get the cell at the given point, or null if the cell does not +/// exist or is out of bounds. +/// +/// Warning: this is slow and should not be used in performance critical paths +pub fn getCell(self: *const PageList, pt: point.Point) ?Cell { + const pt_pin = self.pin(pt) orelse return null; + const rac = pt_pin.node.data.getRowAndCell(pt_pin.x, pt_pin.y); + return .{ + .node = pt_pin.node, + .row = rac.row, + .cell = rac.cell, + .row_idx = pt_pin.y, + .col_idx = pt_pin.x, + }; +} + +/// Log a debug diagram of the page list to the provided writer. +/// +/// EXAMPLE: +/// +/// +-----+ = PAGE 0 +/// ... | | +/// 50 | foo | +/// ... | | +/// +--------+ ACTIVE +/// 124 | | | 0 +/// 125 |Text | | 1 +/// : ^ : : = PIN 0 +/// 126 |Wrap… | 2 +/// +-----+ : +/// +-----+ : = PAGE 1 +/// 0 …ed | | 3 +/// 1 | etc.| | 4 +/// +-----+ : +/// +--------+ +pub fn diagram( + self: *const PageList, + writer: *std.Io.Writer, +) std.Io.Writer.Error!void { + const active_pin = self.getTopLeft(.active); + + var active = false; + var active_index: usize = 0; + + var page_index: usize = 0; + var cols: usize = 0; + + var it = self.pageIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |chunk| : (page_index += 1) { + cols = chunk.node.data.size.cols; + + // Whether we've just skipped some number of rows and drawn + // an ellipsis row (this is reset when a row is not skipped). + var skipped = false; + + for (0..chunk.node.data.size.rows) |y| { + // Active header + if (!active and + chunk.node == active_pin.node and + active_pin.y == y) + { + active = true; + try writer.writeAll(" +-"); + try writer.writeByteNTimes('-', cols); + try writer.writeAll("--+ ACTIVE"); + try writer.writeByte('\n'); + } + + // Page header + if (y == 0) { + try writer.writeAll(" +"); + try writer.writeByteNTimes('-', cols); + try writer.writeByte('+'); + if (active) try writer.writeAll(" :"); + try writer.print(" = PAGE {}", .{page_index}); + try writer.writeByte('\n'); + } + + // Row contents + { + const row = chunk.node.data.getRow(y); + const cells = chunk.node.data.getCells(row)[0..cols]; + + var row_has_content = false; + + for (cells) |cell| { + if (cell.hasText()) { + row_has_content = true; + break; + } + } + + // We don't want to print this row's contents + // unless it has text or is in the active area. + if (!active and !row_has_content) { + // If we haven't, draw an ellipsis row. + if (!skipped) { + try writer.writeAll(" ... :"); + try writer.writeByteNTimes(' ', cols); + try writer.writeByte(':'); + if (active) try writer.writeAll(" :"); + try writer.writeByte('\n'); + } + skipped = true; + continue; + } + + skipped = false; + + // Left pad row number to 5 wide + const y_digits = if (y == 0) 0 else std.math.log10_int(y); + try writer.writeByteNTimes(' ', 4 - y_digits); + try writer.print("{} ", .{y}); + + // Left edge or wrap continuation marker + try writer.writeAll(if (row.wrap_continuation) "…" else "|"); + + // Row text + if (row_has_content) { + for (cells) |*cell| { + // Skip spacer tails, since wide cells are, well, wide. + if (cell.wide == .spacer_tail) continue; + + // Write non-printing bytes as base36, for convenience. + if (cell.codepoint() < ' ') { + try writer.writeByte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[cell.codepoint()]); + continue; + } + try writer.print("{u}", .{cell.codepoint()}); + if (cell.hasGrapheme()) { + const grapheme = chunk.node.data.lookupGrapheme(cell).?; + for (grapheme) |cp| { + try writer.print("{u}", .{cp}); + } + } + } + } else { + try writer.writeByteNTimes(' ', cols); + } + + // Right edge or wrap marker + try writer.writeAll(if (row.wrap) "…" else "|"); + if (active) { + try writer.print(" | {}", .{active_index}); + active_index += 1; + } + + try writer.writeByte('\n'); + } + + // Tracked pin marker(s) + pins: { + // If we have more than 16 tracked pins in a row, oh well, + // don't wanna bother making this function allocating. + var pin_buf: [16]*Pin = undefined; + var pin_count: usize = 0; + const pin_keys = self.tracked_pins.keys(); + for (pin_keys) |p| { + if (p.node != chunk.node) continue; + if (p.y != y) continue; + pin_buf[pin_count] = p; + pin_count += 1; + if (pin_count >= pin_buf.len) return error.TooManyTrackedPinsInRow; + } + + if (pin_count == 0) break :pins; + + const pins = pin_buf[0..pin_count]; + std.mem.sort( + *Pin, + pins, + {}, + struct { + fn lt(_: void, a: *Pin, b: *Pin) bool { + return a.x < b.x; + } + }.lt, + ); + + try writer.writeAll(" :"); + var x: usize = 0; + + for (pins) |p| { + if (x > p.x) continue; + try writer.writeByteNTimes(' ', p.x - x); + try writer.writeByte('^'); + x = p.x + 1; + } + + try writer.writeByteNTimes(' ', cols - x); + try writer.writeByte(':'); + + if (active) try writer.writeAll(" :"); + + try writer.print(" = PIN{s}", .{if (pin_count > 1) "S" else ""}); + + x = pins[0].x; + for (pins, 0..) |p, i| { + if (p.x != x) try writer.writeByte(','); + try writer.print(" {}", .{i}); + } + + try writer.writeByte('\n'); + } + } + + // Page footer + { + try writer.writeAll(" +"); + try writer.writeByteNTimes('-', cols); + try writer.writeByte('+'); + if (active) try writer.writeAll(" :"); + try writer.writeByte('\n'); + } + } + + // Active footer + { + try writer.writeAll(" +-"); + try writer.writeByteNTimes('-', cols); + try writer.writeAll("--+"); + try writer.writeByte('\n'); + } +} + +/// Returns the boundaries of the given semantic content type for +/// the prompt at the given pin. The pin row MUST be the first row +/// of a prompt, otherwise the results may be nonsense. +/// +/// To get prompt pins, use promptIterator. Warning that if there are +/// no semantic prompts ever present, promptIterator will iterate the +/// entire PageList. Downstream callers should keep track of a flag if +/// they've ever seen semantic prompt operations to prevent this performance +/// case. +/// +/// Note that some semantic content type such as "input" is usually +/// nested within prompt boundaries, so the returned boundaries may include +/// prompt text. +pub fn highlightSemanticContent( + self: *const PageList, + at: Pin, + content: pagepkg.Cell.SemanticContent, +) ?highlight.Untracked { + // Performance note: we can do this more efficiently in a single + // forward-pass. Semantic content operations aren't usually fast path + // but if someone wants to optimize them someday that's great. + + const end: Pin = end: { + // Safety assertion, our starting point should be a prompt row. + // so the first returned prompt should be ourselves. + var it = at.promptIterator(.right_down, null); + assert(it.next().?.y == at.y); + + // Our end is the end of the line just before the next prompt + // line, which should exist since we verified we have at least + // two prompts here. + if (it.next()) |next| next: { + var prev = next.up(1) orelse break :next; + prev.x = prev.node.data.size.cols - 1; + break :end prev; + } + + // Didn't find any further prompt so the end of our zone is + // the end of the screen. + break :end self.getBottomRight(.screen).?; + }; + + switch (content) { + // For the prompt, we select all the way up to command output. + // We include all the input lines, too. + .prompt => { + var result: highlight.Untracked = .{ + .start = at.left(at.x), + .end = at, + }; + + var it = at.cellIterator(.right_down, end); + while (it.next()) |p| { + switch (p.rowAndCell().cell.semantic_content) { + .prompt, .input => result.end = p, + .output => break, + } + } + + return result; + }, + + // For input, we include the start of the input to the end of + // the input, which may include all the prompts in the middle, too. + .input => { + var result: highlight.Untracked = .{ + .start = undefined, + .end = undefined, + }; + + // Find the start + var it = at.cellIterator(.right_down, end); + while (it.next()) |p| { + switch (p.rowAndCell().cell.semantic_content) { + .prompt => {}, + .input => { + result.start = p; + result.end = p; + break; + }, + .output => return null, + } + } else { + // No input found + return null; + } + + // Find the end + while (it.next()) |p| { + switch (p.rowAndCell().cell.semantic_content) { + // Prompts can be nested in our input for continuation + .prompt => {}, + + // Output means we're done + .output => break, + + .input => result.end = p, + } + } + + return result; + }, + + .output => { + var result: highlight.Untracked = .{ + .start = undefined, + .end = undefined, + }; + + // Find the start + var it = at.cellIterator(.right_down, end); + while (it.next()) |p| { + const cell = p.rowAndCell().cell; + switch (cell.semantic_content) { + .prompt, .input => {}, + .output => { + // Skip empty cells - they default to .output but aren't real output + if (!cell.hasText()) continue; + result.start = p; + result.end = p; + break; + }, + } + } else { + // No output found + return null; + } + + // Find the end + while (it.next()) |p| { + const cell = p.rowAndCell().cell; + switch (cell.semantic_content) { + .prompt, .input => break, + .output => { + // Only extend to cells with actual text + if (cell.hasText()) result.end = p; + }, + } + } + + return result; + }, + } +} + +/// Direction that iterators can move. +pub const Direction = enum { left_up, right_down }; + +pub const PromptIterator = struct { + /// The pin that we are currently at. Also the starting pin when + /// initializing. + current: ?Pin, + + /// The pin to end at or null if we end when we can't traverse + /// anymore. + limit: ?Pin, + + /// The direction to do the traversal. + direction: Direction, + + pub const empty: PromptIterator = .{ + .current = null, + .limit = null, + .direction = .left_up, + }; + + /// Return the next pin that represents the first row in a prompt. + /// From here, you can find the prompt input, command output, etc. + pub fn next(self: *PromptIterator) ?Pin { + switch (self.direction) { + .left_up => return self.nextLeftUp(), + .right_down => return self.nextRightDown(), + } + } + + pub fn nextRightDown(self: *PromptIterator) ?Pin { + // Start at our current pin. If we have no current it means + // we reached the end and we're done. + const start: Pin = self.current orelse return null; + + // We need to traverse downwards and look for prompts. + var current: ?Pin = start; + while (current) |p| : (current = p.down(1)) { + // Check our limit. + const at_limit = if (self.limit) |limit| limit.eql(p) else false; + + const rac = p.rowAndCell(); + switch (rac.row.semantic_prompt) { + // This row isn't a prompt. Keep looking. + .none => if (at_limit) break, + + // This is a prompt line or continuation line. In either + // case we consider the first line the prompt, and then + // skip over any remaining prompt lines. This handles the + // case where scrollback pruned the prompt. + .prompt, .prompt_continuation => { + // If we're at our limit just return this prompt. + if (at_limit) { + self.current = null; + return p.left(p.x); + } + + // Skip over any continuation lines that follow this prompt, + // up to our limit. + var end_pin = p; + while (end_pin.down(1)) |next_pin| : (end_pin = next_pin) { + switch (next_pin.rowAndCell().row.semantic_prompt) { + .prompt_continuation => if (self.limit) |limit| { + if (limit.eql(next_pin)) break; + }, + + .prompt, .none => { + self.current = next_pin; + return p.left(p.x); + }, + } + } + + self.current = null; + return p.left(p.x); + }, + } + } + + self.current = null; + return null; + } + + pub fn nextLeftUp(self: *PromptIterator) ?Pin { + // Start at our current pin. If we have no current it means + // we reached the end and we're done. + const start: Pin = self.current orelse return null; + + // We need to traverse upwards and look for prompts. + var current: ?Pin = start; + while (current) |p| : (current = p.up(1)) { + // Check our limit. + const at_limit = if (self.limit) |limit| limit.eql(p) else false; + + const rac = p.rowAndCell(); + switch (rac.row.semantic_prompt) { + // This row isn't a prompt. Keep looking. + .none => if (at_limit) break, + + // This is a prompt line. + .prompt => { + self.current = if (at_limit) null else p.up(1); + return p.left(p.x); + }, + + // If this is a prompt continuation, then we continue + // looking for the start of the prompt OR a non-prompt + // line, whichever is first. The non-prompt line is to handle + // poorly behaved programs or scrollback that's been cut-off. + .prompt_continuation => { + // If we're at our limit just return this continuation as prompt. + if (at_limit) { + self.current = null; + return p.left(p.x); + } + + var end_pin = p; + while (end_pin.up(1)) |prior| : (end_pin = prior) { + if (self.limit) |limit| { + if (limit.eql(prior)) break; + } + + switch (prior.rowAndCell().row.semantic_prompt) { + // No prompt. That means our last pin is good! + .none => { + self.current = prior; + return end_pin.left(end_pin.x); + }, + + // Prompt continuation, keep looking. + .prompt_continuation => {}, + + // Prompt! Found it! + .prompt => { + self.current = prior.up(1); + return prior.left(prior.x); + }, + } + } + + // No prior rows, trimmed scrollback probably. + self.current = null; + return p.left(p.x); + }, + } + } + + self.current = null; + return null; + } +}; + +pub fn promptIterator( + self: *const PageList, + direction: Direction, + tl_pt: point.Point, + bl_pt: ?point.Point, +) PromptIterator { + const tl_pin = self.pin(tl_pt).?; + const bl_pin = if (bl_pt) |pt| + self.pin(pt).? + else + self.getBottomRight(tl_pt) orelse return .empty; + + return switch (direction) { + .right_down => tl_pin.promptIterator(.right_down, bl_pin), + .left_up => bl_pin.promptIterator(.left_up, tl_pin), + }; +} + +pub const CellIterator = struct { + row_it: RowIterator, + cell: ?Pin = null, + + pub fn next(self: *CellIterator) ?Pin { + const cell = self.cell orelse return null; + + switch (self.row_it.page_it.direction) { + .right_down => { + if (cell.x + 1 < cell.node.data.size.cols) { + // We still have cells in this row, increase x. + var copy = cell; + copy.x += 1; + self.cell = copy; + } else { + // We need to move to the next row. + self.cell = self.row_it.next(); + } + }, + + .left_up => { + if (cell.x > 0) { + // We still have cells in this row, decrease x. + var copy = cell; + copy.x -= 1; + self.cell = copy; + } else { + // We need to move to the previous row and last col + if (self.row_it.next()) |next_cell| { + var copy = next_cell; + copy.x = next_cell.node.data.size.cols - 1; + self.cell = copy; + } else { + self.cell = null; + } + } + }, + } + + return cell; + } +}; + +pub fn cellIterator( + self: *const PageList, + direction: Direction, + tl_pt: point.Point, + bl_pt: ?point.Point, +) CellIterator { + const tl_pin = self.pin(tl_pt).?; + const bl_pin = if (bl_pt) |pt| + self.pin(pt).? + else + self.getBottomRight(tl_pt) orelse + return .{ .row_it = undefined }; + + return switch (direction) { + .right_down => tl_pin.cellIterator(.right_down, bl_pin), + .left_up => bl_pin.cellIterator(.left_up, tl_pin), + }; +} + +pub const RowIterator = struct { + page_it: PageIterator, + chunk: ?PageIterator.Chunk = null, + offset: size.CellCountInt = 0, + + pub fn next(self: *RowIterator) ?Pin { + const chunk = self.chunk orelse return null; + const row: Pin = .{ .node = chunk.node, .y = self.offset }; + + switch (self.page_it.direction) { + .right_down => { + // Increase our offset in the chunk + self.offset += 1; + + // If we are beyond the chunk end, we need to move to the next chunk. + if (self.offset >= chunk.end) { + self.chunk = self.page_it.next(); + if (self.chunk) |c| self.offset = c.start; + } + }, + + .left_up => { + // If we are at the start of the chunk, we need to move to the + // previous chunk. + if (self.offset == 0) { + self.chunk = self.page_it.next(); + if (self.chunk) |c| self.offset = c.end - 1; + } else { + // If we're at the start of the chunk and its a non-zero + // offset then we've reached a limit. + if (self.offset == chunk.start) { + self.chunk = null; + } else { + self.offset -= 1; + } + } + }, + } + + return row; + } +}; + +/// Create an iterator that can be used to iterate all the rows in +/// a region of the screen from the given top-left. The tag of the +/// top-left point will also determine the end of the iteration, +/// so convert from one reference point to another to change the +/// iteration bounds. +pub fn rowIterator( + self: *const PageList, + direction: Direction, + tl_pt: point.Point, + bl_pt: ?point.Point, +) RowIterator { + const tl_pin = self.pin(tl_pt).?; + const bl_pin = if (bl_pt) |pt| + self.pin(pt).? + else + self.getBottomRight(tl_pt) orelse + return .{ .page_it = undefined }; + + return switch (direction) { + .right_down => tl_pin.rowIterator(.right_down, bl_pin), + .left_up => bl_pin.rowIterator(.left_up, tl_pin), + }; +} + +pub const PageIterator = struct { + row: ?Pin = null, + limit: Limit = .none, + direction: Direction = .right_down, + + const Limit = union(enum) { + none, + count: usize, + row: Pin, + }; + + pub fn next(self: *PageIterator) ?Chunk { + return switch (self.direction) { + .left_up => self.nextUp(), + .right_down => self.nextDown(), + }; + } + + fn nextDown(self: *PageIterator) ?Chunk { + // Get our current row location + const row = self.row orelse return null; + + return switch (self.limit) { + .none => none: { + // If we have no limit, then we consume this entire page. Our + // next row is the next page. + self.row = next: { + const next_page = row.node.next orelse break :next null; + break :next .{ .node = next_page }; + }; + + break :none .{ + .node = row.node, + .start = row.y, + .end = row.node.data.size.rows, + }; + }, + + .count => |*limit| count: { + assert(limit.* > 0); // should be handled already + const len = @min(row.node.data.size.rows - row.y, limit.*); + if (len > limit.*) { + self.row = row.down(len); + limit.* -= len; + } else { + self.row = null; + } + + break :count .{ + .node = row.node, + .start = row.y, + .end = row.y + len, + }; + }, + + .row => |limit_row| row: { + // If this is not the same page as our limit then we + // can consume the entire page. + if (limit_row.node != row.node) { + self.row = next: { + const next_page = row.node.next orelse break :next null; + break :next .{ .node = next_page }; + }; + + break :row .{ + .node = row.node, + .start = row.y, + .end = row.node.data.size.rows, + }; + } + + // If this is the same page then we only consume up to + // the limit row. + self.row = null; + if (row.y > limit_row.y) return null; + break :row .{ + .node = row.node, + .start = row.y, + .end = limit_row.y + 1, + }; + }, + }; + } + + fn nextUp(self: *PageIterator) ?Chunk { + // Get our current row location + const row = self.row orelse return null; + + return switch (self.limit) { + .none => none: { + // If we have no limit, then we consume this entire page. Our + // next row is the next page. + self.row = next: { + const next_page = row.node.prev orelse break :next null; + break :next .{ + .node = next_page, + .y = next_page.data.size.rows - 1, + }; + }; + + break :none .{ + .node = row.node, + .start = 0, + .end = row.y + 1, + }; + }, + + .count => |*limit| count: { + assert(limit.* > 0); // should be handled already + const len = @min(row.y, limit.*); + if (len > limit.*) { + self.row = row.up(len); + limit.* -= len; + } else { + self.row = null; + } + + break :count .{ + .node = row.node, + .start = row.y - len, + .end = row.y - 1, + }; + }, + + .row => |limit_row| row: { + // If this is not the same page as our limit then we + // can consume the entire page. + if (limit_row.node != row.node) { + self.row = next: { + const next_page = row.node.prev orelse break :next null; + break :next .{ + .node = next_page, + .y = next_page.data.size.rows - 1, + }; + }; + + break :row .{ + .node = row.node, + .start = 0, + .end = row.y + 1, + }; + } + + // If this is the same page then we only consume up to + // the limit row. + self.row = null; + if (row.y < limit_row.y) return null; + break :row .{ + .node = row.node, + .start = limit_row.y, + .end = row.y + 1, + }; + }, + }; + } + + pub const Chunk = struct { + node: *List.Node, + + /// Start y index (inclusive) of this chunk in the page. + start: size.CellCountInt, + + /// End y index (exclusive) of this chunk in the page. + end: size.CellCountInt, + + pub fn rows(self: Chunk) []Row { + const rows_ptr = self.node.data.rows.ptr(self.node.data.memory); + return rows_ptr[self.start..self.end]; + } + + /// Returns true if this chunk represents every row in the page. + pub fn fullPage(self: Chunk) bool { + return self.start == 0 and self.end == self.node.data.size.rows; + } + + /// Returns true if this chunk overlaps with the given other chunk + /// in any way. + pub fn overlaps(self: Chunk, other: Chunk) bool { + if (self.node != other.node) return false; + if (self.end <= other.start) return false; + if (self.start >= other.end) return false; + return true; + } + }; +}; + +/// Return an iterator that iterates through the rows in the tagged area +/// of the point. The iterator returns row "chunks", which are the largest +/// contiguous set of rows in a single backing page for a given portion of +/// the point region. +/// +/// This is a more efficient way to iterate through the data in a region, +/// since you can do simple pointer math and so on. +/// +/// If bl_pt is non-null, iteration will stop at the bottom left point +/// (inclusive). If bl_pt is null, the entire region specified by the point +/// tag will be iterated over. tl_pt and bl_pt must be the same tag, and +/// bl_pt must be greater than or equal to tl_pt. +/// +/// If direction is left_up, iteration will go from bl_pt to tl_pt. If +/// direction is right_down, iteration will go from tl_pt to bl_pt. +/// Both inclusive. +pub fn pageIterator( + self: *const PageList, + direction: Direction, + tl_pt: point.Point, + bl_pt: ?point.Point, +) PageIterator { + const tl_pin = self.pin(tl_pt).?; + const bl_pin = if (bl_pt) |pt| + self.pin(pt).? + else + self.getBottomRight(tl_pt) orelse return .{ .row = null }; + + if (build_options.slow_runtime_safety) { + assert(tl_pin.eql(bl_pin) or tl_pin.before(bl_pin)); + } + + return switch (direction) { + .right_down => tl_pin.pageIterator(.right_down, bl_pin), + .left_up => bl_pin.pageIterator(.left_up, tl_pin), + }; +} + +/// Get the top-left of the screen for the given tag. +pub fn getTopLeft(self: *const PageList, tag: point.Tag) Pin { + return switch (tag) { + // The full screen or history is always just the first page. + .screen, .history => .{ .node = self.pages.first.? }, + + .viewport => switch (self.viewport) { + .active => self.getTopLeft(.active), + .top => self.getTopLeft(.screen), + .pin => self.viewport_pin.*, + }, + + // The active area is calculated backwards from the last page. + // This makes getting the active top left slower but makes scrolling + // much faster because we don't need to update the top left. Under + // heavy load this makes a measurable difference. + .active => active: { + var rem = self.rows; + var it = self.pages.last; + while (it) |node| : (it = node.prev) { + if (rem <= node.data.size.rows) break :active .{ + .node = node, + .y = node.data.size.rows - rem, + }; + + rem -= node.data.size.rows; + } + + unreachable; // assertion: we always have enough rows for active + }, + }; +} + +/// Returns the bottom right of the screen for the given tag. This can +/// return null because it is possible that a tag is not in the screen +/// (e.g. history does not yet exist). +pub fn getBottomRight(self: *const PageList, tag: point.Tag) ?Pin { + return switch (tag) { + .screen, .active => last: { + const node = self.pages.last.?; + break :last .{ + .node = node, + .y = node.data.size.rows - 1, + .x = node.data.size.cols - 1, + }; + }, + + .viewport => viewport: { + var br = self.getTopLeft(.viewport); + br = br.down(self.rows - 1).?; + br.x = br.node.data.size.cols - 1; + break :viewport br; + }, + + .history => active: { + var br = self.getTopLeft(.active); + br = br.up(1) orelse return null; + br.x = br.node.data.size.cols - 1; + break :active br; + }, + }; +} + +/// The total rows in the screen. This is the actual row count currently +/// and not a capacity or maximum. +/// +/// This is very slow, it traverses the full list of pages to count the +/// rows, so it is not pub. This is only used for testing/debugging. +fn totalRows(self: *const PageList) usize { + var rows: usize = 0; + var node_ = self.pages.first; + while (node_) |node| { + rows += node.data.size.rows; + node_ = node.next; + } + + return rows; +} + +/// The total number of pages in this list. This should only be used +/// for tests since it is O(N) over the list of pages. +pub fn totalPages(self: *const PageList) usize { + var pages: usize = 0; + var node_ = self.pages.first; + while (node_) |node| { + pages += 1; + node_ = node.next; + } + + return pages; +} + +/// Grow the number of rows available in the page list by n. +/// This is only used for testing so it isn't optimized in any way. +fn growRows(self: *PageList, n: usize) Allocator.Error!void { + for (0..n) |_| _ = try self.grow(); +} + +/// Clear all dirty bits on all pages. This is not efficient since it +/// traverses the entire list of pages. This is used for testing/debugging. +pub fn clearDirty(self: *PageList) void { + var page = self.pages.first; + while (page) |p| : (page = p.next) { + p.data.dirty = false; + for (p.data.rows.ptr(p.data.memory)[0..p.data.size.rows]) |*row| { + row.dirty = false; + } + } +} + +/// Returns true if the point is dirty, used for testing. +pub fn isDirty(self: *const PageList, pt: point.Point) bool { + return self.getCell(pt).?.isDirty(); +} + +/// Mark a point as dirty, used for testing. +fn markDirty(self: *PageList, pt: point.Point) void { + self.pin(pt).?.markDirty(); +} + +/// Represents an exact x/y coordinate within the screen. This is called +/// a "pin" because it is a fixed point within the pagelist direct to +/// a specific page pointer and memory offset. The benefit is that this +/// point remains valid even through scrolling without any additional work. +/// +/// A downside is that the pin is only valid until the pagelist is modified +/// in a way that may invalidate page pointers or shuffle rows, such as resizing, +/// erasing rows, etc. +/// +/// A pin can also be "tracked" which means that it will be updated as the +/// PageList is modified. +/// +/// The PageList maintains a list of active pin references and keeps them +/// all up to date as the pagelist is modified. This isn't cheap so callers +/// should limit the number of active pins as much as possible. +pub const Pin = struct { + node: *List.Node, + y: size.CellCountInt = 0, + x: size.CellCountInt = 0, + + /// This is flipped to true for tracked pins that were tracking + /// a page that got pruned for any reason and where the tracked pin + /// couldn't be moved to a sensical location. Users of the tracked + /// pin could use this data and make their own determination of + /// semantics. + garbage: bool = false, + + pub inline fn rowAndCell(self: Pin) struct { + row: *pagepkg.Row, + cell: *pagepkg.Cell, + } { + const rac = self.node.data.getRowAndCell(self.x, self.y); + return .{ .row = rac.row, .cell = rac.cell }; + } + + pub const CellSubset = enum { all, left, right }; + + /// Returns the cells for the row that this pin is on. The subset determines + /// what subset of the cells are returned. The "left/right" subsets are + /// inclusive of the x coordinate of the pin. + pub inline fn cells(self: Pin, subset: CellSubset) []pagepkg.Cell { + const rac = self.rowAndCell(); + const all = self.node.data.getCells(rac.row); + return switch (subset) { + .all => all, + .left => all[0 .. self.x + 1], + .right => all[self.x..], + }; + } + + /// Returns the grapheme codepoints for the given cell. These are only + /// the EXTRA codepoints and not the first codepoint. + pub inline fn grapheme(self: Pin, cell: *const pagepkg.Cell) ?[]u21 { + return self.node.data.lookupGrapheme(cell); + } + + /// Returns the style for the given cell in this pin. + pub inline fn style(self: Pin, cell: *const pagepkg.Cell) stylepkg.Style { + if (cell.style_id == stylepkg.default_id) return .{}; + return self.node.data.styles.get( + self.node.data.memory, + cell.style_id, + ).*; + } + + /// Check if this pin is dirty. + pub inline fn isDirty(self: Pin) bool { + return self.node.data.dirty or self.rowAndCell().row.dirty; + } + + /// Mark this pin location as dirty. + pub inline fn markDirty(self: Pin) void { + self.rowAndCell().row.dirty = true; + } + + /// Iterators. These are the same as PageList iterator funcs but operate + /// on pins rather than points. This is MUCH more efficient than calling + /// pointFromPin and building up the iterator from points. + /// + /// The limit pin is inclusive. + pub inline fn pageIterator( + self: Pin, + direction: Direction, + limit: ?Pin, + ) PageIterator { + if (build_options.slow_runtime_safety) { + if (limit) |l| { + // Check the order according to the iteration direction. + switch (direction) { + .right_down => assert(self.eql(l) or self.before(l)), + .left_up => assert(self.eql(l) or l.before(self)), + } + } + } + + return .{ + .row = self, + .limit = if (limit) |p| .{ .row = p } else .{ .none = {} }, + .direction = direction, + }; + } + + pub inline fn rowIterator( + self: Pin, + direction: Direction, + limit: ?Pin, + ) RowIterator { + var page_it = self.pageIterator(direction, limit); + const chunk = page_it.next() orelse return .{ .page_it = page_it }; + return .{ + .page_it = page_it, + .chunk = chunk, + .offset = switch (direction) { + .right_down => chunk.start, + .left_up => chunk.end - 1, + }, + }; + } + + pub inline fn cellIterator( + self: Pin, + direction: Direction, + limit: ?Pin, + ) CellIterator { + var row_it = self.rowIterator(direction, limit); + var cell = row_it.next() orelse return .{ .row_it = row_it }; + cell.x = self.x; + return .{ .row_it = row_it, .cell = cell }; + } + + pub inline fn promptIterator( + self: Pin, + direction: Direction, + limit: ?Pin, + ) PromptIterator { + return .{ + .current = self, + .limit = limit, + .direction = direction, + }; + } + + /// Returns true if this pin is between the top and bottom, inclusive. + // + // Note: this is primarily unit tested as part of the Kitty + // graphics deletion code. + pub fn isBetween(self: Pin, top: Pin, bottom: Pin) bool { + if (build_options.slow_runtime_safety) { + if (top.node == bottom.node) { + // If top is bottom, must be ordered. + assert(top.y <= bottom.y); + if (top.y == bottom.y) { + assert(top.x <= bottom.x); + } + } else { + // If top is not bottom, top must be before bottom. + var node_ = top.node.next; + while (node_) |node| : (node_ = node.next) { + if (node == bottom.node) break; + } else assert(false); + } + } + + if (self.node == top.node) { + // If our pin is the top page and our y is less than the top y + // then we can't possibly be between the top and bottom. + if (self.y < top.y) return false; + + // If our y is after the top y but we're on the same page + // then we're between the top and bottom if our y is less + // than or equal to the bottom y if its the same page. If the + // bottom is another page then it means that the range is + // at least the full top page and since we're the same page + // we're in the range. + if (self.y > top.y) { + return if (self.node == bottom.node) + self.y <= bottom.y + else + true; + } + + // Otherwise our y is the same as the top y, so we need to + // check the x coordinate. + assert(self.y == top.y); + if (self.x < top.x) return false; + } + if (self.node == bottom.node) { + // Our page is the bottom page so we're between the top and + // bottom if our y is less than the bottom y. + if (self.y > bottom.y) return false; + if (self.y < bottom.y) return true; + + // If our y is the same, then we're between if we're before + // or equal to the bottom x. + assert(self.y == bottom.y); + return self.x <= bottom.x; + } + + // Our page isn't the top or bottom so we need to check if + // our page is somewhere between the top and bottom. + + // Since our loop starts at top.page.next we need to check that + // top != bottom because if they're the same then we can't possibly + // be between them. + if (top.node == bottom.node) return false; + var node_ = top.node.next; + while (node_) |node| : (node_ = node.next) { + if (node == bottom.node) break; + if (node == self.node) return true; + } + + return false; + } + + /// Returns true if self is before other. This is very expensive since + /// it requires traversing the linked list of pages. This should not + /// be called in performance critical paths. + pub fn before(self: Pin, other: Pin) bool { + if (self.node == other.node) { + if (self.y < other.y) return true; + if (self.y > other.y) return false; + return self.x < other.x; + } + + var node_ = self.node.next; + while (node_) |node| : (node_ = node.next) { + if (node == other.node) return true; + } + + return false; + } + + pub inline fn eql(self: Pin, other: Pin) bool { + return self.node == other.node and + self.y == other.y and + self.x == other.x; + } + + /// Move the pin left n columns. n must fit within the size. + pub inline fn left(self: Pin, n: usize) Pin { + assert(n <= self.x); + var result = self; + result.x -= std.math.cast(size.CellCountInt, n) orelse result.x; + return result; + } + + /// Move the pin right n columns. n must fit within the size. + pub inline fn right(self: Pin, n: usize) Pin { + assert(self.x + n < self.node.data.size.cols); + var result = self; + result.x +|= std.math.cast(size.CellCountInt, n) orelse + std.math.maxInt(size.CellCountInt); + return result; + } + + /// Move the pin left n columns, stopping at the start of the row. + pub inline fn leftClamp(self: Pin, n: size.CellCountInt) Pin { + var result = self; + result.x -|= n; + return result; + } + + /// Move the pin right n columns, stopping at the end of the row. + pub inline fn rightClamp(self: Pin, n: size.CellCountInt) Pin { + var result = self; + result.x = @min(self.x +| n, self.node.data.size.cols - 1); + return result; + } + + /// Move the pin left n cells, wrapping to the previous row as needed. + /// + /// If the offset goes beyond the top of the screen, returns null. + /// + /// TODO: Unit tests. + pub fn leftWrap(self: Pin, n: usize) ?Pin { + // NOTE: This assumes that all pages have the same width, which may + // be violated under certain circumstances by incomplete reflow. + const cols = self.node.data.size.cols; + const remaining_in_row = self.x; + + if (n <= remaining_in_row) return self.left(n); + + const extra_after_remaining = n - remaining_in_row; + + const rows_off = 1 + extra_after_remaining / cols; + + switch (self.upOverflow(rows_off)) { + .offset => |v| { + var result = v; + result.x = @intCast(cols - extra_after_remaining % cols); + return result; + }, + .overflow => return null, + } + } + + /// Move the pin right n cells, wrapping to the next row as needed. + /// + /// If the offset goes beyond the bottom of the screen, returns null. + /// + /// TODO: Unit tests. + pub fn rightWrap(self: Pin, n: usize) ?Pin { + // NOTE: This assumes that all pages have the same width, which may + // be violated under certain circumstances by incomplete reflow. + const cols = self.node.data.size.cols; + const remaining_in_row = cols - self.x - 1; + + if (n <= remaining_in_row) return self.right(n); + + const extra_after_remaining = n - remaining_in_row; + + const rows_off = 1 + extra_after_remaining / cols; + + switch (self.downOverflow(rows_off)) { + .offset => |v| { + var result = v; + result.x = @intCast(extra_after_remaining % cols - 1); + return result; + }, + .overflow => return null, + } + } + + /// Move the pin down a certain number of rows, or return null if + /// the pin goes beyond the end of the screen. + pub inline fn down(self: Pin, n: usize) ?Pin { + return switch (self.downOverflow(n)) { + .offset => |v| v, + .overflow => null, + }; + } + + /// Move the pin up a certain number of rows, or return null if + /// the pin goes beyond the start of the screen. + pub inline fn up(self: Pin, n: usize) ?Pin { + return switch (self.upOverflow(n)) { + .offset => |v| v, + .overflow => null, + }; + } + + /// Move the offset down n rows. If the offset goes beyond the + /// end of the screen, return the overflow amount. + pub fn downOverflow(self: Pin, n: usize) union(enum) { + offset: Pin, + overflow: struct { + end: Pin, + remaining: usize, + }, + } { + // Index fits within this page + const rows = self.node.data.size.rows - (self.y + 1); + if (n <= rows) return .{ .offset = .{ + .node = self.node, + .y = std.math.cast(size.CellCountInt, self.y + n) orelse + std.math.maxInt(size.CellCountInt), + .x = self.x, + } }; + + // Need to traverse page links to find the page + var node: *List.Node = self.node; + var n_left: usize = n - rows; + while (true) { + node = node.next orelse return .{ .overflow = .{ + .end = .{ + .node = node, + .y = node.data.size.rows - 1, + .x = self.x, + }, + .remaining = n_left, + } }; + if (n_left <= node.data.size.rows) return .{ .offset = .{ + .node = node, + .y = std.math.cast(size.CellCountInt, n_left - 1) orelse + std.math.maxInt(size.CellCountInt), + .x = self.x, + } }; + n_left -= node.data.size.rows; + } + } + + /// Move the offset up n rows. If the offset goes beyond the + /// start of the screen, return the overflow amount. + pub fn upOverflow(self: Pin, n: usize) union(enum) { + offset: Pin, + overflow: struct { + end: Pin, + remaining: usize, + }, + } { + // Index fits within this page + if (n <= self.y) return .{ .offset = .{ + .node = self.node, + .y = std.math.cast(size.CellCountInt, self.y - n) orelse + std.math.maxInt(size.CellCountInt), + .x = self.x, + } }; + + // Need to traverse page links to find the page + var node: *List.Node = self.node; + var n_left: usize = n - self.y; + while (true) { + node = node.prev orelse return .{ .overflow = .{ + .end = .{ .node = node, .y = 0, .x = self.x }, + .remaining = n_left, + } }; + if (n_left <= node.data.size.rows) return .{ .offset = .{ + .node = node, + .y = std.math.cast(size.CellCountInt, node.data.size.rows - n_left) orelse + std.math.maxInt(size.CellCountInt), + .x = self.x, + } }; + n_left -= node.data.size.rows; + } + } +}; + +pub const Cell = struct { + node: *List.Node, + row: *pagepkg.Row, + cell: *pagepkg.Cell, + row_idx: size.CellCountInt, + col_idx: size.CellCountInt, + + /// Returns true if this cell is marked as dirty. + /// + /// This is not very performant this is primarily used for assertions + /// and testing. + pub fn isDirty(self: Cell) bool { + return self.node.data.dirty or self.row.dirty; + } + + /// Get the cell style. + /// + /// Not meant for non-test usage since this is inefficient. + pub fn style(self: Cell) stylepkg.Style { + if (self.cell.style_id == stylepkg.default_id) return .{}; + return self.node.data.styles.get( + self.node.data.memory, + self.cell.style_id, + ).*; + } + + /// Gets the screen point for the given cell. + /// + /// This is REALLY expensive/slow so it isn't pub. This was built + /// for debugging and tests. If you have a need for this outside of + /// this file then consider a different approach and ask yourself very + /// carefully if you really need this. + pub fn screenPoint(self: Cell) point.Point { + var y: size.CellCountInt = self.row_idx; + var node_ = self.node; + while (node_.prev) |node| { + y += node.data.size.rows; + node_ = node; + } + + return .{ .screen = .{ + .x = self.col_idx, + .y = y, + } }; + } +}; + +test "PageList" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expect(s.viewport == .active); + try testing.expect(s.pages.first != null); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Initial total rows should be our row count + try testing.expectEqual(s.rows, s.total_rows); + + // Our viewport pin must be defined. It isn't used until the + // viewport is a pin but it prevents undefined access on clone. + try testing.expect(s.viewport_pin.node == s.pages.first.?); + + // Active area should be the top + try testing.expectEqual(Pin{ + .node = s.pages.first.?, + .y = 0, + .x = 0, + }, s.getTopLeft(.active)); + + // Scrollbar should be where we expect it + try testing.expectEqual(Scrollbar{ + .total = s.rows, + .offset = 0, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList init error" { + // Test every failure point in `init` and ensure that we don't + // leak memory (testing.allocator verifies) since we're exiting early. + for (std.meta.tags(init_tw.FailPoint)) |tag| { + const tw = init_tw; + defer tw.end(.reset) catch unreachable; + tw.errorAlways(tag, error.OutOfMemory); + try std.testing.expectError( + error.OutOfMemory, + init( + std.testing.allocator, + 80, + 24, + null, + ), + ); + } + + // init calls initPages transitively, so let's check that if + // any failures happen in initPages, we also don't leak memory. + for (std.meta.tags(initPages_tw.FailPoint)) |tag| { + const tw = initPages_tw; + defer tw.end(.reset) catch unreachable; + tw.errorAlways(tag, error.OutOfMemory); + + const cols: size.CellCountInt = if (tag == .page_buf_std) 80 else std_capacity.maxCols().? + 1; + try std.testing.expectError( + error.OutOfMemory, + init( + std.testing.allocator, + cols, + 24, + null, + ), + ); + } + + // Try non-standard pages since they don't go in our pool. + for ([_]initPages_tw.FailPoint{ + .page_buf_non_std, + }) |tag| { + const tw = initPages_tw; + defer tw.end(.reset) catch unreachable; + tw.errorAfter(tag, error.OutOfMemory, 1); + try std.testing.expectError( + error.OutOfMemory, + init( + std.testing.allocator, + std_capacity.maxCols().? + 1, + std_capacity.rows + 1, + null, + ), + ); + } +} + +test "PageList init rows across two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + // Find a cap that makes it so that rows don't fit on one page. + const rows = 100; + const cap = cap: { + var cap = try std_capacity.adjust(.{ .cols = 50 }); + while (cap.rows >= rows) cap = try std_capacity.adjust(.{ + .cols = cap.cols + 50, + }); + + break :cap cap; + }; + + // Init + var s = try init(alloc, cap.cols, rows, null); + defer s.deinit(); + try testing.expect(s.viewport == .active); + try testing.expect(s.pages.first != null); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Initial total rows should be our row count + try testing.expectEqual(s.rows, s.total_rows); + + // Scrollbar should be where we expect it + try testing.expectEqual(Scrollbar{ + .total = s.rows, + .offset = 0, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList init more than max cols" { + const testing = std.testing; + const alloc = testing.allocator; + + // Initialize with more columns than we can fit in our standard + // capacity. This is going to force us to go to a non-standard page + // immediately. + var s = try init( + alloc, + std_capacity.maxCols().? + 1, + 80, + null, + ); + defer s.deinit(); + try testing.expect(s.viewport == .active); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // We expect a single, non-standard page + try testing.expect(s.pages.first != null); + try testing.expect(s.pages.first.?.data.memory.len > std_size); + + // Initial total rows should be our row count + try testing.expectEqual(s.rows, s.total_rows); + + // Scrollbar should be where we expect it + try testing.expectEqual(Scrollbar{ + .total = s.rows, + .offset = 0, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList pointFromPin active no history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + { + try testing.expectEqual(point.Point{ + .active = .{ + .y = 0, + .x = 0, + }, + }, s.pointFromPin(.active, .{ + .node = s.pages.first.?, + .y = 0, + .x = 0, + }).?); + } + { + try testing.expectEqual(point.Point{ + .active = .{ + .y = 2, + .x = 4, + }, + }, s.pointFromPin(.active, .{ + .node = s.pages.first.?, + .y = 2, + .x = 4, + }).?); + } +} + +test "PageList pointFromPin active with history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(30); + + { + try testing.expectEqual(point.Point{ + .active = .{ + .y = 0, + .x = 2, + }, + }, s.pointFromPin(.active, .{ + .node = s.pages.first.?, + .y = 30, + .x = 2, + }).?); + } + + // In history, invalid + { + try testing.expect(s.pointFromPin(.active, .{ + .node = s.pages.first.?, + .y = 21, + .x = 2, + }) == null); + } +} + +test "PageList pointFromPin active from prior page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + + { + try testing.expectEqual(point.Point{ + .active = .{ + .y = 0, + .x = 2, + }, + }, s.pointFromPin(.active, .{ + .node = s.pages.last.?, + .y = 0, + .x = 2, + }).?); + } + + // Prior page + { + try testing.expect(s.pointFromPin(.active, .{ + .node = s.pages.first.?, + .y = 0, + .x = 0, + }) == null); + } +} + +test "PageList pointFromPin traverse pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up at least 2 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 2) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + + { + const pages = s.totalPages(); + const page_cap = page.capacity.rows; + const expected_y = page_cap * (pages - 2) + 5; + + try testing.expectEqual(point.Point{ + .screen = .{ + .y = @intCast(expected_y), + .x = 2, + }, + }, s.pointFromPin(.screen, .{ + .node = s.pages.last.?.prev.?, + .y = 5, + .x = 2, + }).?); + } + + // Prior page + { + try testing.expect(s.pointFromPin(.active, .{ + .node = s.pages.first.?, + .y = 0, + .x = 0, + }) == null); + } +} +test "PageList active after grow" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + try s.growRows(10); + try testing.expectEqual(@as(usize, s.rows + 10), s.totalRows()); + + // Make sure all points make sense + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + { + const pt = s.getCell(.{ .screen = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + // Scrollbar should be in the active area + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 10, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList grow allows exceeding max size for active area" { + const testing = std.testing; + const alloc = testing.allocator; + + // Setup our initial page so that we fully take up one page. + const cap = try std_capacity.adjust(.{ .cols = 5 }); + var s = try init(alloc, 5, cap.rows, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Grow once because we guarantee at least two pages of + // capacity so we want to get to that. + _ = try s.grow(); + const start_pages = s.totalPages(); + try testing.expect(start_pages >= 2); + + // Surgically modify our pages so that they have a smaller size. + { + var it = s.pages.first; + while (it) |page| : (it = page.next) { + page.data.size.rows = 1; + page.data.capacity.rows = 1; + } + + // Avoid integrity check failures + s.total_rows = s.totalRows(); + } + + // Grow our row and ensure we don't prune pages because we need + // enough for the active area. + _ = try s.grow(); + try testing.expectEqual(start_pages + 1, s.totalPages()); +} + +test "PageList grow prune required with a single page" { + const testing = std.testing; + const alloc = testing.allocator; + + // Need scrollback > 0 to have a scrollbar to test + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // This block is all test setup. There is nothing required about this + // behavior during a refactor. This is setting up a scenario that is + // possible to trigger a bug (#2280). + { + // Increase our capacity until our page is larger than the standard size. + // This is important because it triggers a scenario where our calculated + // minSize() which is supposed to accommodate 2 pages is no longer true. + while (true) { + const layout = Page.layout(s.pages.first.?.data.capacity); + if (layout.total_size > std_size) break; + _ = try s.increaseCapacity(s.pages.first.?, .grapheme_bytes); + } + try testing.expect(s.pages.first != null); + try testing.expect(s.pages.first == s.pages.last); + } + + // Figure out the remaining number of rows. This is the amount that + // can be added to the current page before we need to allocate a new + // page. + const rem = rem: { + const page = s.pages.first.?; + break :rem page.data.capacity.rows - page.data.size.rows; + }; + for (0..rem) |_| try testing.expect(try s.grow() == null); + + // The next one we add will trigger a new page. + const new = try s.grow(); + try testing.expect(new != null); + try testing.expect(new != s.pages.first); + + // Scrollbar should be in the active area + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scrollbar with max_size 0 after grow" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, 0); + defer s.deinit(); + + // Grow some rows (simulates normal terminal output) + try s.growRows(10); + + const sb = s.scrollbar(); + + // With no scrollback (max_size = 0), total should equal rows + try testing.expectEqual(s.rows, sb.total); + + // With no scrollback, offset should be 0 (nowhere to scroll back to) + try testing.expectEqual(@as(usize, 0), sb.offset); +} + +test "PageList scroll with max_size 0 no history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, 0); + defer s.deinit(); + + try s.growRows(10); + + // Remember initial viewport position + const pt_before = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + + // Try to scroll backwards into "history" - should be no-op + s.scroll(.{ .delta_row = -5 }); + try testing.expect(s.viewport == .active); + + // Scroll to top - should also be no-op with no scrollback + s.scroll(.{ .top = {} }); + const pt_after = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(pt_before, pt_after); +} + +test "PageList scroll top" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + s.scroll(.{ .top = {} }); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 0, + .len = s.rows, + }, s.scrollbar()); + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 0, + .len = s.rows, + }, s.scrollbar()); + + s.scroll(.{ .active = {} }); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 20, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll delta row back" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + s.scroll(.{ .delta_row = -1 }); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows - 1, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 9, + } }, pt); + } + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 9, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows - 11, + .len = s.rows, + }, s.scrollbar()); + + s.scroll(.{ .delta_row = -1 }); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows - 12, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll delta row back overflow" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + s.scroll(.{ .delta_row = -100 }); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 0, + .len = s.rows, + }, s.scrollbar()); + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 0, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll delta row forward" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + s.scroll(.{ .top = {} }); + s.scroll(.{ .delta_row = 2 }); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 2, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 2, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll delta row forward into active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + s.scroll(.{ .delta_row = 2 }); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll delta row back without space preserves active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + s.scroll(.{ .delta_row = -1 }); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expect(s.viewport == .active); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to pin" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + s.scroll(.{ .pin = s.pin(.{ .screen = .{ + .y = 4, + .x = 2, + } }).? }); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 4, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 4, + } }, pt); + } + + s.scroll(.{ .pin = s.pin(.{ .screen = .{ + .y = 5, + .x = 2, + } }).? }); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 5, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, pt); + } +} + +test "PageList scroll to pin in active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + s.scroll(.{ .pin = s.pin(.{ .screen = .{ + .y = 30, + .x = 2, + } }).? }); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } +} + +test "PageList scroll to pin at top" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + s.scroll(.{ .pin = s.pin(.{ .screen = .{ + .y = 0, + .x = 2, + } }).? }); + + try testing.expect(s.viewport == .top); + + try testing.expectEqual(Scrollbar{ + .total = s.totalRows(), + .offset = 0, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } +} + +test "PageList scroll to row 0" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + s.scroll(.{ .row = 0 }); + try testing.expect(s.viewport == .top); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 0, + .len = s.rows, + }, s.scrollbar()); + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 0, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row in scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(20); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 20, + } }, pt); + } + + s.scroll(.{ .row = 5 }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 5, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, pt); + } + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 5, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row in middle" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(50); + + const total = s.total_rows; + const midpoint = total / 2; + s.scroll(.{ .row = midpoint }); + + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = midpoint, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = @as(size.CellCountInt, @intCast(midpoint)), + } }, pt); + } + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = @as(size.CellCountInt, @intCast(midpoint)), + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = midpoint, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row at active boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(20); + + const active_start = s.total_rows - s.rows; + + s.scroll(.{ .row = active_start }); + + try testing.expect(s.viewport == .active); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = @as(size.CellCountInt, @intCast(active_start)), + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); + + try s.growRows(10); + + try testing.expect(s.viewport == .active); + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row beyond active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(10); + + s.scroll(.{ .row = 1000 }); + + try testing.expect(s.viewport == .active); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row without scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + s.scroll(.{ .row = 5 }); + + try testing.expect(s.viewport == .active); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row then delta" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(30); + + s.scroll(.{ .row = 10 }); + + try testing.expect(s.viewport == .pin); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 10, + .len = s.rows, + }, s.scrollbar()); + + s.scroll(.{ .delta_row = 5 }); + + try testing.expect(s.viewport == .pin); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 15, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 15, + .len = s.rows, + }, s.scrollbar()); + + s.scroll(.{ .delta_row = -3 }); + + try testing.expect(s.viewport == .pin); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 12, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 12, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row with cache fast path down" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(50); + + s.scroll(.{ .row = 10 }); + + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 10, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, pt); + } + + // Verify cache is populated + try testing.expect(s.viewport_pin_row_offset != null); + try testing.expectEqual(@as(usize, 10), s.viewport_pin_row_offset.?); + + // Now scroll to a different row - this should use the fast path + s.scroll(.{ .row = 20 }); + + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 20, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 20, + } }, pt); + } + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 20, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 20, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll to row with cache fast path up" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(50); + + s.scroll(.{ .row = 30 }); + + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 30, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 30, + } }, pt); + } + + // Verify cache is populated + try testing.expect(s.viewport_pin_row_offset != null); + try testing.expectEqual(@as(usize, 30), s.viewport_pin_row_offset.?); + + // Now scroll up to a different row - this should use the fast path + s.scroll(.{ .row = 15 }); + + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 15, + .len = s.rows, + }, s.scrollbar()); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 15, + } }, pt); + } + + try s.growRows(10); + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 15, + } }, pt); + } + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 15, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList scroll clear" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + { + const cell = s.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + cell.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + { + const cell = s.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + cell.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + try s.scrollClear(); + + { + const pt = s.getCell(.{ .viewport = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } +} + +test "PageList: jump zero prompts" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, null); + defer s.deinit(); + try s.growRows(3); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + const rac = page.getRowAndCell(0, 1); + rac.row.semantic_prompt = .prompt; + } + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + } + + s.scroll(.{ .delta_prompt = 0 }); + try testing.expect(s.viewport == .active); + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); +} + +test "Screen: jump back one prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, null); + defer s.deinit(); + try s.growRows(3); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + const rac = page.getRowAndCell(0, 1); + rac.row.semantic_prompt = .prompt; + } + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + } + + // Jump back + { + s.scroll(.{ .delta_prompt = -1 }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pointFromPin(.screen, s.pin(.{ .viewport = .{} }).?).?); + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 1, + .len = s.rows, + }, s.scrollbar()); + } + { + s.scroll(.{ .delta_prompt = -1 }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pointFromPin(.screen, s.pin(.{ .viewport = .{} }).?).?); + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 1, + .len = s.rows, + }, s.scrollbar()); + } + + // Jump forward + { + s.scroll(.{ .delta_prompt = 1 }); + try testing.expect(s.viewport == .active); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); + } + { + s.scroll(.{ .delta_prompt = 1 }); + try testing.expect(s.viewport == .active); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = s.total_rows - s.rows, + .len = s.rows, + }, s.scrollbar()); + } +} + +test "Screen: jump forward prompt skips multiline continuation" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, null); + defer s.deinit(); + try s.growRows(7); + + // Multiline prompt on rows 1-3. + { + const p = s.pin(.{ .screen = .{ .y = 1 } }).?; + p.rowAndCell().row.semantic_prompt = .prompt; + } + { + const p = s.pin(.{ .screen = .{ .y = 2 } }).?; + p.rowAndCell().row.semantic_prompt = .prompt_continuation; + } + { + const p = s.pin(.{ .screen = .{ .y = 3 } }).?; + p.rowAndCell().row.semantic_prompt = .prompt_continuation; + } + + // Next prompt after command output. + { + const p = s.pin(.{ .screen = .{ .y = 6 } }).?; + p.rowAndCell().row.semantic_prompt = .prompt; + } + + // Starting at the first prompt line should jump to the next prompt, + // not to continuation lines. + s.scroll(.{ .row = 1 }); + s.scroll(.{ .delta_prompt = 1 }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 6, + } }, s.pointFromPin(.screen, s.pin(.{ .viewport = .{} }).?).?); + + // Starting in the middle of continuation lines should also jump to + // the next prompt. + s.scroll(.{ .row = 2 }); + s.scroll(.{ .delta_prompt = 1 }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 6, + } }, s.pointFromPin(.screen, s.pin(.{ .viewport = .{} }).?).?); +} + +test "PageList grow fit in capacity" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // So we know we're using capacity to grow + const last = &s.pages.last.?.data; + try testing.expect(last.size.rows < last.capacity.rows); + + // Grow + try testing.expect(try s.grow() == null); + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, pt); + } +} + +test "PageList grow allocate" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow to capacity + const last_node = s.pages.last.?; + const last = &s.pages.last.?.data; + for (0..last.capacity.rows - last.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + + // Grow, should allocate + const new = (try s.grow()).?; + try testing.expect(s.pages.last.? == new); + try testing.expect(last_node.next.? == new); + { + const cell = s.getCell(.{ .active = .{ .y = s.rows - 1 } }).?; + try testing.expect(cell.node == new); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = last.capacity.rows, + } }, cell.screenPoint()); + } +} + +test "PageList grow prune scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + // Use std_size to limit scrollback so pruning is triggered. + var s = try init(alloc, 80, 24, std_size); + defer s.deinit(); + + // Grow to capacity + const page1_node = s.pages.last.?; + const page1 = page1_node.data; + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + + // Grow and allocate one more page. Then fill that page up. + const page2_node = (try s.grow()).?; + const page2 = page2_node.data; + for (0..page2.capacity.rows - page2.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + + // Get our page size + const old_page_size = s.page_size; + + // Create a tracked pin in the first page + const p = try s.trackPin(s.pin(.{ .screen = .{} }).?); + defer s.untrackPin(p); + try testing.expect(p.node == s.pages.first.?); + + // Scroll back to create a pinned viewport (not active) + const pin_y = page1.capacity.rows / 2; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + + // Get the scrollbar state to populate the cache + const scrollbar_before = s.scrollbar(); + try testing.expectEqual(pin_y, scrollbar_before.offset); + + // Next should create a new page, but it should reuse our first + // page since we're at max size. + const new = (try s.grow()).?; + try testing.expect(s.pages.last.? == new); + try testing.expectEqual(s.page_size, old_page_size); + + // Our first should now be page2 and our last should be page1 + try testing.expectEqual(page2_node, s.pages.first.?); + try testing.expectEqual(page1_node, s.pages.last.?); + + // Our tracked pin should point to the top-left of the first page + try testing.expect(p.node == s.pages.first.?); + try testing.expect(p.x == 0); + try testing.expect(p.y == 0); + try testing.expect(p.garbage); + + // Verify the viewport offset cache was invalidated. After pruning, + // the offset should have changed because we removed rows from + // the beginning. + { + const scrollbar_after = s.scrollbar(); + const rows_pruned = page1.capacity.rows; + const expected_offset = if (pin_y >= rows_pruned) + pin_y - rows_pruned + else + 0; + try testing.expectEqual(expected_offset, scrollbar_after.offset); + } +} + +test "PageList grow prune scrollback with viewport pin not in pruned page" { + const testing = std.testing; + const alloc = testing.allocator; + + // Use std_size to limit scrollback so pruning is triggered. + var s = try init(alloc, 80, 24, std_size); + defer s.deinit(); + + // Grow to capacity of first page + const page1_node = s.pages.last.?; + const page1 = page1_node.data; + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + + // Grow and allocate second page, then fill it up + const page2_node = (try s.grow()).?; + const page2 = page2_node.data; + for (0..page2.capacity.rows - page2.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + + // Get our page size + const old_page_size = s.page_size; + + // Scroll back to create a pinned viewport in page2 (NOT page1) + // This is the key difference from the previous test - the viewport + // pin is NOT in the page that will be pruned. + const pin_y = page1.capacity.rows + 5; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expect(s.viewport_pin.node == page2_node); + + // Get the scrollbar state to populate the cache + const scrollbar_before = s.scrollbar(); + try testing.expectEqual(pin_y, scrollbar_before.offset); + + // Next grow will trigger pruning of the first page. + // The viewport_pin.node is page2, not page1, so it won't be moved + // by the pin update loop, but the cached offset still needs to be + // invalidated because rows were removed from the beginning. + const new = (try s.grow()).?; + try testing.expect(s.pages.last.? == new); + try testing.expectEqual(s.page_size, old_page_size); + + // Our first should now be page2 (page1 was pruned) + try testing.expectEqual(page2_node, s.pages.first.?); + + // The viewport pin should still be on page2, unchanged + try testing.expect(s.viewport_pin.node == page2_node); + + // Verify the viewport offset cache was invalidated/updated. + // After pruning, the offset should have decreased by the number + // of rows that were pruned. + const scrollbar_after = s.scrollbar(); + const rows_pruned = page1.capacity.rows; + const expected_offset = pin_y - rows_pruned; + try testing.expectEqual(expected_offset, scrollbar_after.offset); +} + +test "PageList eraseRows invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up several pages worth of history + const page = &s.pages.last.?.data; + { + var cur_page = s.pages.last.?; + for (0..page.capacity.rows * 3) |_| { + if (try s.grow()) |new_page| cur_page = new_page; + } + } + + // Scroll back to create a pinned viewport somewhere in the middle + // of the scrollback + const pin_y = page.capacity.rows; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Erase some history rows BEFORE the viewport pin. + // This removes rows from before our pin, which changes its absolute + // offset from the top, but the cache is not invalidated. + const rows_to_erase = page.capacity.rows / 2; + s.eraseHistory(.{ .history = .{ .y = rows_to_erase - 1 } }); + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y - rows_to_erase, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList eraseRow invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up several pages worth of history + const page = &s.pages.last.?.data; + { + var cur_page = s.pages.last.?; + for (0..page.capacity.rows * 3) |_| { + if (try s.grow()) |new_page| cur_page = new_page; + } + } + + // Scroll back to create a pinned viewport somewhere in the middle + // of the scrollback + const pin_y = page.capacity.rows; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Erase a single row from the history BEFORE the viewport pin. + // This removes one row from before our pin, which changes its absolute + // offset from the top by 1, but the cache is not invalidated. + try s.eraseRow(.{ .history = .{ .y = 0 } }); + + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y - 1, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList eraseRowBounded invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up several pages worth of history + const page = &s.pages.last.?.data; + { + var cur_page = s.pages.last.?; + for (0..page.capacity.rows * 3) |_| { + if (try s.grow()) |new_page| cur_page = new_page; + } + } + + // Scroll back to create a pinned viewport somewhere in the middle + // of the scrollback + const pin_y: u16 = 4; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Erase a row from the history BEFORE the viewport pin with a bounded + // shift. This removes one row from before our pin, which changes its + // absolute offset from the top by 1, but the cache is not invalidated. + try s.eraseRowBounded(.{ .history = .{ .y = 0 } }, 10); + + // Verify the scrollbar reflects the change (offset decreased by 1) + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y - 1, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList eraseRowBounded multi-page invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up several pages worth of history + const page = &s.pages.last.?.data; + { + var cur_page = s.pages.last.?; + for (0..page.capacity.rows * 3) |_| { + if (try s.grow()) |new_page| cur_page = new_page; + } + } + + // Scroll back to create a pinned viewport somewhere in the middle + // of the scrollback, after the first page + const pin_y = page.capacity.rows + 1; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Erase a row from the beginning of history with a limit that spans + // across multiple pages. This ensures we hit the code path where + // eraseRowBounded finds the limit boundary in a subsequent page. + const limit = page.capacity.rows + 10; + try s.eraseRowBounded(.{ .history = .{ .y = 0 } }, limit); + + // Verify the scrollbar reflects the change (offset decreased by 1) + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y - 1, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList eraseRowBounded full page shift invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up several pages worth of history + const page = &s.pages.last.?.data; + { + var cur_page = s.pages.last.?; + for (0..page.capacity.rows * 4) |_| { + if (try s.grow()) |new_page| cur_page = new_page; + } + } + + // Scroll back to create a pinned viewport somewhere well beyond + // the first two pages + const pin_y = 5; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Erase a row from the beginning of history with a limit that is + // larger than multiple full pages. This ensures we hit the code path + // where eraseRowBounded continues looping through entire pages, + // rotating all rows in each page until it reaches the limit or + // runs out of pages. + const limit = page.capacity.rows * 2 + 10; + try s.eraseRowBounded(.{ .history = .{ .y = 0 } }, limit); + + // Verify the scrollbar reflects the change (offset decreased by 1) + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y - 1, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList eraseRowBounded exhausts pages invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up several pages worth of history + const page = &s.pages.last.?.data; + { + var cur_page = s.pages.last.?; + for (0..page.capacity.rows * 3) |_| { + if (try s.grow()) |new_page| cur_page = new_page; + } + } + + // Our total rows should include history + const total_rows_before = s.totalRows(); + try testing.expect(total_rows_before > s.rows); + + // Scroll back to create a pinned viewport somewhere in the history, + // well after the erase will complete + const pin_y = page.capacity.rows * 2 + 10; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Erase a row from the beginning of history with a limit that is + // LARGER than all remaining pages combined. This ensures we exhaust + // all pages in the while loop and reach the cleanup code after the loop. + const limit = total_rows_before * 2; + try s.eraseRowBounded(.{ .history = .{ .y = 0 } }, limit); + + // Verify the scrollbar reflects the change (offset decreased by 1) + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y - 1, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList increaseCapacity to increase styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + + const original_styles_cap = s.pages.first.?.data.capacity.styles; + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write all our data so we can assert its the same after + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + } + + // Increase our styles + _ = try s.increaseCapacity(s.pages.first.?, .styles); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Verify capacity doubled + try testing.expectEqual( + original_styles_cap * 2, + page.capacity.styles, + ); + + // Verify data preserved + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + try testing.expectEqual( + @as(u21, @intCast(x)), + rac.cell.content.codepoint, + ); + } + } + } +} + +test "PageList increaseCapacity to increase graphemes" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + + const original_cap = s.pages.first.?.data.capacity.grapheme_bytes; + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + } + + _ = try s.increaseCapacity(s.pages.first.?, .grapheme_bytes); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + try testing.expectEqual(original_cap * 2, page.capacity.grapheme_bytes); + + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + try testing.expectEqual( + @as(u21, @intCast(x)), + rac.cell.content.codepoint, + ); + } + } + } +} + +test "PageList increaseCapacity to increase hyperlinks" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + + const original_cap = s.pages.first.?.data.capacity.hyperlink_bytes; + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + } + + _ = try s.increaseCapacity(s.pages.first.?, .hyperlink_bytes); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + try testing.expectEqual(original_cap * 2, page.capacity.hyperlink_bytes); + + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + try testing.expectEqual( + @as(u21, @intCast(x)), + rac.cell.content.codepoint, + ); + } + } + } +} + +test "PageList increaseCapacity to increase string_bytes" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + + const original_cap = s.pages.first.?.data.capacity.string_bytes; + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + } + + _ = try s.increaseCapacity(s.pages.first.?, .string_bytes); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + try testing.expectEqual(original_cap * 2, page.capacity.string_bytes); + + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + try testing.expectEqual( + @as(u21, @intCast(x)), + rac.cell.content.codepoint, + ); + } + } + } +} + +test "PageList increaseCapacity tracked pins" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + + // Create a tracked pin on the first page + const tracked = try s.trackPin(s.pin(.{ .active = .{ .x = 1, .y = 1 } }).?); + defer s.untrackPin(tracked); + + const old_node = s.pages.first.?; + try testing.expectEqual(old_node, tracked.node); + + // Increase capacity + const new_node = try s.increaseCapacity(s.pages.first.?, .styles); + + // Pin should now point to the new node + try testing.expectEqual(new_node, tracked.node); + try testing.expectEqual(@as(size.CellCountInt, 1), tracked.x); + try testing.expectEqual(@as(size.CellCountInt, 1), tracked.y); +} + +test "PageList increaseCapacity returns OutOfSpace at max capacity" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + + // Keep increasing styles capacity until we get OutOfSpace + const max_styles = std.math.maxInt(size.StyleCountInt); + while (true) { + _ = s.increaseCapacity( + s.pages.first.?, + .styles, + ) catch |err| { + // Before OutOfSpace, we should have reached maxInt + try testing.expectEqual(error.OutOfSpace, err); + try testing.expectEqual(max_styles, s.pages.first.?.data.capacity.styles); + break; + }; + } +} + +test "PageList increaseCapacity after col shrink" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 2, 0); + defer s.deinit(); + + // Shrink columns + try s.resize(.{ .cols = 5, .reflow = false }); + try testing.expectEqual(5, s.cols); + + { + const page = &s.pages.first.?.data; + try testing.expectEqual(5, page.size.cols); + try testing.expect(page.capacity.cols >= 10); + } + + // Increase capacity + _ = try s.increaseCapacity(s.pages.first.?, .styles); + + { + const page = &s.pages.first.?.data; + // size.cols should still be 5, not reverted to capacity.cols + try testing.expectEqual(5, page.size.cols); + try testing.expectEqual(5, s.cols); + } +} + +test "PageList increaseCapacity multi-page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow to create a second page + const page1_node = s.pages.last.?; + page1_node.data.pauseIntegrityChecks(true); + for (0..page1_node.data.capacity.rows - page1_node.data.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + page1_node.data.pauseIntegrityChecks(false); + try testing.expect(try s.grow() != null); + + // Now we have two pages + try testing.expect(s.pages.first != s.pages.last); + const page2_node = s.pages.last.?; + + const page1_styles_cap = s.pages.first.?.data.capacity.styles; + const page2_styles_cap = page2_node.data.capacity.styles; + + // Increase capacity on the first page only + _ = try s.increaseCapacity(s.pages.first.?, .styles); + + // First page capacity should be doubled + try testing.expectEqual( + page1_styles_cap * 2, + s.pages.first.?.data.capacity.styles, + ); + + // Second page should be unchanged + try testing.expectEqual( + page2_styles_cap, + s.pages.last.?.data.capacity.styles, + ); +} + +test "PageList increaseCapacity preserves dirty flag" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, 0); + defer s.deinit(); + + // Set page dirty flag and mark some rows as dirty + const page = &s.pages.first.?.data; + page.dirty = true; + + const rows = page.rows.ptr(page.memory); + rows[0].dirty = true; + rows[1].dirty = false; + rows[2].dirty = true; + rows[3].dirty = false; + + // Increase capacity + const new_node = try s.increaseCapacity(s.pages.first.?, .styles); + + // The page dirty flag should be preserved + try testing.expect(new_node.data.dirty); + + // Row dirty flags should be preserved + const new_rows = new_node.data.rows.ptr(new_node.data.memory); + try testing.expect(new_rows[0].dirty); + try testing.expect(!new_rows[1].dirty); + try testing.expect(new_rows[2].dirty); + try testing.expect(!new_rows[3].dirty); +} + +test "PageList pageIterator single page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // The viewport should be within a single page + try testing.expect(s.pages.first.?.next == null); + + // Iterate the active area + var it = s.pageIterator(.right_down, .{ .active = .{} }, null); + { + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.first.?); + try testing.expectEqual(@as(usize, 0), chunk.start); + try testing.expectEqual(@as(usize, s.rows), chunk.end); + } + + // Should only have one chunk + try testing.expect(it.next() == null); +} + +test "PageList pageIterator two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow to capacity + const page1_node = s.pages.last.?; + const page1 = page1_node.data; + page1_node.data.pauseIntegrityChecks(true); + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + page1_node.data.pauseIntegrityChecks(false); + try testing.expect(try s.grow() != null); + + // Iterate the active area + var it = s.pageIterator(.right_down, .{ .active = .{} }, null); + { + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.first.?); + const start = chunk.node.data.size.rows - s.rows + 1; + try testing.expectEqual(start, chunk.start); + try testing.expectEqual(chunk.node.data.size.rows, chunk.end); + } + { + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.last.?); + const start: usize = 0; + try testing.expectEqual(start, chunk.start); + try testing.expectEqual(start + 1, chunk.end); + } + try testing.expect(it.next() == null); +} + +test "PageList pageIterator history two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow to capacity + const page1_node = s.pages.last.?; + const page1 = page1_node.data; + page1_node.data.pauseIntegrityChecks(true); + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + page1_node.data.pauseIntegrityChecks(false); + try testing.expect(try s.grow() != null); + + // Iterate the active area + var it = s.pageIterator(.right_down, .{ .history = .{} }, null); + { + const active_tl = s.getTopLeft(.active); + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.first.?); + const start: usize = 0; + try testing.expectEqual(start, chunk.start); + try testing.expectEqual(active_tl.y, chunk.end); + } + try testing.expect(it.next() == null); +} + +test "PageList pageIterator reverse single page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // The viewport should be within a single page + try testing.expect(s.pages.first.?.next == null); + + // Iterate the active area + var it = s.pageIterator(.left_up, .{ .active = .{} }, null); + { + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.first.?); + try testing.expectEqual(@as(usize, 0), chunk.start); + try testing.expectEqual(@as(usize, s.rows), chunk.end); + } + + // Should only have one chunk + try testing.expect(it.next() == null); +} + +test "PageList pageIterator reverse two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow to capacity + const page1_node = s.pages.last.?; + const page1 = page1_node.data; + page1_node.data.pauseIntegrityChecks(true); + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + page1_node.data.pauseIntegrityChecks(false); + try testing.expect(try s.grow() != null); + + // Iterate the active area + var it = s.pageIterator(.left_up, .{ .active = .{} }, null); + var count: usize = 0; + { + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.last.?); + const start: usize = 0; + try testing.expectEqual(start, chunk.start); + try testing.expectEqual(start + 1, chunk.end); + count += chunk.end - chunk.start; + } + { + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.first.?); + const start = chunk.node.data.size.rows - s.rows + 1; + try testing.expectEqual(start, chunk.start); + try testing.expectEqual(chunk.node.data.size.rows, chunk.end); + count += chunk.end - chunk.start; + } + try testing.expect(it.next() == null); + try testing.expectEqual(s.rows, count); +} + +test "PageList pageIterator reverse history two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow to capacity + const page1_node = s.pages.last.?; + const page1 = page1_node.data; + page1_node.data.pauseIntegrityChecks(true); + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try s.grow() == null); + } + page1_node.data.pauseIntegrityChecks(false); + try testing.expect(try s.grow() != null); + + // Iterate the active area + var it = s.pageIterator(.left_up, .{ .history = .{} }, null); + { + const active_tl = s.getTopLeft(.active); + const chunk = it.next().?; + try testing.expect(chunk.node == s.pages.first.?); + const start: usize = 0; + try testing.expectEqual(start, chunk.start); + try testing.expectEqual(active_tl.y, chunk.end); + } + try testing.expect(it.next() == null); +} + +test "PageList cellIterator" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + var it = s.cellIterator(.right_down, .{ .screen = .{} }, null); + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 1, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList cellIterator reverse" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + var it = s.cellIterator(.left_up, .{ .screen = .{} }, null); + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 1, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList promptIterator left_up" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + // Normal prompt + { + const rac = page.getRowAndCell(0, 3); + rac.row.semantic_prompt = .prompt; + } + // Continuation + { + const rac = page.getRowAndCell(0, 6); + rac.row.semantic_prompt = .prompt; + } + { + const rac = page.getRowAndCell(0, 7); + rac.row.semantic_prompt = .prompt_continuation; + } + { + const rac = page.getRowAndCell(0, 8); + rac.row.semantic_prompt = .prompt_continuation; + } + // Broken continuation that has non-prompts in between + { + const rac = page.getRowAndCell(0, 12); + rac.row.semantic_prompt = .prompt_continuation; + } + + var it = s.promptIterator(.left_up, .{ .screen = .{} }, null); + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 12, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 6, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 3, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList promptIterator right_down" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + // Normal prompt + { + const rac = page.getRowAndCell(0, 3); + rac.row.semantic_prompt = .prompt; + } + // Continuation (prompt on row 6, continuation on rows 7-8) + { + const rac = page.getRowAndCell(0, 6); + rac.row.semantic_prompt = .prompt; + } + { + const rac = page.getRowAndCell(0, 7); + rac.row.semantic_prompt = .prompt_continuation; + } + { + const rac = page.getRowAndCell(0, 8); + rac.row.semantic_prompt = .prompt_continuation; + } + // Broken continuation that has non-prompts in between (orphaned continuation at row 12) + { + const rac = page.getRowAndCell(0, 12); + rac.row.semantic_prompt = .prompt_continuation; + } + + var it = s.promptIterator(.right_down, .{ .screen = .{} }, null); + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 3, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 6, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 12, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList promptIterator right_down continuation at start" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt continuation at row 0 (no prior rows - simulates trimmed scrollback) + { + const rac = page.getRowAndCell(0, 0); + rac.row.semantic_prompt = .prompt_continuation; + } + { + const rac = page.getRowAndCell(0, 1); + rac.row.semantic_prompt = .prompt_continuation; + } + // Normal prompt later + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + } + + var it = s.promptIterator(.right_down, .{ .screen = .{} }, null); + { + // Should return the first continuation line since there's no prior prompt + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pointFromPin(.screen, p).?); + } + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList promptIterator right_down with prompt before continuation" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 2, continuation on rows 3-4 + // Starting iteration from row 3 should still find the prompt at row 2 + { + const rac = page.getRowAndCell(0, 2); + rac.row.semantic_prompt = .prompt; + } + { + const rac = page.getRowAndCell(0, 3); + rac.row.semantic_prompt = .prompt_continuation; + } + { + const rac = page.getRowAndCell(0, 4); + rac.row.semantic_prompt = .prompt_continuation; + } + + // Start iteration from row 3 (middle of the continuation) + // Since we start on a continuation line, we treat it as the prompt start + // (handles case where scrollback pruned the actual prompt) + var it = s.promptIterator(.right_down, .{ .screen = .{ .y = 3 } }, null); + { + const p = it.next().?; + // Returns row 3 since that's the first prompt-related line we encounter + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 3, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList promptIterator right_down limit inclusive" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Iterate with limit at row 5 (the prompt row) - should include it + var it = s.promptIterator(.right_down, .{ .screen = .{} }, .{ .screen = .{ .y = 5 } }); + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList promptIterator left_up limit inclusive" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Iterate with limit at row 10 (the prompt row) - should include it + // tl_pt is the limit (upper bound), bl_pt is the start point for left_up + var it = s.promptIterator(.left_up, .{ .screen = .{ .y = 10 } }, .{ .screen = .{ .y = 15 } }); + { + const p = it.next().?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 10, + } }, s.pointFromPin(.screen, p).?); + } + try testing.expect(it.next() == null); +} + +test "PageList highlightSemanticContent prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // Start the prompt for the first 5 cols + for (0..5) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + .semantic_content = .prompt, + }; + } + + // Next 3 let's make input + for (5..8) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'B' }, + .semantic_content = .input, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 2, .y = 5 } }).?, + .prompt, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 5, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent prompt with output" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 3 cols are prompt + for (0..3) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Next 4 are input + for (3..7) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'l' }, + .semantic_content = .input, + }; + } + + // Rest is output (shouldn't be included in prompt highlight) + for (7..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting from prompt should include prompt and input, but stop at output + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .prompt, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 6, + .y = 5, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent prompt multiline" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt starts on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First row is all prompt + for (0..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + } + // Row 6 continues with input + { + for (0..5) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting should span both rows + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 2, .y = 5 } }).?, + .prompt, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 6, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent prompt only" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 with only prompt content (no input) + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + for (0..5) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting should only include the prompt cells + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .prompt, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 5, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent prompt to end of screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Single prompt on row 15, no following prompt + { + const rac = page.getRowAndCell(0, 15); + rac.row.semantic_prompt = .prompt; + + for (0..3) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + for (3..8) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + } + + // Highlighting should include prompt and input up to column 7 + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 15 } }).?, + .prompt, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 15, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 15, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent input basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 3 cols are prompt + for (0..3) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Next 5 are input + for (3..8) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'l' }, + .semantic_content = .input, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting input should only include input cells + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .input, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 5, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent input with output" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 2 cols are prompt + for (0..2) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Next 3 are input + for (2..5) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + + // Rest is output + for (5..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting input should stop at output + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .input, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 5, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent input multiline with continuation" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 2 cols are prompt + for (0..2) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Rest is input + for (2..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + } + // Row 6 has continuation prompt then more input + { + // Continuation prompt + for (0..2) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '>' }, + .semantic_content = .prompt, + }; + } + + // More input + for (2..6) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'd' }, + .semantic_content = .input, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting input should span both rows, skipping continuation prompts + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .input, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 6, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent input no input returns null" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 with only prompt, then immediately output + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 3 cols are prompt + for (0..3) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Rest is output (no input!) + for (3..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting input should return null when there's no input + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .input, + ); + try testing.expect(hl == null); +} + +test "PageList highlightSemanticContent input to end of screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Single prompt on row 15, no following prompt + { + const rac = page.getRowAndCell(0, 15); + rac.row.semantic_prompt = .prompt; + + for (0..2) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + for (2..7) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + } + + // Highlighting input with no following prompt + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 15 } }).?, + .input, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 15, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 6, + .y = 15, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent input prompt only returns null" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 with only prompt content, no input or output + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // All cells are prompt + for (0..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + } + // Mark rows 6-9 as prompt to ensure no input before next prompt + { + for (6..10) |y| { + for (0..10) |x| { + const cell = page.getRowAndCell(x, y).cell; + cell.semantic_content = .prompt; + } + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting input should return null when there's only prompts + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .input, + ); + try testing.expect(hl == null); +} + +test "PageList highlightSemanticContent output basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 2 cols are prompt + for (0..2) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Next 3 are input + for (2..5) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'l' }, + .semantic_content = .input, + }; + } + + // Cols 5-7 are output + for (5..8) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + + // Mark remaining cells as prompt to bound the output + for (8..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.semantic_content = .prompt; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting output should only include output cells + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .output, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 5, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent output multiline" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 2 cols are prompt + for (0..2) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Next 2 are input + for (2..4) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'l' }, + .semantic_content = .input, + }; + } + + // Rest of row 5 is output + for (4..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Row 6 is all output + { + for (0..10) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Row 7 has partial output then input to bound it + { + for (0..5) |x| { + const cell = page.getRowAndCell(x, 7).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + for (5..10) |x| { + const cell = page.getRowAndCell(x, 7).cell; + cell.semantic_content = .input; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting output should span multiple rows + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .output, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 7, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent output stops at next prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 2 cols are prompt + for (0..2) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Next 2 are input + for (2..4) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'l' }, + .semantic_content = .input, + }; + } + + // Rest is output + for (4..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Row 6 has output then prompt starts + { + for (0..3) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + // Next prompt marker on same row + for (3..6) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + } + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting output should stop before prompt/input + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .output, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 5, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 6, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent output to end of screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Single prompt on row 15, no following prompt + { + const rac = page.getRowAndCell(0, 15); + rac.row.semantic_prompt = .prompt; + + for (0..2) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + for (2..4) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + + for (4..10) |x| { + const cell = page.getRowAndCell(x, 15).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + // Row 16 has output then prompt to bound it + { + for (0..8) |x| { + const cell = page.getRowAndCell(x, 16).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + for (8..10) |x| { + const cell = page.getRowAndCell(x, 16).cell; + cell.semantic_content = .prompt; + } + } + + // Highlighting output with no following prompt + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 15 } }).?, + .output, + ).?; + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 15, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 16, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList highlightSemanticContent output no output returns null" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 with only prompt and input, no output + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 3 cols are prompt + for (0..3) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + + // Rest is input (must explicitly mark all cells to avoid default .output) + for (3..10) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'c' }, + .semantic_content = .input, + }; + } + } + // Mark rows 6-9 as input to ensure no output between prompts + { + for (6..10) |y| { + for (0..10) |x| { + const cell = page.getRowAndCell(x, y).cell; + cell.semantic_content = .input; + } + } + } + // Prompt on row 10 (no output between prompts) + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting output should return null when there's no output + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .output, + ); + try testing.expect(hl == null); +} + +test "PageList highlightSemanticContent output skips empty cells" { + // Tests that empty cells with default .output semantic content are + // not selected as output. This can happen when a prompt/input line + // doesn't fill the entire row - trailing cells have default .output. + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 20, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Prompt on row 5 - only fills first 3 cells, rest are empty with default .output + { + const rac = page.getRowAndCell(0, 5); + rac.row.semantic_prompt = .prompt; + + // First 3 cols are prompt with text + for (0..3) |x| { + const cell = page.getRowAndCell(x, 5).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '$' }, + .semantic_content = .prompt, + }; + } + // Cells 3-9 are empty (codepoint = 0) with default .output semantic content + // This simulates what happens when a short prompt is written + } + + // Row 6 has input (short, doesn't fill line) + { + for (0..4) |x| { + const cell = page.getRowAndCell(x, 6).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'l' }, + .semantic_content = .input, + }; + } + // Cells 4-9 are empty with default .output + } + + // Row 7-8 have actual output with text + { + for (7..9) |y| { + for (0..5) |x| { + const cell = page.getRowAndCell(x, y).cell; + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'o' }, + .semantic_content = .output, + }; + } + } + } + + // Prompt on row 10 + { + const rac = page.getRowAndCell(0, 10); + rac.row.semantic_prompt = .prompt; + } + + // Highlighting output should skip empty cells on rows 5-6 and find + // the actual output starting at row 7 + const hl = s.highlightSemanticContent( + s.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + .output, + ).?; + // Output should start at row 7, not row 5 (where empty cells have default .output) + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 7, + } }, s.pointFromPin(.screen, hl.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 8, + } }, s.pointFromPin(.screen, hl.end).?); +} + +test "PageList erase" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 6), s.totalPages()); + + // Our total rows should be large + try testing.expect(s.total_rows > s.rows); + + // Erase the entire history, we should be back to just our active set. + s.eraseHistory(null); + try testing.expectEqual(s.rows, s.total_rows); + + // We should be back to just one page + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try testing.expect(s.pages.first == s.pages.last); +} + +test "PageList erase reaccounts page size" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + const start_size = s.page_size; + + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + try testing.expect(s.page_size > start_size); + + // Erase the entire history, we should be back to just our active set. + s.eraseHistory(null); + try testing.expectEqual(start_size, s.page_size); +} + +test "PageList erase row with tracked pin resets to top-left" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + + // Our total rows should be large + try testing.expect(s.total_rows > s.rows); + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .history = .{} }).?); + defer s.untrackPin(p); + + // Erase the entire history, we should be back to just our active set. + s.eraseHistory(null); + try testing.expectEqual(s.rows, s.total_rows); + + // Our pin should move to the first page + try testing.expectEqual(s.pages.first.?, p.node); + try testing.expectEqual(@as(usize, 0), p.y); + try testing.expectEqual(@as(usize, 0), p.x); +} + +test "PageList erase row with tracked pin shifts" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .y = 4, .x = 2 } }).?); + defer s.untrackPin(p); + + // Erase only a few rows in our active + s.eraseActive(3); + try testing.expectEqual(s.rows, s.total_rows); + + // Our pin should move to the first page + try testing.expectEqual(s.pages.first.?, p.node); + try testing.expectEqual(@as(usize, 0), p.y); + try testing.expectEqual(@as(usize, 2), p.x); +} + +test "PageList erase row with tracked pin is erased" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .y = 2, .x = 2 } }).?); + defer s.untrackPin(p); + + // Erase the entire history, we should be back to just our active set. + s.eraseActive(3); + try testing.expectEqual(s.rows, s.total_rows); + + // Our pin should move to the first page + try testing.expectEqual(s.pages.first.?, p.node); + try testing.expectEqual(@as(usize, 0), p.y); + try testing.expectEqual(@as(usize, 0), p.x); +} + +test "PageList erase resets viewport to active if moves within active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + + // Move our viewport to the top + s.scroll(.{ .delta_row = -@as(isize, @intCast(s.total_rows)) }); + try testing.expect(s.viewport == .top); + + // Erase the entire history, we should be back to just our active set. + s.eraseHistory(null); + try testing.expect(s.viewport == .active); +} + +test "PageList erase resets viewport if inside erased page but not active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + + // Move our viewport to the top + s.scroll(.{ .delta_row = -@as(isize, @intCast(s.total_rows)) }); + try testing.expect(s.viewport == .top); + + // Erase the entire history, we should be back to just our active set. + s.eraseHistory(.{ .history = .{ .y = 2 } }); + try testing.expect(s.viewport == .top); +} + +test "PageList erase resets viewport to active if top is inside active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow so we take up at least 5 pages. + const page = &s.pages.last.?.data; + var cur_page = s.pages.last.?; + cur_page.data.pauseIntegrityChecks(true); + for (0..page.capacity.rows * 5) |_| { + if (try s.grow()) |new_page| { + cur_page.data.pauseIntegrityChecks(false); + cur_page = new_page; + cur_page.data.pauseIntegrityChecks(true); + } + } + cur_page.data.pauseIntegrityChecks(false); + + // Move our viewport to the top + s.scroll(.{ .top = {} }); + + // Erase the entire history, we should be back to just our active set. + s.eraseHistory(null); + try testing.expect(s.viewport == .active); +} + +test "PageList erase active regrows automatically" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expect(s.totalRows() == s.rows); + s.eraseActive(10); + try testing.expect(s.totalRows() == s.rows); +} + +test "PageList erase a one-row active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 1, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Write our letter + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + s.eraseActive(0); + try testing.expectEqual(s.rows, s.total_rows); + + // The row should be empty + { + const get = s.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expectEqual(@as(u21, 0), get.cell.content.codepoint); + } +} + +test "PageList eraseRowBounded less than full row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 10, null); + defer s.deinit(); + + // Pins + const p_top = try s.trackPin(s.pin(.{ .active = .{ .y = 5, .x = 0 } }).?); + defer s.untrackPin(p_top); + const p_bot = try s.trackPin(s.pin(.{ .active = .{ .y = 8, .x = 0 } }).?); + defer s.untrackPin(p_bot); + const p_out = try s.trackPin(s.pin(.{ .active = .{ .y = 9, .x = 0 } }).?); + defer s.untrackPin(p_out); + + // Erase only a few rows in our active + try s.eraseRowBounded(.{ .active = .{ .y = 5 } }, 3); + try testing.expectEqual(s.rows, s.totalRows()); + + // The erased rows should be dirty + try testing.expect(s.isDirty(.{ .active = .{ .x = 0, .y = 5 } })); + try testing.expect(s.isDirty(.{ .active = .{ .x = 0, .y = 6 } })); + try testing.expect(s.isDirty(.{ .active = .{ .x = 0, .y = 7 } })); + + try testing.expectEqual(s.pages.first.?, p_top.node); + try testing.expectEqual(@as(usize, 4), p_top.y); + try testing.expectEqual(@as(usize, 0), p_top.x); + + try testing.expectEqual(s.pages.first.?, p_bot.node); + try testing.expectEqual(@as(usize, 7), p_bot.y); + try testing.expectEqual(@as(usize, 0), p_bot.x); + + try testing.expectEqual(s.pages.first.?, p_out.node); + try testing.expectEqual(@as(usize, 9), p_out.y); + try testing.expectEqual(@as(usize, 0), p_out.x); +} + +test "PageList eraseRowBounded with pin at top" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 10, null); + defer s.deinit(); + + // Pins + const p_top = try s.trackPin(s.pin(.{ .active = .{ .y = 0, .x = 5 } }).?); + defer s.untrackPin(p_top); + + // Erase only a few rows in our active + try s.eraseRowBounded(.{ .active = .{ .y = 0 } }, 3); + try testing.expectEqual(s.rows, s.totalRows()); + + // The erased rows should be dirty + try testing.expect(s.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(s.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(s.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + try testing.expectEqual(s.pages.first.?, p_top.node); + try testing.expectEqual(@as(usize, 0), p_top.y); + try testing.expectEqual(@as(usize, 0), p_top.x); +} + +test "PageList eraseRowBounded full rows single page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 10, null); + defer s.deinit(); + + // Pins + const p_in = try s.trackPin(s.pin(.{ .active = .{ .y = 7, .x = 0 } }).?); + defer s.untrackPin(p_in); + const p_out = try s.trackPin(s.pin(.{ .active = .{ .y = 9, .x = 0 } }).?); + defer s.untrackPin(p_out); + + // Erase only a few rows in our active + try s.eraseRowBounded(.{ .active = .{ .y = 5 } }, 10); + try testing.expectEqual(s.rows, s.totalRows()); + + // The erased rows should be dirty + for (5..10) |y| try testing.expect(s.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + // Our pin should move to the first page + try testing.expectEqual(s.pages.first.?, p_in.node); + try testing.expectEqual(@as(usize, 6), p_in.y); + try testing.expectEqual(@as(usize, 0), p_in.x); + + try testing.expectEqual(s.pages.first.?, p_out.node); + try testing.expectEqual(@as(usize, 8), p_out.y); + try testing.expectEqual(@as(usize, 0), p_out.x); +} + +test "PageList eraseRowBounded full rows two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 10, null); + defer s.deinit(); + + // Grow to two pages so our active area straddles + { + const page = &s.pages.last.?.data; + page.pauseIntegrityChecks(true); + for (0..page.capacity.rows - page.size.rows) |_| _ = try s.grow(); + page.pauseIntegrityChecks(false); + try s.growRows(5); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + try testing.expectEqual(@as(usize, 5), s.pages.last.?.data.size.rows); + } + + // Pins + const p_first = try s.trackPin(s.pin(.{ .active = .{ .y = 4, .x = 0 } }).?); + defer s.untrackPin(p_first); + const p_first_out = try s.trackPin(s.pin(.{ .active = .{ .y = 3, .x = 0 } }).?); + defer s.untrackPin(p_first_out); + const p_in = try s.trackPin(s.pin(.{ .active = .{ .y = 8, .x = 0 } }).?); + defer s.untrackPin(p_in); + const p_out = try s.trackPin(s.pin(.{ .active = .{ .y = 9, .x = 0 } }).?); + defer s.untrackPin(p_out); + + { + try testing.expectEqual(s.pages.last.?.prev.?, p_first.node); + try testing.expectEqual(@as(usize, p_first.node.data.size.rows - 1), p_first.y); + try testing.expectEqual(@as(usize, 0), p_first.x); + + try testing.expectEqual(s.pages.last.?.prev.?, p_first_out.node); + try testing.expectEqual(@as(usize, p_first_out.node.data.size.rows - 2), p_first_out.y); + try testing.expectEqual(@as(usize, 0), p_first_out.x); + + try testing.expectEqual(s.pages.last.?, p_in.node); + try testing.expectEqual(@as(usize, 3), p_in.y); + try testing.expectEqual(@as(usize, 0), p_in.x); + + try testing.expectEqual(s.pages.last.?, p_out.node); + try testing.expectEqual(@as(usize, 4), p_out.y); + try testing.expectEqual(@as(usize, 0), p_out.x); + } + + // Erase only a few rows in our active + try s.eraseRowBounded(.{ .active = .{ .y = 4 } }, 4); + + // The erased rows should be dirty + for (4..8) |y| try testing.expect(s.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + // In page in first page is shifted + try testing.expectEqual(s.pages.last.?.prev.?, p_first.node); + try testing.expectEqual(@as(usize, p_first.node.data.size.rows - 2), p_first.y); + try testing.expectEqual(@as(usize, 0), p_first.x); + + // Out page in first page should not be shifted + try testing.expectEqual(s.pages.last.?.prev.?, p_first_out.node); + try testing.expectEqual(@as(usize, p_first_out.node.data.size.rows - 2), p_first_out.y); + try testing.expectEqual(@as(usize, 0), p_first_out.x); + + // In page is shifted + try testing.expectEqual(s.pages.last.?, p_in.node); + try testing.expectEqual(@as(usize, 2), p_in.y); + try testing.expectEqual(@as(usize, 0), p_in.x); + + // Out page is not shifted + try testing.expectEqual(s.pages.last.?, p_out.node); + try testing.expectEqual(@as(usize, 4), p_out.y); + try testing.expectEqual(@as(usize, 0), p_out.x); +} + +test "PageList clone" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + var s2 = try s.clone(alloc, .{ + .top = .{ .screen = .{} }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, s.rows), s2.totalRows()); +} + +test "PageList clone partial trimmed right" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 20, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + try s.growRows(30); + + var s2 = try s.clone(alloc, .{ + .top = .{ .screen = .{} }, + .bot = .{ .screen = .{ .y = 39 } }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, 40), s2.totalRows()); +} + +test "PageList clone partial trimmed left" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 20, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + try s.growRows(30); + + var s2 = try s.clone(alloc, .{ + .top = .{ .screen = .{ .y = 10 } }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, 40), s2.totalRows()); +} + +test "PageList clone partial trimmed left reclaims styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 20, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + try s.growRows(30); + + // Style the rows we're trimming + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + const style: stylepkg.Style = .{ .flags = .{ .bold = true } }; + const style_id = try page.styles.add(page.memory, style); + + var it = s.rowIterator(.left_up, .{ .screen = .{} }, .{ .screen = .{ .y = 9 } }); + while (it.next()) |p| { + const rac = p.rowAndCell(); + rac.row.styled = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + .style_id = style_id, + }; + page.styles.use(page.memory, style_id); + } + + // We're over-counted by 1 because `add` implies `use`. + page.styles.release(page.memory, style_id); + + // Expect to have one style + try testing.expectEqual(1, page.styles.count()); + } + + var s2 = try s.clone(alloc, .{ + .top = .{ .screen = .{ .y = 10 } }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, 40), s2.totalRows()); + + { + try testing.expect(s2.pages.first == s2.pages.last); + const page = &s2.pages.first.?.data; + try testing.expectEqual(0, page.styles.count()); + } +} + +test "PageList clone partial trimmed both" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 20, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + try s.growRows(30); + + var s2 = try s.clone(alloc, .{ + .top = .{ .screen = .{ .y = 10 } }, + .bot = .{ .screen = .{ .y = 35 } }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, 26), s2.totalRows()); +} + +test "PageList clone less than active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + var s2 = try s.clone(alloc, .{ + .top = .{ .active = .{ .y = 5 } }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, s.rows), s2.totalRows()); +} + +test "PageList clone remap tracked pin" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Put a tracked pin in the screen + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 6 } }).?); + defer s.untrackPin(p); + + var pin_remap = Clone.TrackedPinsRemap.init(alloc); + defer pin_remap.deinit(); + var s2 = try s.clone(alloc, .{ + .top = .{ .active = .{ .y = 5 } }, + .tracked_pins = &pin_remap, + }); + defer s2.deinit(); + + // We should be able to find our tracked pin + const p2 = pin_remap.get(p).?; + try testing.expectEqual( + point.Point{ .active = .{ .x = 0, .y = 1 } }, + s2.pointFromPin(.active, p2.*).?, + ); +} + +test "PageList clone remap tracked pin not in cloned area" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Put a tracked pin in the screen + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 3 } }).?); + defer s.untrackPin(p); + + var pin_remap = Clone.TrackedPinsRemap.init(alloc); + defer pin_remap.deinit(); + var s2 = try s.clone(alloc, .{ + .top = .{ .active = .{ .y = 5 } }, + .tracked_pins = &pin_remap, + }); + defer s2.deinit(); + + // We should be able to find our tracked pin + try testing.expect(pin_remap.get(p) == null); +} + +test "PageList clone full dirty" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Mark a row as dirty + s.markDirty(.{ .active = .{ .x = 0, .y = 0 } }); + s.markDirty(.{ .active = .{ .x = 0, .y = 12 } }); + s.markDirty(.{ .active = .{ .x = 0, .y = 23 } }); + + var s2 = try s.clone(alloc, .{ + .top = .{ .screen = .{} }, + }); + defer s2.deinit(); + try testing.expectEqual(@as(usize, s.rows), s2.totalRows()); + + // Should still be dirty + try testing.expect(s2.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!s2.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(s2.isDirty(.{ .active = .{ .x = 0, .y = 12 } })); + try testing.expect(!s2.isDirty(.{ .active = .{ .x = 0, .y = 14 } })); + try testing.expect(s2.isDirty(.{ .active = .{ .x = 0, .y = 23 } })); +} + +test "PageList resize (no reflow) more rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 3, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 2 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .rows = 10, .reflow = false }); + try testing.expectEqual(@as(usize, 10), s.rows); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // Our cursor should not move because we have no scrollback so + // we just grew. + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, s.pointFromPin(.active, p.*).?); + + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } +} + +test "PageList resize (no reflow) more rows with history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 3, null); + defer s.deinit(); + try s.growRows(50); + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 50, + } }, pt); + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 2 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .rows = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.rows); + try testing.expectEqual(@as(usize, 53), s.totalRows()); + + // Our cursor should move since it's in the scrollback + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 4, + } }, s.pointFromPin(.active, p.*).?); + + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 48, + } }, pt); + } +} + +test "PageList resize (no reflow) less rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // This is required for our writing below to work + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write into all rows so we don't get trim behavior + for (0..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + // Resize + try s.resize(.{ .rows = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.rows); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, pt); + } +} + +test "PageList resize (no reflow) one rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // This is required for our writing below to work + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write into all rows so we don't get trim behavior + for (0..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + // Resize + try s.resize(.{ .rows = 1, .reflow = false }); + try testing.expectEqual(@as(usize, 1), s.rows); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 9, + } }, pt); + } +} + +test "PageList resize (no reflow) less rows cursor on bottom" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // This is required for our writing below to work + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write into all rows so we don't get trim behavior + for (0..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 9 } }).?); + defer s.untrackPin(p); + { + const cursor = s.pointFromPin(.active, p.*).?.active; + const get = s.getCell(.{ .active = .{ + .x = cursor.x, + .y = cursor.y, + } }).?; + try testing.expectEqual(@as(u21, 9), get.cell.content.codepoint); + } + + // Resize + try s.resize(.{ .rows = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.rows); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // Our cursor should move since it's in the scrollback + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 4, + } }, s.pointFromPin(.active, p.*).?); + + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, pt); + } +} +test "PageList resize (no reflow) less rows cursor in scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // This is required for our writing below to work + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write into all rows so we don't get trim behavior + for (0..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 2 } }).?); + defer s.untrackPin(p); + { + const cursor = s.pointFromPin(.active, p.*).?.active; + const get = s.getCell(.{ .active = .{ + .x = cursor.x, + .y = cursor.y, + } }).?; + try testing.expectEqual(@as(u21, 2), get.cell.content.codepoint); + } + + // Resize + try s.resize(.{ .rows = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.rows); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // Our cursor should move since it's in the scrollback + try testing.expect(s.pointFromPin(.active, p.*) == null); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, s.pointFromPin(.screen, p.*).?); + + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 5, + } }, pt); + } +} + +test "PageList resize (no reflow) less rows trims blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 5, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write codepoint into first line + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + // Fill remaining lines with a background color + for (1..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .bg_color_rgb, + .content = .{ .color_rgb = .{ .r = 0xFF, .g = 0, .b = 0 } }, + }; + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 0 } }).?); + defer s.untrackPin(p); + { + const cursor = s.pointFromPin(.active, p.*).?.active; + const get = s.getCell(.{ .active = .{ + .x = cursor.x, + .y = cursor.y, + } }).?; + try testing.expectEqual(@as(u21, 'A'), get.cell.content.codepoint); + } + + // Resize + try s.resize(.{ .rows = 2, .reflow = false }); + try testing.expectEqual(@as(usize, 2), s.rows); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + // Our cursor should not move since we trimmed + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); + + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } +} + +test "PageList resize (no reflow) less rows trims blank lines cursor in blank line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 5, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write codepoint into first line + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + // Fill remaining lines with a background color + for (1..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .bg_color_rgb, + .content = .{ .color_rgb = .{ .r = 0xFF, .g = 0, .b = 0 } }, + }; + } + + // Put a tracked pin in a blank line + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 3 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .rows = 2, .reflow = false }); + try testing.expectEqual(@as(usize, 2), s.rows); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Our cursor should not move since we trimmed + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize (no reflow) less rows trims blank lines erases pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 100, 5, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Resize to take up two pages + { + const rows = page.capacity.rows + 10; + try s.resize(.{ .rows = rows, .reflow = false }); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + } + + // Write codepoint into first line + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + // Resize down. Every row except the first is blank so we + // should erase the second page. + try s.resize(.{ .rows = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.rows); + try testing.expectEqual(@as(usize, 5), s.totalRows()); + try testing.expectEqual(@as(usize, 1), s.totalPages()); +} + +test "PageList resize (no reflow) more rows extends blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 3, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write codepoint into first line + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + + // Fill remaining lines with a background color + for (1..s.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .bg_color_rgb, + .content = .{ .color_rgb = .{ .r = 0xFF, .g = 0, .b = 0 } }, + }; + } + + // Resize + try s.resize(.{ .rows = 7, .reflow = false }); + try testing.expectEqual(@as(usize, 7), s.rows); + try testing.expectEqual(@as(usize, 7), s.totalRows()); + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } +} + +test "PageList resize (no reflow) more rows contains viewport" { + const testing = std.testing; + const alloc = testing.allocator; + + // When the rows are increased we need to make sure that the viewport + // doesn't end up below the active area if it's currently in pin mode. + + var s = try init(alloc, 5, 5, 1); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + + // Make it so we have scrollback + _ = try s.grow(); + + try testing.expectEqual(@as(usize, 5), s.rows); + try testing.expectEqual(@as(usize, 6), s.totalRows()); + + // Set viewport above active by scrolling up one. + s.scroll(.{ .delta_row = -1 }); + // The viewport should be a pin now. + try testing.expectEqual(Viewport.top, s.viewport); + + // Resize + try s.resize(.{ .rows = 7, .reflow = false }); + try testing.expectEqual(@as(usize, 7), s.rows); + try testing.expectEqual(@as(usize, 7), s.totalRows()); + + // Question: maybe the viewport should actually be in the active + // here and not pinned to the top. + try testing.expectEqual(Viewport.top, s.viewport); +} + +test "PageList resize (no reflow) less cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Resize + try s.resize(.{ .cols = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 5), cells.len); + } +} + +test "PageList resize (no reflow) less cols pin in trimmed cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 8, .y = 2 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 5), cells.len); + } + + try testing.expectEqual(point.Point{ .active = .{ + .x = 4, + .y = 2, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize (no reflow) less cols clears graphemes" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Add a grapheme. + const page = &s.pages.first.?.data; + { + const rac = page.getRowAndCell(9, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + try page.appendGrapheme(rac.row, rac.cell, 'A'); + } + try testing.expectEqual(@as(usize, 1), page.graphemeCount()); + + // Resize + try s.resize(.{ .cols = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + var it = s.pageIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |chunk| { + try testing.expectEqual(@as(usize, 0), chunk.node.data.graphemeCount()); + } +} + +test "PageList resize (no reflow) more cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, 0); + defer s.deinit(); + + // Resize + try s.resize(.{ .cols = 10, .reflow = false }); + try testing.expectEqual(@as(usize, 10), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 10), cells.len); + } +} + +test "PageList resize (no reflow) more cols with spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 3, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + } + { + const rac = page.getRowAndCell(0, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(1, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 3, .reflow = false }); + try testing.expectEqual(@as(usize, 3), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + // try testing.expect(!rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + { + const rac = page.getRowAndCell(2, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + } +} + +// Regression test for fuzz crash. When we shrink cols and then +// grow back, the page retains capacity from the original size so the grow +// takes the fast path (just bumps page.size.cols). If any row has a +// spacer_head at the old last column, that cell is no longer at the end +// of the wider row, violating page integrity. +test "PageList resize (no reflow) grow cols fast path with spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 3, 0); + defer s.deinit(); + + // Shrink to 5 cols. The page keeps capacity for 10 cols. + try s.resize(.{ .cols = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + + // Place a spacer_head at the last column (col 4) on two rows + // to simulate a wide character that didn't fit at the right edge. + { + const page = &s.pages.first.?.data; + + // Row 0: 'x' at col 0..3, spacer_head at col 4, wrap = true + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(4, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + rac.row.wrap = true; + } + + // Row 1: spacer_head at col 4, wrap = true + { + const rac = page.getRowAndCell(4, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + rac.row.wrap = true; + } + } + + // Grow back to 10 cols. This must not leave stale spacer_head + // cells at col 4 (which is no longer the last column). + try s.resize(.{ .cols = 10, .reflow = false }); + try testing.expectEqual(@as(usize, 10), s.cols); + + // Verify the old spacer_head positions are now narrow. + { + const page = &s.pages.first.?.data; + { + const rac = page.getRowAndCell(4, 0); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(!rac.row.wrap); + } + { + const rac = page.getRowAndCell(4, 1); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(!rac.row.wrap); + } + } +} + +// This test is a bit convoluted so I want to explain: what we are trying +// to verify here is that when we increase cols such that our rows per page +// shrinks, we don't fragment our rows across many pages because this ends +// up wasting a lot of memory. +// +// This is particularly important for alternate screen buffers where we +// don't have scrollback so our max size is very small. If we don't do this, +// we end up pruning our pages and that causes resizes to fail! +test "PageList resize (no reflow) more cols forces less rows per page" { + const testing = std.testing; + const alloc = testing.allocator; + + // This test requires initially that our rows fit into one page. + const cols: size.CellCountInt = 5; + const rows: size.CellCountInt = 150; + try testing.expect((try std_capacity.adjust(.{ .cols = cols })).rows >= rows); + var s = try init(alloc, cols, rows, 0); + defer s.deinit(); + + // Then we need to resize our cols so that our rows per page shrinks. + // This will force our resize to split our rows across two pages. + { + const new_cols = new_cols: { + var new_cols: size.CellCountInt = 50; + var cap = try std_capacity.adjust(.{ .cols = new_cols }); + while (cap.rows >= rows) { + new_cols += 50; + cap = try std_capacity.adjust(.{ .cols = new_cols }); + } + + break :new_cols new_cols; + }; + try s.resize(.{ .cols = new_cols, .reflow = false }); + try testing.expectEqual(@as(usize, new_cols), s.cols); + try testing.expectEqual(@as(usize, rows), s.totalRows()); + } + + // Every page except the last should be full + { + var it = s.pages.first; + while (it) |page| : (it = page.next) { + if (page == s.pages.last.?) break; + try testing.expectEqual(page.data.capacity.rows, page.data.size.rows); + } + } + + // Now we need to resize again to a col size that further shrinks + // our last capacity. + { + const page = &s.pages.first.?.data; + try testing.expect(page.size.rows == page.capacity.rows); + const new_cols = new_cols: { + var new_cols = page.size.cols + 50; + var cap = try std_capacity.adjust(.{ .cols = new_cols }); + while (cap.rows >= page.size.rows) { + new_cols += 50; + cap = try std_capacity.adjust(.{ .cols = new_cols }); + } + + break :new_cols new_cols; + }; + + try s.resize(.{ .cols = new_cols, .reflow = false }); + try testing.expectEqual(@as(usize, new_cols), s.cols); + try testing.expectEqual(@as(usize, rows), s.totalRows()); + } + + // Every page except the last should be full + { + var it = s.pages.first; + while (it) |page| : (it = page.next) { + if (page == s.pages.last.?) break; + try testing.expectEqual(page.data.capacity.rows, page.data.size.rows); + } + } +} + +test "PageList resize (no reflow) less cols then more cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, 0); + defer s.deinit(); + + // Resize less + try s.resize(.{ .cols = 2, .reflow = false }); + try testing.expectEqual(@as(usize, 2), s.cols); + + // Resize + try s.resize(.{ .cols = 5, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 5), cells.len); + } +} + +test "PageList resize (no reflow) less rows and cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Resize less + try s.resize(.{ .cols = 5, .rows = 7, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 7), s.rows); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 5), cells.len); + } +} + +test "PageList resize (no reflow) more rows and less cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Resize less + try s.resize(.{ .cols = 5, .rows = 20, .reflow = false }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 20), s.rows); + try testing.expectEqual(@as(usize, 20), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 5), cells.len); + } +} + +test "PageList resize more rows and cols doesn't fit in single std page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Resize to a size that requires more than one page to fit our rows. + const new_cols = 600; + const new_rows = 600; + const cap = try std_capacity.adjust(.{ .cols = new_cols }); + try testing.expect(cap.rows < new_rows); + + try s.resize(.{ .cols = new_cols, .rows = new_rows, .reflow = true }); + try testing.expectEqual(@as(usize, new_cols), s.cols); + try testing.expectEqual(@as(usize, new_rows), s.rows); + try testing.expectEqual(@as(usize, new_rows), s.totalRows()); +} + +test "PageList resize (no reflow) empty screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 5, 0); + defer s.deinit(); + + // Resize + try s.resize(.{ .cols = 10, .rows = 10, .reflow = false }); + try testing.expectEqual(@as(usize, 10), s.cols); + try testing.expectEqual(@as(usize, 10), s.rows); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 10), cells.len); + } +} + +test "PageList resize (no reflow) more cols forces smaller cap" { + const testing = std.testing; + const alloc = testing.allocator; + + // We want a cap that forces us to have less rows + const cap = try std_capacity.adjust(.{ .cols = 100 }); + const cap2 = try std_capacity.adjust(.{ .cols = 500 }); + try testing.expectEqual(@as(size.CellCountInt, 500), cap2.cols); + try testing.expect(cap2.rows < cap.rows); + + // Create initial cap, fits in one page + var s = try init(alloc, cap.cols, cap.rows, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + } + + // Resize to our large cap + const rows = s.totalRows(); + try s.resize(.{ .cols = cap2.cols, .reflow = false }); + + // Our total rows should be the same, and contents should be the same. + try testing.expectEqual(rows, s.totalRows()); + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, cap2.cols), cells.len); + try testing.expectEqual(@as(u21, 'A'), cells[0].content.codepoint); + } +} + +test "PageList resize (no reflow) more rows adds blank rows if cursor at bottom" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, null); + defer s.deinit(); + + // Grow to 5 total rows, simulating 3 active + 2 scrollback + try s.growRows(2); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.totalRows()) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Active should be on row 3 + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = s.rows - 2 } }).?); + defer s.untrackPin(p); + const original_cursor = s.pointFromPin(.active, p.*).?.active; + { + const get = s.getCell(.{ .active = .{ + .x = original_cursor.x, + .y = original_cursor.y, + } }).?; + try testing.expectEqual(@as(u21, 3), get.cell.content.codepoint); + } + + // Resize + try s.resizeWithoutReflow(.{ + .rows = 10, + .reflow = false, + .cursor = .{ .x = 0, .y = s.rows - 2 }, + }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 10), s.rows); + + // Our cursor should not change + try testing.expectEqual(original_cursor, s.pointFromPin(.active, p.*).?.active); + + // 12 because we have our 10 rows in the active + 2 in the scrollback + // because we're preserving the cursor. + try testing.expectEqual(@as(usize, 12), s.totalRows()); + + // Active should be at the same place it was. + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } + + // Go through our active, we should get only 3,4,5 + for (0..3) |y| { + const get = s.getCell(.{ .active = .{ .y = @intCast(y) } }).?; + const expected: u21 = @intCast(y + 2); + try testing.expectEqual(expected, get.cell.content.codepoint); + } +} + +test "PageList resize reflow more cols no wrapped rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 10, .reflow = true }); + try testing.expectEqual(@as(usize, 10), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 10), cells.len); + try testing.expectEqual(@as(u21, 'A'), cells[0].content.codepoint); + } +} + +test "PageList resize reflow more cols wrapped rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + if (y % 2 == 0) { + const rac = page.getRowAndCell(0, y); + rac.row.wrap = true; + } else { + const rac = page.getRowAndCell(0, y); + rac.row.wrap_continuation = true; + } + + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Active should still be on top + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, pt); + } + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + { + // First row should be unwrapped + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 4), cells.len); + try testing.expectEqual(@as(u21, 'A'), cells[0].content.codepoint); + try testing.expectEqual(@as(u21, 'A'), cells[2].content.codepoint); + } +} + +test "PageList resize reflow invalidates viewport offset cache" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, null); + defer s.deinit(); + try s.growRows(20); + + const page = &s.pages.last.?.data; + for (0..s.rows) |y| { + if (y % 2 == 0) { + const rac = page.getRowAndCell(0, y); + rac.row.wrap = true; + } else { + const rac = page.getRowAndCell(0, y); + rac.row.wrap_continuation = true; + } + + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + } + + // Scroll to a pinned viewport in history + const pin_y = 10; + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = pin_y } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = pin_y, + .len = s.rows, + }, s.scrollbar()); + + // Resize with reflow - unwrapping rows changes total_rows + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + + // Verify scrollbar cache was invalidated during reflow + try testing.expectEqual(Scrollbar{ + .total = s.total_rows, + .offset = 5, + .len = s.rows, + }, s.scrollbar()); +} + +test "PageList resize reflow more cols creates multiple pages" { + const testing = std.testing; + const alloc = testing.allocator; + + // We want a wide viewport so our row limit is rather small. This will + // force the reflow below to create multiple pages, which we assert. + const cap = cap: { + var current: size.CellCountInt = 100; + while (true) : (current += 100) { + const cap = try std_capacity.adjust(.{ .cols = current }); + if (cap.rows < 100) break :cap cap; + } + unreachable; + }; + + var s = try init(alloc, cap.cols, cap.rows, null); + defer s.deinit(); + + // Wrap every other row so every line is wrapped for reflow + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + if (y % 2 == 0) { + const rac = page.getRowAndCell(0, y); + rac.row.wrap = true; + } else { + const rac = page.getRowAndCell(0, y); + rac.row.wrap_continuation = true; + } + + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + } + + // Resize + const newcap = try cap.adjust(.{ .cols = cap.cols + 100 }); + try testing.expect(newcap.rows < cap.rows); + try s.resize(.{ .cols = newcap.cols, .reflow = true }); + try testing.expectEqual(@as(usize, newcap.cols), s.cols); + try testing.expectEqual(@as(usize, cap.rows), s.totalRows()); + + { + var count: usize = 0; + var it = s.pages.first; + while (it) |page| : (it = page.next) { + count += 1; + + // All pages should have the new capacity + try testing.expectEqual(newcap.cols, page.data.capacity.cols); + try testing.expectEqual(newcap.rows, page.data.capacity.rows); + } + + // We should have more than one page, meaning we created at least + // one page. This is the critical aspect of this test so if this + // ever goes false we need to adjust this test. + try testing.expect(count > 1); + } +} + +test "PageList resize reflow more cols wrap across page boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow to the capacity of the first page. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(1); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + } + + // At this point, we have some rows on the first page, and some on the second. + // We can now wrap across the boundary condition. + { + const page = &s.pages.first.?.data; + const y = page.size.rows - 1; + { + const rac = page.getRowAndCell(0, y); + rac.row.wrap = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + const page2 = &s.pages.last.?.data; + const y = 0; + { + const rac = page2.getRowAndCell(0, y); + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page2.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // PageList.diagram -> + // + // +--+ = PAGE 0 + // ... : : + // +-----+ ACTIVE + // 15744 | | | 0 + // 15745 | | | 1 + // 15746 | | | 2 + // 15747 | | | 3 + // 15748 | | | 4 + // 15749 | | | 5 + // 15750 | | | 6 + // 15751 | | | 7 + // 15752 |01… | 8 + // +--+ : + // +--+ : = PAGE 1 + // 0 …01| | 9 + // +--+ : + // +-----+ + + // We expect one fewer rows since we unwrapped a row. + const end_rows = s.totalRows() - 1; + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, end_rows), s.totalRows()); + + // PageList.diagram -> + // + // +----+ = PAGE 0 + // ... : : + // +----+ + // +----+ = PAGE 1 + // ... : : + // +-------+ ACTIVE + // 6272 | | | 0 + // 6273 | | | 1 + // 6274 | | | 2 + // 6275 | | | 3 + // 6276 | | | 4 + // 6277 | | | 5 + // 6278 | | | 6 + // 6279 | | | 7 + // 6280 | | | 8 + // 6281 |0101| | 9 + // +----+ : + // +-------+ + + { + // PAGE 1 ROW 6280, ACTIVE 8 + const p = s.pin(.{ .active = .{ .y = 8 } }).?; + const row = p.rowAndCell().row; + try testing.expect(!row.wrap); + try testing.expect(!row.wrap_continuation); + + const cells = p.cells(.all); + try testing.expect(!cells[0].hasText()); + try testing.expect(!cells[1].hasText()); + try testing.expect(!cells[2].hasText()); + try testing.expect(!cells[3].hasText()); + } + { + // PAGE 1 ROW 6281, ACTIVE 9 + const p = s.pin(.{ .active = .{ .y = 9 } }).?; + const row = p.rowAndCell().row; + try testing.expect(!row.wrap); + try testing.expect(!row.wrap_continuation); + + const cells = p.cells(.all); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + try testing.expectEqual(@as(u21, 1), cells[1].content.codepoint); + try testing.expectEqual(@as(u21, 0), cells[2].content.codepoint); + try testing.expectEqual(@as(u21, 1), cells[3].content.codepoint); + } +} + +test "PageList resize reflow more cols wrap across page boundary cursor in second page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow to the capacity of the first page. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(1); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + } + + // At this point, we have some rows on the first page, and some on the second. + // We can now wrap across the boundary condition. + { + const page = &s.pages.first.?.data; + const y = page.size.rows - 1; + { + const rac = page.getRowAndCell(0, y); + rac.row.wrap = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + const page2 = &s.pages.last.?.data; + const y = 0; + { + const rac = page2.getRowAndCell(0, y); + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page2.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in wrapped row on the last page + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 1, .y = 9 } }).?); + defer s.untrackPin(p); + try testing.expect(p.node == s.pages.last.?); + + // We expect one fewer rows since we unwrapped a row. + const end_rows = s.totalRows() - 1; + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, end_rows), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 9, + } }, s.pointFromPin(.active, p.*).?); + + { + const p2 = s.pin(.{ .active = .{ .y = 9 } }).?; + const row = p2.rowAndCell().row; + try testing.expect(!row.wrap); + + const cells = p2.cells(.all); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + try testing.expectEqual(@as(u21, 1), cells[1].content.codepoint); + try testing.expectEqual(@as(u21, 0), cells[2].content.codepoint); + try testing.expectEqual(@as(u21, 1), cells[3].content.codepoint); + } +} + +test "PageList resize reflow less cols wrap across page boundary cursor in second page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 10, null); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow to the capacity of the first page. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(5); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + } + + // At this point, we have some rows on the first page, and some on the second. + // We can now wrap across the boundary condition. + { + const page = &s.pages.first.?.data; + const y = page.size.rows - 1; + { + const rac = page.getRowAndCell(0, y); + rac.row.wrap = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + const page2 = &s.pages.last.?.data; + const y = 0; + { + const rac = page2.getRowAndCell(0, y); + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page2.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in wrapped row on the last page + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 2, .y = 5 } }).?); + defer s.untrackPin(p); + try testing.expect(p.node == s.pages.last.?); + try testing.expect(p.y == 0); + + // PageList.diagram -> + // + // +-----+ = PAGE 0 + // ... : : + // +--------+ ACTIVE + // 7892 | | | 0 + // 7893 | | | 1 + // 7894 | | | 2 + // 7895 | | | 3 + // 7896 |01234… | 4 + // +-----+ : + // +-----+ : = PAGE 1 + // 0 …01234| | 5 + // : ^ : : = PIN 0 + // 1 | | | 6 + // 2 | | | 7 + // 3 | | | 8 + // 4 | | | 9 + // +-----+ : + // +--------+ + + // Resize + try s.resize(.{ + .cols = 4, + .reflow = true, + .cursor = .{ .x = 2, .y = 5 }, + }); + try testing.expectEqual(@as(usize, 4), s.cols); + + // PageList.diagram -> + // + // +----+ = PAGE 0 + // ... : : + // +-------+ ACTIVE + // 7892 | | | 0 + // 7893 | | | 1 + // 7894 | | | 2 + // 7895 | | | 3 + // 7896 |0123… | 4 + // 7897 …4012… | 5 + // : ^: : = PIN 0 + // 7898 …3400| | 6 + // 7899 | | | 7 + // 7900 | | | 8 + // 7901 | | | 9 + // +----+ : + // +-------+ + + // Our cursor should remain on the same cell + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 5, + } }, s.pointFromPin(.active, p.*).?); + + { + // PAGE 0 ROW 7895, ACTIVE 3 + const p2 = s.pin(.{ .active = .{ .y = 3 } }).?; + const row = p2.rowAndCell().row; + try testing.expect(!row.wrap); + try testing.expect(!row.wrap_continuation); + + const cells = p2.cells(.all); + try testing.expect(!cells[0].hasText()); + try testing.expect(!cells[1].hasText()); + try testing.expect(!cells[2].hasText()); + try testing.expect(!cells[3].hasText()); + } + { + // PAGE 0 ROW 7896, ACTIVE 4 + const p2 = s.pin(.{ .active = .{ .y = 4 } }).?; + const row = p2.rowAndCell().row; + try testing.expect(row.wrap); + try testing.expect(!row.wrap_continuation); + + const cells = p2.cells(.all); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + try testing.expectEqual(@as(u21, 1), cells[1].content.codepoint); + try testing.expectEqual(@as(u21, 2), cells[2].content.codepoint); + try testing.expectEqual(@as(u21, 3), cells[3].content.codepoint); + } + { + // PAGE 0 ROW 7897, ACTIVE 5 + const p2 = s.pin(.{ .active = .{ .y = 5 } }).?; + const row = p2.rowAndCell().row; + try testing.expect(row.wrap); + try testing.expect(row.wrap_continuation); + + const cells = p2.cells(.all); + try testing.expectEqual(@as(u21, 4), cells[0].content.codepoint); + try testing.expectEqual(@as(u21, 0), cells[1].content.codepoint); + try testing.expectEqual(@as(u21, 1), cells[2].content.codepoint); + try testing.expectEqual(@as(u21, 2), cells[3].content.codepoint); + } + { + // PAGE 0 ROW 7898, ACTIVE 6 + const p2 = s.pin(.{ .active = .{ .y = 6 } }).?; + const row = p2.rowAndCell().row; + try testing.expect(!row.wrap); + try testing.expect(row.wrap_continuation); + + const cells = p2.cells(.all); + try testing.expectEqual(@as(u21, 3), cells[0].content.codepoint); + try testing.expectEqual(@as(u21, 4), cells[1].content.codepoint); + } + { + // PAGE 0 ROW 7899, ACTIVE 7 + const p2 = s.pin(.{ .active = .{ .y = 7 } }).?; + const row = p2.rowAndCell().row; + try testing.expect(!row.wrap); + try testing.expect(!row.wrap_continuation); + + const cells = p2.cells(.all); + try testing.expect(!cells[0].hasText()); + try testing.expect(!cells[1].hasText()); + try testing.expect(!cells[2].hasText()); + try testing.expect(!cells[3].hasText()); + } +} + +test "PageList resize reflow more cols cursor in wrapped row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 1, .y = 1 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow more cols cursor in not wrapped row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 1, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow more cols cursor in wrapped row that isn't unwrapped" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap = true; + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + { + const rac = page.getRowAndCell(0, 2); + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 2); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 1, .y = 2 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 1, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow more cols no reflow preserves semantic prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 4, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(0, 1); + rac.row.semantic_prompt = .prompt; + } + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(0, 1); + try testing.expect(rac.row.semantic_prompt == .prompt); + } +} + +test "PageList resize reflow exceeds hyperlink memory forcing capacity increase" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow to the capacity of the first page and add + // one more row so that we have two pages total. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(1); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + + // We now have two pages. + try std.testing.expect(s.pages.first.? != s.pages.last.?); + try std.testing.expectEqual(s.pages.last.?, s.pages.first.?.next); + } + + // We use almost all string alloc capacity with a hyperlink in the final + // row of the first page, and do the same on the first row of the second + // page. We also mark the row as wrapped so that when we resize with more + // cols the row unwraps and we have a single row that requires almost two + // times the base string alloc capacity. + // + // This forces the reflow to increase capacity. + // + // +--+ = PAGE 0 + // : : + // | X… <- where X is hyperlinked with almost all string cap. + // +--+ + // +--+ = PAGE 1 + // …X | <- X here also almost hits string cap with a hyperlink. + // +--+ + + // Almost hit string alloc cap in bottom right of first page. + // Mark the final row as wrapped. + { + const page = &s.pages.first.?.data; + const id = try page.insertHyperlink(.{ + .id = .{ .implicit = 0 }, + .uri = "a" ** (pagepkg.string_bytes_default - 1), + }); + const rac = page.getRowAndCell(page.size.cols - 1, page.size.rows - 1); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'X' }, + }; + try page.setHyperlink(rac.row, rac.cell, id); + try std.testing.expectError( + error.StringsOutOfMemory, + page.insertHyperlink(.{ + .id = .{ .implicit = 1 }, + .uri = "AAAAAAAAAAAAAAAAAAAAAAAAAA", + }), + ); + } + + // Almost hit string alloc cap in top left of second page. + // Mark the first row as a wrap continuation. + { + const page = &s.pages.last.?.data; + const id = try page.insertHyperlink(.{ + .id = .{ .implicit = 1 }, + .uri = "a" ** (pagepkg.string_bytes_default - 1), + }); + const rac = page.getRowAndCell(0, 0); + rac.row.wrap_continuation = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'X' }, + }; + try page.setHyperlink(rac.row, rac.cell, id); + try std.testing.expectError( + error.StringsOutOfMemory, + page.insertHyperlink(.{ + .id = .{ .implicit = 2 }, + .uri = "AAAAAAAAAAAAAAAAAAAAAAAAAA", + }), + ); + } + + // Resize to 1 column wider, unwrapping the row. + try s.resize(.{ .cols = s.cols + 1, .reflow = true }); +} + +test "PageList resize reflow exceeds grapheme memory forcing capacity increase" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow to the capacity of the first page and add + // one more row so that we have two pages total. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(1); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + + // We now have two pages. + try std.testing.expect(s.pages.first.? != s.pages.last.?); + try std.testing.expectEqual(s.pages.last.?, s.pages.first.?.next); + } + + // We use almost all grapheme alloc capacity with a grapheme in the final + // row of the first page, and do the same on the first row of the second + // page. We also mark the row as wrapped so that when we resize with more + // cols the row unwraps and we have a single row that requires almost two + // times the base grapheme alloc capacity. + // + // This forces the reflow to increase capacity. + // + // +--+ = PAGE 0 + // : : + // | X… <- where X is a grapheme which uses almost all the capacity. + // +--+ + // +--+ = PAGE 1 + // …X | <- X here also almost hits grapheme cap. + // +--+ + + // Almost hit grapheme alloc cap in bottom right of first page. + // Mark the final row as wrapped. + { + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(page.size.cols - 1, page.size.rows - 1); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'X' }, + }; + try page.setGraphemes( + rac.row, + rac.cell, + &@as( + [ + @divFloor( + pagepkg.grapheme_bytes_default - 1, + @sizeOf(u21), + ) + ]u21, + @splat('a'), + ), + ); + try std.testing.expectError( + error.OutOfMemory, + page.grapheme_alloc.alloc( + u21, + page.memory, + 16, + ), + ); + } + + // Almost hit grapheme alloc cap in top left of second page. + // Mark the first row as a wrap continuation. + { + const page = &s.pages.last.?.data; + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'X' }, + }; + try page.setGraphemes( + rac.row, + rac.cell, + &@as( + [ + @divFloor( + pagepkg.grapheme_bytes_default - 1, + @sizeOf(u21), + ) + ]u21, + @splat('a'), + ), + ); + try std.testing.expectError( + error.OutOfMemory, + page.grapheme_alloc.alloc( + u21, + page.memory, + 16, + ), + ); + } + + // Resize to 1 column wider, unwrapping the row. + try s.resize(.{ .cols = s.cols + 1, .reflow = true }); +} + +test "PageList resize reflow exceeds style memory forcing capacity increase" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, pagepkg.std_capacity.styles - 1, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Grow to the capacity of the first page and add + // one more row so that we have two pages total. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(1); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + + // We now have two pages. + try std.testing.expect(s.pages.first.? != s.pages.last.?); + try std.testing.expectEqual(s.pages.last.?, s.pages.first.?.next); + } + + // Give each cell in the final row of the first page a unique style. + // Mark the final row as wrapped. + { + const page = &s.pages.first.?.data; + for (0..s.cols) |x| { + const id = page.styles.add( + page.memory, + .{ + .bg_color = .{ .rgb = .{ + .r = @truncate(x), + .g = @truncate(x >> 8), + .b = @truncate(x >> 16), + } }, + }, + ) catch break; + + const rac = page.getRowAndCell(x, page.size.rows - 1); + rac.row.wrap = true; + rac.row.styled = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'X' }, + .style_id = id, + }; + } + } + + // Do the same for the first row of the second page. + // Mark the first row as a wrap continuation. + { + const page = &s.pages.last.?.data; + for (0..s.cols) |x| { + const id = page.styles.add( + page.memory, + .{ + .fg_color = .{ .rgb = .{ + .r = @truncate(x), + .g = @truncate(x >> 8), + .b = @truncate(x >> 16), + } }, + }, + ) catch break; + + const rac = page.getRowAndCell(x, 0); + rac.row.wrap_continuation = true; + rac.row.styled = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'X' }, + .style_id = id, + }; + } + } + + // Resize to twice as wide, fully unwrapping the row. + try s.resize(.{ .cols = s.cols * 2, .reflow = true }); +} + +test "PageList resize reflow more cols unwrap wide spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + } + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap_continuation = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(1, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(!rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, '😀'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + } + { + const rac = page.getRowAndCell(2, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + } +} + +test "PageList resize reflow more cols unwrap wide spacer head across two rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 3, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap_continuation = true; + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + } + { + const rac = page.getRowAndCell(0, 2); + rac.row.wrap_continuation = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(1, 2); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + { + const rac = page.getRowAndCell(2, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + { + const rac = page.getRowAndCell(3, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_head, rac.cell.wide); + } + { + const rac = page.getRowAndCell(0, 1); + try testing.expectEqual(@as(u21, '😀'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + } + { + const rac = page.getRowAndCell(1, 1); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + } +} + +test "PageList resize reflow more cols unwrap still requires wide spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap_continuation = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(1, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 3, .reflow = true }); + try testing.expectEqual(@as(usize, 3), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + { + const rac = page.getRowAndCell(2, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_head, rac.cell.wide); + } + { + const rac = page.getRowAndCell(0, 1); + try testing.expectEqual(@as(u21, '😀'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + } + { + const rac = page.getRowAndCell(1, 1); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + } +} +test "PageList resize reflow less cols no reflow preserves semantic prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 4, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + const rac = page.getRowAndCell(0, 1); + rac.row.semantic_prompt = .prompt; + } + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + { + const p = s.pin(.{ .active = .{ .y = 1 } }).?; + const rac = p.rowAndCell(); + try testing.expect(rac.row.wrap); + try testing.expect(rac.row.semantic_prompt == .prompt); + } + { + const p = s.pin(.{ .active = .{ .y = 2 } }).?; + const rac = p.rowAndCell(); + try testing.expect(rac.row.semantic_prompt == .prompt); + } + } +} + +test "PageList resize reflow less cols no reflow preserves semantic prompt on first line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 4, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(0, 0); + rac.row.semantic_prompt = .prompt; + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(0, 0); + try testing.expect(rac.row.semantic_prompt == .prompt); + } +} + +test "PageList resize reflow less cols wrap preserves semantic prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 4, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(0, 0); + rac.row.semantic_prompt = .prompt; + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + const rac = page.getRowAndCell(0, 0); + try testing.expect(rac.row.semantic_prompt == .prompt); + } +} + +test "PageList resize reflow less cols no wrapped rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 3, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + const end = 4; + assert(end < s.cols); + for (0..4) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 5, .reflow = true }); + try testing.expectEqual(@as(usize, 5), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |offset| { + for (0..4) |x| { + var offset_copy = offset; + offset_copy.x = @intCast(x); + const rac = offset_copy.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(usize, 5), cells.len); + try testing.expectEqual(@as(u21, @intCast(x)), cells[x].content.codepoint); + } + } +} + +test "PageList resize reflow less cols wrapped rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Active moves due to scrollback + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } + + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + { + // First row should be wrapped + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 2), cells[0].content.codepoint); + } + { + // First row should be wrapped + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 2), cells[0].content.codepoint); + } +} + +test "PageList resize reflow less cols wrapped rows with graphemes" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, null); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + + const rac = page.getRowAndCell(2, y); + try page.appendGrapheme(rac.row, rac.cell, 'A'); + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Active moves due to scrollback + { + const pt = s.getCell(.{ .active = .{} }).?.screenPoint(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, pt); + } + + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + var it = s.rowIterator(.right_down, .{ .screen = .{} }, null); + { + // First row should be wrapped + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expect(rac.row.grapheme); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 2), cells[0].content.codepoint); + + const cps = page.lookupGrapheme(rac.cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + try testing.expectEqual(@as(u21, 'A'), cps[0]); + } + { + // First row should be wrapped + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expect(rac.row.grapheme); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 2), cells[0].content.codepoint); + + const cps = page.lookupGrapheme(rac.cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + try testing.expectEqual(@as(u21, 'A'), cps[0]); + } +} + +test "PageList resize reflow less cols cursor in wrapped row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 2, .y = 1 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow less cols wraps spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 3, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.row.wrap = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(2, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(3, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + }; + } + { + const rac = page.getRowAndCell(0, 1); + rac.row.wrap_continuation = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(1, 1); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 3, .reflow = true }); + try testing.expectEqual(@as(usize, 3), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + { + const rac = page.getRowAndCell(2, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + { + const rac = page.getRowAndCell(0, 1); + try testing.expectEqual(@as(u21, '😀'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + } + { + const rac = page.getRowAndCell(1, 1); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + } +} +test "PageList resize reflow less cols cursor goes to scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 2, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 4), s.totalRows()); + + // Our cursor should move to the first row + try testing.expect(s.pointFromPin(.active, p.*) == null); +} + +test "PageList resize reflow less cols cursor in unchanged row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..2) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 1, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow less cols cursor in blank cell" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 6, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..2) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 2, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + // Our cursor should not move + try testing.expectEqual(point.Point{ .active = .{ + .x = 2, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow less cols cursor in final blank cell" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 6, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..2) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 3, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow less cols cursor in wrapped blank cell" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 6, 2, null); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..2) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 5, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow less cols blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 3, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..1) |y| { + for (0..4) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + { + // First row should be wrapped + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 2), cells[0].content.codepoint); + } +} + +test "PageList resize reflow less cols blank lines between" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 3, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + for (0..4) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + { + for (0..4) |x| { + const rac = page.getRowAndCell(x, 2); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 5), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + try testing.expect(!rac.row.wrap); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 2), cells[0].content.codepoint); + } +} + +test "PageList resize reflow less cols blank lines between no scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 3, 0); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + { + const rac = page.getRowAndCell(0, 2); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'C' }, + }; + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 3), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 'A'), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expectEqual(@as(u21, 0), cells[0].content.codepoint); + } + { + const offset = it.next().?; + const rac = offset.rowAndCell(); + const cells = offset.node.data.getCells(rac.row); + try testing.expect(!rac.row.wrap); + try testing.expectEqual(@as(usize, 2), cells.len); + try testing.expectEqual(@as(u21, 'C'), cells[0].content.codepoint); + } +} + +test "PageList resize reflow less cols cursor not on last line preserves location" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 5, 5, 1); + defer s.deinit(); + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + for (0..s.rows) |y| { + for (0..2) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + }; + } + } + + // Grow blank rows to push our rows back into scrollback + try s.growRows(5); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // Put a tracked pin in the history + const p = try s.trackPin(s.pin(.{ .active = .{ .x = 0, .y = 0 } }).?); + defer s.untrackPin(p); + + // Resize + try s.resize(.{ + .cols = 4, + .reflow = true, + + // Important: not on last row + .cursor = .{ .x = 1, .y = 1 }, + }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 10), s.totalRows()); + + // Our cursor should move to the first row + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pointFromPin(.active, p.*).?); +} + +test "PageList resize reflow less cols copy style" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Create a style + const style: stylepkg.Style = .{ .flags = .{ .bold = true } }; + const style_id = try page.styles.add(page.memory, style); + + for (0..s.cols - 1) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x) }, + .style_id = style_id, + }; + page.styles.use(page.memory, style_id); + } + + // We're over-counted by 1 because `add` implies `use`. + page.styles.release(page.memory, style_id); + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + while (it.next()) |offset| { + for (0..s.cols - 1) |x| { + var offset_copy = offset; + offset_copy.x = @intCast(x); + const rac = offset_copy.rowAndCell(); + const style_id = rac.cell.style_id; + try testing.expect(style_id != 0); + + const style = offset.node.data.styles.get( + offset.node.data.memory, + style_id, + ); + try testing.expect(style.flags.bold); + + const row = rac.row; + try testing.expect(row.styled); + } + } +} + +test "PageList resize reflow less cols to eliminate a wide char" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 1, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 1, .reflow = true }); + try testing.expectEqual(@as(usize, 1), s.cols); + try testing.expectEqual(@as(usize, 1), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + } + } +} + +test "PageList resize reflow less cols to wrap a wide char" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 3, 1, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'x' }, + }; + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = '😀' }, + .wide = .wide, + }; + } + { + const rac = page.getRowAndCell(2, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 'x'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.narrow, rac.cell.wide); + try testing.expect(rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_head, rac.cell.wide); + } + { + const rac = page.getRowAndCell(0, 1); + try testing.expectEqual(@as(u21, '😀'), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + } + { + const rac = page.getRowAndCell(1, 1); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + } +} + +test "PageList resize reflow less cols to wrap a multi-codepoint grapheme with a spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // We want to make the screen look like this: + // + // 👨‍👨‍👦‍👦👨‍👨‍👦‍👦 + + // First family emoji at (0, 0) + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0x1F468 }, // First codepoint of the grapheme + .wide = .wide, + }; + try page.setGraphemes(rac.row, rac.cell, &.{ + 0x200D, 0x1F468, + 0x200D, 0x1F466, + 0x200D, 0x1F466, + }); + } + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + // Second family emoji at (2, 0) + { + const rac = page.getRowAndCell(2, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0x1F468 }, // First codepoint of the grapheme + .wide = .wide, + }; + try page.setGraphemes(rac.row, rac.cell, &.{ + 0x200D, 0x1F468, + 0x200D, 0x1F466, + 0x200D, 0x1F466, + }); + } + { + const rac = page.getRowAndCell(3, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + }; + } + } + + // Resize + try s.resize(.{ .cols = 3, .reflow = true }); + try testing.expectEqual(@as(usize, 3), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 0x1F468), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + + const cps = page.lookupGrapheme(rac.cell).?; + try testing.expectEqual(@as(usize, 6), cps.len); + try testing.expectEqual(@as(u21, 0x200D), cps[0]); + try testing.expectEqual(@as(u21, 0x1F468), cps[1]); + try testing.expectEqual(@as(u21, 0x200D), cps[2]); + try testing.expectEqual(@as(u21, 0x1F466), cps[3]); + try testing.expectEqual(@as(u21, 0x200D), cps[4]); + try testing.expectEqual(@as(u21, 0x1F466), cps[5]); + + // Row should be wrapped + try testing.expect(rac.row.wrap); + } + { + const rac = page.getRowAndCell(1, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + { + const rac = page.getRowAndCell(2, 0); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_head, rac.cell.wide); + } + + { + const rac = page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 0x1F468), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.wide, rac.cell.wide); + + const cps = page.lookupGrapheme(rac.cell).?; + try testing.expectEqual(@as(usize, 6), cps.len); + try testing.expectEqual(@as(u21, 0x200D), cps[0]); + try testing.expectEqual(@as(u21, 0x1F468), cps[1]); + try testing.expectEqual(@as(u21, 0x200D), cps[2]); + try testing.expectEqual(@as(u21, 0x1F466), cps[3]); + try testing.expectEqual(@as(u21, 0x200D), cps[4]); + try testing.expectEqual(@as(u21, 0x1F466), cps[5]); + } + { + const rac = page.getRowAndCell(1, 1); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + try testing.expectEqual(pagepkg.Cell.Wide.spacer_tail, rac.cell.wide); + } + } +} + +test "PageList resize reflow less cols copy kitty placeholder" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write unicode placeholders + for (0..s.cols - 1) |x| { + const rac = page.getRowAndCell(x, 0); + rac.row.kitty_virtual_placeholder = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = kitty.graphics.unicode.placeholder }, + }; + } + } + + // Resize + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + while (it.next()) |offset| { + for (0..s.cols - 1) |x| { + var offset_copy = offset; + offset_copy.x = @intCast(x); + const rac = offset_copy.rowAndCell(); + + const row = rac.row; + try testing.expect(row.kitty_virtual_placeholder); + } + } +} + +test "PageList resize reflow more cols clears kitty placeholder" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write unicode placeholders + for (0..s.cols - 1) |x| { + const rac = page.getRowAndCell(x, 0); + rac.row.kitty_virtual_placeholder = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = kitty.graphics.unicode.placeholder }, + }; + } + } + + // Resize smaller then larger + try s.resize(.{ .cols = 2, .reflow = true }); + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + { + const row = it.next().?; + const rac = row.rowAndCell(); + try testing.expect(rac.row.kitty_virtual_placeholder); + } + { + const row = it.next().?; + const rac = row.rowAndCell(); + try testing.expect(!rac.row.kitty_virtual_placeholder); + } + try testing.expect(it.next() == null); +} + +test "PageList resize reflow wrap moves kitty placeholder" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 2, 0); + defer s.deinit(); + { + try testing.expect(s.pages.first == s.pages.last); + const page = &s.pages.first.?.data; + + // Write unicode placeholders + for (2..s.cols - 1) |x| { + const rac = page.getRowAndCell(x, 0); + rac.row.kitty_virtual_placeholder = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = kitty.graphics.unicode.placeholder }, + }; + } + } + + try s.resize(.{ .cols = 2, .reflow = true }); + try testing.expectEqual(@as(usize, 2), s.cols); + try testing.expectEqual(@as(usize, 2), s.totalRows()); + + var it = s.rowIterator(.right_down, .{ .active = .{} }, null); + { + const row = it.next().?; + const rac = row.rowAndCell(); + try testing.expect(!rac.row.kitty_virtual_placeholder); + } + { + const row = it.next().?; + const rac = row.rowAndCell(); + try testing.expect(rac.row.kitty_virtual_placeholder); + } + try testing.expect(it.next() == null); +} + +test "PageList reset" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + s.reset(); + try testing.expect(s.viewport == .active); + try testing.expect(s.pages.first != null); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Active area should be the top + try testing.expectEqual(Pin{ + .node = s.pages.first.?, + .y = 0, + .x = 0, + }, s.getTopLeft(.active)); +} + +test "PageList reset across two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + // Find a cap that makes it so that rows don't fit on one page. + const rows = 100; + const cap = cap: { + var cap = try std_capacity.adjust(.{ .cols = 50 }); + while (cap.rows >= rows) cap = try std_capacity.adjust(.{ + .cols = cap.cols + 50, + }); + + break :cap cap; + }; + + // Init + var s = try init(alloc, cap.cols, rows, null); + defer s.deinit(); + s.reset(); + try testing.expect(s.viewport == .active); + try testing.expect(s.pages.first != null); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); +} + +test "PageList reset moves tracked pins and marks them as garbage" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Create a tracked pin into the active area + const p = try s.trackPin(s.pin(.{ .active = .{ + .x = 42, + .y = 12, + } }).?); + defer s.untrackPin(p); + + s.reset(); + + // Our added pin should now be garbage + try testing.expect(p.garbage); + + // Viewport pin should not be garbage because it makes sense. + try testing.expect(!s.viewport_pin.garbage); +} + +test "PageList clears history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + try s.growRows(30); + s.reset(); + try testing.expect(s.viewport == .active); + try testing.expect(s.pages.first != null); + try testing.expectEqual(@as(usize, s.rows), s.totalRows()); + + // Active area should be the top + try testing.expectEqual(Pin{ + .node = s.pages.first.?, + .y = 0, + .x = 0, + }, s.getTopLeft(.active)); +} + +test "PageList resize reflow grapheme map capacity exceeded" { + // This test verifies that when reflowing content with many graphemes, + // the grapheme map capacity is correctly increased when needed. + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 4, 10, 0); + defer s.deinit(); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + + // Get the grapheme capacity from the page. We need more than this many + // graphemes in a single destination page to trigger capacity increase + // during reflow. Since each source page can only hold this many graphemes, + // we create two source pages with graphemes that will merge into one + // destination page. + const grapheme_capacity = s.pages.first.?.data.graphemeCapacity(); + // Use slightly more than half the capacity per page, so combined they + // exceed the capacity of a single destination page. + const graphemes_per_page = grapheme_capacity / 2 + grapheme_capacity / 4; + + // Grow to the capacity of the first page and add more rows + // so that we have two pages total. + { + const page = &s.pages.first.?.data; + page.pauseIntegrityChecks(true); + for (page.size.rows..page.capacity.rows) |_| { + _ = try s.grow(); + } + page.pauseIntegrityChecks(false); + try testing.expectEqual(@as(usize, 1), s.totalPages()); + try s.growRows(graphemes_per_page); + try testing.expectEqual(@as(usize, 2), s.totalPages()); + + // We now have two pages. + try testing.expect(s.pages.first.? != s.pages.last.?); + try testing.expectEqual(s.pages.last.?, s.pages.first.?.next); + } + + // Add graphemes to both pages. We add graphemes to rows at the END of the + // first page, and graphemes to rows at the START of the second page. + // When reflowing to 2 columns, these rows will wrap and stay together + // on the same destination page, requiring capacity increase. + + // Add graphemes to the end of the first page (last rows) + { + const page = &s.pages.first.?.data; + const start_row = page.size.rows - graphemes_per_page; + for (0..graphemes_per_page) |i| { + const y = start_row + i; + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + try page.appendGrapheme(rac.row, rac.cell, @as(u21, @intCast(0x0301))); + } + } + + // Add graphemes to the beginning of the second page + { + const page = &s.pages.last.?.data; + const count = @min(graphemes_per_page, page.size.rows); + for (0..count) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'B' }, + }; + try page.appendGrapheme(rac.row, rac.cell, @as(u21, @intCast(0x0302))); + } + } + + // Resize to fewer columns to trigger reflow. + // The graphemes from both pages will be copied to destination pages. + // They will all end up in a contiguous region of the destination. + // If the bug exists (hyperlink_bytes increased instead of grapheme_bytes), + // this will fail with GraphemeMapOutOfMemory when we exceed capacity. + try s.resize(.{ .cols = 2, .reflow = true }); + + // Verify the resize succeeded + try testing.expectEqual(@as(usize, 2), s.cols); +} + +test "PageList resize grow cols with unwrap fixes viewport pin" { + // Regression test: after resize/reflow, the viewport pin can end up at a + // position where pin.y + rows > total_rows, causing getBottomRight to panic. + + // The plan is to pin viewport in history, then grow columns to unwrap rows. + // The unwrap reduces total_rows, but the tracked pin moves to a position + // that no longer has enough rows below it for the viewport height. + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 2, 10, null); + defer s.deinit(); + + // Make sure we have some history, in this case we have 30 rows of history + try s.growRows(30); + try testing.expectEqual(@as(usize, 40), s.totalRows()); + + // Fill all rows with wrapped content (pairs that unwrap when cols increase) + var it = s.pageIterator(.right_down, .{ .screen = .{} }, null); + while (it.next()) |chunk| { + const page = &chunk.node.data; + for (chunk.start..chunk.end) |y| { + const rac = page.getRowAndCell(0, y); + if (y % 2 == 0) { + rac.row.wrap = true; + } else { + rac.row.wrap_continuation = true; + } + for (0..s.cols) |x| { + page.getRowAndCell(x, y).cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'A' }, + }; + } + } + } + + // Pin viewport at row 28 (in history, 2 rows before active area at row 30). + // After unwrap: row 28 -> row 14, total_rows 40 -> 20, active starts at 10. + // Pin at 14 needs rows 14-23, but only 0-19 exist -> overflow. + s.scroll(.{ .pin = s.pin(.{ .screen = .{ .y = 28 } }).? }); + try testing.expect(s.viewport == .pin); + try testing.expect(s.getBottomRight(.viewport) != null); + + // Resize with reflow: unwraps rows, reducing total_rows + try s.resize(.{ .cols = 4, .reflow = true }); + try testing.expectEqual(@as(usize, 4), s.cols); + try testing.expect(s.totalRows() < 40); + + // Used to panic here, so test that we can get the bottom right. + const br_after = s.getBottomRight(.viewport); + try testing.expect(br_after != null); +} + +test "PageList grow reuses non-standard page without leak" { + const testing = std.testing; + const alloc = testing.allocator; + + // Create a PageList with 3 * std_size max so we can fit multiple pages + // but will still trigger reuse. + var s = try init(alloc, 80, 24, 3 * std_size); + defer s.deinit(); + + // Increase the first page capacity to make it non-standard (larger than std_size). + while (s.pages.first.?.data.memory.len <= std_size) { + _ = try s.increaseCapacity(s.pages.first.?, .grapheme_bytes); + } + + // The first page should now have non-standard memory size. + try testing.expect(s.pages.first.?.data.memory.len > std_size); + + // First, fill up the first page's capacity + const first_page = s.pages.first.?; + while (first_page.data.size.rows < first_page.data.capacity.rows) { + _ = try s.grow(); + } + + // Now grow to create a second page + _ = try s.grow(); + try testing.expect(s.pages.first != s.pages.last); + + // Continue growing until we exceed max_size AND the last page is full + while (s.page_size + PagePool.item_size <= s.maxSize() or + s.pages.last.?.data.size.rows < s.pages.last.?.data.capacity.rows) + { + _ = try s.grow(); + } + + // The first page should still be non-standard + try testing.expect(s.pages.first.?.data.memory.len > std_size); + + // Verify we have enough rows for active area (so prune path isn't skipped) + try testing.expect(s.totalRows() >= s.rows); + + // Verify last page is full (so grow will need to allocate/reuse) + try testing.expect(s.pages.last.?.data.size.rows == s.pages.last.?.data.capacity.rows); + + // Remember the first page memory pointer before the reuse attempt + const first_page_ptr = s.pages.first.?; + const first_page_mem_ptr = s.pages.first.?.data.memory.ptr; + + // Create a tracked pin pointing to the non-standard first page + const tracked_pin = try s.trackPin(.{ .node = first_page_ptr, .x = 0, .y = 0 }); + defer s.untrackPin(tracked_pin); + + // Now grow one more time to trigger the reuse path. Since the first page + // is non-standard, it should be destroyed (not reused). The testing + // allocator will detect a leak if destroyNode doesn't properly free + // the non-standard memory. + _ = try s.grow(); + + // After grow, check if the first page is a different one + // (meaning the non-standard page was pruned, not reused at the end) + // The original first page should no longer be the first page + try testing.expect(s.pages.first.? != first_page_ptr); + + // If the non-standard page was properly destroyed and not reused, + // the last page should not have the same memory pointer + try testing.expect(s.pages.last.?.data.memory.ptr != first_page_mem_ptr); + + // The tracked pin should have been moved to the new first page and marked as garbage + try testing.expectEqual(s.pages.first.?, tracked_pin.node); + try testing.expectEqual(0, tracked_pin.x); + try testing.expectEqual(0, tracked_pin.y); + try testing.expect(tracked_pin.garbage); +} + +test "PageList grow non-standard page prune protection" { + const testing = std.testing; + const alloc = testing.allocator; + + // This test specifically verifies the fix for the bug where pruning a + // non-standard page would cause totalRows() < self.rows. + // + // Bug trigger conditions (all must be true simultaneously): + // 1. first page is non-standard (memory.len > std_size) + // 2. page_size + PagePool.item_size > maxSize() (triggers prune consideration) + // 3. pages.first != pages.last (have multiple pages) + // 4. total_rows >= self.rows (have enough rows for active area) + // 5. total_rows - first.size.rows + 1 < self.rows (prune would lose too many) + + // This is kind of magic and likely depends on std_size. + const rows_count = 600; + var s = try init(alloc, 80, rows_count, std_size); + defer s.deinit(); + + // Make the first page non-standard + while (s.pages.first.?.data.memory.len <= std_size) { + _ = try s.increaseCapacity( + s.pages.first.?, + .grapheme_bytes, + ); + } + try testing.expect(s.pages.first.?.data.memory.len > std_size); + + const first_page_node = s.pages.first.?; + const first_page_cap = first_page_node.data.capacity.rows; + + // Fill first page to capacity + while (first_page_node.data.size.rows < first_page_cap) _ = try s.grow(); + + // Grow until we have a second page (first page fills up first) + var second_node: ?*List.Node = null; + while (s.pages.first == s.pages.last) second_node = try s.grow(); + try testing.expect(s.pages.first != s.pages.last); + + // Fill the second page to capacity so that the next grow() triggers prune + const last_node = s.pages.last.?; + const second_cap = last_node.data.capacity.rows; + while (last_node.data.size.rows < second_cap) _ = try s.grow(); + + // Now the last page is full. The next grow must either: + // 1. Prune the first page and reuse it, OR + // 2. Allocate a new page + const total = s.totalRows(); + const would_remain = total - first_page_cap + 1; + + // Verify the bug condition is present: pruning first page would leave < rows + try testing.expect(would_remain < s.rows); + + // Verify prune path conditions are met + try testing.expect(s.pages.first != s.pages.last); + try testing.expect(s.page_size + PagePool.item_size > s.maxSize()); + try testing.expect(s.totalRows() >= s.rows); + + // Verify last page is at capacity (so grow must prune or allocate new) + try testing.expectEqual(second_cap, last_node.data.size.rows); + + // The next grow should trigger prune consideration. + // Without the fix, this would destroy the non-standard first page, + // leaving only second_cap + 1 rows, which is < self.rows. + _ = try s.grow(); + + // Verify the invariant holds - the fix prevents the destructive prune + try testing.expect(s.totalRows() >= s.rows); +} + +test "PageList resize (no reflow) more cols remaps pins in backfill path" { + // Regression test: when resizeWithoutReflowGrowCols copies rows to a previous + // page with spare capacity, tracked pins in those rows must be remapped. + // Without the fix, pins become dangling pointers when the original page is destroyed. + const testing = std.testing; + const alloc = testing.allocator; + + const cols: size.CellCountInt = 5; + const cap = try std_capacity.adjust(.{ .cols = cols }); + var s = try init(alloc, cols, cap.rows, null); + defer s.deinit(); + + // Grow until we have two pages. + while (s.pages.first == s.pages.last) { + _ = try s.grow(); + } + const first_page = s.pages.first.?; + const second_page = s.pages.last.?; + try testing.expect(first_page != second_page); + + // Trim a history row so the first page has spare capacity. + // This triggers the backfill path in resizeWithoutReflowGrowCols. + s.eraseHistory(.{ .history = .{ .y = 0 } }); + try testing.expect(first_page.data.size.rows < first_page.data.capacity.rows); + + // Ensure the resize takes the slow path (new capacity > current capacity). + const new_cols: size.CellCountInt = cols + 1; + const adjusted = try second_page.data.capacity.adjust(.{ .cols = new_cols }); + try testing.expect(second_page.data.capacity.cols < adjusted.cols); + + // Track a pin in row 0 of the second page. This row will be copied + // to the first page during backfill and the pin must be remapped. + const tracked = try s.trackPin(.{ .node = second_page, .x = 0, .y = 0 }); + defer s.untrackPin(tracked); + + // Write a marker character to the tracked cell so we can verify + // the pin points to the correct cell after resize. + const marker: u21 = 'X'; + tracked.rowAndCell().cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = marker }, + }; + + try s.resize(.{ .cols = new_cols, .reflow = false }); + + // Verify the pin points to a valid node still in the page list. + var found = false; + var it = s.pages.first; + while (it) |node| : (it = node.next) { + if (node == tracked.node) { + found = true; + break; + } + } + try testing.expect(found); + try testing.expect(tracked.y < tracked.node.data.size.rows); + + // Verify the pin still points to the cell with our marker content. + const cell = tracked.rowAndCell().cell; + try testing.expectEqual(.codepoint, cell.content_tag); + try testing.expectEqual(marker, cell.content.codepoint); +} + +test "PageList compact std_size page returns null" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, 0); + defer s.deinit(); + + // A freshly created page should be at std_size + const node = s.pages.first.?; + try testing.expect(node.data.memory.len <= std_size); + + // compact should return null since there's nothing to compact + const result = try s.compact(node); + try testing.expectEqual(null, result); + + // Page should still be the same + try testing.expectEqual(node, s.pages.first.?); +} + +test "PageList compact oversized page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, null); + defer s.deinit(); + + // Grow until we have multiple pages + const page1_node = s.pages.first.?; + page1_node.data.pauseIntegrityChecks(true); + for (0..page1_node.data.capacity.rows - page1_node.data.size.rows) |_| { + _ = try s.grow(); + } + page1_node.data.pauseIntegrityChecks(false); + _ = try s.grow(); + try testing.expect(s.pages.first != s.pages.last); + + var node = s.pages.first.?; + + // Write content to verify it's preserved + { + const page = &node.data; + for (0..page.size.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + y * s.cols) }, + }; + } + } + } + + // Create a tracked pin on this page + const tracked = try s.trackPin(.{ .node = node, .x = 5, .y = 10 }); + defer s.untrackPin(tracked); + + // Make the page oversized + while (node.data.memory.len <= std_size) { + node = try s.increaseCapacity(node, .grapheme_bytes); + } + try testing.expect(node.data.memory.len > std_size); + const oversized_len = node.data.memory.len; + const original_size = node.data.size; + const second_node = node.next.?; + + // Set dirty flag after increaseCapacity + node.data.dirty = true; + + // Compact the page + const new_node = try s.compact(node); + try testing.expect(new_node != null); + + // Verify memory is smaller + try testing.expect(new_node.?.data.memory.len < oversized_len); + + // Verify size preserved + try testing.expectEqual(original_size.rows, new_node.?.data.size.rows); + try testing.expectEqual(original_size.cols, new_node.?.data.size.cols); + + // Verify dirty flag preserved + try testing.expect(new_node.?.data.dirty); + + // Verify linked list integrity + try testing.expectEqual(new_node.?, s.pages.first.?); + try testing.expectEqual(null, new_node.?.prev); + try testing.expectEqual(second_node, new_node.?.next); + try testing.expectEqual(new_node.?, second_node.prev); + + // Verify pin updated correctly + try testing.expectEqual(new_node.?, tracked.node); + try testing.expectEqual(@as(size.CellCountInt, 5), tracked.x); + try testing.expectEqual(@as(size.CellCountInt, 10), tracked.y); + + // Verify content preserved + const page = &new_node.?.data; + for (0..page.size.rows) |y| { + for (0..s.cols) |x| { + const rac = page.getRowAndCell(x, y); + try testing.expectEqual( + @as(u21, @intCast(x + y * s.cols)), + rac.cell.content.codepoint, + ); + } + } +} + +test "PageList compact insufficient savings returns null" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 80, 24, 0); + defer s.deinit(); + + var node = s.pages.first.?; + + // Make the page slightly oversized (just one increase) + // This might not provide enough savings to justify compaction + node = try s.increaseCapacity(node, .grapheme_bytes); + + // If the page is still at or below std_size, compact returns null + if (node.data.memory.len <= std_size) { + const result = try s.compact(node); + try testing.expectEqual(null, result); + } else { + // If it did grow beyond std_size, verify that compaction + // works or returns null based on savings calculation + const result = try s.compact(node); + // Either it compacted or determined insufficient savings + if (result) |new_node| { + try testing.expect(new_node.data.memory.len < node.data.memory.len); + } + } +} + +test "PageList split at middle row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Write content to rows: row 0 gets codepoint 0, row 1 gets 1, etc. + for (0..page.size.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Split at row 5 (middle) + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 5, .x = 0 }; + try s.split(split_pin); + + // Verify two pages exist + try testing.expect(s.pages.first != null); + try testing.expect(s.pages.first.?.next != null); + + const first_page = &s.pages.first.?.data; + const second_page = &s.pages.first.?.next.?.data; + + // First page should have rows 0-4 (5 rows) + try testing.expectEqual(@as(usize, 5), first_page.size.rows); + // Second page should have rows 5-9 (5 rows) + try testing.expectEqual(@as(usize, 5), second_page.size.rows); + + // Verify content in first page is preserved (rows 0-4 have codepoints 0-4) + for (0..5) |y| { + const rac = first_page.getRowAndCell(0, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } + + // Verify content in second page (original rows 5-9, now at y=0-4) + for (0..5) |y| { + const rac = second_page.getRowAndCell(0, y); + try testing.expectEqual(@as(u21, @intCast(y + 5)), rac.cell.content.codepoint); + } +} + +test "PageList split at row 0 is no-op" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Write content to all rows + for (0..page.size.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Split at row 0 should be a no-op + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 0, .x = 0 }; + try s.split(split_pin); + + // Verify only one page exists (no split occurred) + try testing.expect(s.pages.first != null); + try testing.expect(s.pages.first.?.next == null); + + // Verify all content is still in the original page + try testing.expectEqual(@as(usize, 10), page.size.rows); + for (0..10) |y| { + const rac = page.getRowAndCell(0, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } +} + +test "PageList split at last row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Write content to all rows + for (0..page.size.rows) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Split at last row (row 9) + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 9, .x = 0 }; + try s.split(split_pin); + + // Verify two pages exist + try testing.expect(s.pages.first != null); + try testing.expect(s.pages.first.?.next != null); + + const first_page = &s.pages.first.?.data; + const second_page = &s.pages.first.?.next.?.data; + + // First page should have 9 rows + try testing.expectEqual(@as(usize, 9), first_page.size.rows); + // Second page should have 1 row + try testing.expectEqual(@as(usize, 1), second_page.size.rows); + + // Verify content in second page (original row 9, now at y=0) + const rac = second_page.getRowAndCell(0, 0); + try testing.expectEqual(@as(u21, 9), rac.cell.content.codepoint); +} + +test "PageList split single row page returns OutOfSpace" { + const testing = std.testing; + const alloc = testing.allocator; + + // Initialize with 1 row + var s = try init(alloc, 10, 1, 0); + defer s.deinit(); + + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 0, .x = 0 }; + const result = s.split(split_pin); + + try testing.expectError(error.OutOfSpace, result); +} + +test "PageList split moves tracked pins" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Track a pin at row 7 + const tracked = try s.trackPin(.{ .node = s.pages.first.?, .y = 7, .x = 3 }); + defer s.untrackPin(tracked); + + // Split at row 5 + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 5, .x = 0 }; + try s.split(split_pin); + + // The tracked pin should now be in the second page + try testing.expect(tracked.node == s.pages.first.?.next.?); + // y should be adjusted: was 7, split at 5, so new y = 7 - 5 = 2 + try testing.expectEqual(@as(usize, 2), tracked.y); + // x should remain unchanged + try testing.expectEqual(@as(usize, 3), tracked.x); +} + +test "PageList split tracked pin before split point unchanged" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const original_node = s.pages.first.?; + + // Track a pin at row 2 (before the split point) + const tracked = try s.trackPin(.{ .node = original_node, .y = 2, .x = 5 }); + defer s.untrackPin(tracked); + + // Split at row 5 + const split_pin: Pin = .{ .node = original_node, .y = 5, .x = 0 }; + try s.split(split_pin); + + // The tracked pin should remain in the original page + try testing.expect(tracked.node == s.pages.first.?); + // y and x should be unchanged + try testing.expectEqual(@as(usize, 2), tracked.y); + try testing.expectEqual(@as(usize, 5), tracked.x); +} + +test "PageList split tracked pin at split point moves to new page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const original_node = s.pages.first.?; + + // Track a pin at the exact split point (row 5) + const tracked = try s.trackPin(.{ .node = original_node, .y = 5, .x = 4 }); + defer s.untrackPin(tracked); + + // Split at row 5 + const split_pin: Pin = .{ .node = original_node, .y = 5, .x = 0 }; + try s.split(split_pin); + + // The tracked pin should be in the new page + try testing.expect(tracked.node == s.pages.first.?.next.?); + // y should be 0 since it was at the split point: 5 - 5 = 0 + try testing.expectEqual(@as(usize, 0), tracked.y); + // x should remain unchanged + try testing.expectEqual(@as(usize, 4), tracked.x); +} + +test "PageList split multiple tracked pins across regions" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const original_node = s.pages.first.?; + + // Track multiple pins in different regions + const pin_before = try s.trackPin(.{ .node = original_node, .y = 1, .x = 0 }); + defer s.untrackPin(pin_before); + const pin_at_split = try s.trackPin(.{ .node = original_node, .y = 5, .x = 2 }); + defer s.untrackPin(pin_at_split); + const pin_after1 = try s.trackPin(.{ .node = original_node, .y = 7, .x = 3 }); + defer s.untrackPin(pin_after1); + const pin_after2 = try s.trackPin(.{ .node = original_node, .y = 9, .x = 8 }); + defer s.untrackPin(pin_after2); + + // Split at row 5 + const split_pin: Pin = .{ .node = original_node, .y = 5, .x = 0 }; + try s.split(split_pin); + + const first_page = s.pages.first.?; + const second_page = first_page.next.?; + + // Pin before split point stays in original page + try testing.expect(pin_before.node == first_page); + try testing.expectEqual(@as(usize, 1), pin_before.y); + try testing.expectEqual(@as(usize, 0), pin_before.x); + + // Pin at split point moves to new page with y=0 + try testing.expect(pin_at_split.node == second_page); + try testing.expectEqual(@as(usize, 0), pin_at_split.y); + try testing.expectEqual(@as(usize, 2), pin_at_split.x); + + // Pins after split point move to new page with adjusted y + try testing.expect(pin_after1.node == second_page); + try testing.expectEqual(@as(usize, 2), pin_after1.y); // 7 - 5 = 2 + try testing.expectEqual(@as(usize, 3), pin_after1.x); + + try testing.expect(pin_after2.node == second_page); + try testing.expectEqual(@as(usize, 4), pin_after2.y); // 9 - 5 = 4 + try testing.expectEqual(@as(usize, 8), pin_after2.x); +} + +test "PageList split tracked viewport_pin in split region moves correctly" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const original_node = s.pages.first.?; + + // Set viewport_pin to row 7 (after split point) + s.viewport_pin.node = original_node; + s.viewport_pin.y = 7; + s.viewport_pin.x = 6; + + // Split at row 5 + const split_pin: Pin = .{ .node = original_node, .y = 5, .x = 0 }; + try s.split(split_pin); + + // viewport_pin should be in the new page + try testing.expect(s.viewport_pin.node == s.pages.first.?.next.?); + // y should be adjusted: 7 - 5 = 2 + try testing.expectEqual(@as(usize, 2), s.viewport_pin.y); + // x should remain unchanged + try testing.expectEqual(@as(usize, 6), s.viewport_pin.x); +} + +test "PageList split middle page preserves linked list order" { + const testing = std.testing; + const alloc = testing.allocator; + + // Create a single page with 12 rows + var s = try init(alloc, 10, 12, 0); + defer s.deinit(); + + // Split at row 4 to create: page1 (rows 0-3), page2 (rows 4-11) + const first_node = s.pages.first.?; + const split_pin1: Pin = .{ .node = first_node, .y = 4, .x = 0 }; + try s.split(split_pin1); + + // Now we have 2 pages + const page1 = s.pages.first.?; + const page2 = s.pages.first.?.next.?; + try testing.expectEqual(@as(usize, 4), page1.data.size.rows); + try testing.expectEqual(@as(usize, 8), page2.data.size.rows); + + // Split page2 at row 4 to create: page1 -> page2 (rows 0-3) -> page3 (rows 4-7) + const split_pin2: Pin = .{ .node = page2, .y = 4, .x = 0 }; + try s.split(split_pin2); + + // Now we have 3 pages + const first = s.pages.first.?; + const middle = first.next.?; + const last = middle.next.?; + + // Verify linked list order: first -> middle -> last + try testing.expectEqual(page1, first); + try testing.expectEqual(page2, middle); + try testing.expectEqual(s.pages.last.?, last); + + // Verify prev pointers + try testing.expect(first.prev == null); + try testing.expectEqual(first, middle.prev.?); + try testing.expectEqual(middle, last.prev.?); + + // Verify next pointers + try testing.expectEqual(middle, first.next.?); + try testing.expectEqual(last, middle.next.?); + try testing.expect(last.next == null); + + // Verify row counts + try testing.expectEqual(@as(usize, 4), first.data.size.rows); + try testing.expectEqual(@as(usize, 4), middle.data.size.rows); + try testing.expectEqual(@as(usize, 4), last.data.size.rows); +} + +test "PageList split last page makes new page the last" { + const testing = std.testing; + const alloc = testing.allocator; + + // Create a single page with 10 rows + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + // Split to create 2 pages first + const first_node = s.pages.first.?; + const split_pin1: Pin = .{ .node = first_node, .y = 5, .x = 0 }; + try s.split(split_pin1); + + // Now split the last page + const last_before_split = s.pages.last.?; + try testing.expectEqual(@as(usize, 5), last_before_split.data.size.rows); + + const split_pin2: Pin = .{ .node = last_before_split, .y = 2, .x = 0 }; + try s.split(split_pin2); + + // The new page should be the new last + const new_last = s.pages.last.?; + try testing.expect(new_last != last_before_split); + try testing.expectEqual(last_before_split, new_last.prev.?); + try testing.expect(new_last.next == null); + + // Verify row counts: original last has 2 rows, new last has 3 rows + try testing.expectEqual(@as(usize, 2), last_before_split.data.size.rows); + try testing.expectEqual(@as(usize, 3), new_last.data.size.rows); +} + +test "PageList split first page keeps original as first" { + const testing = std.testing; + const alloc = testing.allocator; + + // Create 2 pages by splitting + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const original_first = s.pages.first.?; + const split_pin1: Pin = .{ .node = original_first, .y = 5, .x = 0 }; + try s.split(split_pin1); + + // Get second page (created by first split) + const second_page = s.pages.first.?.next.?; + + // Now split the first page again + const split_pin2: Pin = .{ .node = s.pages.first.?, .y = 2, .x = 0 }; + try s.split(split_pin2); + + // Original first should still be first + try testing.expectEqual(original_first, s.pages.first.?); + try testing.expect(s.pages.first.?.prev == null); + + // New page should be inserted between first and second + const inserted = s.pages.first.?.next.?; + try testing.expect(inserted != second_page); + try testing.expectEqual(second_page, inserted.next.?); + + // Verify row counts: first has 2, inserted has 3, second has 5 + try testing.expectEqual(@as(usize, 2), s.pages.first.?.data.size.rows); + try testing.expectEqual(@as(usize, 3), inserted.data.size.rows); + try testing.expectEqual(@as(usize, 5), second_page.data.size.rows); +} + +test "PageList split preserves wrap flags" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Set wrap flags on rows that will be in the second page after split + // Row 5: wrap = true (this is the start of a wrapped line) + // Row 6: wrap_continuation = true (this continues the wrap) + // Row 7: wrap = true, wrap_continuation = true (wrapped and continues) + { + const rac5 = page.getRowAndCell(0, 5); + rac5.row.wrap = true; + + const rac6 = page.getRowAndCell(0, 6); + rac6.row.wrap_continuation = true; + + const rac7 = page.getRowAndCell(0, 7); + rac7.row.wrap = true; + rac7.row.wrap_continuation = true; + } + + // Split at row 5 + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 5, .x = 0 }; + try s.split(split_pin); + + const second_page = &s.pages.first.?.next.?.data; + + // Verify wrap flags are preserved in new page + // Original row 5 is now row 0 in second page + { + const rac0 = second_page.getRowAndCell(0, 0); + try testing.expect(rac0.row.wrap); + try testing.expect(!rac0.row.wrap_continuation); + } + + // Original row 6 is now row 1 in second page + { + const rac1 = second_page.getRowAndCell(0, 1); + try testing.expect(!rac1.row.wrap); + try testing.expect(rac1.row.wrap_continuation); + } + + // Original row 7 is now row 2 in second page + { + const rac2 = second_page.getRowAndCell(0, 2); + try testing.expect(rac2.row.wrap); + try testing.expect(rac2.row.wrap_continuation); + } +} + +test "PageList split preserves styled cells" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Create a style and apply it to cells in rows 5-7 (which will be in the second page) + const style: stylepkg.Style = .{ .flags = .{ .bold = true } }; + const style_id = try page.styles.add(page.memory, style); + + for (5..8) |y| { + const rac = page.getRowAndCell(0, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'S' }, + .style_id = style_id, + }; + rac.row.styled = true; + page.styles.use(page.memory, style_id); + } + // Release the extra ref from add + page.styles.release(page.memory, style_id); + + // Split at row 5 + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 5, .x = 0 }; + try s.split(split_pin); + + const first_page = &s.pages.first.?.data; + const second_page = &s.pages.first.?.next.?.data; + + // First page should have no styles (all styled rows moved to second page) + try testing.expectEqual(@as(usize, 0), first_page.styles.count()); + + // Second page should have exactly 1 style (the bold style, used by 3 cells) + try testing.expectEqual(@as(usize, 1), second_page.styles.count()); + + // Verify styled cells are preserved in new page + for (0..3) |y| { + const rac = second_page.getRowAndCell(0, y); + try testing.expectEqual(@as(u21, 'S'), rac.cell.content.codepoint); + try testing.expect(rac.cell.style_id != 0); + + const got_style = second_page.styles.get(second_page.memory, rac.cell.style_id); + try testing.expect(got_style.flags.bold); + try testing.expect(rac.row.styled); + } +} + +test "PageList split preserves grapheme clusters" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Add a grapheme cluster to row 6 (will be row 1 in second page after split at 5) + { + const rac = page.getRowAndCell(0, 6); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0x1F468 }, // Man emoji + }; + try page.setGraphemes(rac.row, rac.cell, &.{ + 0x200D, // ZWJ + 0x1F469, // Woman emoji + }); + } + + // Split at row 5 + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 5, .x = 0 }; + try s.split(split_pin); + + const first_page = &s.pages.first.?.data; + const second_page = &s.pages.first.?.next.?.data; + + // First page should have no graphemes (the grapheme row moved to second page) + try testing.expectEqual(@as(usize, 0), first_page.graphemeCount()); + + // Second page should have exactly 1 grapheme + try testing.expectEqual(@as(usize, 1), second_page.graphemeCount()); + + // Verify grapheme is preserved in new page (original row 6 is now row 1) + { + const rac = second_page.getRowAndCell(0, 1); + try testing.expectEqual(@as(u21, 0x1F468), rac.cell.content.codepoint); + try testing.expect(rac.row.grapheme); + + const cps = second_page.lookupGrapheme(rac.cell).?; + try testing.expectEqual(@as(usize, 2), cps.len); + try testing.expectEqual(@as(u21, 0x200D), cps[0]); + try testing.expectEqual(@as(u21, 0x1F469), cps[1]); + } +} + +test "PageList split preserves hyperlinks" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, 10, 10, 0); + defer s.deinit(); + + const page = &s.pages.first.?.data; + + // Add a hyperlink to row 7 (will be row 2 in second page after split at 5) + const hyperlink_id = try page.insertHyperlink(.{ + .id = .{ .implicit = 0 }, + .uri = "https://example.com", + }); + { + const rac = page.getRowAndCell(0, 7); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'L' }, + }; + try page.setHyperlink(rac.row, rac.cell, hyperlink_id); + } + + // Split at row 5 + const split_pin: Pin = .{ .node = s.pages.first.?, .y = 5, .x = 0 }; + try s.split(split_pin); + + const first_page = &s.pages.first.?.data; + const second_page = &s.pages.first.?.next.?.data; + + // First page should have no hyperlinks (the hyperlink row moved to second page) + try testing.expectEqual(@as(usize, 0), first_page.hyperlink_set.count()); + + // Second page should have exactly 1 hyperlink + try testing.expectEqual(@as(usize, 1), second_page.hyperlink_set.count()); + + // Verify hyperlink is preserved in new page (original row 7 is now row 2) + { + const rac = second_page.getRowAndCell(0, 2); + try testing.expectEqual(@as(u21, 'L'), rac.cell.content.codepoint); + try testing.expect(rac.cell.hyperlink); + + const link_id = second_page.lookupHyperlink(rac.cell).?; + const link = second_page.hyperlink_set.get(second_page.memory, link_id); + try testing.expectEqualStrings("https://example.com", link.uri.slice(second_page.memory)); + } +} diff --git a/vendor/libghostty-vt/src/terminal/Parser.zig b/vendor/libghostty-vt/src/terminal/Parser.zig new file mode 100644 index 00000000..88e7edf7 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/Parser.zig @@ -0,0 +1,1099 @@ +//! VT-series parser for escape and control sequences. +//! +//! This is implemented directly as the state machine described on +//! vt100.net: https://vt100.net/emu/dec_ansi_parser +const Parser = @This(); + +const std = @import("std"); +const testing = std.testing; +const table = @import("parse_table.zig").table; +const osc = @import("osc.zig"); + +const log = std.log.scoped(.parser); + +/// States for the state machine +pub const State = enum { + ground, + escape, + escape_intermediate, + csi_entry, + csi_intermediate, + csi_param, + csi_ignore, + dcs_entry, + dcs_param, + dcs_intermediate, + dcs_passthrough, + dcs_ignore, + osc_string, + sos_pm_apc_string, +}; + +/// Transition action is an action that can be taken during a state +/// transition. This is more of an internal action, not one used by +/// end users, typically. +pub const TransitionAction = enum { + none, + ignore, + print, + execute, + collect, + param, + esc_dispatch, + csi_dispatch, + put, + osc_put, + apc_put, +}; + +/// Action is the action that a caller of the parser is expected to +/// take as a result of some input character. +pub const Action = union(enum) { + pub const Tag = std.meta.FieldEnum(Action); + + /// Draw character to the screen. This is a unicode codepoint. + print: u21, + + /// Execute the C0 or C1 function. + execute: u8, + + /// Execute the CSI command. Note that pointers within this + /// structure are only valid until the next call to "next". + csi_dispatch: CSI, + + /// Execute the ESC command. + esc_dispatch: ESC, + + /// Execute the OSC command. + osc_dispatch: osc.Command, + + /// DCS-related events. + dcs_hook: DCS, + dcs_put: u8, + dcs_unhook: void, + + /// APC data + apc_start: void, + apc_put: u8, + apc_end: void, + + pub const CSI = struct { + intermediates: []u8, + params: []u16, + params_sep: SepList, + final: u8, + + /// The list of separators used for CSI params. The value of the + /// bit can be mapped to Sep. The index of this bit set specifies + /// the separator AFTER that param. For example: 0;4:3 would have + /// index 1 set. + pub const SepList = std.StaticBitSet(MAX_PARAMS); + + /// The separator used for CSI params. + pub const Sep = enum(u1) { semicolon = 0, colon = 1 }; + + // Implement formatter for logging + pub fn format( + self: CSI, + writer: *std.Io.Writer, + ) !void { + try writer.print("ESC [ {s} {any} {c}", .{ + self.intermediates, + self.params, + self.final, + }); + } + }; + + pub const ESC = struct { + intermediates: []u8, + final: u8, + + // Implement formatter for logging + pub fn format( + self: ESC, + writer: *std.Io.Writer, + ) !void { + try writer.print("ESC {s} {c}", .{ + self.intermediates, + self.final, + }); + } + }; + + pub const DCS = struct { + intermediates: []const u8 = "", + params: []const u16 = &.{}, + final: u8, + + pub const C = extern struct { + intermediates: [*]const u8, + intermediates_len: usize, + params: [*]const u16, + params_len: usize, + final: u8, + }; + }; + + // Implement formatter for logging. This is mostly copied from the + // std.fmt implementation, but we modify it slightly so that we can + // print out custom formats for some of our primitives. + pub fn format( + self: Action, + writer: *std.Io.Writer, + ) !void { + const T = Action; + const info = @typeInfo(T).@"union"; + + try writer.writeAll(@typeName(T)); + if (info.tag_type) |TagType| { + try writer.writeAll("{ ."); + try writer.writeAll(@tagName(@as(TagType, self))); + try writer.writeAll(" = "); + + inline for (info.fields) |u_field| { + // If this is the active field... + if (self == @field(TagType, u_field.name)) { + const value = @field(self, u_field.name); + switch (@TypeOf(value)) { + // Unicode + u21 => try writer.print("'{u}' (U+{X})", .{ value, value }), + + // Byte + u8 => try writer.print("0x{x}", .{value}), + + // Note: we don't do ASCII (u8) because there are a lot + // of invisible characters we don't want to handle right + // now. + + // All others do the default behavior + else => try writer.printValue( + "any", + .{}, + @field(self, u_field.name), + 3, + ), + } + } + } + + try writer.writeAll(" }"); + } else { + try format(writer, "@{x}", .{@intFromPtr(&self)}); + } + } +}; + +/// Maximum number of intermediate characters during parsing. This is +/// 4 because we also use the intermediates array for UTF8 decoding which +/// can be at most 4 bytes. +pub const MAX_INTERMEDIATE = 4; + +/// Maximum number of CSI parameters. This is arbitrary. Practically, the +/// only CSI command that uses more than 3 parameters is the SGR command +/// which can be infinitely long. 24 is a reasonable limit based on empirical +/// data. This used to be 16 but Kakoune has a SGR command that uses 17 +/// parameters. +/// +/// We could in the future make this the static limit and then allocate after +/// but that's a lot more work and practically its so rare to exceed this +/// number. I implore TUI authors to not use more than this number of CSI +/// params, but I suspect we'll introduce a slow path with heap allocation +/// one day. +pub const MAX_PARAMS = 24; + +/// Current state of the state machine +state: State, + +/// Intermediate tracking. +intermediates: [MAX_INTERMEDIATE]u8, +intermediates_idx: u8, + +/// Param tracking, building +params: [MAX_PARAMS]u16, +params_sep: Action.CSI.SepList, +params_idx: u8, +param_acc: u16, +param_acc_idx: u8, + +/// Parser for OSC sequences +osc_parser: osc.Parser, + +pub fn init() Parser { + var result: Parser = .{ + .state = .ground, + .intermediates_idx = 0, + .params_sep = .initEmpty(), + .params_idx = 0, + .param_acc = 0, + .param_acc_idx = 0, + .osc_parser = .init(null), + + .intermediates = undefined, + .params = undefined, + }; + if (std.valgrind.runningOnValgrind() > 0) { + // Initialize our undefined fields so Valgrind can catch it. + // https://github.com/ziglang/zig/issues/19148 + result.intermediates = undefined; + result.params = undefined; + } + return result; +} + +pub fn deinit(self: *Parser) void { + self.osc_parser.deinit(); +} + +/// Next consumes the next character c and returns the actions to execute. +/// Up to 3 actions may need to be executed -- in order -- representing +/// the state exit, transition, and entry actions. +pub fn next(self: *Parser, c: u8) [3]?Action { + const effect = table[c][@intFromEnum(self.state)]; + + // log.info("next: {x}", .{c}); + + const next_state = effect.state; + const action = effect.action; + + // After generating the actions, we set our next state. + defer self.state = next_state; + + // When going from one state to another, the actions take place in this order: + // + // 1. exit action from old state + // 2. transition action + // 3. entry action to new state + return [3]?Action{ + // Exit depends on current state + if (self.state == next_state) null else switch (self.state) { + .osc_string => if (self.osc_parser.end(c)) |cmd| + Action{ .osc_dispatch = cmd.* } + else + null, + .dcs_passthrough => Action{ .dcs_unhook = {} }, + .sos_pm_apc_string => Action{ .apc_end = {} }, + else => null, + }, + + self.doAction(action, c), + + // Entry depends on new state + if (self.state == next_state) null else switch (next_state) { + .escape, .dcs_entry, .csi_entry => clear: { + self.clear(); + break :clear null; + }, + .osc_string => osc_string: { + self.osc_parser.reset(); + break :osc_string null; + }, + .dcs_passthrough => dcs_hook: { + // Ignore too many parameters + if (self.params_idx >= MAX_PARAMS) break :dcs_hook null; + // Finalize parameters + if (self.param_acc_idx > 0) { + self.params[self.params_idx] = self.param_acc; + self.params_idx += 1; + } + break :dcs_hook .{ + .dcs_hook = .{ + .intermediates = self.intermediates[0..self.intermediates_idx], + .params = self.params[0..self.params_idx], + .final = c, + }, + }; + }, + .sos_pm_apc_string => Action{ .apc_start = {} }, + else => null, + }, + }; +} + +pub inline fn collect(self: *Parser, c: u8) void { + if (self.intermediates_idx >= MAX_INTERMEDIATE) { + @branchHint(.cold); + log.warn("invalid intermediates count", .{}); + return; + } + + self.intermediates[self.intermediates_idx] = c; + self.intermediates_idx += 1; +} + +inline fn doAction(self: *Parser, action: TransitionAction, c: u8) ?Action { + return switch (action) { + .none, .ignore => null, + .print => Action{ .print = c }, + .execute => Action{ .execute = c }, + .collect => collect: { + self.collect(c); + break :collect null; + }, + .param => param: { + // Semicolon separates parameters. If we encounter a semicolon + // we need to store and move on to the next parameter. + if (c == ';' or c == ':') { + // Ignore too many parameters + if (self.params_idx >= MAX_PARAMS) break :param null; + + // Set param final value + self.params[self.params_idx] = self.param_acc; + if (c == ':') self.params_sep.set(self.params_idx); + self.params_idx += 1; + + // Reset current param value to 0 + self.param_acc = 0; + self.param_acc_idx = 0; + break :param null; + } + + // A numeric value. Add it to our accumulator. + self.param_acc *|= 10; + self.param_acc +|= c - '0'; + + // Increment our accumulator index. If we overflow then + // we're out of bounds and we exit immediately. + self.param_acc_idx, const overflow = @addWithOverflow(self.param_acc_idx, 1); + if (overflow > 0) break :param null; + + // The client is expected to perform no action. + break :param null; + }, + .osc_put => osc_put: { + @call(.always_inline, osc.Parser.next, .{ &self.osc_parser, c }); + break :osc_put null; + }, + .csi_dispatch => csi_dispatch: { + // Ignore too many parameters + if (self.params_idx >= MAX_PARAMS) break :csi_dispatch null; + + // Finalize parameters if we have one + if (self.param_acc_idx > 0) { + self.params[self.params_idx] = self.param_acc; + self.params_idx += 1; + } + + const result: Action = .{ + .csi_dispatch = .{ + .intermediates = self.intermediates[0..self.intermediates_idx], + .params = self.params[0..self.params_idx], + .params_sep = self.params_sep, + .final = c, + }, + }; + + // We only allow colon or mixed separators for the 'm' command. + if (c != 'm' and self.params_sep.count() > 0) { + @branchHint(.cold); + log.warn( + "CSI colon or mixed separators only allowed for 'm' command, got: {f}", + .{result}, + ); + break :csi_dispatch null; + } + + break :csi_dispatch result; + }, + .esc_dispatch => Action{ + .esc_dispatch = .{ + .intermediates = self.intermediates[0..self.intermediates_idx], + .final = c, + }, + }, + .put => Action{ .dcs_put = c }, + .apc_put => Action{ .apc_put = c }, + }; +} + +pub inline fn clear(self: *Parser) void { + self.intermediates_idx = 0; + self.params_idx = 0; + self.params_sep = .initEmpty(); + self.param_acc = 0; + self.param_acc_idx = 0; +} + +test { + var p = init(); + _ = p.next(0x9E); + try testing.expect(p.state == .sos_pm_apc_string); + _ = p.next(0x9C); + try testing.expect(p.state == .ground); + + { + const a = p.next('a'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .print); + try testing.expect(a[2] == null); + } + + { + const a = p.next(0x19); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .execute); + try testing.expect(a[2] == null); + } +} + +test "esc: ESC ( B" { + var p = init(); + _ = p.next(0x1B); + _ = p.next('('); + + { + const a = p.next('B'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .esc_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.esc_dispatch; + try testing.expect(d.final == 'B'); + try testing.expect(d.intermediates.len == 1); + try testing.expect(d.intermediates[0] == '('); + } +} + +test "csi: ESC [ H" { + var p = init(); + _ = p.next(0x1B); + _ = p.next(0x5B); + + { + const a = p.next(0x48); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 0x48); + try testing.expect(d.params.len == 0); + } +} + +test "csi: ESC [ 1 ; 4 H" { + var p = init(); + _ = p.next(0x1B); + _ = p.next(0x5B); + _ = p.next(0x31); // 1 + _ = p.next(0x3B); // ; + _ = p.next(0x34); // 4 + + { + const a = p.next(0x48); // H + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'H'); + try testing.expect(d.params.len == 2); + try testing.expectEqual(@as(u16, 1), d.params[0]); + try testing.expectEqual(@as(u16, 4), d.params[1]); + } +} + +test "csi: SGR ESC [ 38 : 2 m" { + var p = init(); + _ = p.next(0x1B); + _ = p.next('['); + _ = p.next('3'); + _ = p.next('8'); + _ = p.next(':'); + _ = p.next('2'); + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'm'); + try testing.expect(d.params.len == 2); + try testing.expectEqual(@as(u16, 38), d.params[0]); + try testing.expect(d.params_sep.isSet(0)); + try testing.expectEqual(@as(u16, 2), d.params[1]); + try testing.expect(!d.params_sep.isSet(1)); + } +} + +test "csi: SGR colon followed by semicolon" { + var p = init(); + _ = p.next(0x1B); + for ("[48:2") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + } + + _ = p.next(0x1B); + _ = p.next('['); + { + const a = p.next('H'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + } +} + +test "csi: SGR mixed colon and semicolon" { + var p = init(); + _ = p.next(0x1B); + for ("[38:5:1;48:5:0") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + } +} + +test "csi: SGR ESC [ 48 : 2 m" { + var p = init(); + _ = p.next(0x1B); + for ("[48:2:240:143:104") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'm'); + try testing.expect(d.params.len == 5); + try testing.expectEqual(@as(u16, 48), d.params[0]); + try testing.expect(d.params_sep.isSet(0)); + try testing.expectEqual(@as(u16, 2), d.params[1]); + try testing.expect(d.params_sep.isSet(1)); + try testing.expectEqual(@as(u16, 240), d.params[2]); + try testing.expect(d.params_sep.isSet(2)); + try testing.expectEqual(@as(u16, 143), d.params[3]); + try testing.expect(d.params_sep.isSet(3)); + try testing.expectEqual(@as(u16, 104), d.params[4]); + try testing.expect(!d.params_sep.isSet(4)); + } +} + +test "csi: SGR ESC [4:3m colon" { + var p = init(); + _ = p.next(0x1B); + _ = p.next('['); + _ = p.next('4'); + _ = p.next(':'); + _ = p.next('3'); + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'm'); + try testing.expect(d.params.len == 2); + try testing.expectEqual(@as(u16, 4), d.params[0]); + try testing.expect(d.params_sep.isSet(0)); + try testing.expectEqual(@as(u16, 3), d.params[1]); + try testing.expect(!d.params_sep.isSet(1)); + } +} + +test "csi: SGR with many blank and colon" { + var p = init(); + _ = p.next(0x1B); + for ("[58:2::240:143:104") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'm'); + try testing.expect(d.params.len == 6); + try testing.expectEqual(@as(u16, 58), d.params[0]); + try testing.expect(d.params_sep.isSet(0)); + try testing.expectEqual(@as(u16, 2), d.params[1]); + try testing.expect(d.params_sep.isSet(1)); + try testing.expectEqual(@as(u16, 0), d.params[2]); + try testing.expect(d.params_sep.isSet(2)); + try testing.expectEqual(@as(u16, 240), d.params[3]); + try testing.expect(d.params_sep.isSet(3)); + try testing.expectEqual(@as(u16, 143), d.params[4]); + try testing.expect(d.params_sep.isSet(4)); + try testing.expectEqual(@as(u16, 104), d.params[5]); + try testing.expect(!d.params_sep.isSet(5)); + } +} + +// This is from a Kakoune actual SGR sequence. +test "csi: SGR mixed colon and semicolon with blank" { + var p = init(); + _ = p.next(0x1B); + for ("[;4:3;38;2;175;175;215;58:2::190:80:70") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'm'); + try testing.expectEqual(14, d.params.len); + try testing.expectEqual(@as(u16, 0), d.params[0]); + try testing.expect(!d.params_sep.isSet(0)); + try testing.expectEqual(@as(u16, 4), d.params[1]); + try testing.expect(d.params_sep.isSet(1)); + try testing.expectEqual(@as(u16, 3), d.params[2]); + try testing.expect(!d.params_sep.isSet(2)); + try testing.expectEqual(@as(u16, 38), d.params[3]); + try testing.expect(!d.params_sep.isSet(3)); + try testing.expectEqual(@as(u16, 2), d.params[4]); + try testing.expect(!d.params_sep.isSet(4)); + try testing.expectEqual(@as(u16, 175), d.params[5]); + try testing.expect(!d.params_sep.isSet(5)); + try testing.expectEqual(@as(u16, 175), d.params[6]); + try testing.expect(!d.params_sep.isSet(6)); + try testing.expectEqual(@as(u16, 215), d.params[7]); + try testing.expect(!d.params_sep.isSet(7)); + try testing.expectEqual(@as(u16, 58), d.params[8]); + try testing.expect(d.params_sep.isSet(8)); + try testing.expectEqual(@as(u16, 2), d.params[9]); + try testing.expect(d.params_sep.isSet(9)); + try testing.expectEqual(@as(u16, 0), d.params[10]); + try testing.expect(d.params_sep.isSet(10)); + try testing.expectEqual(@as(u16, 190), d.params[11]); + try testing.expect(d.params_sep.isSet(11)); + try testing.expectEqual(@as(u16, 80), d.params[12]); + try testing.expect(d.params_sep.isSet(12)); + try testing.expectEqual(@as(u16, 70), d.params[13]); + try testing.expect(!d.params_sep.isSet(13)); + } +} + +// This is from a Kakoune actual SGR sequence also. +test "csi: SGR mixed colon and semicolon setting underline, bg, fg" { + var p = init(); + _ = p.next(0x1B); + for ("[4:3;38;2;51;51;51;48;2;170;170;170;58;2;255;97;136") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('m'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'm'); + try testing.expectEqual(17, d.params.len); + try testing.expectEqual(@as(u16, 4), d.params[0]); + try testing.expect(d.params_sep.isSet(0)); + try testing.expectEqual(@as(u16, 3), d.params[1]); + try testing.expect(!d.params_sep.isSet(1)); + try testing.expectEqual(@as(u16, 38), d.params[2]); + try testing.expect(!d.params_sep.isSet(2)); + try testing.expectEqual(@as(u16, 2), d.params[3]); + try testing.expect(!d.params_sep.isSet(3)); + try testing.expectEqual(@as(u16, 51), d.params[4]); + try testing.expect(!d.params_sep.isSet(4)); + try testing.expectEqual(@as(u16, 51), d.params[5]); + try testing.expect(!d.params_sep.isSet(5)); + try testing.expectEqual(@as(u16, 51), d.params[6]); + try testing.expect(!d.params_sep.isSet(6)); + try testing.expectEqual(@as(u16, 48), d.params[7]); + try testing.expect(!d.params_sep.isSet(7)); + try testing.expectEqual(@as(u16, 2), d.params[8]); + try testing.expect(!d.params_sep.isSet(8)); + try testing.expectEqual(@as(u16, 170), d.params[9]); + try testing.expect(!d.params_sep.isSet(9)); + try testing.expectEqual(@as(u16, 170), d.params[10]); + try testing.expect(!d.params_sep.isSet(10)); + try testing.expectEqual(@as(u16, 170), d.params[11]); + try testing.expect(!d.params_sep.isSet(11)); + try testing.expectEqual(@as(u16, 58), d.params[12]); + try testing.expect(!d.params_sep.isSet(12)); + try testing.expectEqual(@as(u16, 2), d.params[13]); + try testing.expect(!d.params_sep.isSet(13)); + try testing.expectEqual(@as(u16, 255), d.params[14]); + try testing.expect(!d.params_sep.isSet(14)); + try testing.expectEqual(@as(u16, 97), d.params[15]); + try testing.expect(!d.params_sep.isSet(15)); + try testing.expectEqual(@as(u16, 136), d.params[16]); + try testing.expect(!d.params_sep.isSet(16)); + } +} + +test "csi: colon for non-m final" { + var p = init(); + _ = p.next(0x1B); + for ("[38:2h") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + try testing.expect(p.state == .ground); +} + +test "csi: request mode decrqm" { + var p = init(); + _ = p.next(0x1B); + for ("[?2026$") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('p'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'p'); + try testing.expectEqual(@as(usize, 2), d.intermediates.len); + try testing.expectEqual(@as(usize, 1), d.params.len); + try testing.expectEqual(@as(u16, '?'), d.intermediates[0]); + try testing.expectEqual(@as(u16, '$'), d.intermediates[1]); + try testing.expectEqual(@as(u16, 2026), d.params[0]); + } +} + +test "csi: change cursor" { + var p = init(); + _ = p.next(0x1B); + for ("[3 ") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('q'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const d = a[1].?.csi_dispatch; + try testing.expect(d.final == 'q'); + try testing.expectEqual(@as(usize, 1), d.intermediates.len); + try testing.expectEqual(@as(usize, 1), d.params.len); + try testing.expectEqual(@as(u16, ' '), d.intermediates[0]); + try testing.expectEqual(@as(u16, 3), d.params[0]); + } +} + +test "osc: change window title" { + var p = init(); + _ = p.next(0x1B); + _ = p.next(']'); + _ = p.next('0'); + _ = p.next(';'); + _ = p.next('a'); + _ = p.next('b'); + _ = p.next('c'); + + { + const a = p.next(0x07); // BEL + try testing.expect(p.state == .ground); + try testing.expect(a[0].? == .osc_dispatch); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + + const cmd = a[0].?.osc_dispatch; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings("abc", cmd.change_window_title); + } +} + +test "osc: change window title (end in esc)" { + var p = init(); + _ = p.next(0x1B); + _ = p.next(']'); + _ = p.next('0'); + _ = p.next(';'); + _ = p.next('a'); + _ = p.next('b'); + _ = p.next('c'); + + { + const a = p.next(0x1B); + _ = p.next('\\'); + try testing.expect(p.state == .ground); + try testing.expect(a[0].? == .osc_dispatch); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + + const cmd = a[0].?.osc_dispatch; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings("abc", cmd.change_window_title); + } +} + +// https://github.com/darrenstarr/VtNetCore/pull/14 +// Saw this on HN, decided to add a test case because why not. +test "osc: 112 incomplete sequence" { + var p: Parser = init(); + defer p.deinit(); + p.osc_parser.alloc = std.testing.allocator; + + _ = p.next(0x1B); + _ = p.next(']'); + _ = p.next('1'); + _ = p.next('1'); + _ = p.next('2'); + + { + const a = p.next(0x07); + try testing.expect(p.state == .ground); + try testing.expect(a[0].? == .osc_dispatch); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + + const cmd = a[0].?.osc_dispatch; + try testing.expect(cmd == .color_operation); + try testing.expectEqual(cmd.color_operation.terminator, .bel); + try testing.expect(cmd.color_operation.op == .osc_112); + try testing.expect(cmd.color_operation.requests.count() == 1); + var it = cmd.color_operation.requests.constIterator(0); + { + const op = it.next().?; + try testing.expect(op.* == .reset); + try testing.expectEqual( + osc.color.Request{ .reset = .{ .dynamic = .cursor } }, + op.*, + ); + } + try std.testing.expect(it.next() == null); + } +} + +test "osc: 104 empty" { + var p: Parser = init(); + defer p.deinit(); + p.osc_parser.alloc = std.testing.allocator; + + _ = p.next(0x1B); + _ = p.next(']'); + _ = p.next('1'); + _ = p.next('0'); + _ = p.next('4'); + + { + const a = p.next(0x07); + try testing.expect(p.state == .ground); + try testing.expect(a[0].? == .osc_dispatch); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + + const cmd = a[0].?.osc_dispatch; + try testing.expect(cmd == .color_operation); + try testing.expectEqual(cmd.color_operation.terminator, .bel); + try testing.expect(cmd.color_operation.op == .osc_104); + try testing.expect(cmd.color_operation.requests.count() == 1); + var it = cmd.color_operation.requests.constIterator(0); + { + const op = it.next().?; + try testing.expect(op.* == .reset_palette); + } + try std.testing.expect(it.next() == null); + } +} + +test "csi: too many params" { + var p = init(); + _ = p.next(0x1B); + _ = p.next('['); + for (0..100) |_| { + _ = p.next('1'); + _ = p.next(';'); + } + _ = p.next('1'); + + { + const a = p.next('C'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } +} + +test "csi: sgr with up to our max parameters" { + for (1..MAX_PARAMS + 1) |max| { + var p = init(); + _ = p.next(0x1B); + _ = p.next('['); + + for (0..max - 1) |_| { + _ = p.next('1'); + _ = p.next(';'); + } + _ = p.next('2'); + + { + const a = p.next('H'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1].? == .csi_dispatch); + try testing.expect(a[2] == null); + + const csi = a[1].?.csi_dispatch; + try testing.expectEqual(@as(usize, max), csi.params.len); + try testing.expectEqual(@as(u16, 2), csi.params[max - 1]); + } + } +} + +test "csi: sgr beyond our max drops it" { + // Has to be +2 for the loops below + const max = MAX_PARAMS + 2; + + var p = init(); + _ = p.next(0x1B); + _ = p.next('['); + + for (0..max - 1) |_| { + _ = p.next('1'); + _ = p.next(';'); + } + _ = p.next('2'); + + { + const a = p.next('H'); + try testing.expect(p.state == .ground); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } +} + +test "dcs: XTGETTCAP" { + var p = init(); + _ = p.next(0x1B); + for ("P+") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('q'); + try testing.expect(p.state == .dcs_passthrough); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2].? == .dcs_hook); + + const hook = a[2].?.dcs_hook; + try testing.expectEqualSlices(u8, &[_]u8{'+'}, hook.intermediates); + try testing.expectEqualSlices(u16, &[_]u16{}, hook.params); + try testing.expectEqual('q', hook.final); + } +} + +test "dcs: params" { + var p = init(); + _ = p.next(0x1B); + for ("P1000") |c| { + const a = p.next(c); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); + } + + { + const a = p.next('p'); + try testing.expect(p.state == .dcs_passthrough); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2].? == .dcs_hook); + + const hook = a[2].?.dcs_hook; + try testing.expectEqualSlices(u16, &[_]u16{1000}, hook.params); + try testing.expectEqual('p', hook.final); + } +} + +test "dcs: too many params" { + // Regression test for a crash found by fuzzing (afl). When a DCS + // sequence has more than MAX_PARAMS parameters and param_acc_idx > 0, + // entering dcs_passthrough wrote to params[params_idx] without a + // bounds check, causing an out-of-bounds access. + var p = init(); + _ = p.next(0x1B); // ESC + _ = p.next('P'); // DCS entry + + // Feed a digit then MAX_PARAMS semicolons to fill all param slots. + _ = p.next('6'); + for (0..MAX_PARAMS) |_| { + _ = p.next(';'); + } + // Feed another digit so param_acc_idx > 0 while params_idx == MAX_PARAMS. + _ = p.next('7'); + + // A final byte triggers entry to dcs_passthrough. The DCS should + // be dropped entirely, consistent with how CSI handles overflow. + const a = p.next('p'); + try testing.expect(a[0] == null); + try testing.expect(a[1] == null); + try testing.expect(a[2] == null); +} diff --git a/vendor/libghostty-vt/src/terminal/Screen.zig b/vendor/libghostty-vt/src/terminal/Screen.zig new file mode 100644 index 00000000..77e05b09 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/Screen.zig @@ -0,0 +1,10354 @@ +const Screen = @This(); + +const std = @import("std"); +const build_options = @import("terminal_options"); +const Allocator = std.mem.Allocator; +const assert = @import("../quirks.zig").inlineAssert; +const ansi = @import("ansi.zig"); +const charsets = @import("charsets.zig"); +const fastmem = @import("../fastmem.zig"); +const kitty = @import("kitty.zig"); +const sgr = @import("sgr.zig"); +const tripwire = @import("../tripwire.zig"); +const unicode = @import("../unicode/main.zig"); +const Selection = @import("Selection.zig"); +const PageList = @import("PageList.zig"); +const StringMap = @import("StringMap.zig"); +const ScreenFormatter = @import("formatter.zig").ScreenFormatter; +const osc = @import("osc.zig"); +const pagepkg = @import("page.zig"); +const point = @import("point.zig"); +const size = @import("size.zig"); +const style = @import("style.zig"); +const hyperlink = @import("hyperlink.zig"); +const Offset = size.Offset; +const Page = pagepkg.Page; +const Row = pagepkg.Row; +const Cell = pagepkg.Cell; +const Pin = PageList.Pin; + +pub const CursorStyle = @import("cursor.zig").Style; + +const log = std.log.scoped(.screen); + +/// The general purpose allocator to use for all memory allocations. +/// Unfortunately some screen operations do require allocation. +alloc: Allocator, + +/// The list of pages in the screen. +pages: PageList, + +/// Special-case where we want no scrollback whatsoever. We have to flag +/// this because max_size 0 in PageList gets rounded up to two pages so +/// we can always have an active screen. +no_scrollback: bool = false, + +/// The current cursor position +cursor: Cursor, + +/// The saved cursor +saved_cursor: ?SavedCursor = null, + +/// The selection for this screen (if any). This MUST be a tracked selection +/// otherwise the selection will become invalid. Instead of accessing this +/// directly to set it, use the `select` function which will assert and +/// automatically setup tracking. +selection: ?Selection = null, + +/// The charset state +charset: CharsetState = .{}, + +/// The current or most recent protected mode. Once a protection mode is +/// set, this will never become "off" again until the screen is reset. +/// The current state of whether protection attributes should be set is +/// set on the Cell pen; this is only used to determine the most recent +/// protection mode since some sequences such as ECH depend on this. +protected_mode: ansi.ProtectedMode = .off, + +/// The kitty keyboard settings. +kitty_keyboard: kitty.KeyFlagStack = .{}, + +/// Kitty graphics protocol state. +kitty_images: if (build_options.kitty_graphics) + kitty.graphics.ImageStorage +else + struct {} = .{}, + +/// Semantic prompt (OSC133) state. +semantic_prompt: SemanticPrompt = .disabled, + +/// Dirty flags for the renderer. +dirty: Dirty = .{}, + +/// See Terminal.Dirty. This behaves the same way. +pub const Dirty = packed struct { + /// Set when the selection is set or unset, regardless of if the + /// selection is changed or not. + selection: bool = false, + + /// When an OSC8 hyperlink is hovered, we set the full screen as dirty + /// because links can span multiple lines. + hyperlink_hover: bool = false, +}; + +pub const SemanticPrompt = struct { + /// This is flipped to true when any sort of semantic content is + /// seen. In particular, this is set to true only when a `prompt` type + /// is ever set on our cursor. + /// + /// This is used to optimize away semantic content operations if we know + /// we've never seen them. + seen: bool, + + /// This is set on any `cl` or `click_events` option set on the + /// most recent OSC 133 commands to specify how click handling in a + /// prompt is handling. + click: SemanticClick, + + pub const disabled: SemanticPrompt = .{ + .seen = false, + .click = .none, + }; + + pub const SemanticClick = union(enum) { + none, + click_events, + cl: osc.semantic_prompt.Click, + }; +}; + +/// The cursor position and style. +pub const Cursor = struct { + // The x/y position within the active area. + x: size.CellCountInt = 0, + y: size.CellCountInt = 0, + + /// The visual style of the cursor. This defaults to block because + /// it has to default to something, but users of this struct are + /// encouraged to set their own default. + cursor_style: CursorStyle = .block, + + /// The "last column flag (LCF)" as its called. If this is set then the + /// next character print will force a soft-wrap. + pending_wrap: bool = false, + + /// The protected mode state of the cursor. If this is true then + /// all new characters printed will have the protected state set. + protected: bool = false, + + /// The currently active style. This is the concrete style value + /// that should be kept up to date. The style ID to use for cell writing + /// is below. + style: style.Style = .{}, + + /// The currently active style ID. The style is page-specific so when + /// we change pages we need to ensure that we update that page with + /// our style when used. + style_id: style.Id = style.default_id, + + /// The hyperlink ID that is currently active for the cursor. A value + /// of zero means no hyperlink is active. (Implements OSC8, saying that + /// so code search can find it.). + hyperlink_id: hyperlink.Id = 0, + + /// This is the implicit ID to use for hyperlinks that don't specify + /// an ID. We do an overflowing add to this so repeats can technically + /// happen with carefully crafted inputs but for real workloads its + /// highly unlikely -- and the fix is for the TUI program to use explicit + /// IDs. + hyperlink_implicit_id: size.OffsetInt = 0, + + /// Heap-allocated hyperlink state so that we can recreate it when + /// the cursor page pin changes. We can't get it from the old screen + /// state because the page may be cleared. This is heap allocated + /// because its most likely null. + hyperlink: ?*hyperlink.Hyperlink = null, + + /// The current semantic content type for the cursor that will be + /// applied to any newly written cells. + semantic_content: pagepkg.Cell.SemanticContent = .output, + semantic_content_clear_eol: bool = false, + + /// The pointers into the page list where the cursor is currently + /// located. This makes it faster to move the cursor. + page_pin: *PageList.Pin, + page_row: *pagepkg.Row, + page_cell: *pagepkg.Cell, + + pub fn deinit(self: *Cursor, alloc: Allocator) void { + if (self.hyperlink) |link| { + link.deinit(alloc); + alloc.destroy(link); + } + } +}; + +/// Saved cursor state. +pub const SavedCursor = struct { + x: size.CellCountInt, + y: size.CellCountInt, + style: style.Style, + protected: bool, + pending_wrap: bool, + origin: bool, + charset: CharsetState, +}; + +/// State required for all charset operations. +pub const CharsetState = struct { + /// The list of graphical charsets by slot + charsets: CharsetArray = .{}, + + /// GL is the slot to use when using a 7-bit printable char (up to 127) + /// GR used for 8-bit printable chars. + gl: charsets.Slots = .G0, + gr: charsets.Slots = .G2, + + /// Single shift where a slot is used for exactly one char. + single_shift: ?charsets.Slots = null, + + /// An array to map a charset slot to a lookup table. + /// + /// We use this bespoke struct instead of `std.EnumArray` because + /// accessing these slots is very performance critical since it's + /// done for every single print. This benchmarks faster. + const CharsetArray = struct { + g0: charsets.Charset = .utf8, + g1: charsets.Charset = .utf8, + g2: charsets.Charset = .utf8, + g3: charsets.Charset = .utf8, + + pub inline fn get( + self: *const CharsetArray, + slot: charsets.Slots, + ) charsets.Charset { + return switch (slot) { + .G0 => self.g0, + .G1 => self.g1, + .G2 => self.g2, + .G3 => self.g3, + }; + } + + pub inline fn set( + self: *CharsetArray, + slot: charsets.Slots, + charset: charsets.Charset, + ) void { + switch (slot) { + .G0 => self.g0 = charset, + .G1 => self.g1 = charset, + .G2 => self.g2 = charset, + .G3 => self.g3 = charset, + } + } + }; +}; + +pub const Options = struct { + cols: size.CellCountInt, + rows: size.CellCountInt, + + /// The maximum size of scrollback in bytes. Zero means unlimited. Any + /// other value will be clamped to support a minimum of the active area. + max_scrollback: usize = 0, + + /// The total storage limit for Kitty images in bytes for this + /// screen. Kitty image storage is per-screen. + kitty_image_storage_limit: usize = 320 * 1000 * 1000, // 320MB + + /// A simple, default terminal. If you rely on specific dimensions or + /// scrollback (or lack of) then do not use this directly. This is just + /// for callers that need some defaults. + pub const default: Options = .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }; +}; + +/// Initialize a new screen. +/// +/// max_scrollback is the amount of scrollback to keep in bytes. This +/// will be rounded UP to the nearest page size because our minimum allocation +/// size is that anyways. +/// +/// If max scrollback is 0, then no scrollback is kept at all. +pub fn init( + alloc: Allocator, + opts: Options, +) Allocator.Error!Screen { + // Initialize our backing pages. + var pages = try PageList.init( + alloc, + opts.cols, + opts.rows, + opts.max_scrollback, + ); + errdefer pages.deinit(); + + // Create our tracked pin for the cursor. + const page_pin = try pages.trackPin(.{ .node = pages.pages.first.? }); + errdefer pages.untrackPin(page_pin); + const page_rac = page_pin.rowAndCell(); + + var result: Screen = .{ + .alloc = alloc, + .pages = pages, + .no_scrollback = opts.max_scrollback == 0, + .cursor = .{ + .x = 0, + .y = 0, + .page_pin = page_pin, + .page_row = page_rac.row, + .page_cell = page_rac.cell, + }, + }; + + if (comptime build_options.kitty_graphics) { + // This can't fail because the storage is always empty at this point + // and the only fail-able case is that we have to evict images. + result.kitty_images.setLimit( + alloc, + &result, + opts.kitty_image_storage_limit, + ) catch unreachable; + } + + return result; +} + +pub fn deinit(self: *Screen) void { + if (comptime build_options.kitty_graphics) { + self.kitty_images.deinit(self.alloc, self); + } + self.cursor.deinit(self.alloc); + self.pages.deinit(); +} + +/// Assert that the screen is in a consistent state. This doesn't check +/// all pages in the page list because that is SO SLOW even just for +/// tests. This only asserts the screen specific data so callers should +/// ensure they're also calling page integrity checks if necessary. +pub fn assertIntegrity(self: *const Screen) void { + if (build_options.slow_runtime_safety) { + // We don't run integrity checks on Valgrind because its soooooo slow, + // Valgrind is our integrity checker, and we run these during unit + // tests (non-Valgrind) anyways so we're verifying anyways. + if (std.valgrind.runningOnValgrind() > 0) return; + + assert(self.cursor.x < self.pages.cols); + assert(self.cursor.y < self.pages.rows); + + // Our cursor x/y should always match the pin. If this doesn't + // match then it indicates that the tracked pin moved and we didn't + // account for it by either calling cursorReload or manually + // adjusting. + const pt: point.Point = self.pages.pointFromPin( + .active, + self.cursor.page_pin.*, + ) orelse unreachable; + assert(self.cursor.x == pt.active.x); + assert(self.cursor.y == pt.active.y); + } +} + +/// Reset the screen according to the logic of a DEC RIS sequence. +/// +/// - Clears the screen and attempts to reclaim memory. +/// - Moves the cursor to the top-left. +/// - Clears any cursor state: style, hyperlink, etc. +/// - Resets the charset +/// - Clears the selection +/// - Deletes all Kitty graphics +/// - Resets Kitty Keyboard settings +/// - Disables protection mode +/// +pub fn reset(self: *Screen) void { + // Reset our pages + self.pages.reset(); + + // The above reset preserves tracked pins so we can still use + // our cursor pin, which should be at the top-left already. + const cursor_pin: *PageList.Pin = self.cursor.page_pin; + assert(cursor_pin.node == self.pages.pages.first.?); + assert(cursor_pin.x == 0); + assert(cursor_pin.y == 0); + const cursor_rac = cursor_pin.rowAndCell(); + self.cursor.deinit(self.alloc); + self.cursor = .{ + .page_pin = cursor_pin, + .page_row = cursor_rac.row, + .page_cell = cursor_rac.cell, + }; + + if (comptime build_options.kitty_graphics) { + // Reset kitty graphics storage + self.kitty_images.deinit(self.alloc, self); + self.kitty_images = .{ .dirty = true }; + } + + // Reset our basic state + self.saved_cursor = null; + self.charset = .{}; + self.kitty_keyboard = .{}; + self.protected_mode = .off; + self.semantic_prompt = .disabled; + self.clearSelection(); +} + +/// Clone the screen. +/// +/// This will copy: +/// +/// - Screen dimensions +/// - Screen data (cell state, etc.) for the region +/// +/// Anything not mentioned above is NOT copied. Some of this is for +/// very good reason: +/// +/// - Kitty images have a LOT of data. This is not efficient to copy. +/// Use a lock and access the image data. The dirty bit is there for +/// a reason. +/// - Cursor location can be expensive to calculate with respect to the +/// specified region. It is faster to grab the cursor from the old +/// screen and then move it to the new screen. +/// - Current hyperlink cursor state has heap allocations. Since clone +/// is only for read-only operations, it is better to not have any +/// hyperlink state. Note that already-written hyperlinks are cloned. +/// +/// If not mentioned above, then there isn't a specific reason right now +/// to not copy some data other than we probably didn't need it and it +/// isn't necessary for screen coherency. +/// +/// Other notes: +/// +/// - The viewport will always be set to the active area of the new +/// screen. This is the bottom "rows" rows. +/// - If the clone region is smaller than a viewport area, blanks will +/// be filled in at the bottom. +/// +pub fn clone( + self: *const Screen, + alloc: Allocator, + top: point.Point, + bot: ?point.Point, +) !Screen { + // Create a tracked pin remapper for our selection and cursor. Note + // that we may want to expose this generally in the future but at the + // time of doing this we don't need to. + var pin_remap = PageList.Clone.TrackedPinsRemap.init(alloc); + defer pin_remap.deinit(); + + var pages = try self.pages.clone(alloc, .{ + .top = top, + .bot = bot, + .tracked_pins = &pin_remap, + }); + errdefer pages.deinit(); + + // Find our cursor. If the cursor isn't in the cloned area, we move it + // to the top-left arbitrarily because a screen must have SOME cursor. + const cursor: Cursor = cursor: { + if (pin_remap.get(self.cursor.page_pin)) |p| remap: { + const page_rac = p.rowAndCell(); + const pt = pages.pointFromPin(.active, p.*) orelse break :remap; + break :cursor .{ + .x = @intCast(pt.active.x), + .y = @intCast(pt.active.y), + .page_pin = p, + .page_row = page_rac.row, + .page_cell = page_rac.cell, + }; + } + + const page_pin = try pages.trackPin(.{ .node = pages.pages.first.? }); + const page_rac = page_pin.rowAndCell(); + break :cursor .{ + .x = 0, + .y = 0, + .page_pin = page_pin, + .page_row = page_rac.row, + .page_cell = page_rac.cell, + }; + }; + + // Preserve our selection if we have one. + const sel: ?Selection = if (self.selection) |sel| sel: { + assert(sel.tracked()); + + const ordered: struct { + tl: *Pin, + br: *Pin, + } = switch (sel.order(self)) { + .forward, .mirrored_forward => .{ + .tl = sel.bounds.tracked.start, + .br = sel.bounds.tracked.end, + }, + .reverse, .mirrored_reverse => .{ + .tl = sel.bounds.tracked.end, + .br = sel.bounds.tracked.start, + }, + }; + + const start_pin = pin_remap.get(ordered.tl) orelse start: { + // No start means it is outside the cloned area. + + // If we have no end pin then either + // (1) our whole selection is outside the cloned area or + // (2) our cloned area is within the selection + if (pin_remap.get(ordered.br) == null) { + // We check if the selection bottom right pin is above + // the cloned area or if the top left pin is below the + // cloned area, in either of these cases it means that + // the selection is fully out of bounds, so we have no + // selection in the cloned area and break out now. + const clone_top = self.pages.pin(top) orelse break :sel null; + const clone_top_y = self.pages.pointFromPin( + .screen, + clone_top, + ).?.screen.y; + if (self.pages.pointFromPin( + .screen, + ordered.br.*, + ).?.screen.y < clone_top_y) break :sel null; + if (self.pages.pointFromPin( + .screen, + ordered.tl.*, + ).?.screen.y > clone_top_y) break :sel null; + } + + // We move the top pin back in bounds to the top row. + break :start try pages.trackPin(.{ + .node = pages.pages.first.?, + .x = if (sel.rectangle) ordered.tl.x else 0, + }); + }; + + // If we got to this point it means that the selection is not + // fully out of bounds, so we move the bottom right pin back + // in bounds if it isn't already. + const end_pin = pin_remap.get(ordered.br) orelse try pages.trackPin(.{ + .node = pages.pages.last.?, + .x = if (sel.rectangle) ordered.br.x else pages.cols - 1, + .y = pages.pages.last.?.data.size.rows - 1, + }); + + break :sel .{ + .bounds = .{ .tracked = .{ + .start = start_pin, + .end = end_pin, + } }, + .rectangle = sel.rectangle, + }; + } else null; + + const result: Screen = .{ + .alloc = alloc, + .pages = pages, + .no_scrollback = self.no_scrollback, + .cursor = cursor, + .selection = sel, + .dirty = self.dirty, + }; + result.assertIntegrity(); + return result; +} +pub fn increaseCapacity( + self: *Screen, + node: *PageList.List.Node, + adjustment: ?PageList.IncreaseCapacity, +) PageList.IncreaseCapacityError!*PageList.List.Node { + // If the page being modified isn't our cursor page then + // this is a quick operation because we have no additional + // accounting. We have to do this check here BEFORE calling + // increaseCapacity because increaseCapacity will update all + // our tracked pins (including our cursor). + if (node != self.cursor.page_pin.node) return try self.pages.increaseCapacity( + node, + adjustment, + ); + + // We're modifying the cursor page. When we increase the + // capacity below it will be short the ref count on our + // current style and hyperlink, so we need to init those. + const new_node = try self.pages.increaseCapacity(node, adjustment); + const new_page: *Page = &new_node.data; + + // Re-add the style, if the page somehow doesn't have enough + // memory to add it, we emit a warning and gracefully degrade + // to the default style for the cursor. + if (self.cursor.style_id != style.default_id) { + self.cursor.style_id = new_page.styles.add( + new_page.memory, + self.cursor.style, + ) catch |err| id: { + // TODO: Should we increase the capacity further in this case? + log.warn( + "(Screen.increaseCapacity) Failed to add cursor style back to page, err={}", + .{err}, + ); + + // Reset the cursor style. + self.cursor.style = .{}; + break :id style.default_id; + }; + } + + // Re-add the hyperlink, if the page somehow doesn't have enough + // memory to add it, we emit a warning and gracefully degrade to + // no hyperlink. + if (self.cursor.hyperlink) |link| { + // So we don't attempt to free any memory in the replaced page. + self.cursor.hyperlink_id = 0; + self.cursor.hyperlink = null; + + // Re-add + self.startHyperlinkOnce(link.*) catch |err| { + // TODO: Should we increase the capacity further in this case? + log.warn( + "(Screen.increaseCapacity) Failed to add cursor hyperlink back to page, err={}", + .{err}, + ); + }; + + // Remove our old link + link.deinit(self.alloc); + self.alloc.destroy(link); + } + + // Reload the cursor information because the pin changed. + // So our page row/cell and so on are all off. + self.cursorReload(); + + return new_node; +} + +pub inline fn cursorCellRight(self: *Screen, n: size.CellCountInt) *pagepkg.Cell { + assert(self.cursor.x + n < self.pages.cols); + const cell: [*]pagepkg.Cell = @ptrCast(self.cursor.page_cell); + return @ptrCast(cell + n); +} + +pub inline fn cursorCellLeft(self: *Screen, n: size.CellCountInt) *pagepkg.Cell { + assert(self.cursor.x >= n); + const cell: [*]pagepkg.Cell = @ptrCast(self.cursor.page_cell); + return @ptrCast(cell - n); +} + +pub fn cursorCellEndOfPrev(self: *Screen) *pagepkg.Cell { + assert(self.cursor.y > 0); + + var page_pin = self.cursor.page_pin.up(1).?; + page_pin.x = self.pages.cols - 1; + const page_rac = page_pin.rowAndCell(); + return page_rac.cell; +} + +/// Move the cursor right. This is a specialized function that is very fast +/// if the caller can guarantee we have space to move right (no wrapping). +pub fn cursorRight(self: *Screen, n: size.CellCountInt) void { + assert(self.cursor.x + n < self.pages.cols); + defer self.assertIntegrity(); + + const cell: [*]pagepkg.Cell = @ptrCast(self.cursor.page_cell); + self.cursor.page_cell = @ptrCast(cell + n); + self.cursor.page_pin.x += n; + self.cursor.x += n; +} + +/// Move the cursor left. +pub fn cursorLeft(self: *Screen, n: size.CellCountInt) void { + assert(self.cursor.x >= n); + defer self.assertIntegrity(); + + const cell: [*]pagepkg.Cell = @ptrCast(self.cursor.page_cell); + self.cursor.page_cell = @ptrCast(cell - n); + self.cursor.page_pin.x -= n; + self.cursor.x -= n; +} + +/// Move the cursor up. +/// +/// Precondition: The cursor is not at the top of the screen. +pub fn cursorUp(self: *Screen, n: size.CellCountInt) void { + assert(self.cursor.y >= n); + defer self.assertIntegrity(); + + self.cursor.y -= n; // Must be set before cursorChangePin + self.cursorChangePin(self.cursor.page_pin.up(n).?); + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; +} + +pub fn cursorRowUp(self: *Screen, n: size.CellCountInt) *pagepkg.Row { + assert(self.cursor.y >= n); + defer self.assertIntegrity(); + + const page_pin = self.cursor.page_pin.up(n).?; + const page_rac = page_pin.rowAndCell(); + return page_rac.row; +} + +/// Move the cursor down. +/// +/// Precondition: The cursor is not at the bottom of the screen. +pub fn cursorDown(self: *Screen, n: size.CellCountInt) void { + assert(self.cursor.y + n < self.pages.rows); + defer self.assertIntegrity(); + + self.cursor.y += n; // Must be set before cursorChangePin + + // We move the offset into our page list to the next row and then + // get the pointers to the row/cell and set all the cursor state up. + self.cursorChangePin(self.cursor.page_pin.down(n).?); + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; +} + +/// Move the cursor to some absolute horizontal position. +pub fn cursorHorizontalAbsolute(self: *Screen, x: size.CellCountInt) void { + assert(x < self.pages.cols); + defer self.assertIntegrity(); + + self.cursor.page_pin.x = x; + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_cell = page_rac.cell; + self.cursor.x = x; +} + +/// Move the cursor to some absolute position. +pub fn cursorAbsolute(self: *Screen, x: size.CellCountInt, y: size.CellCountInt) void { + assert(x < self.pages.cols); + assert(y < self.pages.rows); + defer self.assertIntegrity(); + + var page_pin = if (y < self.cursor.y) + self.cursor.page_pin.up(self.cursor.y - y).? + else if (y > self.cursor.y) + self.cursor.page_pin.down(y - self.cursor.y).? + else + self.cursor.page_pin.*; + page_pin.x = x; + self.cursor.x = x; // Must be set before cursorChangePin + self.cursor.y = y; + self.cursorChangePin(page_pin); + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; +} + +/// Reloads the cursor pointer information into the screen. This is expensive +/// so it should only be done in cases where the pointers are invalidated +/// in such a way that its difficult to recover otherwise. +pub fn cursorReload(self: *Screen) void { + defer self.assertIntegrity(); + + // Our tracked pin is ALWAYS accurate, so we derive the active + // point from the pin. If this returns null it means our pin + // points outside the active area. In that case, we update the + // pin to be the top-left. + const pt: point.Point = self.pages.pointFromPin( + .active, + self.cursor.page_pin.*, + ) orelse reset: { + const pin = self.pages.pin(.{ .active = .{} }).?; + self.cursor.page_pin.* = pin; + break :reset self.pages.pointFromPin(.active, pin).?; + }; + + self.cursor.x = @intCast(pt.active.x); + self.cursor.y = @intCast(pt.active.y); + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; + + // If we have a style, we need to ensure it is in the page because this + // method may also be called after a page change. + if (self.cursor.style_id != style.default_id) { + self.manualStyleUpdate() catch |err| { + // This failure should not happen because manualStyleUpdate + // handles page splitting, overflow, and more. This should only + // happen if we're out of RAM. In this case, we'll just degrade + // gracefully back to the default style. + log.err("failed to update style on cursor reload err={}", .{err}); + self.cursor.style = .{}; + self.cursor.style_id = 0; + }; + } +} + +/// Scroll the active area and keep the cursor at the bottom of the screen. +/// This is a very specialized function but it keeps it fast. +pub fn cursorDownScroll(self: *Screen) !void { + assert(self.cursor.y == self.pages.rows - 1); + defer self.assertIntegrity(); + + if (comptime build_options.kitty_graphics) { + // Scrolling dirties the images because it updates their placements pins. + self.kitty_images.dirty = true; + } + + // If we have no scrollback, then we shift all our rows instead. + if (self.no_scrollback) { + // If we have a single-row screen, we have no rows to shift + // so our cursor is in the correct place we just have to clear + // the cells. + if (self.pages.rows == 1) { + const page: *Page = &self.cursor.page_pin.node.data; + self.clearCells( + page, + self.cursor.page_row, + page.getCells(self.cursor.page_row), + ); + self.cursorMarkDirty(); + } else { + // The call to `eraseRow` will move the tracked cursor pin up by one + // row, but we don't actually want that, so we keep the old pin and + // put it back after calling `eraseRow`. + const old_pin = self.cursor.page_pin.*; + + // eraseRow will shift everything below it up. + try self.pages.eraseRow(.{ .active = .{} }); + + // Note we don't need to mark anything dirty in this branch + // because eraseRow will mark all the rotated rows as dirty + // in the entire page. + + // We don't use `cursorChangePin` here because we aren't + // actually changing the pin, we're keeping it the same. + self.cursor.page_pin.* = old_pin; + + // We do, however, need to refresh the cached page row + // and cell, because `eraseRow` will have moved the row. + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; + } + } else { + const old_pin = self.cursor.page_pin.*; + + // Grow our pages by one row. The PageList will handle if we need to + // allocate, prune scrollback, whatever. + _ = try self.pages.grow(); + + self.cursorChangePin(new_pin: { + // We do this all in a block here because referencing this pin + // after cursorChangePin is unsafe, and we want to keep it out + // of scope. + + // If our pin page change it means that the page that the pin + // was on was pruned. In this case, grow() moves the pin to + // the top-left of the new page. This effectively moves it by + // one already, we just need to fix up the x value. + const page_pin = if (old_pin.node == self.cursor.page_pin.node) + self.cursor.page_pin.down(1).? + else reuse: { + var pin = self.cursor.page_pin.*; + pin.x = self.cursor.x; + break :reuse pin; + }; + + // These assertions help catch some pagelist math errors. Our + // x/y should be unchanged after the grow. + if (build_options.slow_runtime_safety) { + const active = self.pages.pointFromPin( + .active, + page_pin, + ).?.active; + assert(active.x == self.cursor.x); + assert(active.y == self.cursor.y); + } + + break :new_pin page_pin; + }); + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; + + // Our new row is always dirty + self.cursorMarkDirty(); + + // Clear the new row so it gets our bg color. We only do this + // if we have a bg color at all. + if (self.cursor.style.bg_color != .none) { + const page: *Page = &self.cursor.page_pin.node.data; + self.clearCells( + page, + self.cursor.page_row, + page.getCells(self.cursor.page_row), + ); + } + } + + if (self.cursor.style_id != style.default_id) { + // The newly created line needs to be styled according to + // the bg color if it is set. + if (self.cursor.style.bgCell()) |blank_cell| { + const cell_current: [*]pagepkg.Cell = @ptrCast(self.cursor.page_cell); + const cells = cell_current - self.cursor.x; + @memset(cells[0..self.pages.cols], blank_cell); + } + } +} + +/// This scrolls the active area at and above the cursor. +/// The lines below the cursor are not scrolled. +pub fn cursorScrollAbove(self: *Screen) !void { + // We unconditionally mark the cursor row as dirty here because + // the cursor always changes page rows inside this function, and + // when that happens it can mean the text in the old row needs to + // be re-shaped because the cursor splits runs to break ligatures. + self.cursorMarkDirty(); + + // If the cursor is on the bottom of the screen, its faster to use + // our specialized function for that case. + if (self.cursor.y == self.pages.rows - 1) { + return try self.cursorDownScroll(); + } + + defer self.assertIntegrity(); + + // Logic below assumes we always have at least one row that isn't moving + assert(self.cursor.y < self.pages.rows - 1); + + // Explanation: + // We don't actually move everything that's at or above the cursor row, + // since this would require us to shift up our ENTIRE scrollback, which + // would be ridiculously expensive. Instead, we insert a new row at the + // end of the pagelist (`grow()`), and move everything BELOW the cursor + // DOWN by one row. This has the same practical result but it's a whole + // lot cheaper in 99% of cases. + + const old_pin = self.cursor.page_pin.*; + if (try self.pages.grow()) |_| { + try self.cursorScrollAboveRotate(); + } else { + // In this case, it means grow() didn't allocate a new page. + + if (self.cursor.page_pin.node == self.pages.pages.last) { + // If we're on the last page we can do a very fast path because + // all the rows we need to move around are within a single page. + + // Note: we don't need to call cursorChangePin here because + // the pin page is the same so there is no accounting to do + // for styles or any of that. + assert(old_pin.node == self.cursor.page_pin.node); + self.cursor.page_pin.* = self.cursor.page_pin.down(1).?; + + const pin = self.cursor.page_pin; + const page: *Page = &self.cursor.page_pin.node.data; + + // Rotate the rows so that the newly created empty row is at the + // beginning. e.g. [ 0 1 2 3 ] in to [ 3 0 1 2 ]. + var rows = page.rows.ptr(page.memory.ptr); + fastmem.rotateOnceR(Row, rows[pin.y..page.size.rows]); + + // Mark the whole page as dirty. + // + // Technically we only need to mark from the cursor row to the + // end but this is a hot function, so we want to minimize work. + page.dirty = true; + + // Setup our cursor caches after the rotation so it points to the + // correct data + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; + } else { + // We didn't grow pages but our cursor isn't on the last page. + // In this case we need to do more work because we need to copy + // elements between pages. + // + // An example scenario of this is shown below: + // + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4302 |1A00000000| | 0 + // 4303 |2B00000000| | 1 + // :^ : : = PIN 0 + // 4304 |3C00000000| | 2 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |4D00000000| | 3 + // 1 |5E00000000| | 4 + // +----------+ : + // +-------------+ + try self.cursorScrollAboveRotate(); + } + } + + if (self.cursor.style_id != style.default_id) { + // The newly created line needs to be styled according to + // the bg color if it is set. + if (self.cursor.style.bgCell()) |blank_cell| { + const cell_current: [*]pagepkg.Cell = @ptrCast(self.cursor.page_cell); + const cells = cell_current - self.cursor.x; + @memset(cells[0..self.pages.cols], blank_cell); + } + } +} + +fn cursorScrollAboveRotate(self: *Screen) !void { + self.cursorChangePin(self.cursor.page_pin.down(1).?); + + // Go through each of the pages following our pin, shift all rows + // down by one, and copy the last row of the previous page. + var current = self.pages.pages.last.?; + while (current != self.cursor.page_pin.node) : (current = current.prev.?) { + const prev = current.prev.?; + const prev_page = &prev.data; + const cur_page = ¤t.data; + const prev_rows = prev_page.rows.ptr(prev_page.memory.ptr); + const cur_rows = cur_page.rows.ptr(cur_page.memory.ptr); + + // Rotate the pages down: [ 0 1 2 3 ] => [ 3 0 1 2 ] + fastmem.rotateOnceR(Row, cur_rows[0..cur_page.size.rows]); + + // Copy the last row of the previous page to the top of current. + try cur_page.cloneRowFrom( + prev_page, + &cur_rows[0], + &prev_rows[prev_page.size.rows - 1], + ); + + // Mark dirty on the page, since we are dirtying all rows with this. + cur_page.dirty = true; + } + + // Our current is our cursor page, we need to rotate down from + // our cursor and clear our row. + assert(current == self.cursor.page_pin.node); + const cur_page = ¤t.data; + const cur_rows = cur_page.rows.ptr(cur_page.memory.ptr); + fastmem.rotateOnceR(Row, cur_rows[self.cursor.page_pin.y..cur_page.size.rows]); + self.clearCells( + cur_page, + &cur_rows[self.cursor.page_pin.y], + cur_page.getCells(&cur_rows[self.cursor.page_pin.y]), + ); + + // Mark the whole page as dirty. + // + // Technically we only need to mark from the cursor row to the + // end but this is a hot function, so we want to minimize work. + cur_page.dirty = true; + + // Setup cursor cache data after all the rotations so our + // row is valid. + const page_rac = self.cursor.page_pin.rowAndCell(); + self.cursor.page_row = page_rac.row; + self.cursor.page_cell = page_rac.cell; +} + +/// Move the cursor down if we're not at the bottom of the screen. Otherwise +/// scroll. Currently only used for testing. +inline fn cursorDownOrScroll(self: *Screen) !void { + if (self.cursor.y + 1 < self.pages.rows) { + self.cursorDown(1); + } else { + try self.cursorDownScroll(); + } +} + +/// Copy another cursor. The cursor can be on any screen but the x/y +/// must be within our screen bounds. +pub fn cursorCopy(self: *Screen, other: Cursor, opts: struct { + /// Copy the hyperlink from the other cursor. If not set, this will + /// clear our current hyperlink. + hyperlink: bool = true, +}) !void { + assert(other.x < self.pages.cols); + assert(other.y < self.pages.rows); + + // End any currently active hyperlink on our cursor. + self.endHyperlink(); + + const old = self.cursor; + self.cursor = other; + errdefer self.cursor = old; + + // Keep our old style ID so it can be properly cleaned up below. + self.cursor.style_id = old.style_id; + + // Hyperlinks will be managed separately below. + self.cursor.hyperlink_id = 0; + self.cursor.hyperlink = null; + + // Keep our old page pin and X/Y because: + // 1. The old style will need to be cleaned up from the page it's from. + // 2. The new position navigated to by `cursorAbsolute` needs to be in our + // own screen. + self.cursor.page_pin = old.page_pin; + self.cursor.x = old.x; + self.cursor.y = old.y; + + // Call manual style update in order to clean up our old style, if we have + // one, and also to load the style from the other cursor, if it had one. + try self.manualStyleUpdate(); + + // Move to the correct location to match the other cursor. + self.cursorAbsolute(other.x, other.y); + + // If the other cursor had a hyperlink, add it to ours. + if (opts.hyperlink and other.hyperlink_id != 0) { + // Get the hyperlink from the other cursor's page. + const other_page = &other.page_pin.node.data; + const other_link = other_page.hyperlink_set.get(other_page.memory, other.hyperlink_id); + + const uri = other_link.uri.slice(other_page.memory); + const id_ = switch (other_link.id) { + .explicit => |id| id.slice(other_page.memory), + .implicit => null, + }; + + // And it to our cursor. + self.startHyperlink(uri, id_) catch |err| { + // This shouldn't happen because startHyperlink should handle + // resizing. This only happens if we're truly out of RAM. Degrade + // to forgetting the hyperlink. + log.err("failed to update hyperlink on cursor change err={}", .{err}); + }; + } +} + +/// Always use this to write to cursor.page_pin.*. +/// +/// This specifically handles the case when the new pin is on a different +/// page than the old AND we have a style or hyperlink set. In that case, +/// we must release our old one and insert the new one, since styles are +/// stored per-page. +/// +/// Note that this can change the cursor pin AGAIN if the process of +/// setting up our cursor forces a capacity adjustment of the underlying +/// cursor page, so any references to the page pin should be re-read +/// from `self.cursor.page_pin` after calling this. +inline fn cursorChangePin(self: *Screen, new: Pin) void { + // Moving the cursor affects text run splitting (ligatures) so + // we must mark the old and new page dirty. We do this as long + // as the pins are not equal + if (!self.cursor.page_pin.eql(new)) { + self.cursorMarkDirty(); + new.markDirty(); + } + + // If our pin is on the same page, then we can just update the pin. + // We don't need to migrate any state. + if (self.cursor.page_pin.node == new.node) { + self.cursor.page_pin.* = new; + return; + } + + // If we have an old style then we need to release it from the old page. + const old_style_: ?style.Style = if (self.cursor.style_id == style.default_id) + null + else + self.cursor.style; + if (old_style_ != null) { + // Release the style directly from the old page instead of going through + // manualStyleUpdate, because the cursor position may have already been + // updated but the pin has not, which would fail integrity checks. + const old_page: *Page = &self.cursor.page_pin.node.data; + old_page.styles.release(old_page.memory, self.cursor.style_id); + self.cursor.style = .{}; + self.cursor.style_id = style.default_id; + } + + // If we have a hyperlink then we need to release it from the old page. + if (self.cursor.hyperlink != null) { + const old_page: *Page = &self.cursor.page_pin.node.data; + old_page.hyperlink_set.release(old_page.memory, self.cursor.hyperlink_id); + } + + // Update our pin to the new page + self.cursor.page_pin.* = new; + + // On the new page, we need to migrate our style + if (old_style_) |old_style| { + self.cursor.style = old_style; + self.manualStyleUpdate() catch |err| { + // This failure should not happen because manualStyleUpdate + // handles page splitting, overflow, and more. This should only + // happen if we're out of RAM. In this case, we'll just degrade + // gracefully back to the default style. + log.err("failed to update style on cursor change err={}", .{err}); + self.cursor.style = .{}; + self.cursor.style_id = 0; + }; + } + + // On the new page, we need to migrate our hyperlink + if (self.cursor.hyperlink) |link| { + // So we don't attempt to free any memory in the replaced page. + self.cursor.hyperlink_id = 0; + self.cursor.hyperlink = null; + + // Re-add + self.startHyperlink(link.uri, switch (link.id) { + .explicit => |v| v, + .implicit => null, + }) catch |err| { + // This shouldn't happen because startHyperlink should handle + // resizing. This only happens if we're truly out of RAM. Degrade + // to forgetting the hyperlink. + log.err("failed to update hyperlink on cursor change err={}", .{err}); + }; + + // Remove our old link + link.deinit(self.alloc); + self.alloc.destroy(link); + } +} + +/// Mark the cursor position as dirty. +/// TODO: test +pub inline fn cursorMarkDirty(self: *Screen) void { + self.cursor.page_row.dirty = true; +} + +/// Reset the cursor row's soft-wrap state and the cursor's pending wrap. +/// Also handles clearing the spacer head on the cursor row and resetting +/// the wrap_continuation flag on the next row if necessary. +/// +/// NOTE(qwerasd): This method is not scrolling region aware, and cannot be +/// since it's on Screen not Terminal. This needs to be addressed down the +/// line. Not an extremely urgent issue since it's an edge case of an edge +/// case, but not ideal. +pub fn cursorResetWrap(self: *Screen) void { + // Reset the cursor's pending wrap state + self.cursor.pending_wrap = false; + + const page_row = self.cursor.page_row; + + if (!page_row.wrap) return; + + // This row does not wrap and the next row is not wrapped to + page_row.wrap = false; + + if (self.cursor.page_pin.down(1)) |next_row| { + next_row.rowAndCell().row.wrap_continuation = false; + } + + // If the last cell in the row is a spacer head we need to clear it. + const cells = self.cursor.page_pin.cells(.all); + const cell = cells[self.cursor.page_pin.node.data.size.cols - 1]; + if (cell.wide == .spacer_head) { + self.clearCells( + &self.cursor.page_pin.node.data, + page_row, + cells[self.cursor.page_pin.node.data.size.cols - 1 ..][0..1], + ); + } +} + +/// Options for scrolling the viewport of the terminal grid. The reason +/// we have this in addition to PageList.Scroll is because we have additional +/// scroll behaviors that are not part of the PageList.Scroll enum. +pub const Scroll = union(enum) { + /// For all of these, see PageList.Scroll. + active, + top, + pin: Pin, + row: usize, + delta_row: isize, + delta_prompt: isize, +}; + +/// Scroll the viewport of the terminal grid. +pub inline fn scroll(self: *Screen, behavior: Scroll) void { + defer self.assertIntegrity(); + + if (comptime build_options.kitty_graphics) { + // No matter what, scrolling marks our image state as dirty since + // it could move placements. If there are no placements or no images + // this is still a very cheap operation. + self.kitty_images.dirty = true; + } + + switch (behavior) { + .active => self.pages.scroll(.{ .active = {} }), + .top => self.pages.scroll(.{ .top = {} }), + .pin => |p| self.pages.scroll(.{ .pin = p }), + .row => |v| self.pages.scroll(.{ .row = v }), + .delta_row => |v| self.pages.scroll(.{ .delta_row = v }), + .delta_prompt => |v| self.pages.scroll(.{ .delta_prompt = v }), + } +} + +/// See PageList.scrollClear. In addition to that, we reset the cursor +/// to be on top. +pub inline fn scrollClear(self: *Screen) !void { + defer self.assertIntegrity(); + + try self.pages.scrollClear(); + self.cursorReload(); + + if (comptime build_options.kitty_graphics) { + // No matter what, scrolling marks our image state as dirty since + // it could move placements. If there are no placements or no images + // this is still a very cheap operation. + self.kitty_images.dirty = true; + } +} + +/// Returns true if the viewport is scrolled to the bottom of the screen. +pub inline fn viewportIsBottom(self: Screen) bool { + return self.pages.viewport == .active; +} + +/// Erase the region specified by tl and br, inclusive. This will physically +/// erase the rows meaning the memory will be reclaimed (if the underlying +/// page is empty) and other rows will be shifted up. +pub inline fn eraseHistory( + self: *Screen, + bl: ?point.Point, +) void { + defer self.assertIntegrity(); + self.pages.eraseHistory(bl); + self.cursorReload(); +} + +pub inline fn eraseActive( + self: *Screen, + y: size.CellCountInt, +) void { + defer self.assertIntegrity(); + self.pages.eraseActive(y); + self.cursorReload(); +} + +// Clear the region specified by tl and bl, inclusive. Cleared cells are +// colored with the current style background color. This will clear all +// cells in the rows. +// +// If protected is true, the protected flag will be respected and only +// unprotected cells will be cleared. Otherwise, all cells will be cleared. +pub fn clearRows( + self: *Screen, + tl: point.Point, + bl: ?point.Point, + protected: bool, +) void { + defer self.assertIntegrity(); + + var it = self.pages.pageIterator(.right_down, tl, bl); + while (it.next()) |chunk| { + for (chunk.rows()) |*row| { + const cells_offset = row.cells; + const cells_multi: [*]Cell = row.cells.ptr(chunk.node.data.memory); + const cells = cells_multi[0..self.pages.cols]; + + // Clear all cells + if (protected) { + self.clearUnprotectedCells(&chunk.node.data, row, cells); + // We need to preserve other row attributes since we only + // cleared unprotected cells. + row.cells = cells_offset; + } else { + self.clearCells(&chunk.node.data, row, cells); + row.* = .{ .cells = cells_offset }; + } + + row.dirty = true; + } + } +} + +/// Clear the cells with the blank cell. +/// +/// This takes care to handle cleaning up graphemes and styles. +pub fn clearCells( + self: *Screen, + page: *Page, + row: *Row, + cells: []Cell, +) void { + // This whole operation does unsafe things, so we just want to assert + // the end state. + page.pauseIntegrityChecks(true); + defer { + page.pauseIntegrityChecks(false); + page.assertIntegrity(); + self.assertIntegrity(); + } + + if (comptime std.debug.runtime_safety) { + // Our row and cells should be within the page. + const page_rows = page.rows.ptr(page.memory.ptr); + assert(@intFromPtr(row) >= @intFromPtr(&page_rows[0])); + assert(@intFromPtr(row) <= @intFromPtr(&page_rows[page.size.rows - 1])); + + const row_cells = page.getCells(row); + assert(@intFromPtr(&cells[0]) >= @intFromPtr(&row_cells[0])); + assert(@intFromPtr(&cells[cells.len - 1]) <= @intFromPtr(&row_cells[row_cells.len - 1])); + } + + // If we have managed memory (styles, graphemes, or hyperlinks) + // in this row then we go cell by cell and clear them if present. + if (row.grapheme) { + for (cells) |*cell| { + if (cell.hasGrapheme()) + page.clearGrapheme(cell); + } + + // If we have no left/right scroll region we can be sure + // that we've cleared all the graphemes, so we clear the + // flag, otherwise we ask the page to update the flag. + if (cells.len == self.pages.cols) { + row.grapheme = false; + } else { + page.updateRowGraphemeFlag(row); + } + } + + if (row.hyperlink) { + for (cells) |*cell| { + if (cell.hyperlink) + page.clearHyperlink(cell); + } + + // If we have no left/right scroll region we can be sure + // that we've cleared all the hyperlinks, so we clear the + // flag, otherwise we ask the page to update the flag. + if (cells.len == self.pages.cols) { + row.hyperlink = false; + } else { + page.updateRowHyperlinkFlag(row); + } + } + + if (row.styled) { + for (cells) |*cell| { + if (cell.hasStyling()) + page.styles.release(page.memory, cell.style_id); + } + + // If we have no left/right scroll region we can be sure + // that we've cleared all the styles, so we clear the + // flag, otherwise we ask the page to update the flag. + if (cells.len == self.pages.cols) { + row.styled = false; + } else { + page.updateRowStyledFlag(row); + } + } + + if (comptime build_options.kitty_graphics) { + if (row.kitty_virtual_placeholder and + cells.len == self.pages.cols) + { + for (cells) |c| { + if (c.codepoint() == kitty.graphics.unicode.placeholder) { + break; + } + } else row.kitty_virtual_placeholder = false; + } + } + + @memset(cells, self.blankCell()); +} + +/// Clear cells but only if they are not protected. +pub fn clearUnprotectedCells( + self: *Screen, + page: *Page, + row: *Row, + cells: []Cell, +) void { + var x0: usize = 0; + var x1: usize = 0; + + while (x0 < cells.len) clear: { + while (cells[x0].protected) { + x0 += 1; + if (x0 >= cells.len) break :clear; + } + x1 = x0 + 1; + while (x1 < cells.len and !cells[x1].protected) { + x1 += 1; + } + self.clearCells(page, row, cells[x0..x1]); + x0 = x1; + } + + page.assertIntegrity(); + self.assertIntegrity(); +} + +/// Clean up boundary conditions where a cell will become discontiguous with +/// a neighboring cell because either one of them will be moved and/or cleared. +/// +/// For performance reasons this is specialized to operate on the cursor row. +/// +/// Handles the boundary between the cell at `x` and the cell at `x - 1`. +/// +/// So, for example, when moving a region of cells [a, b] (inclusive), call this +/// function with `x = a` and `x = b + 1`. It is okay if `x` is out of bounds by +/// 1, this will be interpreted correctly. +/// +/// DOES NOT MODIFY ROW WRAP STATE! See `cursorResetWrap` for that. +/// +/// The following boundary conditions are handled: +/// +/// - `x - 1` is a wide character and `x` is a spacer tail: +/// o Both cells will be cleared. +/// o If `x - 1` is the start of the row and was wrapped from a previous row +/// then the previous row is checked for a spacer head, which is cleared if +/// present. +/// +/// - `x == 0` and is a wide character: +/// o If the row is a wrap continuation then the previous row will be checked +/// for a spacer head, which is cleared if present. +/// +/// - `x == cols` and `x - 1` is a spacer head: +/// o `x - 1` will be cleared. +/// +/// NOTE(qwerasd): This method is not scrolling region aware, and cannot be +/// since it's on Screen not Terminal. This needs to be addressed down the +/// line. Not an extremely urgent issue since it's an edge case of an edge +/// case, but not ideal. +pub fn splitCellBoundary( + self: *Screen, + x: size.CellCountInt, +) void { + const page = &self.cursor.page_pin.node.data; + + page.pauseIntegrityChecks(true); + defer page.pauseIntegrityChecks(false); + + const cols = self.cursor.page_pin.node.data.size.cols; + + // `x` may be up to an INCLUDING `cols`, since that signifies splitting + // the boundary to the right of the final cell in the row. + assert(x <= cols); + + // [ A B C D E F|] + // ^ Boundary between final cell and row end. + if (x == cols) { + if (!self.cursor.page_row.wrap) return; + + const cells = self.cursor.page_pin.cells(.all); + + // Spacer head at end of wrapped row. + if (cells[cols - 1].wide == .spacer_head) { + self.clearCells( + page, + self.cursor.page_row, + cells[cols - 1 ..][0..1], + ); + } + + return; + } + + // [|A B C D E F ] + // ^ Boundary between first cell and row start. + // + // OR + // + // [ A|B C D E F ] + // ^ Boundary between first cell and second cell. + // + // First cell may be a wrapped wide cell with a spacer + // head on the previous row that needs to be cleared. + if ((x == 0 or x == 1) and self.cursor.page_row.wrap_continuation) { + const cells = self.cursor.page_pin.cells(.all); + + // If the first cell in a row is wide the previous row + // may have a spacer head which needs to be cleared. + if (cells[0].wide == .wide) { + if (self.cursor.page_pin.up(1)) |p_row| { + const p_rac = p_row.rowAndCell(); + const p_cells = p_row.cells(.all); + const p_cell = p_cells[p_row.node.data.size.cols - 1]; + if (p_cell.wide == .spacer_head) { + self.clearCells( + &p_row.node.data, + p_rac.row, + p_cells[p_row.node.data.size.cols - 1 ..][0..1], + ); + } + } + } + } + + // If x is 0 then we're done. + if (x == 0) return; + + // [ ... X|Y ... ] + // ^ Boundary between two cells in the middle of the row. + { + assert(x > 0); + assert(x < cols); + + const cells = self.cursor.page_pin.cells(.all); + + const left = cells[x - 1]; + switch (left.wide) { + // There should not be spacer heads in the middle of the row. + .spacer_head => unreachable, + + // We don't need to do anything for narrow cells or spacer tails. + .narrow, .spacer_tail => {}, + + // A wide char would be split, so must be cleared. + .wide => { + self.clearCells( + page, + self.cursor.page_row, + cells[x - 1 ..][0..2], + ); + }, + } + } +} + +/// Returns the blank cell to use when doing terminal operations that +/// require preserving the bg color. +pub inline fn blankCell(self: *const Screen) Cell { + if (self.cursor.style_id == style.default_id) return .{}; + return self.cursor.style.bgCell() orelse .{}; +} + +pub const Resize = struct { + /// The new size to resize to + cols: size.CellCountInt, + rows: size.CellCountInt, + + /// Whether to reflow soft-wrapped text. + /// + /// This will reflow soft-wrapped text. If the screen size is getting + /// smaller and the maximum scrollback size is exceeded, data will be + /// lost from the top of the scrollback. + reflow: bool = true, + + /// Set this to enable prompt redraw on resize. This signals + /// that the running program can redraw the prompt if the cursor is + /// currently at a prompt. This detects OSC133 prompts lines and clears + /// them. If set to `.last`, only the most recent prompt line is cleared. + prompt_redraw: osc.semantic_prompt.Redraw = .false, +}; + +/// Resize the screen. The rows or cols can be bigger or smaller. +/// +/// If this returns an error, the screen is left in a likely garbage state. +/// It is very hard to undo this operation without blowing up our memory +/// usage. The only way to recover is to reset the screen. The only way +/// this really fails is if page allocation is required and fails, which +/// probably means the system is in trouble anyways. I'd like to improve this +/// in the future but it is not a priority particularly because this scenario +/// (resize) is difficult. +pub inline fn resize( + self: *Screen, + opts: Resize, +) !void { + defer self.assertIntegrity(); + + if (comptime build_options.kitty_graphics) { + // No matter what we mark our image state as dirty + self.kitty_images.dirty = true; + } + + // Release the cursor style while resizing just + // in case the cursor ends up on a different page. + const cursor_style = self.cursor.style; + self.cursor.style = .{}; + self.manualStyleUpdate() catch unreachable; + defer { + // Restore the cursor style. + self.cursor.style = cursor_style; + self.manualStyleUpdate() catch |err| { + // This failure should not happen because manualStyleUpdate + // handles page splitting, overflow, and more. This should only + // happen if we're out of RAM. In this case, we'll just degrade + // gracefully back to the default style. + log.err("failed to update style on cursor reload err={}", .{err}); + self.cursor.style = .{}; + self.cursor.style_id = 0; + }; + } + + // If we have a hyperlink, release it from the old page + // and then we need to re-add it to the new page. This needs + // to happen because resize below typically reallocates a + // new page so the old hyperlink is invalid. + const hyperlink_ = self.cursor.hyperlink; + if (self.cursor.hyperlink_id != 0) { + // Note we do NOT use endHyperlink because we want to keep + // our allocated self.cursor.hyperlink valid. + var page = &self.cursor.page_pin.node.data; + page.hyperlink_set.release(page.memory, self.cursor.hyperlink_id); + self.cursor.hyperlink_id = 0; + self.cursor.hyperlink = null; + } + + // We need to insert a tracked pin for our saved cursor so we can + // modify its X/Y for reflow. + const saved_cursor_pin: ?*Pin = saved_cursor: { + const sc = self.saved_cursor orelse break :saved_cursor null; + const pin = self.pages.pin(.{ .active = .{ + .x = sc.x, + .y = sc.y, + } }) orelse break :saved_cursor null; + break :saved_cursor try self.pages.trackPin(pin); + }; + defer if (saved_cursor_pin) |p| self.pages.untrackPin(p); + + // If our cursor is on a prompt or input line, clear it so the shell can + // redraw it. This works with OSC 133 semantic prompts. + // + // We check cursor.semantic_content rather than page_row.semantic_prompt + // because some shells (e.g., Nu) mark input areas with OSC 133 B but don't + // mark continuation lines with k=s. If the input spans multiple lines and + // continuation lines are unmarked, checking only page_row.semantic_prompt + // would miss them. By checking semantic_content, we assume that if the + // cursor is on anything other than command output, we're at a prompt/input + // line and should clear from there. + if (opts.prompt_redraw != .false and + self.cursor.semantic_content != .output) + prompt: { + switch (opts.prompt_redraw) { + .false => unreachable, + + // For `.last`, only clear the current line where the cursor is. + // For `.true`, clear all prompt lines starting from the beginning. + .last => { + const page = &self.cursor.page_pin.node.data; + const row = self.cursor.page_row; + const cells = page.getCells(row); + self.clearCells(page, row, cells); + }, + + .true => { + const start = start: { + var it = self.cursor.page_pin.promptIterator( + .left_up, + null, + ); + break :start it.next() orelse { + // This should never happen because promptIterator should always + // find a prompt if we already verified our row is some kind of + // prompt. + log.warn("cursor on prompt line but promptIterator found no prompt", .{}); + break :prompt; + }; + }; + + // Clear cells from our start down. We replace it with spaces, + // and do not physically erase the rows (eraseRows) because the + // shell is going to expect this space to be available. + var it = start.rowIterator(.right_down, null); + while (it.next()) |pin| { + const page = &pin.node.data; + const row = pin.rowAndCell().row; + const cells = page.getCells(row); + self.clearCells(page, row, cells); + } + }, + } + } + + // Perform the resize operation. + try self.pages.resize(.{ + .rows = opts.rows, + .cols = opts.cols, + .reflow = opts.reflow, + .cursor = .{ .x = self.cursor.x, .y = self.cursor.y }, + }); + + // If we have no scrollback and we shrunk our rows, we must explicitly + // erase our history. This is because PageList always keeps at least + // a page size of history. + if (self.no_scrollback) { + self.pages.eraseHistory(null); + } + + // If our cursor was updated, we do a full reload so all our cursor + // state is correct. + self.cursorReload(); + + // If we reflowed a saved cursor, update it. + if (saved_cursor_pin) |p| { + // This should never fail because a non-null saved_cursor_pin + // implies a non-null saved_cursor. + const sc = &self.saved_cursor.?; + if (self.pages.pointFromPin(.active, p.*)) |pt| { + sc.x = @intCast(pt.active.x); + sc.y = @intCast(pt.active.y); + + // If we had pending wrap set and we're no longer at the end of + // the line, we unset the pending wrap and move the cursor to + // reflect the correct next position. + if (sc.pending_wrap and sc.x != opts.cols - 1) { + sc.pending_wrap = false; + sc.x += 1; + } + } else { + // I think this can happen if the screen is resized to be + // less rows or less cols and our saved cursor moves outside + // the active area. In this case, there isn't anything really + // reasonable we can do so we just move the cursor to the + // top-left. It may be reasonable to also move the cursor to + // match the primary cursor. Any behavior is fine since this is + // totally unspecified. + sc.x = 0; + sc.y = 0; + sc.pending_wrap = false; + } + } + + // Fix up our hyperlink if we had one. + if (hyperlink_) |link| { + self.startHyperlink(link.uri, switch (link.id) { + .explicit => |v| v, + .implicit => null, + }) catch |err| { + // This shouldn't happen because startHyperlink should handle + // resizing. This only happens if we're truly out of RAM. Degrade + // to forgetting the hyperlink. + log.err("failed to update hyperlink on resize err={}", .{err}); + }; + + // Remove our old link + link.deinit(self.alloc); + self.alloc.destroy(link); + } +} + +/// Set a style attribute for the current cursor. +/// +/// If the style can't be set due to any internal errors (memory-related), +/// then this will revert back to the existing style and return an error. +pub fn setAttribute( + self: *Screen, + attr: sgr.Attribute, +) PageList.IncreaseCapacityError!void { + // If we fail to set our style for any reason, we should revert + // back to the old style. If we fail to do that, we revert back to + // the default style. + const old_style = self.cursor.style; + errdefer { + self.cursor.style = old_style; + self.manualStyleUpdate() catch |err| { + log.warn("setAttribute error restoring old style after failure err={}", .{err}); + self.cursor.style = .{}; + self.manualStyleUpdate() catch unreachable; + }; + } + + switch (attr) { + .unset => { + self.cursor.style = .{}; + }, + + .bold => { + self.cursor.style.flags.bold = true; + }, + + .reset_bold => { + // Bold and faint share the same SGR code for this + self.cursor.style.flags.bold = false; + self.cursor.style.flags.faint = false; + }, + + .italic => { + self.cursor.style.flags.italic = true; + }, + + .reset_italic => { + self.cursor.style.flags.italic = false; + }, + + .faint => { + self.cursor.style.flags.faint = true; + }, + + .underline => |v| { + self.cursor.style.flags.underline = v; + }, + + .underline_color => |rgb| { + self.cursor.style.underline_color = .{ .rgb = .{ + .r = rgb.r, + .g = rgb.g, + .b = rgb.b, + } }; + }, + + .@"256_underline_color" => |idx| { + self.cursor.style.underline_color = .{ .palette = idx }; + }, + + .reset_underline_color => { + self.cursor.style.underline_color = .none; + }, + + .overline => { + self.cursor.style.flags.overline = true; + }, + + .reset_overline => { + self.cursor.style.flags.overline = false; + }, + + .blink => { + self.cursor.style.flags.blink = true; + }, + + .reset_blink => { + self.cursor.style.flags.blink = false; + }, + + .inverse => { + self.cursor.style.flags.inverse = true; + }, + + .reset_inverse => { + self.cursor.style.flags.inverse = false; + }, + + .invisible => { + self.cursor.style.flags.invisible = true; + }, + + .reset_invisible => { + self.cursor.style.flags.invisible = false; + }, + + .strikethrough => { + self.cursor.style.flags.strikethrough = true; + }, + + .reset_strikethrough => { + self.cursor.style.flags.strikethrough = false; + }, + + .direct_color_fg => |rgb| { + self.cursor.style.fg_color = .{ + .rgb = .{ + .r = rgb.r, + .g = rgb.g, + .b = rgb.b, + }, + }; + }, + + .direct_color_bg => |rgb| { + self.cursor.style.bg_color = .{ + .rgb = .{ + .r = rgb.r, + .g = rgb.g, + .b = rgb.b, + }, + }; + }, + + .@"8_fg" => |n| { + self.cursor.style.fg_color = .{ .palette = @intFromEnum(n) }; + }, + + .@"8_bg" => |n| { + self.cursor.style.bg_color = .{ .palette = @intFromEnum(n) }; + }, + + .reset_fg => self.cursor.style.fg_color = .none, + + .reset_bg => self.cursor.style.bg_color = .none, + + .@"8_bright_fg" => |n| { + self.cursor.style.fg_color = .{ .palette = @intFromEnum(n) }; + }, + + .@"8_bright_bg" => |n| { + self.cursor.style.bg_color = .{ .palette = @intFromEnum(n) }; + }, + + .@"256_fg" => |idx| { + self.cursor.style.fg_color = .{ .palette = idx }; + }, + + .@"256_bg" => |idx| { + self.cursor.style.bg_color = .{ .palette = idx }; + }, + + .unknown => return, + } + + try self.manualStyleUpdate(); +} + +/// Call this whenever you manually change the cursor style. +/// +/// This function can NOT fail if the cursor style is changing to the +/// default style. +/// +/// If this returns an error, the style change did not take effect and +/// the cursor style is reverted back to the default. The only scenario +/// this returns an error is if there is a physical memory allocation failure +/// or if there is no possible way to increase style capacity to store +/// the style. +/// +/// This function WILL split pages as necessary to accommodate the new style. +/// So if OutOfSpace is returned, it means that even after splitting the page +/// there was still no room for the new style. +pub fn manualStyleUpdate(self: *Screen) PageList.IncreaseCapacityError!void { + defer self.assertIntegrity(); + var page: *Page = &self.cursor.page_pin.node.data; + + // std.log.warn("active styles={}", .{page.styles.count()}); + + // Release our previous style if it was not default. + if (self.cursor.style_id != style.default_id) { + page.styles.release(page.memory, self.cursor.style_id); + } + + // If our new style is the default, just reset to that + if (self.cursor.style.default()) { + self.cursor.style_id = style.default_id; + return; + } + + // Clear the cursor style ID to prevent weird things from happening + // if the page capacity has to be adjusted which would end up calling + // manualStyleUpdate again. + // + // This also ensures that if anything fails below, we fall back to + // clearing our style. + self.cursor.style_id = style.default_id; + + // After setting the style, we need to update our style map. + // Note that we COULD lazily do this in print. We should look into + // if that makes a meaningful difference. Our priority is to keep print + // fast because setting a ton of styles that do nothing is uncommon + // and weird. + const id = page.styles.add( + page.memory, + self.cursor.style, + ) catch |err| id: { + // Our style map is full or needs to be rehashed, so we need to + // increase style capacity (or rehash). + const node = self.increaseCapacity( + self.cursor.page_pin.node, + switch (err) { + error.OutOfMemory => .styles, + error.NeedsRehash => null, + }, + ) catch |increase_err| switch (increase_err) { + error.OutOfMemory => return error.OutOfMemory, + error.OutOfSpace => space: { + // Out of space, we need to split the page. Split wherever + // is using less capacity and hope that works. If it doesn't + // work, we tried. + try self.splitForCapacity(self.cursor.page_pin.*); + break :space self.cursor.page_pin.node; + }, + }; + + page = &node.data; + break :id page.styles.add( + page.memory, + self.cursor.style, + ) catch |err2| switch (err2) { + error.OutOfMemory => { + // This shouldn't happen because increaseCapacity is + // guaranteed to increase our capacity by at least one and + // we only need one space, but again, I don't want to crash + // here so let's log loudly and reset. + log.err("style addition failed after capacity increase", .{}); + return error.OutOfMemory; + }, + error.NeedsRehash => { + // This should be impossible because we rehash above + // and rehashing should never result in a duplicate. But + // we don't want to simply hard crash so log it and + // clear our style. + log.err("style rehash resulted in needs rehash", .{}); + return; + }, + }; + }; + errdefer page.styles.release(page.memory, id); + + self.cursor.style_id = id; +} + +/// Split at the given pin so that the pinned row moves to the page +/// with less used capacity after the split. +/// +/// The primary use case for this is to handle IncreaseCapacityError +/// OutOfSpace conditions where we need to split the page in order +/// to make room for more managed memory. +/// +/// If the caller cares about where the pin moves to, they should +/// setup a tracked pin before calling this and then check that. +/// In many calling cases, the input pin is tracked (e.g. the cursor +/// pin). +/// +/// If this returns OOM then its a system OOM. If this returns OutOfSpace +/// then it means the page can't be split further. +fn splitForCapacity( + self: *Screen, + pin: Pin, +) PageList.SplitError!void { + // Get our capacities. We include our target row because its + // capacity will be preserved. + const bytes_above = Page.layout(pin.node.data.exactRowCapacity( + 0, + pin.y + 1, + )).total_size; + const bytes_below = Page.layout(pin.node.data.exactRowCapacity( + pin.y, + pin.node.data.size.rows, + )).total_size; + + // We need to track the old cursor pin because if our split + // moves the cursor pin we need to update our accounting. + const old_cursor = self.cursor.page_pin.*; + + // If our bytes above are less than bytes below, we move the pin + // to split down one since splitting includes the pinned row in + // the new node. + try self.pages.split(if (bytes_above < bytes_below) + pin.down(1) orelse pin + else + pin); + + // Cursor didn't change nodes, we're done. + if (self.cursor.page_pin.node == old_cursor.node) return; + + // Cursor changed, we need to restore the old pin then use + // cursorChangePin to move to the new pin. The old node is guaranteed + // to still exist, just not the row. + // + // Note that page_row and all that will be invalid, it points to the + // new node, but at the time of writing this we don't need any of that + // to be right in cursorChangePin. + const new_cursor = self.cursor.page_pin.*; + self.cursor.page_pin.* = old_cursor; + self.cursorChangePin(new_cursor); +} + +/// Append a grapheme to the given cell within the current cursor row. +pub fn appendGrapheme( + self: *Screen, + cell: *Cell, + cp: u21, +) PageList.IncreaseCapacityError!void { + defer self.cursor.page_pin.node.data.assertIntegrity(); + self.cursor.page_pin.node.data.appendGrapheme( + self.cursor.page_row, + cell, + cp, + ) catch |err| switch (err) { + error.OutOfMemory => { + // We need to determine the actual cell index of the cell so + // that after we adjust the capacity we can reload the cell. + const cell_idx: usize = cell_idx: { + const cells: [*]Cell = @ptrCast(self.cursor.page_cell); + const zero: [*]Cell = cells - self.cursor.x; + const target: [*]Cell = @ptrCast(cell); + const cell_idx = (@intFromPtr(target) - @intFromPtr(zero)) / @sizeOf(Cell); + break :cell_idx cell_idx; + }; + + // Adjust our capacity. This will update our cursor page pin and + // force us to reload. + _ = try self.increaseCapacity( + self.cursor.page_pin.node, + .grapheme_bytes, + ); + + // The cell pointer is now invalid, so we need to get it from + // the reloaded cursor pointers. + const reloaded_cell: *Cell = switch (std.math.order(cell_idx, self.cursor.x)) { + .eq => self.cursor.page_cell, + .lt => self.cursorCellLeft(@intCast(self.cursor.x - cell_idx)), + .gt => self.cursorCellRight(@intCast(cell_idx - self.cursor.x)), + }; + + self.cursor.page_pin.node.data.appendGrapheme( + self.cursor.page_row, + reloaded_cell, + cp, + ) catch |err2| { + comptime assert(@TypeOf(err2) == error{OutOfMemory}); + // This should never happen because we just increased capacity. + // Log loudly but still return an error so we don't just + // crash. + log.err("grapheme append failed after capacity increase", .{}); + return err2; + }; + }, + }; +} + +/// Start the hyperlink state. Future cells will be marked as hyperlinks with +/// this state. Note that various terminal operations may clear the hyperlink +/// state, such as switching screens (alt screen). +pub fn startHyperlink( + self: *Screen, + uri: []const u8, + id_: ?[]const u8, +) PageList.IncreaseCapacityError!void { + // Create our pending entry. + const link: hyperlink.Hyperlink = .{ + .uri = uri, + .id = if (id_) |id| .{ + .explicit = id, + } else implicit: { + defer self.cursor.hyperlink_implicit_id += 1; + break :implicit .{ .implicit = self.cursor.hyperlink_implicit_id }; + }, + }; + errdefer switch (link.id) { + .explicit => {}, + .implicit => self.cursor.hyperlink_implicit_id -= 1, + }; + + // Loop until we have enough page memory to add the hyperlink + while (true) { + if (self.startHyperlinkOnce(link)) { + return; + } else |err| switch (err) { + // An actual self.alloc OOM is a fatal error. + error.OutOfMemory => return error.OutOfMemory, + + // strings table is out of memory, adjust it up + error.StringsOutOfMemory => _ = try self.increaseCapacity( + self.cursor.page_pin.node, + .string_bytes, + ), + + // hyperlink set is out of memory, adjust it up + error.SetOutOfMemory => _ = try self.increaseCapacity( + self.cursor.page_pin.node, + .hyperlink_bytes, + ), + + // hyperlink set is too full, rehash it + error.SetNeedsRehash => _ = try self.increaseCapacity( + self.cursor.page_pin.node, + null, + ), + } + + self.assertIntegrity(); + } +} + +/// This is like startHyperlink but if we have to adjust page capacities +/// this returns error.PageAdjusted. This is useful so that we unwind +/// all the previous state and try again. +fn startHyperlinkOnce( + self: *Screen, + source: hyperlink.Hyperlink, +) (Allocator.Error || Page.InsertHyperlinkError)!void { + // End any prior hyperlink + self.endHyperlink(); + + // Allocate our new Hyperlink entry in non-page memory. This + // lets us quickly get access to URI, ID. + const link = try self.alloc.create(hyperlink.Hyperlink); + errdefer self.alloc.destroy(link); + link.* = try source.dupe(self.alloc); + errdefer link.deinit(self.alloc); + + // Insert the hyperlink into page memory + var page = &self.cursor.page_pin.node.data; + const id: hyperlink.Id = try page.insertHyperlink(link.*); + + // Save it all + self.cursor.hyperlink = link; + self.cursor.hyperlink_id = id; +} + +/// End the hyperlink state so that future cells aren't part of the +/// current hyperlink (if any). This is safe to call multiple times. +pub fn endHyperlink(self: *Screen) void { + // If we have no hyperlink state then do nothing + if (self.cursor.hyperlink_id == 0) { + assert(self.cursor.hyperlink == null); + return; + } + + // Release the old hyperlink state. If there are cells using the + // hyperlink this will work because the creation creates a reference + // and all additional cells create a new reference. This release will + // just release our initial reference. + // + // If the ref count reaches zero the set will not delete the item + // immediately; it is kept around in case it is used again (this is + // how RefCountedSet works). This causes some memory fragmentation but + // is fine because if it is ever pruned the context deleted callback + // will be called. + var page: *Page = &self.cursor.page_pin.node.data; + page.hyperlink_set.release(page.memory, self.cursor.hyperlink_id); + self.cursor.hyperlink.?.deinit(self.alloc); + self.alloc.destroy(self.cursor.hyperlink.?); + self.cursor.hyperlink_id = 0; + self.cursor.hyperlink = null; +} + +/// Set the current hyperlink state on the current cell. +pub fn cursorSetHyperlink(self: *Screen) PageList.IncreaseCapacityError!void { + assert(self.cursor.hyperlink_id != 0); + + var page = &self.cursor.page_pin.node.data; + if (page.setHyperlink( + self.cursor.page_row, + self.cursor.page_cell, + self.cursor.hyperlink_id, + )) { + // Success, increase the refcount for the hyperlink. + page.hyperlink_set.use(page.memory, self.cursor.hyperlink_id); + return; + } else |err| switch (err) { + // hyperlink_map is out of space, realloc the page to be larger + error.HyperlinkMapOutOfMemory => { + // Attempt to allocate the space that would be required to + // insert a new copy of the cursor hyperlink uri in to the + // string alloc, since right now increaseCapacity always just + // adds an extra copy even if one already exists in the page. + // If this alloc fails then we know we also need to grow our + // string bytes. + // + // FIXME: increaseCapacity should not do this. + while (self.cursor.hyperlink) |link| { + if (page.string_alloc.alloc( + u8, + page.memory, + link.uri.len, + )) |slice| { + // We don't bother freeing because we're + // about to free the entire page anyway. + _ = slice; + break; + } else |_| {} + + // We didn't have enough room, let's increase string bytes + const new_node = try self.increaseCapacity( + self.cursor.page_pin.node, + .string_bytes, + ); + assert(new_node == self.cursor.page_pin.node); + page = &new_node.data; + } + + _ = try self.increaseCapacity( + self.cursor.page_pin.node, + .hyperlink_bytes, + ); + + // Retry + // + // We check that the cursor hyperlink hasn't been destroyed + // by the capacity adjustment first though- since despite the + // terrible code above, that can still apparently happen ._. + if (self.cursor.hyperlink_id > 0) { + return try self.cursorSetHyperlink(); + } + }, + } +} + +/// Modify the semantic content type of the cursor. This should +/// be preferred over setting it manually since it handles all the +/// proper accounting. +pub fn cursorSetSemanticContent(self: *Screen, t: union(enum) { + prompt: osc.semantic_prompt.PromptKind, + output, + input: enum { clear_explicit, clear_eol }, +}) void { + const cursor = &self.cursor; + + switch (t) { + .output => { + cursor.semantic_content = .output; + cursor.semantic_content_clear_eol = false; + }, + + .input => |clear| { + cursor.semantic_content = .input; + cursor.semantic_content_clear_eol = switch (clear) { + .clear_explicit => false, + .clear_eol => true, + }; + }, + + .prompt => |kind| { + self.semantic_prompt.seen = true; + cursor.semantic_content = .prompt; + cursor.semantic_content_clear_eol = false; + cursor.page_row.semantic_prompt = switch (kind) { + .initial, .right => .prompt, + .continuation, .secondary => .prompt_continuation, + }; + }, + } +} + +/// Set the selection to the given selection. If this is a tracked selection +/// then the screen will take ownership of the selection. If this is untracked +/// then the screen will convert it to tracked internally. This will automatically +/// untrack the prior selection (if any). +/// +/// Set the selection to null to clear any previous selection. +/// +/// This is always recommended over setting `selection` directly. Beyond +/// managing memory for you, it also performs safety checks that the selection +/// is always tracked. +pub fn select(self: *Screen, sel_: ?Selection) Allocator.Error!void { + const sel = sel_ orelse { + self.clearSelection(); + return; + }; + + // If this selection is untracked then we track it. + const tracked_sel = if (sel.tracked()) sel else try sel.track(self); + errdefer if (!sel.tracked()) tracked_sel.deinit(self); + + // Untrack prior selection + if (self.selection) |*old| old.deinit(self); + self.selection = tracked_sel; + self.dirty.selection = true; +} + +/// Same as select(null) but can't fail. +pub fn clearSelection(self: *Screen) void { + if (self.selection) |*sel| { + sel.deinit(self); + self.dirty.selection = true; + } + self.selection = null; +} + +pub const SelectionString = struct { + /// The selection to convert to a string. + sel: Selection, + + /// If true, trim whitespace around the selection. + trim: bool = true, + + /// If non-null, a stringmap will be written here. This will use + /// the same allocator as the call to selectionString. The string will + /// be duplicated here and in the return value so both must be freed. + map: ?*StringMap = null, +}; + +const selectionString_tw = tripwire.module(enum { + copy_map, +}, selectionString); + +/// Returns the raw text associated with a selection. This will unwrap +/// soft-wrapped edges. The returned slice is owned by the caller and allocated +/// using alloc, not the allocator associated with the screen (unless they match). +/// +/// For more flexibility, use a ScreenFormatter directly. +pub fn selectionString( + self: *Screen, + alloc: Allocator, + opts: SelectionString, +) Allocator.Error![:0]const u8 { + // We'll use this as our buffer to build our string. + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + + // Create a formatter and use that to emit our text. + var formatter: ScreenFormatter = .init( + self, + .{ + .emit = .plain, + .unwrap = true, + .trim = opts.trim, + }, + ); + formatter.content = .{ .selection = opts.sel }; + + // If we have a string map, we need to set that up. + var pins: std.ArrayList(Pin) = .empty; + defer pins.deinit(alloc); + if (opts.map != null) formatter.pin_map = .{ + .alloc = alloc, + .map = &pins, + }; + + // Emit. Since this is an allocating writer, a failed write + // just becomes an OOM. + formatter.format(&aw.writer) catch return error.OutOfMemory; + + // Build our final text and if we have a string map set that up. + const text = try aw.toOwnedSliceSentinel(0); + errdefer alloc.free(text); + if (opts.map) |map| { + const map_string = try alloc.dupeZ(u8, text); + errdefer alloc.free(map_string); + try selectionString_tw.check(.copy_map); + const map_pins = try pins.toOwnedSlice(alloc); + map.* = .{ + .string = map_string, + .map = map_pins, + }; + } + + return text; +} + +pub const SelectLine = struct { + /// The pin of some part of the line to select. + pin: Pin, + + /// These are the codepoints to consider whitespace to trim + /// from the ends of the selection. + whitespace: ?[]const u21 = &.{ 0, ' ', '\t' }, + + /// If true, line selection will consider semantic prompt + /// state changing a boundary. State changing is ANY state + /// change. + semantic_prompt_boundary: bool = true, +}; + +/// Select the line under the given point. This will select across soft-wrapped +/// lines and will omit the leading and trailing whitespace. If the point is +/// over whitespace but the line has non-whitespace characters elsewhere, the +/// line will be selected. +pub fn selectLine(self: *const Screen, opts: SelectLine) ?Selection { + _ = self; + + // Get the current point semantic prompt state since that determines + // boundary conditions too. This makes it so that line selection can + // only happen within the same prompt state. For example, if you triple + // click output, but the shell uses spaces to soft-wrap to the prompt + // then the selection will stop prior to the prompt. See issue #1329. + const semantic_prompt_state: ?Cell.SemanticContent = state: { + if (!opts.semantic_prompt_boundary) break :state null; + const rac = opts.pin.rowAndCell(); + break :state rac.cell.semantic_content; + }; + + // The real start of the row is the first row in the soft-wrap. + const start_pin: Pin = start_pin: { + var it = opts.pin.rowIterator(.left_up, null); + var it_prev: Pin = it.next().?; // skip self + + // First, check the current row for semantic boundaries before the clicked position. + if (semantic_prompt_state) |v| { + const row = it_prev.rowAndCell().row; + const cells = it_prev.node.data.getCells(row); + // Scan backwards from clicked position to find where our content starts + for (0..opts.pin.x + 1) |i| { + const x_rev = opts.pin.x - i; + if (cells[x_rev].semantic_content != v) { + var copy = it_prev; + copy.x = @intCast(x_rev + 1); + break :start_pin copy; + } + } + + // No boundary found before clicked position on current row. + // If row doesn't wrap from above, start is at column 0. + // Otherwise, continue checking previous rows. + } + + while (it.next()) |p| { + const row = p.rowAndCell().row; + + if (!row.wrap) { + var copy = it_prev; + copy.x = 0; + break :start_pin copy; + } + + if (semantic_prompt_state) |v| { + // We need to check every cell in this row in reverse + // order since we're going up and back. + const cells = p.node.data.getCells(row); + for (0..cells.len) |x| { + const x_rev = cells.len - 1 - x; + const cell = cells[x_rev]; + if (cell.semantic_content != v) break :start_pin it_prev; + it_prev = p; + it_prev.x = @intCast(x_rev); + } + + continue; + } + + it_prev = p; + } else { + var copy = it_prev; + copy.x = 0; + break :start_pin copy; + } + }; + + // The real end of the row is the final row in the soft-wrap. + const end_pin: Pin = end_pin: { + var it = opts.pin.rowIterator(.right_down, null); + while (it.next()) |p| { + const row = p.rowAndCell().row; + + if (semantic_prompt_state) |v| { + // We need to check every cell in this row + const cells = p.node.data.getCells(row); + + // If this is our pin row we can start from our x because + // the start_pin logic already found the real start. + const start_offset = if (p.node == opts.pin.node and + p.y == opts.pin.y) opts.pin.x else 0; + + // Handle the zero case specially because if the first + // col doesn't match then we end at the end of the prior + // row. But if this is the first row, we can't go back, + // so we scan forward to find where our content ends. + if (start_offset == 0 and cells[0].semantic_content != v) { + var prev = p.up(1).?; + prev.x = p.node.data.size.cols - 1; + break :end_pin prev; + } + + // For every other case, we end at the prior cell. + for (start_offset.., cells[start_offset..]) |x, cell| { + if (cell.semantic_content != v) { + var copy = p; + copy.x = @intCast(x - 1); + break :end_pin copy; + } + } + } + + if (!row.wrap) { + var copy = p; + copy.x = p.node.data.size.cols - 1; + break :end_pin copy; + } + } + + return null; + }; + + // Go forward from the start to find the first non-whitespace character. + const start: Pin = start: { + const whitespace = opts.whitespace orelse break :start start_pin; + var it = start_pin.cellIterator(.right_down, end_pin); + while (it.next()) |p| { + const cell = p.rowAndCell().cell; + if (!cell.hasText()) continue; + + // Non-empty means we found it. + const this_whitespace = std.mem.indexOfAny( + u21, + whitespace, + &[_]u21{cell.content.codepoint}, + ) != null; + if (this_whitespace) continue; + + break :start p; + } + + return null; + }; + + // Go backward from the end to find the first non-whitespace character. + const end: Pin = end: { + const whitespace = opts.whitespace orelse break :end end_pin; + var it = end_pin.cellIterator(.left_up, start_pin); + while (it.next()) |p| { + const cell = p.rowAndCell().cell; + if (!cell.hasText()) continue; + + // Non-empty means we found it. + const this_whitespace = std.mem.indexOfAny( + u21, + whitespace, + &[_]u21{cell.content.codepoint}, + ) != null; + if (this_whitespace) continue; + + break :end p; + } + + return null; + }; + + return .init(start, end, false); +} + +/// Return the selection for all contents on the screen. Surrounding +/// whitespace is omitted. If there is no selection, this returns null. +pub fn selectAll(self: *Screen) ?Selection { + const whitespace = &[_]u32{ 0, ' ', '\t' }; + + const start: Pin = start: { + var it = self.pages.cellIterator( + .right_down, + .{ .screen = .{} }, + null, + ); + while (it.next()) |p| { + const cell = p.rowAndCell().cell; + if (!cell.hasText()) continue; + + // Non-empty means we found it. + const this_whitespace = std.mem.indexOfAny( + u32, + whitespace, + &[_]u32{cell.content.codepoint}, + ) != null; + if (this_whitespace) continue; + + break :start p; + } + + return null; + }; + + const end: Pin = end: { + var it = self.pages.cellIterator( + .left_up, + .{ .screen = .{} }, + null, + ); + while (it.next()) |p| { + const cell = p.rowAndCell().cell; + if (!cell.hasText()) continue; + + // Non-empty means we found it. + const this_whitespace = std.mem.indexOfAny( + u32, + whitespace, + &[_]u32{cell.content.codepoint}, + ) != null; + if (this_whitespace) continue; + + break :end p; + } + + return null; + }; + + return .init(start, end, false); +} + +/// Select the nearest word to start point that is between start_pt and +/// end_pt (inclusive). Because it selects "nearest" to start point, start +/// point can be before or after end point. +/// +/// The boundary_codepoints parameter should be a slice of u21 codepoints that +/// mark word boundaries, passed through to selectWord. +/// +/// TODO: test this +pub fn selectWordBetween( + self: *Screen, + start: Pin, + end: Pin, + boundary_codepoints: []const u21, +) ?Selection { + const dir: PageList.Direction = if (start.before(end)) .right_down else .left_up; + var it = start.cellIterator(dir, end); + while (it.next()) |pin| { + // Boundary conditions + switch (dir) { + .right_down => if (end.before(pin)) return null, + .left_up => if (pin.before(end)) return null, + } + + // If we found a word, then return it + if (self.selectWord(pin, boundary_codepoints)) |sel| return sel; + } + + return null; +} + +/// Select the word under the given point. A word is any consecutive series +/// of characters that are exclusively whitespace or exclusively non-whitespace. +/// A selection can span multiple physical lines if they are soft-wrapped. +/// +/// This will return null if a selection is impossible. The only scenario +/// this happens is if the point pt is outside of the written screen space. +/// +/// The boundary_codepoints parameter should be a slice of u21 codepoints that +/// mark word boundaries. This is expected to be pre-parsed from the config. +pub fn selectWord( + self: *Screen, + pin: Pin, + boundary_codepoints: []const u21, +) ?Selection { + _ = self; + + // If our cell is empty we can't select a word, because we can't select + // areas where the screen is not yet written. + const start_cell = pin.rowAndCell().cell; + if (!start_cell.hasText()) return null; + + // Determine if we are a boundary or not to determine what our boundary is. + const expect_boundary = std.mem.indexOfAny( + u21, + boundary_codepoints, + &[_]u21{start_cell.content.codepoint}, + ) != null; + + // Go forwards to find our end boundary + const end: Pin = end: { + var it = pin.cellIterator(.right_down, null); + var prev = it.next().?; // Consume one, our start + while (it.next()) |p| { + const rac = p.rowAndCell(); + const cell = rac.cell; + + // If we reached an empty cell its always a boundary + if (!cell.hasText()) break :end prev; + + // If we do not match our expected set, we hit a boundary + const this_boundary = std.mem.indexOfAny( + u21, + boundary_codepoints, + &[_]u21{cell.content.codepoint}, + ) != null; + if (this_boundary != expect_boundary) break :end prev; + + // If we are going to the next row and it isn't wrapped, we + // return the previous. + if (p.x == p.node.data.size.cols - 1 and !rac.row.wrap) { + break :end p; + } + + prev = p; + } + + break :end prev; + }; + + // Go backwards to find our start boundary + const start: Pin = start: { + var it = pin.cellIterator(.left_up, null); + var prev = it.next().?; // Consume one, our start + while (it.next()) |p| { + const rac = p.rowAndCell(); + const cell = rac.cell; + + // If we are going to the next row and it isn't wrapped, we + // return the previous. + if (p.x == p.node.data.size.cols - 1 and !rac.row.wrap) { + break :start prev; + } + + // If we reached an empty cell its always a boundary + if (!cell.hasText()) break :start prev; + + // If we do not match our expected set, we hit a boundary + const this_boundary = std.mem.indexOfAny( + u21, + boundary_codepoints, + &[_]u21{cell.content.codepoint}, + ) != null; + if (this_boundary != expect_boundary) break :start prev; + + prev = p; + } + + break :start prev; + }; + + return .init(start, end, false); +} + +/// Select the command output under the given point. The limits of the output +/// are determined by semantic prompt information provided by shell integration. +/// A selection can span multiple physical lines if they are soft-wrapped. +/// +/// This will return null if a selection is impossible: +/// - the point pt is outside of the written screen space. +/// - the point pt is on a prompt / input line. +pub fn selectOutput(self: *Screen, pin: Pin) ?Selection { + // If our pin right now is not on output, then we return nothing. + if (pin.rowAndCell().cell.semantic_content != .output) return null; + + // Get the post prior prompt from this pin. This is the prompt whose + // output we'll be capturing. + const prompt_pin: Pin = prompt: { + // If we have a prompt above this point (including this point), + // then thats the prompt we want to capture output from. + var it = pin.promptIterator(.left_up, null); + if (it.next()) |p| break :prompt p; + + // If we don't have a prompt, then we assume that we're + // capturing all the output up to the next prompt. + it = pin.promptIterator(.right_down, null); + const next = it.next() orelse return null; + + // We'll capture from the start of the screen to just above + // the prompt and will trim the trailing whitespace. + const start_pin = self.pages.getTopLeft(.screen); + var end_pin = next.up(1) orelse return null; + end_pin.x = end_pin.node.data.size.cols - 1; + var cell_it = end_pin.cellIterator(.left_up, start_pin); + while (cell_it.next()) |p| { + const cell = p.rowAndCell().cell; + end_pin = p; + if (cell.hasText()) break; + } + + return .init( + start_pin, + end_pin, + false, + ); + }; + + // Grab our content + var hl = self.pages.highlightSemanticContent( + prompt_pin, + .output, + ) orelse return null; + + // Trim our trailing whitespace + var cell_it = hl.end.cellIterator(.left_up, hl.start); + while (cell_it.next()) |p| { + const cell = p.rowAndCell().cell; + hl.end = p; + if (cell.hasText()) break; + } + + return .init(hl.start, hl.end, false); +} + +pub const LineIterator = struct { + screen: *const Screen, + current: ?Pin = null, + + pub fn next(self: *LineIterator) ?Selection { + const current = self.current orelse return null; + const result = self.screen.selectLine(.{ + .pin = current, + .whitespace = null, + .semantic_prompt_boundary = false, + }) orelse { + self.current = null; + return null; + }; + + self.current = result.end().down(1); + return result; + } +}; + +/// Returns an iterator to move through the soft-wrapped lines starting +/// from pin. +pub fn lineIterator(self: *const Screen, start: Pin) LineIterator { + return LineIterator{ + .screen = self, + .current = start, + }; +} + +pub const PromptClickMove = struct { + left: usize, + right: usize, + + pub const zero = PromptClickMove{ + .left = 0, + .right = 0, + }; +}; + +/// Determine the inputs necessary to move the cursor to the given +/// click location within a prompt input area. +/// +/// If the cursor isn't currently at a prompt input location, this +/// returns no movement. +/// +/// This feature depends on well-behaved OSC133 shell integration. Specifically, +/// this only moves over designated input areas (OSC 133 B). It is assumed +/// that the shell will only move the cursor to input cells, so prompt cells +/// and other blank cells are ignored as part of the movement calculation. +pub fn promptClickMove( + self: *Screen, + click_pin: Pin, +) PromptClickMove { + // If we're not at an input cell with our cursor, no movement will + // ever be possible. + if (self.cursor.semantic_content != .input and + self.cursor.page_cell.semantic_content != .input) return .zero; + + return switch (self.semantic_prompt.click) { + // None doesn't support movement and click_events must use a + // different mechanism (SGR mouse events) that callers must handle. + .none, .click_events => .zero, + .cl => |cl| switch (cl) { + // All of these currently use dumb line-based navigation. + // But eventually we'll support more. + .line, + .multiple, + .conservative_vertical, + .smart_vertical, + => self.promptClickLine(click_pin), + }, + }; +} + +/// Determine the inputs required to move from the cursor to the given +/// click location. If the cursor isn't currently at a prompt input +/// location, this will return zero. +/// +/// This currently only supports moving a single line. +fn promptClickLine(self: *Screen, click_pin: Pin) PromptClickMove { + // If our click pin is our cursor pin, no movement is needed. + // Do this early so we can assume later that they are different. + const cursor_pin = self.cursor.page_pin.*; + if (cursor_pin.eql(click_pin)) return .zero; + + // If our cursor is before our click, we're only emitting right inputs. + if (cursor_pin.before(click_pin)) { + var count: usize = 0; + + // We go row-by-row because soft-wrapped rows are still a single + // line to a shell, so we can't just look at our page row. + var row_it = cursor_pin.rowIterator( + .right_down, + click_pin, + ); + row_it: while (row_it.next()) |row_pin| { + const rac = row_pin.rowAndCell(); + const cells = row_pin.node.data.getCells(rac.row); + + // Determine if this row is our cursor. + const is_cursor_row = row_pin.node == cursor_pin.node and + row_pin.y == cursor_pin.y; + + // If this is not the cursor row, verify it's still part of the + // continuation of our starting prompt. + if (!is_cursor_row and + rac.row.semantic_prompt != .prompt_continuation) break; + + // Determine where our input starts. + const start_x: usize = start_x: { + // If this is our cursor row then we start after the cursor. + if (is_cursor_row) break :start_x cursor_pin.x + 1; + + // Otherwise, we start at the first input cell, because + // we expect the shell to properly translate arrows across + // lines to the start of the input. Some shells indent + // where input starts on subsequent lines so we must do + // this. + for (cells, 0..) |cell, x| { + if (cell.semantic_content == .input) break :start_x x; + } + + // We never found an input cell, so we need to move to the + // next row. + break :start_x cells.len; + }; + + // Iterate over the input cells and assume arrow keys only + // jump to input cells. + for (cells[start_x..], start_x..) |cell, x| { + // Ignore non-input cells, but allow breaks. We assume + // the shell will translate arrow keys to only input + // areas. + if (cell.semantic_content != .input) continue; + + // Increment our input count + count += 1; + + // If this is our target, we're done. + if (row_pin.node == click_pin.node and + row_pin.y == click_pin.y and + x == click_pin.x) + break :row_it; + } + + // If this row isn't soft-wrapped, we need to break out + // because line based moving only handles single lines. + // We're done! + if (!rac.row.wrap) { + // If we never found our pin, that means we clicked further + // right/beyond it. If we're already on a non-empty input cell + // then we add one so we can move to the newest, empty cell + // at the end, matching typical editor behavior. + if (self.cursor.page_cell.semantic_content == .input) count += 1; + + break; + } + } + + return .{ .left = 0, .right = count }; + } + + // Otherwise, cursor is after click, so we're emitting left inputs. + var count: usize = 0; + + // We go row-by-row because soft-wrapped rows are still a single + // line to a shell, so we can't just look at our page row. + var row_it = cursor_pin.rowIterator( + .left_up, + click_pin, + ); + row_it: while (row_it.next()) |row_pin| { + const rac = row_pin.rowAndCell(); + const cells = row_pin.node.data.getCells(rac.row); + + // Determine the length of the cells we look at in this row. + const end_len: usize = end_len: { + // If this is our cursor row then we end before the cursor. + if (row_pin.node == cursor_pin.node and + row_pin.y == cursor_pin.y) break :end_len cursor_pin.x; + + // Otherwise, we end at the last cell in the row. + break :end_len cells.len; + }; + + // Iterate backwards over the input cells. + for (0..end_len) |rev_x| { + const x: usize = end_len - 1 - rev_x; + const cell = cells[x]; + + // Ignore non-input cells. + if (cell.semantic_content != .input) continue; + + // Increment our input count + count += 1; + + // If this is our target, we're done. + if (row_pin.node == click_pin.node and + row_pin.y == click_pin.y and + x == click_pin.x) + break :row_it; + } + + // If this row is not a wrap continuation, then break out + if (!rac.row.wrap_continuation) break; + } + + return .{ .left = count, .right = 0 }; +} + +/// Dump the screen to a string. The writer given should be buffered; +/// this function does not attempt to efficiently write and generally writes +/// one byte at a time. +pub fn dumpString( + self: *const Screen, + writer: *std.Io.Writer, + opts: struct { + /// The start and end points of the dump, both inclusive. The x will + /// be ignored and the full row will always be dumped. + tl: Pin, + br: ?Pin = null, + + /// If true, this will unwrap soft-wrapped lines. If false, this will + /// dump the screen as it is visually seen in a rendered window. + unwrap: bool = true, + }, +) std.Io.Writer.Error!void { + // Create a formatter and use that to emit our text. + var formatter: ScreenFormatter = .init(self, .{ + .emit = .plain, + .unwrap = opts.unwrap, + .trim = false, + }); + + // Set up the selection based on the pins + const tl = opts.tl; + const br = opts.br orelse self.pages.getBottomRight(.screen).?; + + formatter.content = .{ + .selection = Selection.init( + tl, + br, + false, // not rectangle + ), + }; + + // Emit + try formatter.format(writer); +} + +/// You should use dumpString, this is a restricted version mostly for +/// legacy and convenience reasons for unit tests. +pub fn dumpStringAlloc( + self: *const Screen, + alloc: Allocator, + tl: point.Point, +) ![]const u8 { + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + try self.dumpString(&builder.writer, .{ + .tl = self.pages.getTopLeft(tl), + .br = self.pages.getBottomRight(tl) orelse return error.UnknownPoint, + .unwrap = false, + }); + + return try builder.toOwnedSlice(); +} + +/// You should use dumpString, this is a restricted version mostly for +/// legacy and convenience reasons for unit tests. +pub fn dumpStringAllocUnwrapped( + self: *const Screen, + alloc: Allocator, + tl: point.Point, +) ![]const u8 { + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + try self.dumpString(&builder.writer, .{ + .tl = self.pages.getTopLeft(tl), + .br = self.pages.getBottomRight(tl) orelse return error.UnknownPoint, + .unwrap = true, + }); + + return try builder.toOwnedSlice(); +} + +/// This is basically a really jank version of Terminal.printString. We +/// have to reimplement it here because we want a way to print to the screen +/// to test it but don't want all the features of Terminal. +pub fn testWriteString(self: *Screen, text: []const u8) !void { + const view = try std.unicode.Utf8View.init(text); + var iter = view.iterator(); + while (iter.nextCodepoint()) |c| { + // Explicit newline forces a new row + if (c == '\n') { + try self.cursorDownOrScroll(); + self.cursorHorizontalAbsolute(0); + self.cursor.pending_wrap = false; + if (self.cursor.semantic_content_clear_eol) { + self.cursorSetSemanticContent(.output); + } else switch (self.cursor.semantic_content) { + .output => {}, + .prompt, .input => self.cursor.page_row.semantic_prompt = .prompt_continuation, + } + continue; + } + + const width: usize = if (c <= 0xFF) 1 else @intCast(unicode.table.get(c).width); + if (width == 0) { + const cell = cell: { + var cell = self.cursorCellLeft(1); + switch (cell.wide) { + .narrow => {}, + .wide => {}, + .spacer_head => unreachable, + .spacer_tail => cell = self.cursorCellLeft(2), + } + + break :cell cell; + }; + + try self.cursor.page_pin.node.data.appendGrapheme( + self.cursor.page_row, + cell, + c, + ); + continue; + } + + if (self.cursor.pending_wrap) { + assert(self.cursor.x == self.pages.cols - 1); + self.cursor.pending_wrap = false; + self.cursor.page_row.wrap = true; + try self.cursorDownOrScroll(); + self.cursorHorizontalAbsolute(0); + self.cursor.page_row.wrap_continuation = true; + switch (self.cursor.semantic_content) { + .output => {}, + .input, .prompt => self.cursor.page_row.semantic_prompt = .prompt_continuation, + } + } + + assert(width == 1 or width == 2); + switch (width) { + 1 => { + self.cursor.page_cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = c }, + .style_id = self.cursor.style_id, + .protected = self.cursor.protected, + .semantic_content = self.cursor.semantic_content, + }; + + // If we have a ref-counted style, increase. + if (self.cursor.style_id != style.default_id) { + const page = self.cursor.page_pin.node.data; + page.styles.use(page.memory, self.cursor.style_id); + self.cursor.page_row.styled = true; + } + + // If we have a hyperlink, add it to the cell. + if (self.cursor.hyperlink_id > 0) try self.cursorSetHyperlink(); + }, + + 2 => { + // Need a wide spacer head + if (self.cursor.x == self.pages.cols - 1) { + self.cursor.page_cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_head, + .protected = self.cursor.protected, + .semantic_content = self.cursor.semantic_content, + }; + + // If we have a hyperlink, add it to the cell. + if (self.cursor.hyperlink_id > 0) try self.cursorSetHyperlink(); + + self.cursor.page_row.wrap = true; + try self.cursorDownOrScroll(); + self.cursorHorizontalAbsolute(0); + self.cursor.page_row.wrap_continuation = true; + } + + // Write our wide char + self.cursor.page_cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = c }, + .style_id = self.cursor.style_id, + .wide = .wide, + .protected = self.cursor.protected, + .semantic_content = self.cursor.semantic_content, + }; + + // If we have a hyperlink, add it to the cell. + if (self.cursor.hyperlink_id > 0) try self.cursorSetHyperlink(); + + // Write our tail + self.cursorRight(1); + self.cursor.page_cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + .wide = .spacer_tail, + .protected = self.cursor.protected, + .semantic_content = self.cursor.semantic_content, + }; + + // If we have a hyperlink, add it to the cell. + if (self.cursor.hyperlink_id > 0) try self.cursorSetHyperlink(); + + // If we have a ref-counted style, increase twice. + if (self.cursor.style_id != style.default_id) { + const page = self.cursor.page_pin.node.data; + page.styles.use(page.memory, self.cursor.style_id); + page.styles.use(page.memory, self.cursor.style_id); + self.cursor.page_row.styled = true; + } + }, + + else => unreachable, + } + + if (self.cursor.x + 1 < self.pages.cols) { + self.cursorRight(1); + } else { + self.cursor.pending_wrap = true; + } + } +} + +test "Screen read and write" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + try testing.expectEqual(@as(style.Id, 0), s.cursor.style_id); + + try s.testWriteString("hello, world"); + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("hello, world", str); +} + +test "Screen read and write newline" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + try testing.expectEqual(@as(style.Id, 0), s.cursor.style_id); + + try s.testWriteString("hello\nworld"); + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("hello\nworld", str); +} + +test "Screen read and write scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 2, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.testWriteString("hello\nworld\ntest"); + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("hello\nworld\ntest", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("world\ntest", str); + } +} + +test "Screen read and write no scrollback small" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 2, .max_scrollback = 0 }); + defer s.deinit(); + + try s.testWriteString("hello\nworld\ntest"); + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("world\ntest", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("world\ntest", str); + } +} + +test "Screen read and write no scrollback large" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 2, .max_scrollback = 0 }); + defer s.deinit(); + + for (0..1_000) |i| { + var buf: [128]u8 = undefined; + const str = try std.fmt.bufPrint(&buf, "{}\n", .{i}); + try s.testWriteString(str); + } + try s.testWriteString("1000"); + + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("999\n1000", str); + } +} + +test "Screen cursorCopy x/y" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + s.cursorAbsolute(2, 3); + try testing.expect(s.cursor.x == 2); + try testing.expect(s.cursor.y == 3); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s2.deinit(); + try s2.cursorCopy(s.cursor, .{}); + try testing.expect(s2.cursor.x == 2); + try testing.expect(s2.cursor.y == 3); + try s2.testWriteString("Hello"); + + { + const str = try s2.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("\n\n\n Hello", str); + } +} + +test "Screen cursorCopy style deref" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s2.deinit(); + const page = &s2.cursor.page_pin.node.data; + + // Bold should create our style + try s2.setAttribute(.{ .bold = {} }); + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(s2.cursor.style.flags.bold); + + // Copy default style, should release our style + try s2.cursorCopy(s.cursor, .{}); + try testing.expect(!s2.cursor.style.flags.bold); + try testing.expectEqual(@as(usize, 0), page.styles.count()); +} + +test "Screen cursorCopy style deref new page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 2048 }); + defer s2.deinit(); + + // We need to get the cursor on a new page. + const first_page_size = s2.pages.pages.first.?.data.capacity.rows; + + // Fill the scrollback with blank lines until + // there are only 5 rows left on the first page. + s2.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 5) |_| { + try s2.testWriteString("\n"); + } + s2.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s2.testWriteString("1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); + + // s2.pages.diagram(...): + // + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4300 |1 | | 0 + // 4301 |2 | | 1 + // 4302 |3 | | 2 + // 4303 |4 | | 3 + // 4304 |5 | | 4 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |6 | | 5 + // 1 |7 | | 6 + // 2 |8 | | 7 + // 3 |9 | | 8 + // 4 |10 | | 9 + // : ^ : : = PIN 0 + // +----------+ : + // +-------------+ + + // This should be PAGE 1 + const page = &s2.cursor.page_pin.node.data; + + // It should be the last page in the list. + try testing.expectEqual(&s2.pages.pages.last.?.data, page); + // It should have a previous page. + try testing.expect(s2.cursor.page_pin.node.prev != null); + + // The cursor should be at 2, 9 + try testing.expect(s2.cursor.x == 2); + try testing.expect(s2.cursor.y == 9); + + // Bold should create our style in page 1. + try s2.setAttribute(.{ .bold = {} }); + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(s2.cursor.style.flags.bold); + + // Copy the cursor for the first screen. This should release + // the style from page 1 and move the cursor back to page 0. + try s2.cursorCopy(s.cursor, .{}); + try testing.expect(!s2.cursor.style.flags.bold); + try testing.expectEqual(@as(usize, 0), page.styles.count()); + // The page after the page the cursor is now in should be page 1. + try testing.expectEqual(page, &s2.cursor.page_pin.node.next.?.data); + // The cursor should be at 0, 0 + try testing.expect(s2.cursor.x == 0); + try testing.expect(s2.cursor.y == 0); +} + +test "Screen cursorCopy style copy" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.setAttribute(.{ .bold = {} }); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s2.deinit(); + const page = &s2.cursor.page_pin.node.data; + try s2.cursorCopy(s.cursor, .{}); + try testing.expect(s2.cursor.style.flags.bold); + try testing.expectEqual(@as(usize, 1), page.styles.count()); +} + +test "Screen cursorCopy hyperlink deref" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s2.deinit(); + const page = &s2.cursor.page_pin.node.data; + + // Create a hyperlink for the cursor. + try s2.startHyperlink("https://example.com/", null); + try testing.expectEqual(@as(usize, 1), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id != 0); + + // Copy a cursor with no hyperlink, should release our hyperlink. + try s2.cursorCopy(s.cursor, .{}); + try testing.expectEqual(@as(usize, 0), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id == 0); +} + +test "Screen cursorCopy hyperlink deref new page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 2048 }); + defer s2.deinit(); + + // We need to get the cursor on a new page. + const first_page_size = s2.pages.pages.first.?.data.capacity.rows; + + // Fill the scrollback with blank lines until + // there are only 5 rows left on the first page. + s2.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 5) |_| { + try s2.testWriteString("\n"); + } + s2.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s2.testWriteString("1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); + + // s2.pages.diagram(...): + // + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4300 |1 | | 0 + // 4301 |2 | | 1 + // 4302 |3 | | 2 + // 4303 |4 | | 3 + // 4304 |5 | | 4 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |6 | | 5 + // 1 |7 | | 6 + // 2 |8 | | 7 + // 3 |9 | | 8 + // 4 |10 | | 9 + // : ^ : : = PIN 0 + // +----------+ : + // +-------------+ + + // This should be PAGE 1 + const page = &s2.cursor.page_pin.node.data; + + // It should be the last page in the list. + try testing.expectEqual(&s2.pages.pages.last.?.data, page); + // It should have a previous page. + try testing.expect(s2.cursor.page_pin.node.prev != null); + + // The cursor should be at 2, 9 + try testing.expect(s2.cursor.x == 2); + try testing.expect(s2.cursor.y == 9); + + // Create a hyperlink for the cursor, should be in page 1. + try s2.startHyperlink("https://example.com/", null); + try testing.expectEqual(@as(usize, 1), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id != 0); + + // Copy the cursor for the first screen. This should release + // the hyperlink from page 1 and move the cursor back to page 0. + try s2.cursorCopy(s.cursor, .{}); + try testing.expectEqual(@as(usize, 0), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id == 0); + // The page after the page the cursor is now in should be page 1. + try testing.expectEqual(page, &s2.cursor.page_pin.node.next.?.data); + // The cursor should be at 0, 0 + try testing.expect(s2.cursor.x == 0); + try testing.expect(s2.cursor.y == 0); +} + +test "Screen cursorCopy hyperlink copy" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + // Create a hyperlink for the cursor. + try s.startHyperlink("https://example.com/", null); + try testing.expectEqual(@as(usize, 1), s.cursor.page_pin.node.data.hyperlink_set.count()); + try testing.expect(s.cursor.hyperlink_id != 0); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s2.deinit(); + const page = &s2.cursor.page_pin.node.data; + + try testing.expectEqual(@as(usize, 0), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id == 0); + + // Copy the cursor with the hyperlink. + try s2.cursorCopy(s.cursor, .{}); + try testing.expectEqual(@as(usize, 1), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id != 0); +} + +test "Screen cursorCopy hyperlink copy disabled" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + // Create a hyperlink for the cursor. + try s.startHyperlink("https://example.com/", null); + try testing.expectEqual(@as(usize, 1), s.cursor.page_pin.node.data.hyperlink_set.count()); + try testing.expect(s.cursor.hyperlink_id != 0); + + var s2 = try Screen.init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s2.deinit(); + const page = &s2.cursor.page_pin.node.data; + + try testing.expectEqual(@as(usize, 0), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id == 0); + + // Copy the cursor with the hyperlink. + try s2.cursorCopy(s.cursor, .{ .hyperlink = false }); + try testing.expectEqual(@as(usize, 0), page.hyperlink_set.count()); + try testing.expect(s2.cursor.hyperlink_id == 0); +} + +test "Screen style basics" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 0), page.styles.count()); + + // Set a new style + try s.setAttribute(.{ .bold = {} }); + try testing.expect(s.cursor.style_id != 0); + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(s.cursor.style.flags.bold); + + // Set another style, we should still only have one since it was unused + try s.setAttribute(.{ .italic = {} }); + try testing.expect(s.cursor.style_id != 0); + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(s.cursor.style.flags.italic); +} + +test "Screen style reset to default" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 0), page.styles.count()); + + // Set a new style + try s.setAttribute(.{ .bold = {} }); + try testing.expect(s.cursor.style_id != 0); + try testing.expectEqual(@as(usize, 1), page.styles.count()); + + // Reset to default + try s.setAttribute(.{ .reset_bold = {} }); + try testing.expect(s.cursor.style_id == 0); + try testing.expectEqual(@as(usize, 0), page.styles.count()); +} + +test "Screen style reset with unset" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 0), page.styles.count()); + + // Set a new style + try s.setAttribute(.{ .bold = {} }); + try testing.expect(s.cursor.style_id != 0); + try testing.expectEqual(@as(usize, 1), page.styles.count()); + + // Reset to default + try s.setAttribute(.{ .unset = {} }); + try testing.expect(s.cursor.style_id == 0); + try testing.expectEqual(@as(usize, 0), page.styles.count()); +} + +test "Screen clearRows active one line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.testWriteString("hello, world"); + s.clearRows(.{ .active = .{} }, null, false); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("", str); +} + +test "Screen clearRows active multi line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.testWriteString("hello\nworld"); + s.clearRows(.{ .active = .{} }, null, false); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("", str); +} + +test "Screen clearRows active styled line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.setAttribute(.{ .bold = {} }); + try s.testWriteString("hello world"); + try s.setAttribute(.{ .unset = {} }); + + // We should have one style + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + + s.clearRows(.{ .active = .{} }, null, false); + + // We should have none because active cleared it + try testing.expectEqual(@as(usize, 0), page.styles.count()); + + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("", str); +} + +test "Screen clearRows protected" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.testWriteString("UNPROTECTED"); + s.cursor.protected = true; + try s.testWriteString("PROTECTED"); + s.cursor.protected = false; + try s.testWriteString("UNPROTECTED"); + try s.testWriteString("\n"); + s.cursor.protected = true; + try s.testWriteString("PROTECTED"); + s.cursor.protected = false; + try s.testWriteString("UNPROTECTED"); + s.cursor.protected = true; + try s.testWriteString("PROTECTED"); + s.cursor.protected = false; + + s.clearRows(.{ .active = .{} }, null, true); + + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings(" PROTECTED\nPROTECTED PROTECTED", str); +} + +test "Screen eraseRows history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.testWriteString("1\n2\n3\n4\n5\n6"); + + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("2\n3\n4\n5\n6", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("1\n2\n3\n4\n5\n6", str); + } + + s.eraseHistory(null); + + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("2\n3\n4\n5\n6", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("2\n3\n4\n5\n6", str); + } +} + +test "Screen eraseRows history with more lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 1000 }); + defer s.deinit(); + + try s.testWriteString("A\nB\nC\n1\n2\n3\n4\n5\n6"); + + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("2\n3\n4\n5\n6", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("A\nB\nC\n1\n2\n3\n4\n5\n6", str); + } + + s.eraseHistory(null); + + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("2\n3\n4\n5\n6", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("2\n3\n4\n5\n6", str); + } +} + +test "Screen eraseRows active partial" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + try s.testWriteString("1\n2\n3"); + + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("1\n2\n3", str); + } + + s.eraseActive(1); + + { + const str = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("3", str); + } + { + const str = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(str); + try testing.expectEqualStrings("3", str); + } +} + +test "Screen: cursorDown across pages preserves style" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + + // Scroll down enough to go to another page + const start_page = &s.pages.pages.last.?.data; + const rem = start_page.capacity.rows; + start_page.pauseIntegrityChecks(true); + for (0..rem) |_| try s.cursorDownOrScroll(); + start_page.pauseIntegrityChecks(false); + + // We need our page to change for this test o make sense. If this + // assertion fails then the bug is in the test: we should be scrolling + // above enough for a new page to show up. + { + const page = &s.cursor.page_pin.node.data; + try testing.expect(start_page != page); + } + + // Scroll back to the previous page + s.cursorUp(1); + { + const page = &s.cursor.page_pin.node.data; + try testing.expect(start_page == page); + } + + // Go back up, set a style + try s.setAttribute(.{ .bold = {} }); + { + const page = &s.cursor.page_pin.node.data; + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } + + // Go back down into the next page and we should have that style + s.cursorDown(1); + { + const page = &s.cursor.page_pin.node.data; + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } +} + +test "Screen: cursorUp across pages preserves style" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + + // Scroll down enough to go to another page + const start_page = &s.pages.pages.last.?.data; + const rem = start_page.capacity.rows; + start_page.pauseIntegrityChecks(true); + for (0..rem) |_| try s.cursorDownOrScroll(); + start_page.pauseIntegrityChecks(false); + + // We need our page to change for this test o make sense. If this + // assertion fails then the bug is in the test: we should be scrolling + // above enough for a new page to show up. + { + const page = &s.cursor.page_pin.node.data; + try testing.expect(start_page != page); + } + + // Go back up, set a style + try s.setAttribute(.{ .bold = {} }); + { + const page = &s.cursor.page_pin.node.data; + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } + + // Go back down into the prev page and we should have that style + s.cursorUp(1); + { + const page = &s.cursor.page_pin.node.data; + try testing.expect(start_page == page); + + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } +} + +test "Screen: cursorAbsolute across pages preserves style" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + + // Scroll down enough to go to another page + const start_page = &s.pages.pages.last.?.data; + const rem = start_page.capacity.rows; + start_page.pauseIntegrityChecks(true); + for (0..rem) |_| try s.cursorDownOrScroll(); + start_page.pauseIntegrityChecks(false); + + // We need our page to change for this test o make sense. If this + // assertion fails then the bug is in the test: we should be scrolling + // above enough for a new page to show up. + { + const page = &s.cursor.page_pin.node.data; + try testing.expect(start_page != page); + } + + // Go back up, set a style + try s.setAttribute(.{ .bold = {} }); + { + const page = &s.cursor.page_pin.node.data; + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } + + // Go back down into the prev page and we should have that style + s.cursorAbsolute(1, 1); + { + const page = &s.cursor.page_pin.node.data; + try testing.expect(start_page == page); + + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } +} + +test "Screen: cursorAbsolute to page with insufficient capacity" { + // This test checks for a very specific edge case + // which previously resulted in memory corruption. + // + // The conditions for this edge case are as such: + // - The cursor has an associated style or other managed memory. + // - The cursor moves to a different page. + // - The new page is at capacity and must have its capacity adjusted. + + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + + // Scroll down enough to go to another page + const start_page = &s.pages.pages.last.?.data; + const rem = start_page.capacity.rows; + start_page.pauseIntegrityChecks(true); + for (0..rem) |_| try s.cursorDownOrScroll(); + start_page.pauseIntegrityChecks(false); + + const new_page = &s.cursor.page_pin.node.data; + + // We need our page to change for this test to make sense. If this + // assertion fails then the bug is in the test: we should be scrolling + // above enough for a new page to show up. + try testing.expect(start_page != new_page); + + // Add styles to the start page until it reaches capacity. + { + // Pause integrity checks because they're slow and + // we're not testing this, this is just setup. + start_page.pauseIntegrityChecks(true); + defer start_page.pauseIntegrityChecks(false); + defer start_page.assertIntegrity(); + + var n: u24 = 1; + while (start_page.styles.add( + start_page.memory, + .{ .bg_color = .{ .rgb = @bitCast(n) } }, + )) |_| n += 1 else |_| {} + } + + // Set a style on the cursor. + try s.setAttribute(.{ .bold = {} }); + { + const styleval = new_page.styles.get( + new_page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } + + // Go back up into the start page and we should still have that style. + s.cursorAbsolute(1, 1); + { + const cur_page = &s.cursor.page_pin.node.data; + // The page we're on now should NOT equal start_page, since its + // capacity should have been adjusted, which invalidates our ptr. + try testing.expect(start_page != cur_page); + // To make sure we DID change pages we check we're not on new_page. + try testing.expect(new_page != cur_page); + + const styleval = cur_page.styles.get( + cur_page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); + } + + s.cursor.page_pin.node.data.assertIntegrity(); + new_page.assertIntegrity(); +} + +test "Screen: scrolling" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Scroll down, should still be bottom + try s.cursorDownScroll(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 2 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Everything is dirty because we have no scrollback + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + // Scrolling to the bottom does nothing + s.scroll(.{ .active = {} }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } +} + +test "Screen: scrolling with a single-row screen no scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 1, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1ABCD"); + + // Scroll down, should still be bottom + try s.cursorDownScroll(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + + // Screen should be dirty + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); +} + +test "Screen: scrolling with a single-row screen with scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 1, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD"); + + // Scroll down, should still be bottom + try s.cursorDownScroll(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + + // Active should be dirty + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + // Scrollback also dirty because cursor moved from there + try testing.expect(s.pages.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + s.scroll(.{ .delta_row = -1 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD", contents); + } +} + +test "Screen: scrolling across pages preserves style" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.setAttribute(.{ .bold = {} }); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + const start_page = &s.pages.pages.last.?.data; + + // Scroll down enough to go to another page + const rem = start_page.capacity.rows - start_page.size.rows + 1; + start_page.pauseIntegrityChecks(true); + for (0..rem) |_| try s.cursorDownOrScroll(); + start_page.pauseIntegrityChecks(false); + + // We need our page to change for this test o make sense. If this + // assertion fails then the bug is in the test: we should be scrolling + // above enough for a new page to show up. + const page = &s.pages.pages.last.?.data; + try testing.expect(start_page != page); + + const styleval = page.styles.get( + page.memory, + s.cursor.style_id, + ); + try testing.expect(styleval.flags.bold); +} + +test "Screen: scroll down from 0" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Scrolling up does nothing, but allows it + s.scroll(.{ .delta_row = -1 }); + try testing.expect(s.pages.viewport == .active); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } +} + +test "Screen: scrollback various cases" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + try s.cursorDownScroll(); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + + // Scrolling to the bottom + s.scroll(.{ .active = {} }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + + // Scrolling back should make it visible again + s.scroll(.{ .delta_row = -1 }); + try testing.expect(s.pages.viewport != .active); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } + + // Scrolling back again should do nothing + s.scroll(.{ .delta_row = -1 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } + + // Scrolling to the bottom + s.scroll(.{ .active = {} }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + + // Scrolling forward with no grow should do nothing + s.scroll(.{ .delta_row = 1 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + + // Scrolling to the top should work + s.scroll(.{ .top = {} }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } + + // Should be able to easily clear active area only + s.clearRows(.{ .active = .{} }, null, false); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD", contents); + } + + // Scrolling to the bottom + s.scroll(.{ .active = {} }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } +} + +test "Screen: scrollback with multi-row delta" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH\n6IJKL"); + + // Scroll to top + s.scroll(.{ .top = {} }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } + + // Scroll down multiple + s.scroll(.{ .delta_row = 5 }); + try testing.expect(s.pages.viewport == .active); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("4ABCD\n5EFGH\n6IJKL", contents); + } +} + +test "Screen: scrollback empty" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 50 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + s.scroll(.{ .delta_row = 1 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } +} + +test "Screen: scrollback doesn't move viewport if not at bottom" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"); + + // First test: we scroll up by 1, so we're not at the bottom anymore. + s.scroll(.{ .delta_row = -1 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL\n4ABCD", contents); + } + + // Next, we scroll back down by 1, this grows the scrollback but we + // shouldn't move. + try s.cursorDownScroll(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL\n4ABCD", contents); + } + + // Scroll again, this clears scrollback so we should move viewports + // but still see the same thing since our original view fits. + try s.cursorDownScroll(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL\n4ABCD", contents); + } +} + +test "Screen: scrolling moves selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Select a single line + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + s.pages.pin(.{ .active = .{ .x = s.pages.cols - 1, .y = 1 } }).?, + false, + )); + + // Scroll down, should still be bottom + try s.cursorDownScroll(); + + // Our selection should've moved up + { + const sel = s.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s.pages.cols - 1, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + + // Scrolling to the bottom does nothing + s.scroll(.{ .active = {} }); + + // Our selection should've stayed the same + { + const sel = s.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s.pages.cols - 1, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } + + // Scroll up again + try s.cursorDownScroll(); + + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("3IJKL", contents); + } + + // Our selection should be null because it left the screen. + { + const sel = s.selection.?; + try testing.expect(s.pages.pointFromPin(.active, sel.start()) == null); + try testing.expect(s.pages.pointFromPin(.active, sel.end()) == null); + } +} + +test "Screen: scrolling moves viewport" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n"); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + s.scroll(.{ .delta_row = -2 }); + + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL\n1ABCD", contents); + } + + { + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, s.pages.getTopLeft(.viewport))); + } +} + +test "Screen: scrolling when viewport is pruned" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 215, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + + // Write some to create scrollback and move back into our scrollback. + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n"); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + s.scroll(.{ .delta_row = -2 }); + + // Our viewport is now somewhere pinned. Create so much scrollback + // that we prune it. + try s.testWriteString("\n"); + for (0..1000) |_| try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n"); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + { + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, s.pages.getTopLeft(.viewport))); + } +} + +test "Screen: scroll and clear full screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } + + try s.scrollClear(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } +} + +test "Screen: scroll and clear partial screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH"); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } + + try s.scrollClear(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } +} + +test "Screen: scroll and clear empty screen" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + try s.scrollClear(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } +} + +test "Screen: scroll and clear ignore blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH"); + try s.scrollClear(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + + // Move back to top-left + s.cursorAbsolute(0, 0); + + // Write and clear + try s.testWriteString("3ABCD\n"); + { + const contents = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("3ABCD", contents); + } + + try s.scrollClear(); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + + // Move back to top-left + s.cursorAbsolute(0, 0); + try s.testWriteString("X"); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3ABCD\nX", contents); + } +} + +test "Screen: scroll above same page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + s.cursorAbsolute(0, 1); + s.pages.clearDirty(); + + // At this point: + // +-------------+ ACTIVE + // +----------+ : = PAGE 0 + // 0 |1ABCD00000| | 0 + // 1 |2EFGH00000| | 1 + // :^ : : = PIN 0 + // 2 |3IJKL00000| | 2 + // +----------+ : + // +-------------+ + + try s.cursorScrollAbove(); + + // +----------+ = PAGE 0 + // 0 |1ABCD00000| + // +-------------+ ACTIVE + // 1 |2EFGH00000| | 0 + // 2 | | | 1 + // :^ : : = PIN 0 + // 3 |3IJKL00000| | 2 + // +----------+ : + // +-------------+ + + // try s.pages.diagram(std.io.getStdErr().writer()); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n\n3IJKL", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Page 0 row 1 (active row 0) is dirty because the cursor moved off of it. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + // Page 0 row 2 (active row 1) is dirty because it was cleared. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + // Page 0 row 3 (active row 2) is dirty because it's new. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); +} + +test "Screen: scroll above same page but cursor on previous page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 10 }); + defer s.deinit(); + + // We need to get the cursor to a new page + const first_page_size = s.pages.pages.first.?.data.capacity.rows; + s.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 3) |_| try s.testWriteString("\n"); + s.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1A\n2B\n3C\n4D\n5E"); + s.cursorAbsolute(0, 1); + s.pages.clearDirty(); + + // Ensure we're still on the first page and have a second + try testing.expect(s.cursor.page_pin.node == s.pages.pages.first.?); + try testing.expect(s.pages.pages.first.?.next != null); + + // At this point: + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4305 |1A00000000| | 0 + // 4306 |2B00000000| | 1 + // :^ : : = PIN 0 + // 4307 |3C00000000| | 2 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |4D00000000| | 3 + // 1 |5E00000000| | 4 + // +----------+ : + // +-------------+ + + try s.cursorScrollAbove(); + + // +----------+ = PAGE 0 + // ... : : + // 4305 |1A00000000| + // +-------------+ ACTIVE + // 4306 |2B00000000| | 0 + // 4307 | | | 1 + // :^ : : = PIN 0 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |3C00000000| | 2 + // 1 |4D00000000| | 3 + // 2 |5E00000000| | 4 + // +----------+ : + // +-------------+ + + // try s.pages.diagram(std.io.getStdErr().writer()); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2B\n\n3C\n4D\n5E", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Page 0's penultimate row is dirty because the cursor moved off of it. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + // The rest of the rows are dirty because they've been modified or are new. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); +} + +test "Screen: scroll above same page but cursor on previous page last row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 10 }); + defer s.deinit(); + + // We need to get the cursor to a new page + const first_page_size = s.pages.pages.first.?.data.capacity.rows; + s.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 2) |_| try s.testWriteString("\n"); + s.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1A\n2B\n3C\n4D\n5E"); + s.cursorAbsolute(0, 1); + s.pages.clearDirty(); + + // Ensure we're still on the first page and have a second + try testing.expect(s.cursor.page_pin.node == s.pages.pages.first.?); + try testing.expect(s.pages.pages.first.?.next != null); + + // At this point: + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4306 |1A00000000| | 0 + // 4307 |2B00000000| | 1 + // :^ : : = PIN 0 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |3C00000000| | 2 + // 1 |4D00000000| | 3 + // 2 |5E00000000| | 4 + // +----------+ : + // +-------------+ + + try s.cursorScrollAbove(); + + // +----------+ = PAGE 0 + // ... : : + // 4306 |1A00000000| + // +-------------+ ACTIVE + // 4307 |2B00000000| | 0 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 | | | 1 + // :^ : : = PIN 0 + // 1 |3C00000000| | 2 + // 2 |4D00000000| | 3 + // 3 |5E00000000| | 4 + // +----------+ : + // +-------------+ + + // try s.pages.diagram(std.io.getStdErr().writer()); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2B\n\n3C\n4D\n5E", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Page 0's final row is dirty because the cursor moved off of it. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + // Page 1's rows are all dirty because every row was moved. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + // Attempt to clear the style from the cursor and + // then assert the integrity of both of our pages. + // + // This catches a case of memory corruption where the cursor + // is moved between pages without accounting for style refs. + try s.setAttribute(.{ .reset_bg = {} }); + s.pages.pages.first.?.data.assertIntegrity(); + s.pages.pages.last.?.data.assertIntegrity(); +} + +test "Screen: scroll above creates new page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + + // We need to get the cursor to a new page + const first_page_size = s.pages.pages.first.?.data.capacity.rows; + s.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 3) |_| try s.testWriteString("\n"); + s.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + s.cursorAbsolute(0, 1); + s.pages.clearDirty(); + + // Ensure we're still on the first page + try testing.expect(s.cursor.page_pin.node == s.pages.pages.first.?); + + // At this point: + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4305 |1ABCD00000| | 0 + // 4306 |2EFGH00000| | 1 + // :^ : : = PIN 0 + // 4307 |3IJKL00000| | 2 + // +----------+ : + // +-------------+ + try s.cursorScrollAbove(); + + // +----------+ = PAGE 0 + // ... : : + // 4305 |1ABCD00000| + // +-------------+ ACTIVE + // 4306 |2EFGH00000| | 0 + // 4307 | | | 1 + // :^ : : = PIN 0 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |3IJKL00000| | 2 + // +----------+ : + // +-------------+ + + // try s.pages.diagram(std.io.getStdErr().writer()); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n\n3IJKL", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Page 0's penultimate row is dirty because the cursor moved off of it. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + // Page 0's final row is dirty because it was cleared. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + // Page 1's row is dirty because it's new. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); +} + +test "Screen: scroll above with cursor on non-final row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 4, .max_scrollback = 10 }); + defer s.deinit(); + + // Get the cursor to be 2 rows above a new page + const first_page_size = s.pages.pages.first.?.data.capacity.rows; + s.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 3) |_| try s.testWriteString("\n"); + s.pages.pages.first.?.data.pauseIntegrityChecks(false); + + // Write 3 lines of text, forcing the last line into the first + // row of a new page. Move our cursor onto the previous page. + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1AB\n2BC\n3DE\n4FG"); + s.cursorAbsolute(0, 1); + s.pages.clearDirty(); + + // Ensure we're still on the first page. So our cursor is on the first + // page but we have two pages of data. + try testing.expect(s.cursor.page_pin.node == s.pages.pages.first.?); + + // +----------+ = PAGE 0 + // ... : : + // +-------------+ ACTIVE + // 4305 |1AB0000000| | 0 + // 4306 |2BC0000000| | 1 + // :^ : : = PIN 0 + // 4307 |3DE0000000| | 2 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |4FG0000000| | 3 + // +----------+ : + // +-------------+ + try s.cursorScrollAbove(); + + // +----------+ = PAGE 0 + // ... : : + // 4305 |1AB0000000| + // +-------------+ ACTIVE + // 4306 |2BC0000000| | 0 + // 4307 | | | 1 + // :^ : : = PIN 0 + // +----------+ : + // +----------+ : = PAGE 1 + // 0 |3DE0000000| | 2 + // 1 |4FG0000000| | 3 + // +----------+ : + // +-------------+ + // try s.pages.diagram(std.io.getStdErr().writer()); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2BC\n\n3DE\n4FG", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Page 0's penultimate row is dirty because the cursor moved off of it. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + // Page 0's final row is dirty because it was cleared. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + // Page 1's row is dirty because it's new. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); +} + +test "Screen: scroll above no scrollback bottom of page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + + const first_page_size = s.pages.pages.first.?.data.capacity.rows; + s.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 3) |_| try s.testWriteString("\n"); + s.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s.setAttribute(.{ .direct_color_bg = .{ .r = 155 } }); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + s.cursorAbsolute(0, 1); + s.pages.clearDirty(); + + // At this point: + // +-------------+ ACTIVE + // +----------+ : = PAGE 0 + // 0 |1ABCD00000| | 0 + // 1 |2EFGH00000| | 1 + // :^ : : = PIN 0 + // 2 |3IJKL00000| | 2 + // +----------+ : + // +-------------+ + + try s.cursorScrollAbove(); + + // +----------+ = PAGE 0 + // 0 |1ABCD00000| + // +-------------+ ACTIVE + // 1 |2EFGH00000| | 0 + // 2 | | | 1 + // :^ : : = PIN 0 + // 3 |3IJKL00000| | 2 + // +----------+ : + // +-------------+ + + //try s.pages.diagram(std.io.getStdErr().writer()); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n\n3IJKL", contents); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expect(cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 155, + .g = 0, + .b = 0, + }, cell.content.color_rgb); + } + + // Page 0 row 1 (active row 0) is dirty because the cursor moved off of it. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + // Page 0 row 2 (active row 1) is dirty because it was cleared. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + // Page 0 row 3 (active row 2) is dirty because it is new. + try testing.expect(s.pages.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); +} + +test "Screen: clone" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH"); + { + const contents = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } + try testing.expectEqual(@as(usize, 5), s.cursor.x); + try testing.expectEqual(@as(usize, 1), s.cursor.y); + + // Clone + var s2 = try s.clone(alloc, .{ .active = .{} }, null); + defer s2.deinit(); + { + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } + try testing.expectEqual(@as(usize, 5), s2.cursor.x); + try testing.expectEqual(@as(usize, 1), s2.cursor.y); + + // Write to s1, should not be in s2 + try s.testWriteString("\n34567"); + { + const contents = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n34567", contents); + } + { + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } + try testing.expectEqual(@as(usize, 5), s2.cursor.x); + try testing.expectEqual(@as(usize, 1), s2.cursor.y); +} + +test "Screen: clone partial" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH"); + { + const contents = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } + try testing.expectEqual(@as(usize, 5), s.cursor.x); + try testing.expectEqual(@as(usize, 1), s.cursor.y); + + // Clone + var s2 = try s.clone(alloc, .{ .active = .{ .y = 1 } }, null); + defer s2.deinit(); + { + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH", contents); + } + + // Cursor is shifted since we cloned partial + try testing.expectEqual(@as(usize, 5), s2.cursor.x); + try testing.expectEqual(@as(usize, 0), s2.cursor.y); +} + +test "Screen: clone partial cursor out of bounds" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH"); + { + const contents = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH", contents); + } + try testing.expectEqual(@as(usize, 5), s.cursor.x); + try testing.expectEqual(@as(usize, 1), s.cursor.y); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = 0 } }, + ); + defer s2.deinit(); + { + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD", contents); + } + + // Cursor is shifted since we cloned partial + try testing.expectEqual(@as(usize, 0), s2.cursor.x); + try testing.expectEqual(@as(usize, 0), s2.cursor.y); +} + +test "Screen: clone contains full selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Select a single line + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + s.pages.pin(.{ .active = .{ .x = s.pages.cols - 1, .y = 1 } }).?, + false, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{} }, + null, + ); + defer s2.deinit(); + + // Our selection should remain valid + { + const sel = s2.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, s2.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s2.pages.cols - 1, + .y = 1, + } }, s2.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: clone contains none of selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Select a single line + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = s.pages.cols - 1, .y = 0 } }).?, + false, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 1 } }, + null, + ); + defer s2.deinit(); + + // Our selection should be null + try testing.expect(s2.selection == null); +} + +test "Screen: clone contains selection start cutoff" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Select a single line + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = s.pages.cols - 1, .y = 1 } }).?, + false, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 1 } }, + null, + ); + defer s2.deinit(); + + // Our selection should remain valid + { + const sel = s2.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s2.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s2.pages.cols - 1, + .y = 0, + } }, s2.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: clone contains selection end cutoff" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Select a single line + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + s.pages.pin(.{ .active = .{ .x = 2, .y = 2 } }).?, + false, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = 1 } }, + ); + defer s2.deinit(); + + // Our selection should remain valid + { + const sel = s2.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, s2.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s2.pages.cols - 1, + .y = 2, + } }, s2.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: clone contains selection end cutoff reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + // Select a single line + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 2, .y = 2 } }).?, + s.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + false, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = 1 } }, + ); + defer s2.deinit(); + + // Our selection should remain valid + { + const sel = s2.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, s2.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s2.pages.cols - 1, + .y = 2, + } }, s2.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: clone contains subset of selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 4, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n4ABCD"); + + // Select the full screen + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = 0, .y = 3 } }).?, + false, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 1 } }, + .{ .active = .{ .y = 2 } }, + ); + defer s2.deinit(); + + // Our selection should remain valid + { + const sel = s2.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s2.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = s2.pages.cols - 1, + .y = 3, + } }, s2.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: clone contains subset of rectangle selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 4, .max_scrollback = 1 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n4ABCD"); + + // Select the full screen from x=1 to x=3 + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 1, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = 3, .y = 3 } }).?, + true, + )); + + // Clone + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 1 } }, + .{ .active = .{ .y = 2 } }, + ); + defer s2.deinit(); + + // Our selection should remain valid and be properly clipped + // preserving the columns of the start and end points of the + // selection. + { + const sel = s2.selection.?; + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s2.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 3, + } }, s2.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: clone basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL"); + + { + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 1 } }, + .{ .active = .{ .y = 1 } }, + ); + defer s2.deinit(); + + // Test our contents rotated + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH", contents); + } + + { + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 1 } }, + .{ .active = .{ .y = 2 } }, + ); + defer s2.deinit(); + + // Test our contents rotated + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } +} + +test "Screen: clone empty viewport" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + + { + var s2 = try s.clone( + alloc, + .{ .viewport = .{ .y = 0 } }, + .{ .viewport = .{ .y = 0 } }, + ); + defer s2.deinit(); + + // Test our contents rotated + const contents = try s2.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } +} + +test "Screen: clone one line viewport" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1ABC"); + + { + var s2 = try s.clone( + alloc, + .{ .viewport = .{ .y = 0 } }, + .{ .viewport = .{ .y = 0 } }, + ); + defer s2.deinit(); + + // Test our contents + const contents = try s2.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABC", contents); + } +} + +test "Screen: clone empty active" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + + { + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = 0 } }, + ); + defer s2.deinit(); + + // Test our contents rotated + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } +} + +test "Screen: clone one line active with extra space" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1ABC"); + + { + var s2 = try s.clone( + alloc, + .{ .active = .{ .y = 0 } }, + null, + ); + defer s2.deinit(); + + // Test our contents rotated + const contents = try s2.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABC", contents); + } +} + +test "Screen: clear history with no history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + try s.testWriteString("4ABCD\n5EFGH\n6IJKL"); + try testing.expect(s.pages.viewport == .active); + s.eraseHistory(null); + try testing.expect(s.pages.viewport == .active); + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("4ABCD\n5EFGH\n6IJKL", contents); + } + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("4ABCD\n5EFGH\n6IJKL", contents); + } +} + +test "Screen: clear history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH\n6IJKL"); + try testing.expect(s.pages.viewport == .active); + + // Scroll to top + s.scroll(.{ .top = {} }); + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL", contents); + } + + s.eraseHistory(null); + try testing.expect(s.pages.viewport == .active); + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("4ABCD\n5EFGH\n6IJKL", contents); + } + { + // Test our contents rotated + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("4ABCD\n5EFGH\n6IJKL", contents); + } +} + +test "Screen: clear above cursor" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 3 }); + defer s.deinit(); + try s.testWriteString("4ABCD\n5EFGH\n6IJKL"); + s.clearRows( + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = s.cursor.y - 1 } }, + false, + ); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("\n\n6IJKL", contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("\n\n6IJKL", contents); + } + + try testing.expectEqual(@as(usize, 5), s.cursor.x); + try testing.expectEqual(@as(usize, 2), s.cursor.y); +} + +test "Screen: clear above cursor with history" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + try s.testWriteString("1ABCD\n2EFGH\n3IJKL\n"); + try s.testWriteString("4ABCD\n5EFGH\n6IJKL"); + s.clearRows( + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = s.cursor.y - 1 } }, + false, + ); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("\n\n6IJKL", contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD\n2EFGH\n3IJKL\n\n\n6IJKL", contents); + } + + try testing.expectEqual(@as(usize, 5), s.cursor.x); + try testing.expectEqual(@as(usize, 2), s.cursor.y); +} + +test "Screen: resize (no reflow) more rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + // Resize + try s.resize(.{ .cols = 10, .rows = 10, .reflow = false }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize (no reflow) less rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + try testing.expectEqual(5, s.cursor.x); + try testing.expectEqual(2, s.cursor.y); + try s.resize(.{ .cols = 10, .rows = 2, .reflow = false }); + + // Since we shrunk, we should adjust our cursor + try testing.expectEqual(5, s.cursor.x); + try testing.expectEqual(1, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2EFGH\n3IJKL", contents); + } +} + +test "Screen: resize (no reflow) less rows trims blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD"; + try s.testWriteString(str); + + // Write only a background color into the remaining rows + for (1..s.pages.rows) |y| { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } }).?; + list_cell.cell.* = .{ + .content_tag = .bg_color_rgb, + .content = .{ .color_rgb = .{ .r = 0xFF, .g = 0, .b = 0 } }, + }; + } + + const cursor = s.cursor; + try s.resize(.{ .cols = 6, .rows = 2, .reflow = false }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD", contents); + } +} + +test "Screen: resize (no reflow) more rows trims blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD"; + try s.testWriteString(str); + + // Write only a background color into the remaining rows + for (1..s.pages.rows) |y| { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } }).?; + list_cell.cell.* = .{ + .content_tag = .bg_color_rgb, + .content = .{ .color_rgb = .{ .r = 0xFF, .g = 0, .b = 0 } }, + }; + } + + const cursor = s.cursor; + try s.resize(.{ .cols = 10, .rows = 7, .reflow = false }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD", contents); + } +} + +test "Screen: resize (no reflow) more cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + try s.resize(.{ .cols = 20, .rows = 3, .reflow = false }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize (no reflow) less cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + try s.resize(.{ .cols = 4, .rows = 3, .reflow = false }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABC\n2EFG\n3IJK"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize (no reflow) more rows with scrollback cursor end" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 7, .rows = 3, .max_scrollback = 2 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + try s.resize(.{ .cols = 7, .rows = 10, .reflow = false }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize (no reflow) less rows with scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 7, .rows = 3, .max_scrollback = 2 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + try s.resize(.{ .cols = 7, .rows = 2, .reflow = false }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +// https://github.com/mitchellh/ghostty/issues/1030 +test "Screen: resize (no reflow) less rows with empty trailing" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1\n2\n3\n4\n5\n6\n7\n8"; + try s.testWriteString(str); + try s.scrollClear(); + s.cursorAbsolute(0, 0); + try s.testWriteString("A\nB"); + + const cursor = s.cursor; + try s.resize(.{ .cols = 5, .rows = 2, .reflow = false }); + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("A\nB", contents); + } +} + +test "Screen: resize (no reflow) more rows with soft wrapping" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + const str = "1A2B\n3C4E\n5F6G"; + try s.testWriteString(str); + + // Every second row should be wrapped + for (0..6) |y| { + const list_cell = s.pages.getCell(.{ .screen = .{ + .x = 0, + .y = @intCast(y), + } }).?; + const row = list_cell.row; + const wrapped = (y % 2 == 0); + try testing.expectEqual(wrapped, row.wrap); + } + + // Resize + try s.resize(.{ .cols = 2, .rows = 10, .reflow = false }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1A\n2B\n3C\n4E\n5F\n6G"; + try testing.expectEqualStrings(expected, contents); + } + + // Every second row should be wrapped + for (0..6) |y| { + const list_cell = s.pages.getCell(.{ .screen = .{ + .x = 0, + .y = @intCast(y), + } }).?; + const row = list_cell.row; + const wrapped = (y % 2 == 0); + try testing.expectEqual(wrapped, row.wrap); + } +} + +test "Screen: resize more rows no scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + const cursor = s.cursor; + try s.resize(.{ .cols = 5, .rows = 10 }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize more rows with empty scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + const cursor = s.cursor; + try s.resize(.{ .cols = 5, .rows = 10 }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize more rows with populated scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + // Set our cursor to be on the "4" + s.cursorAbsolute(0, 1); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '4'), list_cell.cell.content.codepoint); + } + + // Resize + try s.resize(.{ .cols = 5, .rows = 10 }); + + // Cursor should still be on the "4" + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '4'), list_cell.cell.content.codepoint); + } + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize more cols no reflow" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + const cursor = s.cursor; + try s.resize(.{ .cols = 10, .rows = 3 }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +// https://github.com/mitchellh/ghostty/issues/272#issuecomment-1676038963 +test "Screen: resize more cols perfect split" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH3IJKL"; + try s.testWriteString(str); + try s.resize(.{ .cols = 10, .rows = 3 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("1ABCD2EFGH\n3IJKL", contents); + } +} + +// https://github.com/mitchellh/ghostty/issues/1159 +test "Screen: resize (no reflow) more cols with scrollback scrolled up" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1\n2\n3\n4\n5\n6\n7\n8"; + try s.testWriteString(str); + + // Cursor at bottom + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); + + s.scroll(.{ .delta_row = -4 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2\n3\n4", contents); + } + + try s.resize(.{ .cols = 8, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + + // Cursor remains at bottom + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); +} + +// https://github.com/mitchellh/ghostty/issues/1159 +test "Screen: resize (no reflow) less cols with scrollback scrolled up" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1\n2\n3\n4\n5\n6\n7\n8"; + try s.testWriteString(str); + + // Cursor at bottom + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); + + s.scroll(.{ .delta_row = -4 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("2\n3\n4", contents); + } + + try s.resize(.{ .cols = 4, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .active = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("6\n7\n8", contents); + } + + // Cursor remains at bottom + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); + + // Old implementation doesn't do this but it makes sense to me: + // { + // const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + // defer alloc.free(contents); + // try testing.expectEqualStrings("2\n3\n4", contents); + // } +} + +test "Screen: resize more cols no reflow preserves semantic prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + + // Set one of the rows to be a prompt + s.cursorSetSemanticContent(.output); + try s.testWriteString("1ABCD\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("2EFGH"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("\n3IJKL"); + + try s.resize(.{ .cols = 10, .rows = 3, .reflow = false }); + + const expected = "1ABCD\n2EFGH\n3IJKL"; + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(expected, contents); + } + + // Our one row should still be a semantic prompt, the others should not. + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.row.semantic_prompt == .none); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 1 } }).?; + try testing.expect(list_cell.row.semantic_prompt == .prompt); + } + { + const list_cell = s.pages.getCell(.{ .active = .{ .x = 0, .y = 2 } }).?; + try testing.expect(list_cell.row.semantic_prompt == .none); + } +} + +test "Screen: resize more cols with reflow that fits full width" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH\n3IJKL"; + try s.testWriteString(str); + + // Verify we soft wrapped + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABCD\n2EFGH\n3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Let's put our cursor on row 2, where the soft wrap is + s.cursorAbsolute(0, 1); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '2'), list_cell.cell.content.codepoint); + } + + // Resize and verify we undid the soft wrap because we have space now + try s.resize(.{ .cols = 10, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + + // Our cursor should've moved + try testing.expectEqual(@as(usize, 5), s.cursor.x); + try testing.expectEqual(@as(usize, 0), s.cursor.y); +} + +test "Screen: resize more cols with reflow that ends in newline" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 6, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH\n3IJKL"; + try s.testWriteString(str); + + // Verify we soft wrapped + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABCD2\nEFGH\n3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Let's put our cursor on the last row + s.cursorAbsolute(0, 2); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '3'), list_cell.cell.content.codepoint); + } + + // Resize and verify we undid the soft wrap because we have space now + try s.resize(.{ .cols = 10, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + + // Our cursor should still be on the 3 + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '3'), list_cell.cell.content.codepoint); + } +} + +test "Screen: resize more cols with reflow that forces more wrapping" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH\n3IJKL"; + try s.testWriteString(str); + + // Let's put our cursor on row 2, where the soft wrap is + s.cursorAbsolute(0, 1); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '2'), list_cell.cell.content.codepoint); + } + + // Verify we soft wrapped + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABCD\n2EFGH\n3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Resize and verify we undid the soft wrap because we have space now + try s.resize(.{ .cols = 7, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABCD2E\nFGH\n3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Our cursor should've moved + try testing.expectEqual(@as(size.CellCountInt, 5), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 0), s.cursor.y); +} + +test "Screen: resize more cols with reflow that unwraps multiple times" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH3IJKL"; + try s.testWriteString(str); + + // Let's put our cursor on row 2, where the soft wrap is + s.cursorAbsolute(0, 2); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '3'), list_cell.cell.content.codepoint); + } + + // Verify we soft wrapped + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABCD\n2EFGH\n3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Resize and verify we undid the soft wrap because we have space now + try s.resize(.{ .cols = 15, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1ABCD2EFGH3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Our cursor should've moved + try testing.expectEqual(@as(size.CellCountInt, 10), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 0), s.cursor.y); +} + +test "Screen: resize more cols with populated scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL\n4ABCD5EFGH"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + // // Set our cursor to be on the "5" + s.cursorAbsolute(0, 2); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '5'), list_cell.cell.content.codepoint); + } + + // Resize + try s.resize(.{ .cols = 10, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "2EFGH\n3IJKL\n4ABCD5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor should still be on the "5" + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u21, '5'), list_cell.cell.content.codepoint); + } +} + +test "Screen: resize more cols with reflow" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1ABC\n2DEF\n3ABC\n4DEF"; + try s.testWriteString(str); + + // Let's put our cursor on row 2, where the soft wrap is + s.cursorAbsolute(0, 2); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u32, 'E'), list_cell.cell.content.codepoint); + } + + // Verify we soft wrapped + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "BC\n4D\nEF"; + try testing.expectEqualStrings(expected, contents); + } + + // Resize and verify we undid the soft wrap because we have space now + try s.resize(.{ .cols = 7, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "1ABC\n2DEF\n3ABC\n4DEF"; + try testing.expectEqualStrings(expected, contents); + } + + // Our cursor should've moved + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); +} + +test "Screen: resize more rows and cols with wrapping" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 4, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1A2B\n3C4D"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1A\n2B\n3C\n4D"; + try testing.expectEqualStrings(expected, contents); + } + + try s.resize(.{ .cols = 5, .rows = 10 }); + + // Cursor should move due to wrapping + try testing.expectEqual(@as(size.CellCountInt, 3), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize less rows no scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + s.cursorAbsolute(0, 0); + const cursor = s.cursor; + try s.resize(.{ .cols = 5, .rows = 1 }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "3IJKL"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less rows moving cursor" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + // Put our cursor on the last line + s.cursorAbsolute(1, 2); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u32, 'I'), list_cell.cell.content.codepoint); + } + + // Resize + try s.resize(.{ .cols = 5, .rows = 1 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "3IJKL"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor should be on the last line + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 0), s.cursor.y); +} + +test "Screen: resize less rows with empty scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + try s.resize(.{ .cols = 5, .rows = 1 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less rows with populated scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + // Resize + try s.resize(.{ .cols = 5, .rows = 1 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "5EFGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less rows with full scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + const str = "00000\n1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + try testing.expectEqual(@as(size.CellCountInt, 4), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); + + // Resize + try s.resize(.{ .cols = 5, .rows = 2 }); + + // Cursor should stay in the same relative place (bottom of the + // screen, same character). + try testing.expectEqual(@as(size.CellCountInt, 4), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "00000\n1ABCD\n2EFGH\n3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less cols no reflow" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1AB\n2EF\n3IJ"; + try s.testWriteString(str); + + s.cursorAbsolute(0, 0); + const cursor = s.cursor; + try s.resize(.{ .cols = 3, .rows = 3 }); + + // Cursor should not move + try testing.expectEqual(cursor.x, s.cursor.x); + try testing.expectEqual(cursor.y, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize less cols with reflow but row space" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + const str = "1ABCD"; + try s.testWriteString(str); + + // Put our cursor on the end + s.cursorAbsolute(4, 0); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u32, 'D'), list_cell.cell.content.codepoint); + } + + try s.resize(.{ .cols = 3, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "1AB\nCD"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "1AB\nCD"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor should be on the last line + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.y); +} + +test "Screen: resize less cols with reflow with trimmed rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + try s.resize(.{ .cols = 3, .rows = 3 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "CD\n5EF\nGH"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "CD\n5EF\nGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less cols with reflow with trimmed rows and scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + const str = "3IJKL\n4ABCD\n5EFGH"; + try s.testWriteString(str); + try s.resize(.{ .cols = 3, .rows = 3 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "CD\n5EF\nGH"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "3IJ\nKL\n4AB\nCD\n5EF\nGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less cols with reflow previously wrapped" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "3IJKL4ABCD5EFGH"; + try s.testWriteString(str); + + // Check + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + try s.resize(.{ .cols = 3, .rows = 3 }); + + // { + // const contents = try s.testString(alloc, .viewport); + // defer alloc.free(contents); + // const expected = "CD\n5EF\nGH"; + // try testing.expectEqualStrings(expected, contents); + // } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "ABC\nD5E\nFGH"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize less cols with reflow and scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1A\n2B\n3C\n4D\n5E"; + try s.testWriteString(str); + + // Put our cursor on the end + s.cursorAbsolute(1, s.pages.rows - 1); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u32, 'E'), list_cell.cell.content.codepoint); + } + + try s.resize(.{ .cols = 3, .rows = 3 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3C\n4D\n5E"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor should be on the last line + try testing.expectEqual(@as(size.CellCountInt, 1), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); +} + +test "Screen: resize less cols with reflow previously wrapped and scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 2 }); + defer s.deinit(); + const str = "1ABCD2EFGH3IJKL4ABCD5EFGH"; + try s.testWriteString(str); + + // Check + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "3IJKL\n4ABCD\n5EFGH"; + try testing.expectEqualStrings(expected, contents); + } + + // Put our cursor on the end + s.cursorAbsolute(s.pages.cols - 1, s.pages.rows - 1); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u32, 'H'), list_cell.cell.content.codepoint); + } + + try s.resize(.{ .cols = 3, .rows = 3 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "CD5\nEFG\nH"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "1AB\nCD2\nEFG\nH3I\nJKL\n4AB\nCD5\nEFG\nH"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor should be on the last line + try testing.expectEqual(@as(size.CellCountInt, 0), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 2), s.cursor.y); + { + const list_cell = s.pages.getCell(.{ .active = .{ + .x = s.cursor.x, + .y = s.cursor.y, + } }).?; + try testing.expectEqual(@as(u32, 'H'), list_cell.cell.content.codepoint); + } +} + +test "Screen: resize less cols with scrollback keeps cursor row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + const str = "1A\n2B\n3C\n4D\n5E"; + try s.testWriteString(str); + + // Lets do a scroll and clear operation + try s.scrollClear(); + + // Move our cursor to the beginning + s.cursorAbsolute(0, 0); + + try s.resize(.{ .cols = 3, .rows = 3 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = ""; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor should be on the last line + try testing.expectEqual(@as(size.CellCountInt, 0), s.cursor.x); + try testing.expectEqual(@as(size.CellCountInt, 0), s.cursor.y); +} + +test "Screen: resize more rows, less cols with reflow with scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 3 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH3IJKL\n4MNOP"; + try s.testWriteString(str); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "1ABCD\n2EFGH\n3IJKL\n4MNOP"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "2EFGH\n3IJKL\n4MNOP"; + try testing.expectEqualStrings(expected, contents); + } + + try s.resize(.{ .cols = 2, .rows = 10 }); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "BC\nD\n2E\nFG\nH3\nIJ\nKL\n4M\nNO\nP"; + try testing.expectEqualStrings(expected, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + const expected = "1A\nBC\nD\n2E\nFG\nH3\nIJ\nKL\n4M\nNO\nP"; + try testing.expectEqualStrings(expected, contents); + } +} + +// This seems like it should work fine but for some reason in practice +// in the initial implementation I found this bug! This is a regression +// test for that. +test "Screen: resize more rows then shrink again" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 10 }); + defer s.deinit(); + const str = "1ABC"; + try s.testWriteString(str); + + // Grow + try s.resize(.{ .cols = 5, .rows = 10 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + + // Shrink + try s.resize(.{ .cols = 5, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + + // Grow again + try s.resize(.{ .cols = 5, .rows = 10 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } +} + +test "Screen: resize less cols to eliminate wide char" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 1, .max_scrollback = 0 }); + defer s.deinit(); + const str = "😀"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expectEqual(@as(u21, '😀'), cell.content.codepoint); + } + + // Resize to 1 column can't fit a wide char. So it should be deleted. + try s.resize(.{ .cols = 1, .rows = 1 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Screen: resize less cols to wrap wide char" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 3, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "x😀"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expectEqual(@as(u21, '😀'), cell.content.codepoint); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + try s.resize(.{ .cols = 2, .rows = 3 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("x\n😀", contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + try testing.expect(list_cell.row.wrap); + } +} + +test "Screen: resize less cols to eliminate wide char with row space" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 2, .max_scrollback = 0 }); + defer s.deinit(); + const str = "😀"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expectEqual(@as(u21, '😀'), cell.content.codepoint); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + try s.resize(.{ .cols = 1, .rows = 2 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("", contents); + } +} + +test "Screen: resize more cols with wide spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 3, .rows = 2, .max_scrollback = 0 }); + defer s.deinit(); + const str = " 😀"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(" \n😀", contents); + } + + // So this is the key point: we end up with a wide spacer head at + // the end of row 1, then the emoji, then a wide spacer tail on row 2. + // We should expect that if we resize to more cols, the wide spacer + // head is replaced with the emoji. + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + try s.resize(.{ .cols = 4, .rows = 2 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expectEqual(@as(u21, '😀'), cell.content.codepoint); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 3, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Screen: resize more cols with wide spacer head multiple lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 3, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "xxxyy😀"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("xxx\nyy\n😀", contents); + } + + // Similar to the "wide spacer head" test, but this time we'er going + // to increase our columns such that multiple rows are unwrapped. + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 2, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 2 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 2 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + try s.resize(.{ .cols = 8, .rows = 2 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(str, contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 5, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expectEqual(@as(u21, '😀'), cell.content.codepoint); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 6, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Screen: resize more cols requiring a wide spacer head" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 2, .max_scrollback = 0 }); + defer s.deinit(); + const str = "xx😀"; + try s.testWriteString(str); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("xx\n😀", contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + // This resizes to 3 columns, which isn't enough space for our wide + // char to enter row 1. But we need to mark the wide spacer head on the + // end of the first row since we're wrapping to the next row. + try s.resize(.{ .cols = 3, .rows = 2 }); + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("xx\n😀", contents); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expectEqual(@as(u21, '😀'), cell.content.codepoint); + } + { + const list_cell = s.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Screen: resize more cols with cursor at prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + + // zig fmt: off + try s.testWriteString("ABCDE\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_eol }); + try s.testWriteString("echo"); + // zig fmt: on + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "ABCDE\n> echo"; + try testing.expectEqualStrings(expected, contents); + } + + try s.resize(.{ + .cols = 20, + .rows = 3, + .prompt_redraw = .true, + }); + + // Cursor should not move + try testing.expectEqual(6, s.cursor.x); + try testing.expectEqual(1, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "ABCDE"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize more cols with cursor not at prompt" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + + // zig fmt: off + try s.testWriteString("ABCDE\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_eol }); + try s.testWriteString("echo\n"); + try s.testWriteString("output"); + // zig fmt: on + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "ABCDE\n> echo\noutput"; + try testing.expectEqualStrings(expected, contents); + } + + try s.resize(.{ + .cols = 20, + .rows = 3, + .prompt_redraw = .true, + }); + + // Cursor should not move + try testing.expectEqual(6, s.cursor.x); + try testing.expectEqual(2, s.cursor.y); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "ABCDE\n> echo\noutput"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize with prompt_redraw last clears only one line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 4, .max_scrollback = 5 }); + defer s.deinit(); + + // zig fmt: off + try s.testWriteString("ABCDE\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello\n"); + try s.testWriteString("world"); + // zig fmt: on + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "ABCDE\n> hello\nworld"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor is at end of "world" line with semantic_content = .input + try s.resize(.{ + .cols = 20, + .rows = 4, + .prompt_redraw = .last, + }); + + // With .last, only the current line where cursor is should be cleared + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "ABCDE\n> hello"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: resize with prompt_redraw last multiline prompt clears only last line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 5 }); + defer s.deinit(); + + // Create a 3-line prompt: 1 initial + 2 continuation lines + // zig fmt: off + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("line1\n"); + s.cursorSetSemanticContent(.{ .prompt = .continuation }); + try s.testWriteString("line2\n"); + s.cursorSetSemanticContent(.{ .prompt = .continuation }); + try s.testWriteString("line3"); + // zig fmt: on + + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "line1\nline2\nline3"; + try testing.expectEqualStrings(expected, contents); + } + + // Cursor is at end of line3 (the last continuation line) + try s.resize(.{ + .cols = 30, + .rows = 5, + .prompt_redraw = .last, + }); + + // With .last, only line3 (where cursor is) should be cleared + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + const expected = "line1\nline2"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: select untracked" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("ABC DEF\n 123\n456"); + + try testing.expect(s.selection == null); + const tracked = s.pages.countTrackedPins(); + try s.select(Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = 3, .y = 0 } }).?, + false, + )); + try testing.expectEqual(tracked + 2, s.pages.countTrackedPins()); + try s.select(null); + try testing.expectEqual(tracked, s.pages.countTrackedPins()); +} + +test "Screen: selectAll" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + { + try s.testWriteString("ABC DEF\n 123\n456"); + var sel = s.selectAll().?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + { + try s.testWriteString("\nFOO\n BAR\n BAZ\n QWERTY\n 12345678"); + var sel = s.selectAll().?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 8, + .y = 7, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectLine" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("ABC DEF\n 123\n456"); + + // Outside of active area + // try testing.expect(s.selectLine(.{ .x = 13, .y = 0 }) == null); + // try testing.expect(s.selectLine(.{ .x = 0, .y = 5 }) == null); + + // Going forward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 0, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going backward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 7, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going forward and backward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Outside active area + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 9, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectLine across soft-wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString(" 12 34012 \n 123"); + + // Going forward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectLine across full soft-wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1ABCD2EFGH\n3IJKL"); + + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectLine across soft-wrap ignores blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString(" 12 34012 \n 123"); + + // Going forward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going backward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going forward and backward + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectLine disabled whitespace trimming" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString(" 12 34012 \n 123"); + + // Going forward + { + var sel = s.selectLine(.{ + .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).?, + .whitespace = null, + }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Non-wrapped + { + var sel = s.selectLine(.{ + .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 3, + } }).?, + .whitespace = null, + }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectLine with scrollback" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 2, .rows = 3, .max_scrollback = 5 }); + defer s.deinit(); + try s.testWriteString("1A\n2B\n3C\n4D\n5E"); + + // Selecting first line + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 0, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + // Selecting last line + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 0, + .y = 2, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 2, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } +} + +// https://github.com/mitchellh/ghostty/issues/1329 +test "Screen: selectLine semantic prompt boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("ABCDE\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("A "); + s.cursorSetSemanticContent(.output); + try s.testWriteString("> "); + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("ABCDE\nA \n> ", contents); + } + + // Selecting output stops at the prompt even if soft-wrapped + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + const expected = "A"; + try testing.expectEqualStrings(expected, contents); + } + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 2, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: selectLine semantic prompt to input boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Write prompt followed by user input on same row: "$>command" + // Using non-whitespace to avoid whitespace trimming affecting the test + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("$>"); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("command"); + + // Selecting from prompt should only select prompt + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 0, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + // Selecting from input should only select input + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 5, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 8, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: selectLine semantic input to output boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Row 0: user input + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("ls -la\n"); + // Row 1: command output + s.cursorSetSemanticContent(.output); + try s.testWriteString("file.txt"); + + // Selecting from input should only select input + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("ls -la", contents); + } + + // Selecting from output should only select output + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("file.txt", contents); + } +} + +test "Screen: selectLine semantic mid-row boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Single row with output then prompt then input: "out$>cmd" + // Using non-whitespace to avoid whitespace trimming affecting the test + s.cursorSetSemanticContent(.output); + try s.testWriteString("out"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("$>"); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("cmd"); + + // Selecting from output should stop at prompt + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + // Selecting from prompt should only select prompt + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + // Selecting from input should only select input + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 6, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 5, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: selectLine semantic boundary soft-wrap with mid-row transition" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Row 0: prompt "$ " + input "cmd" (soft-wraps) + // Row 1: input continues "12" + output "out" + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("$ "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("cmd12"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("out"); + + // Verify layout + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("$ cmd\n12out", contents); + } + + // Selecting from input on row 0 should get all input across soft-wrap + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("cmd12", contents); + } + + // Selecting from input on row 1 should get all input across soft-wrap + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 0, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("cmd12", contents); + } + + // Selecting from output should only get output + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 3, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("out", contents); + } +} + +test "Screen: selectLine semantic boundary disabled" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Write prompt followed by input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("$ "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("command"); + + // With semantic_prompt_boundary = false, should select entire line + { + var sel = s.selectLine(.{ + .pin = s.pages.pin(.{ .active = .{ + .x = 0, + .y = 0, + } }).?, + .semantic_prompt_boundary = false, + }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("$ command", contents); + } +} + +test "Screen: selectLine semantic boundary first cell of row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Row 0: input that soft-wraps + // Row 1: output starts at first cell + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("12345"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("ABCDE"); + + // Verify soft-wrap happened + { + const pin = s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?; + const row = pin.rowAndCell().row; + try testing.expect(row.wrap); + } + + // Selecting from input should stop before output on row 1 + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 0, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + + // Selecting from output should only get output + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 4, + .y = 1, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } +} + +test "Screen: selectLine semantic all same content" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // All prompt content that soft-wraps + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("prompt text"); + + // Verify soft-wrap + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("promp\nt tex\nt", contents); + } + + // Should select all prompt content across soft-wraps + { + var sel = s.selectLine(.{ .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 1, + } }).? }).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("prompt text", contents); + } +} + +test "Screen: selectWord" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("ABC DEF\n 123\n456"); + + // Default boundary codepoints for word selection + const boundary_codepoints = &[_]u21{ + 0, ' ', '\t', '\'', '"', '│', '`', '|', ':', ';', + ',', '(', ')', '[', ']', '{', '}', '<', '>', '$', + }; + + // Outside of active area + // try testing.expect(s.selectWord(.{ .x = 9, .y = 0 }) == null); + // try testing.expect(s.selectWord(.{ .x = 0, .y = 5 }) == null); + + // Going forward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 0, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 2, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going forward and backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Whitespace + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Whitespace single char + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 0, + .y = 1, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // End of screen + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 2, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectWord across soft-wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString(" 1234012\n 123"); + + // Default boundary codepoints for word selection + const boundary_codepoints = &[_]u21{ + 0, ' ', '\t', '\'', '"', '│', '`', '|', ':', ';', + ',', '(', ')', '[', ']', '{', '}', '<', '>', '$', + }; + + { + const contents = try s.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings(" 1234\n012\n 123", contents); + } + + // Going forward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 1, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going forward and backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectWord whitespace across soft-wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("1 1\n 123"); + + // Default boundary codepoints for word selection + const boundary_codepoints = &[_]u21{ + 0, ' ', '\t', '\'', '"', '│', '`', '|', ':', ';', + ',', '(', ')', '[', ']', '{', '}', '<', '>', '$', + }; + + // Going forward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 1, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Going forward and backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Screen: selectWord with character boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + // Default boundary codepoints for word selection + const boundary_codepoints = &[_]u21{ + 0, ' ', '\t', '\'', '"', '│', '`', '|', ':', ';', + ',', '(', ')', '[', ']', '{', '}', '<', '>', '$', + }; + + const cases = [_][]const u8{ + " 'abc' \n123", + " \"abc\" \n123", + " │abc│ \n123", + " `abc` \n123", + " |abc| \n123", + " :abc: \n123", + " ;abc; \n123", + " ,abc, \n123", + " (abc( \n123", + " )abc) \n123", + " [abc[ \n123", + " ]abc] \n123", + " {abc{ \n123", + " }abc} \n123", + " abc> \n123", + " $abc$ \n123", + }; + + for (cases) |case| { + var s = try init(alloc, .{ .cols = 20, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString(case); + + // Inside character forward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 2, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Inside character backward + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 4, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Inside character bidirectional + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 3, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // On quote + // NOTE: this behavior is not ideal, so we can change this one day, + // but I think its also not that important compared to the above. + { + var sel = s.selectWord(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 0, + } }).?, boundary_codepoints).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + } +} + +test "Screen: selectOutput" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 15, .max_scrollback = 0 }); + defer s.deinit(); + + // Build content with cell-level semantic content: + // Row 0-1: output1 (output) + // Row 2: prompt2 (prompt) + // Row 3: input2 (input) + // Row 4-7: output2 (output, with overflow causing wrap) + // Row 8: "$ " (prompt) + "input3" (input) + // Row 9-11: output3 (output) + s.cursorSetSemanticContent(.output); + try s.testWriteString("output1\n"); + try s.testWriteString("output1\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("prompt2\n"); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("input2\n"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("output2output2output2output2\n"); + try s.testWriteString("output2\n"); + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("$ "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("input3\n"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("output3\n"); + try s.testWriteString("output3\n"); + try s.testWriteString("output3"); + + // First output block (rows 0-1), should select those rows + { + var sel = s.selectOutput(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 1, + } }).?).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings("output1\noutput1", contents); + } + // Second output block (rows 4-7) + { + var sel = s.selectOutput(s.pages.pin(.{ .active = .{ + .x = 3, + .y = 7, + } }).?).?; + defer sel.deinit(&s); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + try testing.expectEqualStrings( + "output2output2output2output2\noutput2", + contents, + ); + } + // Third output block (rows 9-11) + { + var sel = s.selectOutput(s.pages.pin(.{ .active = .{ + .x = 2, + .y = 10, + } }).?).?; + defer sel.deinit(&s); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 9, + } }, s.pages.pointFromPin(.active, sel.start()).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 6, + .y = 11, + } }, s.pages.pointFromPin(.active, sel.end()).?); + } + // Click on prompt should return null + { + try testing.expect(s.selectOutput(s.pages.pin(.{ .active = .{ + .x = 1, + .y = 8, + } }).?) == null); + } + // Click on input should return null + { + try testing.expect(s.selectOutput(s.pages.pin(.{ .active = .{ + .x = 5, + .y = 8, + } }).?) == null); + } +} + +test "Screen: selectionString basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "2EFGH\n3IJ"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString start outside of written area" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 5 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 6 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = ""; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString end outside of written area" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 6 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "3IJKL"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString trim space" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1AB \n2EFGH\n3IJKL"; + try s.testWriteString(str); + + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + false, + ); + + { + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "1AB\n2EF"; + try testing.expectEqualStrings(expected, contents); + } + + // No trim + { + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + const expected = "1AB \n2EF"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString trim empty line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1AB \n\n2EFGH\n3IJKL"; + try s.testWriteString(str); + + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + false, + ); + + { + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "1AB\n\n2EF"; + try testing.expectEqualStrings(expected, contents); + } + + // No trim + { + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(contents); + const expected = "1AB \n\n2EF"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString soft wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH3IJKL"; + try s.testWriteString(str); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "2EFGH3IJ"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString wide char" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1A⚡"; + try s.testWriteString(str); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 0 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = str; + try testing.expectEqualStrings(expected, contents); + } + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 0 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = str; + try testing.expectEqualStrings(expected, contents); + } + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 0 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "⚡"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString wide char with header" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 3, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABC⚡"; + try s.testWriteString(str); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 4, .y = 0 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = str; + try testing.expectEqualStrings(expected, contents); + } +} + +// https://github.com/mitchellh/ghostty/issues/289 +test "Screen: selectionString empty with soft wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 2, .max_scrollback = 0 }); + defer s.deinit(); + + // Let me describe the situation that caused this because this + // test is not obvious. By writing an emoji below, we introduce + // one cell with the emoji and one cell as a "wide char spacer". + // We then soft wrap the line by writing spaces. + // + // By selecting only the tail, we'd select nothing and we had + // a logic error that would cause a crash. + try s.testWriteString("👨"); + try s.testWriteString(" "); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 0 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "👨"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString with zero width joiner" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 1, .max_scrollback = 0 }); + defer s.deinit(); + const str = "👨‍"; // this has a ZWJ + try s.testWriteString(str); + + // Integrity check + { + const pin = s.pages.pin(.{ .screen = .{ .y = 0, .x = 0 } }).?; + const cell = pin.rowAndCell().cell; + try testing.expectEqual(@as(u21, 0x1F468), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = pin.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } + + // The real test + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "👨‍"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: selectionString, rectangle, basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 30, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + const str = + \\Lorem ipsum dolor + \\sit amet, consectetur + \\adipiscing elit, sed do + \\eiusmod tempor incididunt + \\ut labore et dolore + ; + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 6, .y = 3 } }).?, + true, + ); + const expected = + \\t ame + \\ipisc + \\usmod + ; + try s.testWriteString(str); + + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + try testing.expectEqualStrings(expected, contents); +} + +test "Screen: selectionString, rectangle, w/EOL" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 30, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + const str = + \\Lorem ipsum dolor + \\sit amet, consectetur + \\adipiscing elit, sed do + \\eiusmod tempor incididunt + \\ut labore et dolore + ; + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 12, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 26, .y = 4 } }).?, + true, + ); + const expected = + \\dolor + \\nsectetur + \\lit, sed do + \\or incididunt + \\ dolore + ; + try s.testWriteString(str); + + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + try testing.expectEqualStrings(expected, contents); +} + +test "Screen: selectionString, rectangle, more complex w/breaks" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 30, .rows = 8, .max_scrollback = 0 }); + defer s.deinit(); + const str = + \\Lorem ipsum dolor + \\sit amet, consectetur + \\adipiscing elit, sed do + \\eiusmod tempor incididunt + \\ut labore et dolore + \\ + \\magna aliqua. Ut enim + \\ad minim veniam, quis + ; + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 11, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = 26, .y = 7 } }).?, + true, + ); + const expected = + \\elit, sed do + \\por incididunt + \\t dolore + \\ + \\a. Ut enim + \\niam, quis + ; + try s.testWriteString(str); + + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + try testing.expectEqualStrings(expected, contents); +} + +test "Screen: selectionString multi-page" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 2048 }); + defer s.deinit(); + + const first_page_size = s.pages.pages.first.?.data.capacity.rows; + + // Lazy way to seek to the first page boundary. + s.pages.pages.first.?.data.pauseIntegrityChecks(true); + for (0..first_page_size - 1) |_| { + try s.testWriteString("\n"); + } + s.pages.pages.first.?.data.pauseIntegrityChecks(false); + + try s.testWriteString("123456789\n!@#$%^&*(\n123456789"); + + { + const sel = Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = 2, .y = 2 } }).?, + false, + ); + const contents = try s.selectionString(alloc, .{ + .sel = sel, + .trim = true, + }); + defer alloc.free(contents); + const expected = "123456789\n!@#$%^&*(\n123"; + try testing.expectEqualStrings(expected, contents); + } +} + +test "Screen: lineIterator" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD\n2EFGH"; + try s.testWriteString(str); + + // Test the line iterator + var iter = s.lineIterator(s.pages.pin(.{ .viewport = .{} }).?); + { + const sel = iter.next().?; + const actual = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(actual); + try testing.expectEqualStrings("1ABCD", actual); + } + { + const sel = iter.next().?; + const actual = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(actual); + try testing.expectEqualStrings("2EFGH", actual); + } +} + +test "Screen: lineIterator soft wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH\n3ABCD"; + try s.testWriteString(str); + + // Test the line iterator + var iter = s.lineIterator(s.pages.pin(.{ .viewport = .{} }).?); + { + const sel = iter.next().?; + const actual = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(actual); + try testing.expectEqualStrings("1ABCD2EFGH", actual); + } + { + const sel = iter.next().?; + const actual = try s.selectionString(alloc, .{ + .sel = sel, + .trim = false, + }); + defer alloc.free(actual); + try testing.expectEqualStrings("3ABCD", actual); + } + // try testing.expect(iter.next() == null); +} + +test "Screen: hyperlink start/end" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + try testing.expect(s.cursor.hyperlink_id == 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(0, page.hyperlink_set.count()); + } + + try s.startHyperlink("http://example.com", null); + try testing.expect(s.cursor.hyperlink_id != 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + + s.endHyperlink(); + try testing.expect(s.cursor.hyperlink_id == 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(0, page.hyperlink_set.count()); + } +} + +test "Screen: hyperlink reuse" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + try testing.expect(s.cursor.hyperlink_id == 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(0, page.hyperlink_set.count()); + } + + // Use it for the first time + try s.startHyperlink("http://example.com", null); + try testing.expect(s.cursor.hyperlink_id != 0); + const id = s.cursor.hyperlink_id; + + // Reuse the same hyperlink, expect we have the same ID + try s.startHyperlink("http://example.com", null); + try testing.expectEqual(id, s.cursor.hyperlink_id); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + + s.endHyperlink(); + try testing.expect(s.cursor.hyperlink_id == 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(0, page.hyperlink_set.count()); + } +} + +test "Screen: hyperlink cursor state on resize" { + const testing = std.testing; + const alloc = testing.allocator; + + // This test depends on underlying PageList implementation so + // it may be invalid one day. It's here to document/verify the + // current behavior. + + var s = try init(alloc, .{ .cols = 5, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + + // Start a hyperlink + try s.startHyperlink("http://example.com", null); + try testing.expect(s.cursor.hyperlink_id != 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + + // Resize. Any column growth will trigger a page to be reallocated. + try s.resize(.{ .cols = 10, .rows = 10 }); + try testing.expect(s.cursor.hyperlink_id != 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + + s.endHyperlink(); + try testing.expect(s.cursor.hyperlink_id == 0); + { + const page = &s.cursor.page_pin.node.data; + try testing.expectEqual(0, page.hyperlink_set.count()); + } +} + +test "Screen: cursorSetHyperlink OOM + URI too large for string alloc" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + + // Start a hyperlink with a URI that just barely fits in the string alloc. + // This will ensure that additional string alloc space is needed for the + // redundant copy of the URI when the page is re-alloced. + const uri = "a" ** (pagepkg.std_capacity.string_bytes - 8); + try s.startHyperlink(uri, null); + + // Figure out how many cells should can have hyperlinks in this page, + // and write twice that number, to guarantee the capacity needs to be + // increased at some point. + const base_capacity = s.cursor.page_pin.node.data.hyperlinkCapacity(); + const base_string_bytes = s.cursor.page_pin.node.data.capacity.string_bytes; + for (0..base_capacity * 2) |_| { + try s.cursorSetHyperlink(); + if (s.cursor.x >= s.pages.cols - 1) { + try s.cursorDownOrScroll(); + s.cursorHorizontalAbsolute(0); + } else { + s.cursorRight(1); + } + } + + // Make sure the capacity really did increase. + try testing.expect(base_capacity < s.cursor.page_pin.node.data.hyperlinkCapacity()); + // And that our string_bytes increased as well. + try testing.expect(base_string_bytes < s.cursor.page_pin.node.data.capacity.string_bytes); +} + +test "Screen: increaseCapacity cursor style ref count preserved" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ + .cols = 5, + .rows = 5, + .max_scrollback = 0, + }); + defer s.deinit(); + try s.setAttribute(.bold); + try s.testWriteString("1ABCD"); + + // We should have one page and it should be our cursor page + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try testing.expect(s.pages.pages.first == s.cursor.page_pin.node); + + const old_style = s.cursor.style; + + { + const page = &s.pages.pages.last.?.data; + // 5 chars + cursor = 6 refs + try testing.expectEqual( + 6, + page.styles.refCount(page.memory, s.cursor.style_id), + ); + } + + // This forces the page to change via increaseCapacity. + const new_node = try s.increaseCapacity( + s.cursor.page_pin.node, + .grapheme_bytes, + ); + + // Cursor's page_pin should now point to the new node + try testing.expect(s.cursor.page_pin.node == new_node); + + // Verify cursor's page_cell and page_row are correctly reloaded from the pin + const page_rac = s.cursor.page_pin.rowAndCell(); + try testing.expect(s.cursor.page_row == page_rac.row); + try testing.expect(s.cursor.page_cell == page_rac.cell); + + // Style should be preserved + try testing.expectEqual(old_style, s.cursor.style); + try testing.expect(s.cursor.style_id != style.default_id); + + // After increaseCapacity, the 5 chars are cloned (5 refs) and + // the cursor's style is re-added (1 ref) = 6 total. + { + const page = &s.pages.pages.last.?.data; + const ref_count = page.styles.refCount(page.memory, s.cursor.style_id); + try testing.expectEqual(6, ref_count); + } +} + +test "Screen: increaseCapacity cursor hyperlink ref count preserved" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ + .cols = 5, + .rows = 5, + .max_scrollback = 0, + }); + defer s.deinit(); + try s.startHyperlink("https://example.com/", null); + try s.testWriteString("1ABCD"); + + // We should have one page and it should be our cursor page + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try testing.expect(s.pages.pages.first == s.cursor.page_pin.node); + + { + const page = &s.pages.pages.last.?.data; + // Cursor has the hyperlink active = 1 count in hyperlink_set + try testing.expectEqual(1, page.hyperlink_set.count()); + try testing.expect(s.cursor.hyperlink_id != 0); + try testing.expect(s.cursor.hyperlink != null); + } + + // This forces the page to change via increaseCapacity. + _ = try s.increaseCapacity( + s.cursor.page_pin.node, + .grapheme_bytes, + ); + + // Hyperlink should be preserved with correct URI + try testing.expect(s.cursor.hyperlink != null); + try testing.expect(s.cursor.hyperlink_id != 0); + try testing.expectEqualStrings("https://example.com/", s.cursor.hyperlink.?.uri); + + // After increaseCapacity, the hyperlink is re-added to the new page. + { + const page = &s.pages.pages.last.?.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } +} + +test "Screen: increaseCapacity cursor with both style and hyperlink preserved" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ + .cols = 5, + .rows = 5, + .max_scrollback = 0, + }); + defer s.deinit(); + + // Set both a non-default style AND an active hyperlink. + // Write one character first with bold to mark the row as styled, + // then start the hyperlink and write more characters. + try s.setAttribute(.bold); + try s.startHyperlink("https://example.com/", null); + try s.testWriteString("1ABCD"); + + // We should have one page and it should be our cursor page + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try testing.expect(s.pages.pages.first == s.cursor.page_pin.node); + + const old_style = s.cursor.style; + + { + const page = &s.pages.pages.last.?.data; + // 5 chars + cursor = 6 refs for bold style + try testing.expectEqual( + 6, + page.styles.refCount(page.memory, s.cursor.style_id), + ); + // Cursor has the hyperlink active = 1 count in hyperlink_set + try testing.expectEqual(1, page.hyperlink_set.count()); + try testing.expect(s.cursor.style_id != style.default_id); + try testing.expect(s.cursor.hyperlink_id != 0); + try testing.expect(s.cursor.hyperlink != null); + } + + // This forces the page to change via increaseCapacity. + _ = try s.increaseCapacity( + s.cursor.page_pin.node, + .grapheme_bytes, + ); + + // Style should be preserved + try testing.expectEqual(old_style, s.cursor.style); + try testing.expect(s.cursor.style_id != style.default_id); + + // Hyperlink should be preserved with correct URI + try testing.expect(s.cursor.hyperlink != null); + try testing.expect(s.cursor.hyperlink_id != 0); + try testing.expectEqualStrings("https://example.com/", s.cursor.hyperlink.?.uri); + + // After increaseCapacity, both style and hyperlink are re-added to the new page. + { + const page = &s.pages.pages.last.?.data; + const ref_count = page.styles.refCount(page.memory, s.cursor.style_id); + try testing.expectEqual(6, ref_count); + try testing.expectEqual(1, page.hyperlink_set.count()); + } +} + +test "Screen: increaseCapacity non-cursor page returns early" { + // Test that calling increaseCapacity on a page that is NOT the cursor's + // page properly delegates to pages.increaseCapacity without doing the + // extra cursor accounting (style/hyperlink re-adding). + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10000, + }); + defer s.deinit(); + + // Set up a custom style and hyperlink on the cursor + try s.setAttribute(.bold); + try s.startHyperlink("https://example.com/", null); + try s.testWriteString("Hello"); + + // Store cursor state before growing pages + const old_style = s.cursor.style; + const old_style_id = s.cursor.style_id; + const old_hyperlink = s.cursor.hyperlink; + const old_hyperlink_id = s.cursor.hyperlink_id; + + // The cursor is on the first (and only) page + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try testing.expect(s.cursor.page_pin.node == s.pages.pages.first.?); + + // Grow pages until we have multiple pages. The cursor's pin stays on + // the first page since we're just adding rows. + const first_page_node = s.pages.pages.first.?; + first_page_node.data.pauseIntegrityChecks(true); + for (0..first_page_node.data.capacity.rows - first_page_node.data.size.rows) |_| { + _ = try s.pages.grow(); + } + first_page_node.data.pauseIntegrityChecks(false); + _ = try s.pages.grow(); + + // Now we have two pages + try testing.expect(s.pages.pages.first != s.pages.pages.last); + const second_page = s.pages.pages.last.?; + + // Cursor should still be on the first page (where it was created) + try testing.expect(s.cursor.page_pin.node == s.pages.pages.first.?); + try testing.expect(s.cursor.page_pin.node != second_page); + + const second_page_styles_cap = second_page.data.capacity.styles; + const cursor_page_styles_cap = s.cursor.page_pin.node.data.capacity.styles; + + // Call increaseCapacity on the second page (NOT the cursor's page) + const new_second_page = try s.increaseCapacity(second_page, .styles); + + // The second page should have increased capacity + try testing.expectEqual( + second_page_styles_cap * 2, + new_second_page.data.capacity.styles, + ); + + // The cursor's page (first page) should be unchanged + try testing.expectEqual( + cursor_page_styles_cap, + s.cursor.page_pin.node.data.capacity.styles, + ); + + // Cursor state should be completely unchanged since we didn't touch its page + try testing.expectEqual(old_style, s.cursor.style); + try testing.expectEqual(old_style_id, s.cursor.style_id); + try testing.expectEqual(old_hyperlink, s.cursor.hyperlink); + try testing.expectEqual(old_hyperlink_id, s.cursor.hyperlink_id); + + // Verify hyperlink is still valid + try testing.expect(s.cursor.hyperlink != null); + try testing.expectEqualStrings("https://example.com/", s.cursor.hyperlink.?.uri); +} + +test "Screen: cursorDown to page with insufficient capacity" { + // Regression test for https://github.com/ghostty-org/ghostty/issues/10282 + // + // This test exposes a use-after-realloc bug in cursorDown (and similar + // cursor movement functions). The bug pattern: + // + // 1. cursorDown creates a by-value copy of the pin via page_pin.down(n) + // 2. cursorChangePin is called, which may trigger adjustCapacity + // if the target page's style map is full + // 3. adjustCapacity frees the old page and creates a new one + // 4. The local pin copy still points to the freed page + // 5. rowAndCell() on the stale pin accesses freed memory + + const testing = std.testing; + const alloc = testing.allocator; + + // Small screen to make page boundary crossing easy to set up + var s = try init(alloc, .{ .cols = 10, .rows = 3, .max_scrollback = 1 }); + defer s.deinit(); + + // Scroll down enough to create a second page + const start_page = &s.pages.pages.last.?.data; + const rem = start_page.capacity.rows; + start_page.pauseIntegrityChecks(true); + for (0..rem) |_| try s.cursorDownOrScroll(); + start_page.pauseIntegrityChecks(false); + + // Cursor should now be on a new page + const new_page = &s.cursor.page_pin.node.data; + try testing.expect(start_page != new_page); + + // Fill new_page's style map to capacity. When we move INTO this page + // with a style set, adjustCapacity will be triggered. + { + new_page.pauseIntegrityChecks(true); + defer new_page.pauseIntegrityChecks(false); + defer new_page.assertIntegrity(); + + var n: u24 = 1; + while (new_page.styles.add( + new_page.memory, + .{ .bg_color = .{ .rgb = @bitCast(n) } }, + )) |_| n += 1 else |_| {} + } + + // Move cursor to start of active area and set a style + s.cursorAbsolute(0, 0); + try s.setAttribute(.bold); + try testing.expect(s.cursor.style.flags.bold); + try testing.expect(s.cursor.style_id != style.default_id); + + // Find the row just before the page boundary + for (0..s.pages.rows - 1) |row| { + s.cursorAbsolute(0, @intCast(row)); + const cur_node = s.cursor.page_pin.node; + if (s.cursor.page_pin.down(1)) |next_pin| { + if (next_pin.node != cur_node) { + // Cursor is at 'row', moving down crosses to new_page + try testing.expect(&next_pin.node.data == new_page); + + // This cursorDown triggers the bug: the local page_pin copy + // becomes stale after adjustCapacity, causing rowAndCell() + // to access freed memory. + s.cursorDown(1); + + // If the fix is applied, verify correct state + try testing.expect(s.cursor.y == row + 1); + try testing.expect(s.cursor.style.flags.bold); + + break; + } + } + } else { + // Didn't find boundary + try testing.expect(false); + } +} + +test "Screen setAttribute increases capacity when style map is full" { + // Tests that setAttribute succeeds when the style map is full by + // increasing page capacity. When capacity is at max and increaseCapacity + // returns OutOfSpace, manualStyleUpdate will split the page instead. + const testing = std.testing; + const alloc = testing.allocator; + + // Use a small screen with multiple rows + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 10 }); + defer s.deinit(); + + // Write content to multiple rows + try s.testWriteString("line1\nline2\nline3\nline4\nline5"); + + // Get the page and fill its style map to capacity + const page = &s.cursor.page_pin.node.data; + const original_styles_capacity = page.capacity.styles; + + // Fill the style map to capacity using the StyleSet's layout capacity + // which accounts for the load factor + { + page.pauseIntegrityChecks(true); + defer page.pauseIntegrityChecks(false); + defer page.assertIntegrity(); + + const max_items = page.styles.layout.cap; + var n: usize = 1; + while (n < max_items) : (n += 1) { + _ = page.styles.add( + page.memory, + .{ .bg_color = .{ .rgb = @bitCast(@as(u24, @intCast(n))) } }, + ) catch break; + } + } + + // Now try to set a new unique attribute that would require a new style slot + // This should succeed by increasing capacity (or splitting if at max capacity) + try s.setAttribute(.bold); + + // The style should have been applied (bold flag set) + try testing.expect(s.cursor.style.flags.bold); + + // The cursor should have a valid non-default style_id + try testing.expect(s.cursor.style_id != style.default_id); + + // Either the capacity increased or the page was split/changed + const current_page = &s.cursor.page_pin.node.data; + const capacity_increased = current_page.capacity.styles > original_styles_capacity; + const page_changed = current_page != page; + try testing.expect(capacity_increased or page_changed); +} + +test "Screen setAttribute splits page on OutOfSpace at max styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ + .cols = 10, + .rows = 10, + .max_scrollback = 0, + }); + defer s.deinit(); + + // Write content to multiple rows so we have something to split + try s.testWriteString("line1\nline2\nline3\nline4\nline5"); + + // Remember the original node + const original_node = s.cursor.page_pin.node; + + // Increase the page's style capacity to max by repeatedly calling increaseCapacity + // Use Screen.increaseCapacity to properly maintain cursor state + const max_styles = std.math.maxInt(size.CellCountInt); + while (s.cursor.page_pin.node.data.capacity.styles < max_styles) { + _ = s.increaseCapacity( + s.cursor.page_pin.node, + .styles, + ) catch break; + } + + // Get the page reference after increaseCapacity - cursor may have moved + var page = &s.cursor.page_pin.node.data; + try testing.expectEqual(max_styles, page.capacity.styles); + + // Fill the style map to capacity using the StyleSet's layout capacity + // which accounts for the load factor + { + page.pauseIntegrityChecks(true); + defer page.pauseIntegrityChecks(false); + defer page.assertIntegrity(); + + const max_items = page.styles.layout.cap; + var n: usize = 1; + while (n < max_items) : (n += 1) { + _ = page.styles.add( + page.memory, + .{ .bg_color = .{ .rgb = @bitCast(@as(u24, @intCast(n))) } }, + ) catch break; + } + } + + // Track the node before setAttribute + const node_before_set = s.cursor.page_pin.node; + + // Now try to set a new unique attribute that would require a new style slot + // At max capacity, increaseCapacity will return OutOfSpace, triggering page split + try s.setAttribute(.bold); + + // The style should have been applied (bold flag set) + try testing.expect(s.cursor.style.flags.bold); + + // The cursor should have a valid non-default style_id + try testing.expect(s.cursor.style_id != style.default_id); + + // The page should have been split + const page_was_split = s.cursor.page_pin.node != node_before_set or + node_before_set.next != null or + node_before_set.prev != null or + s.cursor.page_pin.node != original_node; + try testing.expect(page_was_split); +} + +test "selectionString map allocation failure cleanup" { + // This test verifies that if toOwnedSlice fails when building + // the StringMap, we don't leak the already-allocated map.string. + const testing = std.testing; + const alloc = testing.allocator; + var s = try Screen.init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + try s.testWriteString("hello"); + + // Get a selection + const sel = Selection.init( + s.pages.pin(.{ .active = .{ .x = 0, .y = 0 } }).?, + s.pages.pin(.{ .active = .{ .x = 4, .y = 0 } }).?, + false, + ); + + // Trigger allocation failure on toOwnedSlice + var map: StringMap = undefined; + selectionString_tw.errorAlways(.copy_map, error.OutOfMemory); + const result = s.selectionString(alloc, .{ + .sel = sel, + .map = &map, + }); + try testing.expectError(error.OutOfMemory, result); + try selectionString_tw.end(.reset); + + // If this test passes without memory leaks (when run with testing.allocator), + // it means the errdefer properly cleaned up map.string when toOwnedSlice failed. +} + +test "Screen: promptClickMove line right basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Move cursor back to start of input (column 2, the 'h') + s.cursorAbsolute(2, 0); + + // Click on first 'l' (column 4), should require 2 right movements (h->e->l) + const click_pin = s.pages.pin(.{ .active = .{ .x = 4, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 2), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove line right cursor not on input" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + s.cursorSetSemanticContent(.output); + + // Move cursor back to prompt area (column 0, the '>') + s.cursorAbsolute(0, 0); + + // Cursor is on prompt, not input - should return zero + const click_pin = s.pages.pin(.{ .active = .{ .x = 4, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(PromptClickMove.zero, result); +} + +test "Screen: promptClickMove line right click on same position" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Move cursor to column 4 + s.cursorAbsolute(4, 0); + + // Click on same position - no movement needed + const click_pin = s.pages.pin(.{ .active = .{ .x = 4, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(PromptClickMove.zero, result); +} + +test "Screen: promptClickMove line right skips non-input cells" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write: "> h" then output "X" then input "llo" + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("h"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("X"); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("llo"); + + // Move cursor to column 2 (the 'h') + s.cursorAbsolute(2, 0); + + // Click on 'l' at column 5 - should skip the 'X' output cell + // Movement: h (start) -> l (col 4) -> l (col 5) = 2 right movements + const click_pin = s.pages.pin(.{ .active = .{ .x = 5, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 2), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove line right soft-wrapped line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input that wraps + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + // Write 8 chars of input, first row has 2 for prompt + 8 input = 10 cols + try s.testWriteString("abcdefgh"); + // Continue on next row (soft-wrapped) + try s.testWriteString("ij"); + + // Verify soft wrap occurred + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("> abcdefgh\nij", contents); + } + + // Move cursor to column 2 (the 'a') + s.cursorAbsolute(2, 0); + + // Click on 'j' at column 1, row 1 - should count all input cells + // Movement: a->b->c->d->e->f->g->h->i->j = 9 right movements + const click_pin = s.pages.pin(.{ .active = .{ .x = 1, .y = 1 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 9), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove disabled when click is none" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Click mode is .none by default (disabled) + try testing.expectEqual(Screen.SemanticPrompt.SemanticClick.none, s.semantic_prompt.click); + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Move cursor to start of input + s.cursorAbsolute(2, 0); + + // Click should return zero since click mode is disabled + const click_pin = s.pages.pin(.{ .active = .{ .x = 4, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(PromptClickMove.zero, result); +} + +test "Screen: promptClickMove line right stops at hard wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write prompt and input on first line + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + // Hard wrap (newline) + try s.testWriteString("\n"); + try s.testWriteString("world"); + + // Move cursor to column 2 (the 'h') + s.cursorAbsolute(2, 0); + + // Click on 'w' at column 0, row 1 - but line mode stops at hard wrap + // Should only move to end of first line: h->e->l->l->o = 4 movements + const click_pin = s.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?; + const result = s.promptClickMove(click_pin); + + // Should stop at end of first line, not cross hard wrap + try testing.expectEqual(@as(usize, 5), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove line right stops at non-continuation row" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Row 0: PROMPT "> hello" + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello\n"); + + // Row 1: CONTINUATION "world" + s.cursorSetSemanticContent(.{ .prompt = .continuation }); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("world\n"); + + // Row 2: NEW PROMPT "> again" + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("again"); + + // Verify content + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("> hello\nworld\n> again", contents); + } + + // Move cursor to 'w' at column 0, row 1 + s.cursorAbsolute(0, 1); + + // Click on 'a' at column 2, row 2 - but row 2 is a new prompt + // Should stop at end of "world": w->o->r->l->d = 4 movements + const click_pin = s.pages.pin(.{ .active = .{ .x = 2, .y = 2 } }).?; + const result = s.promptClickMove(click_pin); + + // Should stop at 'd' (end of world), not cross to new prompt + try testing.expectEqual(@as(usize, 5), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove line left basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Cursor is at column 7 (after 'o'), move it to column 6 (the 'o') + s.cursorAbsolute(6, 0); + + // Click on 'h' (column 2), should require 4 left movements (o->l->l->e->h) + const click_pin = s.pages.pin(.{ .active = .{ .x = 2, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 4), result.left); + try testing.expectEqual(@as(usize, 0), result.right); +} + +test "Screen: promptClickMove line left skips non-input cells" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write: "> h" then output "X" then input "llo" + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("h"); + s.cursorSetSemanticContent(.output); + try s.testWriteString("X"); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("llo"); + + // Move cursor to column 6 (the 'o') + s.cursorAbsolute(6, 0); + + // Click on 'h' at column 2 - should skip the 'X' output cell + // Movement: o->l->l->h = 3 left movements (skipping X) + const click_pin = s.pages.pin(.{ .active = .{ .x = 2, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 3), result.left); + try testing.expectEqual(@as(usize, 0), result.right); +} + +test "Screen: promptClickMove line left soft-wrapped line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input that wraps + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + // Write 8 chars of input, first row has 2 for prompt + 8 input = 10 cols + try s.testWriteString("abcdefgh"); + // Continue on next row (soft-wrapped) + try s.testWriteString("ij"); + + // Verify soft wrap occurred + { + const contents = try s.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer alloc.free(contents); + try testing.expectEqualStrings("> abcdefgh\nij", contents); + } + + // Cursor is at column 2, row 1 (after 'j'). Move to 'j' at column 1. + s.cursorAbsolute(1, 1); + + // Click on 'a' at column 2, row 0 - should count all input cells backwards + // Movement: j->i->h->g->f->e->d->c->b->a = 9 left movements + const click_pin = s.pages.pin(.{ .active = .{ .x = 2, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 9), result.left); + try testing.expectEqual(@as(usize, 0), result.right); +} + +test "Screen: promptClickMove line left stops at hard wrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write prompt and input on first line, then hard wrap + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + // Hard wrap (newline) + try s.testWriteString("\n"); + try s.testWriteString("world"); + + // Move cursor to 'd' at column 4, row 1 (an actual input cell) + s.cursorAbsolute(4, 1); + + // Click on 'h' at column 2, row 0 - but line mode stops at hard wrap + // Should only move to start of second line, not cross to row 0 + const click_pin = s.pages.pin(.{ .active = .{ .x = 2, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + // Should stop at start of second line: d->l->r->o->w = 4 movements + try testing.expectEqual(@as(usize, 4), result.left); + try testing.expectEqual(@as(usize, 0), result.right); +} + +test "Screen: promptClickMove click right of input same line" { + const testing = std.testing; + const alloc = testing.allocator; + + // Set up: "> hello" where "> " is prompt and "hello" is input + // Clicking to the right of the 'o' should move cursor past the input + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Move cursor to start of input (column 2, the 'h') + s.cursorAbsolute(2, 0); + + // Click beyond the input (column 15) - should move to one past the 'o' + const click_pin = s.pages.pin(.{ .active = .{ .x = 15, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 5), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove click right of input cursor at end" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Cursor is already at column 7 (one past 'o') after writing + // Click beyond the input (column 15) - no movement needed since + // cursor is already at the end position + const click_pin = s.pages.pin(.{ .active = .{ .x = 15, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 0), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove click right of input on lower line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Move cursor to start of input (column 2, the 'h') + s.cursorAbsolute(2, 0); + + // Click on a lower line (row 1) - should move to end of input + // This is outside the prompt area so should clamp to end + const click_pin = s.pages.pin(.{ .active = .{ .x = 5, .y = 1 } }).?; + const result = s.promptClickMove(click_pin); + + // From 'h', we need to pass e, l, l, o (4 cells) + 1 past end = 5 + try testing.expectEqual(@as(usize, 5), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove click right of input cursor at end lower line" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Cursor is at column 7 after writing (one past 'o') + // Click on a lower line (row 1) - cursor already at end, no movement needed + const click_pin = s.pages.pin(.{ .active = .{ .x = 5, .y = 1 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 0), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} + +test "Screen: promptClickMove click right of input cursor on last char" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try init(alloc, .{ .cols = 20, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + // Enable line click mode + s.semantic_prompt.click = .{ .cl = .line }; + + // Write a prompt and input + s.cursorSetSemanticContent(.{ .prompt = .initial }); + try s.testWriteString("> "); + s.cursorSetSemanticContent(.{ .input = .clear_explicit }); + try s.testWriteString("hello"); + + // Move cursor to last input char (column 6, the 'o') + s.cursorAbsolute(6, 0); + + // Click beyond the input (column 15) + const click_pin = s.pages.pin(.{ .active = .{ .x = 15, .y = 0 } }).?; + const result = s.promptClickMove(click_pin); + + try testing.expectEqual(@as(usize, 1), result.right); + try testing.expectEqual(@as(usize, 0), result.left); +} diff --git a/vendor/libghostty-vt/src/terminal/ScreenSet.zig b/vendor/libghostty-vt/src/terminal/ScreenSet.zig new file mode 100644 index 00000000..d0856da5 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/ScreenSet.zig @@ -0,0 +1,107 @@ +/// A ScreenSet holds multiple terminal screens. This is initially created +/// to handle simple primary vs alternate screens, but could be extended +/// in the future to handle N screens. +/// +/// One of the goals of this is to allow lazy initialization of screens +/// as needed. The primary screen is always initialized, but the alternate +/// screen may not be until first used. +const ScreenSet = @This(); + +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const lib = @import("lib.zig"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const Screen = @import("Screen.zig"); + +/// The possible keys for screens in the screen set. +pub const Key = lib.Enum(lib.target, &.{ + "primary", + "alternate", +}); + +/// The key value of the currently active screen. Useful for simple +/// comparisons, e.g. "is this screen the primary screen". +active_key: Key, + +/// The active screen pointer. +active: *Screen, + +/// All screens that are initialized. +all: std.EnumMap(Key, *Screen), + +pub fn init( + alloc: Allocator, + opts: Screen.Options, +) Allocator.Error!ScreenSet { + // We need to initialize our initial primary screen + const screen = try alloc.create(Screen); + errdefer alloc.destroy(screen); + screen.* = try .init(alloc, opts); + return .{ + .active_key = .primary, + .active = screen, + .all = .init(.{ .primary = screen }), + }; +} + +pub fn deinit(self: *ScreenSet, alloc: Allocator) void { + // Destroy all initialized screens + var it = self.all.iterator(); + while (it.next()) |entry| { + entry.value.*.deinit(); + alloc.destroy(entry.value.*); + } +} + +/// Get the screen for the given key, if it is initialized. +pub fn get(self: *const ScreenSet, key: Key) ?*Screen { + return self.all.get(key); +} + +/// Get the screen for the given key, initializing it if necessary. +pub fn getInit( + self: *ScreenSet, + alloc: Allocator, + key: Key, + opts: Screen.Options, +) Allocator.Error!*Screen { + if (self.get(key)) |screen| return screen; + const screen = try alloc.create(Screen); + errdefer alloc.destroy(screen); + screen.* = try .init(alloc, opts); + self.all.put(key, screen); + return screen; +} + +/// Remove a key from the set. The primary screen cannot be removed (asserted). +pub fn remove( + self: *ScreenSet, + alloc: Allocator, + key: Key, +) void { + assert(key != .primary); + if (self.all.fetchRemove(key)) |screen| { + screen.deinit(); + alloc.destroy(screen); + } +} + +/// Switch the active screen to the given key. Requires that the +/// screen is initialized. +pub fn switchTo(self: *ScreenSet, key: Key) void { + self.active_key = key; + self.active = self.all.get(key).?; +} + +test ScreenSet { + const alloc = testing.allocator; + var set: ScreenSet = try .init(alloc, .default); + defer set.deinit(alloc); + try testing.expectEqual(.primary, set.active_key); + + // Initialize a secondary screen + _ = try set.getInit(alloc, .alternate, .default); + set.switchTo(.alternate); + try testing.expectEqual(.alternate, set.active_key); +} diff --git a/vendor/libghostty-vt/src/terminal/Selection.zig b/vendor/libghostty-vt/src/terminal/Selection.zig new file mode 100644 index 00000000..8cb52816 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/Selection.zig @@ -0,0 +1,1598 @@ +//! Represents a single selection within the terminal (i.e. a highlight region). +const Selection = @This(); + +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const page = @import("page.zig"); +const point = @import("point.zig"); +const PageList = @import("PageList.zig"); +const Screen = @import("Screen.zig"); +const Pin = PageList.Pin; + +// NOTE(mitchellh): I'm not very happy with how this is implemented, because +// the ordering operations which are used frequently require using +// pointFromPin which -- at the time of writing this -- is slow. The overall +// style of this struct is due to porting it from the previous implementation +// which had an efficient ordering operation. +// +// While reimplementing this, there were too many callers that already +// depended on this behavior so I kept it despite the inefficiency. In the +// future, we should take a look at this again! + +/// The bounds of the selection. +bounds: Bounds, + +/// Whether or not this selection refers to a rectangle, rather than whole +/// lines of a buffer. In this mode, start and end refer to the top left and +/// bottom right of the rectangle, or vice versa if the selection is backwards. +rectangle: bool = false, + +/// The bounds of the selection. A selection bounds can be either tracked +/// or untracked. Untracked bounds are unsafe beyond the point the terminal +/// screen may be modified, since they may point to invalid memory. Tracked +/// bounds are always valid and will be updated as the screen changes, but +/// are more expensive to exist. +/// +/// In all cases, start and end can be in any order. There is no guarantee that +/// start is before end or vice versa. If a user selects backwards, +/// start will be after end, and vice versa. Use the struct functions +/// to not have to worry about this. +pub const Bounds = union(enum) { + untracked: struct { + start: Pin, + end: Pin, + }, + + tracked: struct { + start: *Pin, + end: *Pin, + }, +}; + +/// Initialize a new selection with the given start and end pins on +/// the screen. The screen will be used for pin tracking. +pub fn init( + start_pin: Pin, + end_pin: Pin, + rect: bool, +) Selection { + return .{ + .bounds = .{ .untracked = .{ + .start = start_pin, + .end = end_pin, + } }, + .rectangle = rect, + }; +} + +pub fn deinit( + self: Selection, + s: *Screen, +) void { + switch (self.bounds) { + .tracked => |v| { + s.pages.untrackPin(v.start); + s.pages.untrackPin(v.end); + }, + + .untracked => {}, + } +} + +/// Returns true if this selection is equal to another selection. +pub fn eql(self: Selection, other: Selection) bool { + return self.start().eql(other.start()) and + self.end().eql(other.end()) and + self.rectangle == other.rectangle; +} + +/// The starting pin of the selection. This is NOT ordered. +pub fn startPtr(self: *Selection) *Pin { + return switch (self.bounds) { + .untracked => |*v| &v.start, + .tracked => |v| v.start, + }; +} + +/// The ending pin of the selection. This is NOT ordered. +pub fn endPtr(self: *Selection) *Pin { + return switch (self.bounds) { + .untracked => |*v| &v.end, + .tracked => |v| v.end, + }; +} + +pub fn start(self: Selection) Pin { + return switch (self.bounds) { + .untracked => |v| v.start, + .tracked => |v| v.start.*, + }; +} + +pub fn end(self: Selection) Pin { + return switch (self.bounds) { + .untracked => |v| v.end, + .tracked => |v| v.end.*, + }; +} + +/// Returns true if this is a tracked selection. +pub fn tracked(self: *const Selection) bool { + return switch (self.bounds) { + .untracked => false, + .tracked => true, + }; +} + +/// Convert this selection a tracked selection. It is asserted this is +/// an untracked selection. The tracked selection is returned. +pub fn track(self: *const Selection, s: *Screen) Allocator.Error!Selection { + assert(!self.tracked()); + + // Track our pins + const start_pin = self.bounds.untracked.start; + const end_pin = self.bounds.untracked.end; + const tracked_start = try s.pages.trackPin(start_pin); + errdefer s.pages.untrackPin(tracked_start); + const tracked_end = try s.pages.trackPin(end_pin); + errdefer s.pages.untrackPin(tracked_end); + + return .{ + .bounds = .{ .tracked = .{ + .start = tracked_start, + .end = tracked_end, + } }, + .rectangle = self.rectangle, + }; +} + +/// Returns the top left point of the selection. +pub fn topLeft(self: Selection, s: *const Screen) Pin { + return switch (self.order(s)) { + .forward => self.start(), + .reverse => self.end(), + .mirrored_forward => pin: { + var p = self.start(); + p.x = self.end().x; + break :pin p; + }, + .mirrored_reverse => pin: { + var p = self.end(); + p.x = self.start().x; + break :pin p; + }, + }; +} + +/// Returns the bottom right point of the selection. +pub fn bottomRight(self: Selection, s: *const Screen) Pin { + return switch (self.order(s)) { + .forward => self.end(), + .reverse => self.start(), + .mirrored_forward => pin: { + var p = self.end(); + p.x = self.start().x; + break :pin p; + }, + .mirrored_reverse => pin: { + var p = self.start(); + p.x = self.end().x; + break :pin p; + }, + }; +} + +/// The order of the selection: +/// +/// * forward: start(x, y) is before end(x, y) (top-left to bottom-right). +/// * reverse: end(x, y) is before start(x, y) (bottom-right to top-left). +/// * mirrored_[forward|reverse]: special, rectangle selections only (see below). +/// +/// For regular selections, the above also holds for top-right to bottom-left +/// (forward) and bottom-left to top-right (reverse). However, for rectangle +/// selections, both of these selections are *mirrored* as orientation +/// operations only flip the x or y axis, not both. Depending on the y axis +/// direction, this is either mirrored_forward or mirrored_reverse. +/// +pub const Order = enum { forward, reverse, mirrored_forward, mirrored_reverse }; + +pub fn order(self: Selection, s: *const Screen) Order { + const start_pt = s.pages.pointFromPin(.screen, self.start()).?.screen; + const end_pt = s.pages.pointFromPin(.screen, self.end()).?.screen; + + if (self.rectangle) { + // Reverse (also handles single-column) + if (start_pt.y > end_pt.y and start_pt.x >= end_pt.x) return .reverse; + if (start_pt.y >= end_pt.y and start_pt.x > end_pt.x) return .reverse; + + // Mirror, bottom-left to top-right + if (start_pt.y > end_pt.y and start_pt.x < end_pt.x) return .mirrored_reverse; + + // Mirror, top-right to bottom-left + if (start_pt.y < end_pt.y and start_pt.x > end_pt.x) return .mirrored_forward; + + // Forward + return .forward; + } + + if (start_pt.y < end_pt.y) return .forward; + if (start_pt.y > end_pt.y) return .reverse; + if (start_pt.x <= end_pt.x) return .forward; + return .reverse; +} + +/// Returns the selection in the given order. +/// +/// The returned selection is always a new untracked selection. +/// +/// Note that only forward and reverse are useful desired orders for this +/// function. All other orders act as if forward order was desired. +pub fn ordered(self: Selection, s: *const Screen, desired: Order) Selection { + if (self.order(s) == desired) return .init( + self.start(), + self.end(), + self.rectangle, + ); + + const tl = self.topLeft(s); + const br = self.bottomRight(s); + return switch (desired) { + .forward => .init(tl, br, self.rectangle), + .reverse => .init(br, tl, self.rectangle), + else => .init(tl, br, self.rectangle), + }; +} + +/// Returns true if the selection contains the given point. +/// +/// This recalculates top left and bottom right each call. If you have +/// many points to check, it is cheaper to do the containment logic +/// yourself and cache the topleft/bottomright. +pub fn contains(self: Selection, s: *const Screen, pin: Pin) bool { + const tl_pin = self.topLeft(s); + const br_pin = self.bottomRight(s); + + // This is definitely not very efficient. Low-hanging fruit to + // improve this. + const tl = s.pages.pointFromPin(.screen, tl_pin).?.screen; + const br = s.pages.pointFromPin(.screen, br_pin).?.screen; + const p = s.pages.pointFromPin(.screen, pin).?.screen; + + // If we're in rectangle select, we can short-circuit with an easy check + // here + if (self.rectangle) + return p.y >= tl.y and p.y <= br.y and p.x >= tl.x and p.x <= br.x; + + // If tl/br are same line + if (tl.y == br.y) return p.y == tl.y and + p.x >= tl.x and + p.x <= br.x; + + // If on top line, just has to be left of X + if (p.y == tl.y) return p.x >= tl.x; + + // If on bottom line, just has to be right of X + if (p.y == br.y) return p.x <= br.x; + + // If between the top/bottom, always good. + return p.y > tl.y and p.y < br.y; +} + +/// Get a selection for a single row in the screen. This will return null +/// if the row is not included in the selection. +/// +/// This is a very expensive operation. It has to traverse the linked list +/// of pages for the top-left, bottom-right, and the given pin to find +/// the coordinates. If you are calling this repeatedly, prefer +/// `containedRowCached`. +pub fn containedRow(self: Selection, s: *const Screen, pin: Pin) ?Selection { + const tl_pin = self.topLeft(s); + const br_pin = self.bottomRight(s); + + // This is definitely not very efficient. Low-hanging fruit to + // improve this. Callers should prefer containedRowCached if they + // can swing it. + const tl = s.pages.pointFromPin(.screen, tl_pin).?.screen; + const br = s.pages.pointFromPin(.screen, br_pin).?.screen; + const p = s.pages.pointFromPin(.screen, pin).?.screen; + + return self.containedRowCached( + s, + tl_pin, + br_pin, + pin, + tl, + br, + p, + ); +} + +/// Same as containedRow but useful if you're calling it repeatedly +/// so that the pins can be cached across calls. Advanced. +pub fn containedRowCached( + self: Selection, + s: *const Screen, + tl_pin: Pin, + br_pin: Pin, + pin: Pin, + tl: point.Coordinate, + br: point.Coordinate, + p: point.Coordinate, +) ?Selection { + if (p.y < tl.y or p.y > br.y) return null; + + // Rectangle case: we can return early as the x range will always be the + // same. We've already validated that the row is in the selection. + if (self.rectangle) return init( + start: { + var copy: Pin = pin; + copy.x = tl.x; + break :start copy; + }, + end: { + var copy: Pin = pin; + copy.x = br.x; + break :end copy; + }, + true, + ); + + if (p.y == tl.y) { + // If the selection is JUST this line, return it as-is. + if (p.y == br.y) { + return init(tl_pin, br_pin, false); + } + + // Selection top-left line matches only. + return init( + tl_pin, + end: { + var copy: Pin = pin; + copy.x = s.pages.cols - 1; + break :end copy; + }, + false, + ); + } + + // Row is our bottom selection, so we return the selection from the + // beginning of the line to the br. We know our selection is more than + // one line (due to conditionals above) + if (p.y == br.y) { + assert(p.y != tl.y); + return init( + start: { + var copy: Pin = pin; + copy.x = 0; + break :start copy; + }, + br_pin, + false, + ); + } + + // Row is somewhere between our selection lines so we return the full line. + return init( + start: { + var copy: Pin = pin; + copy.x = 0; + break :start copy; + }, + end: { + var copy: Pin = pin; + copy.x = s.pages.cols - 1; + break :end copy; + }, + false, + ); +} + +/// Possible adjustments to the selection. +pub const Adjustment = enum { + left, + right, + up, + down, + home, + end, + page_up, + page_down, + beginning_of_line, + end_of_line, +}; + +/// Adjust the selection by some given adjustment. An adjustment allows +/// a selection to be expanded slightly left, right, up, down, etc. +pub fn adjust( + self: *Selection, + s: *const Screen, + adjustment: Adjustment, +) void { + // Note that we always adjust "end" because end always represents + // the last point of the selection by mouse, not necessarily the + // top/bottom visually. So this results in the correct behavior + // whether the user drags up or down. + const end_pin = self.endPtr(); + switch (adjustment) { + .up => if (end_pin.up(1)) |new_end| { + end_pin.* = new_end; + } else { + self.adjust(s, .beginning_of_line); + }, + + .down => { + // Find the next non-blank row + var current = end_pin.*; + while (current.down(1)) |next| : (current = next) { + const rac = next.rowAndCell(); + const cells = next.node.data.getCells(rac.row); + if (page.Cell.hasTextAny(cells)) { + end_pin.* = next; + break; + } + } else { + // If we're at the bottom, just go to the end of the line + self.adjust(s, .end_of_line); + } + }, + + .left => { + var it = end_pin.cellIterator(.left_up, null); + _ = it.next(); + while (it.next()) |next| { + const rac = next.rowAndCell(); + if (rac.cell.hasText()) { + end_pin.* = next; + break; + } + } + }, + + .right => { + // Step right, wrapping to the next row down at the start of each new line, + // until we find a non-empty cell. + var it = end_pin.cellIterator(.right_down, null); + _ = it.next(); + while (it.next()) |next| { + const rac = next.rowAndCell(); + if (rac.cell.hasText()) { + end_pin.* = next; + break; + } + } + }, + + .page_up => if (end_pin.up(s.pages.rows)) |new_end| { + end_pin.* = new_end; + } else { + self.adjust(s, .home); + }, + + .page_down => if (end_pin.down(s.pages.rows)) |new_end| { + end_pin.* = new_end; + } else { + self.adjust(s, .end); + }, + + .home => end_pin.* = s.pages.pin(.{ .screen = .{ + .x = 0, + .y = 0, + } }).?, + + .end => { + var it = s.pages.rowIterator( + .left_up, + .{ .screen = .{} }, + null, + ); + while (it.next()) |next| { + const rac = next.rowAndCell(); + const cells = next.node.data.getCells(rac.row); + if (page.Cell.hasTextAny(cells)) { + end_pin.* = next; + end_pin.x = @intCast(cells.len - 1); + break; + } + } + }, + + .beginning_of_line => end_pin.x = 0, + + .end_of_line => end_pin.x = end_pin.node.data.size.cols - 1, + } +} + +test "Selection: adjust right" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A1234\nB5678\nC1234\nD5678"); + + // Simple movement right + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .right); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Already at end of the line. + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 4, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 4, .y = 2 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .right); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Already at end of the screen + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 4, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .right); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust left" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A1234\nB5678\nC1234\nD5678"); + + // Simple movement left + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .left); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Already at beginning of the line. + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 0, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .left); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust left skips blanks" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A1234\nB5678\nC12\nD56"); + + // Same line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 4, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .left); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 3, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Edge + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 0, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .left); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust up" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A\nB\nC\nD\nE"); + + // Not on the first line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .up); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // On the first line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 0 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .up); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust down" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A\nB\nC\nD\nE"); + + // Not on the first line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .down); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 4, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // On the last line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 4, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 4 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .down); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 9, + .y = 4, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust down with not full screen" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A\nB\nC"); + + // On the last line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 4, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 2 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .down); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 9, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust home" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A\nB\nC"); + + // On the last line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 4, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 2 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .home); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust end with not full screen" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A\nB\nC"); + + // On the last line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 4, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .end); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 4, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 9, + .y = 2, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust beginning of line" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 8, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A12 B34\nC12 D34"); + + // Not at beginning of the line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .beginning_of_line); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Already at beginning of the line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 0, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .beginning_of_line); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 5, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // End pin moves to start pin + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .beginning_of_line); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: adjust end of line" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 8, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("A12 B34\nC12 D34"); + + // Not at end of the line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .end_of_line); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // Already at end of the line + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 7, .y = 0 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .end_of_line); + + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + // End pin moves to start pin + { + var sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 7, .y = 0 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + false, + ); + defer sel.deinit(&s); + sel.adjust(&s, .end_of_line); + + // Start line + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } +} + +test "Selection: order, standard" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 100, .rows = 100, .max_scrollback = 1 }); + defer s.deinit(); + + { + // forward, multi-line + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + false, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } + { + // reverse, multi-line + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .reverse); + } + { + // forward, same-line + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } + { + // forward, single char + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } + { + // reverse, single line + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .reverse); + } +} + +test "Selection: order, rectangle" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 100, .rows = 100, .max_scrollback = 1 }); + defer s.deinit(); + + // Conventions: + // TL - top left + // BL - bottom left + // TR - top right + // BR - bottom right + { + // forward (TL -> BR) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } + { + // reverse (BR -> TL) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .reverse); + } + { + // mirrored_forward (TR -> BL) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .mirrored_forward); + } + { + // mirrored_reverse (BL -> TR) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .mirrored_reverse); + } + { + // forward, single line (left -> right ) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } + { + // reverse, single line (right -> left) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .reverse); + } + { + // forward, single column (top -> bottom) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 3 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } + { + // reverse, single column (bottom -> top) + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .reverse); + } + { + // forward, single cell + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + + try testing.expect(sel.order(&s) == .forward); + } +} + +test "topLeft" { + const testing = std.testing; + + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + { + // forward + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + const tl = sel.topLeft(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 1, + } }, s.pages.pointFromPin(.screen, tl)); + } + { + // reverse + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + const tl = sel.topLeft(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 1, + } }, s.pages.pointFromPin(.screen, tl)); + } + { + // mirrored_forward + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + true, + ); + defer sel.deinit(&s); + const tl = sel.topLeft(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 1, + } }, s.pages.pointFromPin(.screen, tl)); + } + { + // mirrored_reverse + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + const tl = sel.topLeft(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 1, + } }, s.pages.pointFromPin(.screen, tl)); + } +} + +test "bottomRight" { + const testing = std.testing; + + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + { + // forward + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + const br = sel.bottomRight(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, s.pages.pointFromPin(.screen, br)); + } + { + // reverse + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + false, + ); + defer sel.deinit(&s); + const br = sel.bottomRight(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, s.pages.pointFromPin(.screen, br)); + } + { + // mirrored_forward + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + true, + ); + defer sel.deinit(&s); + const br = sel.bottomRight(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 3, + } }, s.pages.pointFromPin(.screen, br)); + } + { + // mirrored_reverse + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + true, + ); + defer sel.deinit(&s); + const br = sel.bottomRight(&s); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 3, + } }, s.pages.pointFromPin(.screen, br)); + } +} + +test "ordered" { + const testing = std.testing; + + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + { + // forward + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + false, + ); + const sel_reverse = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + false, + ); + try testing.expect(sel.ordered(&s, .forward).eql(sel)); + try testing.expect(sel.ordered(&s, .reverse).eql(sel_reverse)); + try testing.expect(sel.ordered(&s, .mirrored_forward).eql(sel)); + } + { + // reverse + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + false, + ); + const sel_forward = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + false, + ); + try testing.expect(sel.ordered(&s, .forward).eql(sel_forward)); + try testing.expect(sel.ordered(&s, .reverse).eql(sel)); + try testing.expect(sel.ordered(&s, .mirrored_forward).eql(sel_forward)); + } + { + // mirrored_forward + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + true, + ); + const sel_forward = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + true, + ); + const sel_reverse = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + true, + ); + try testing.expect(sel.ordered(&s, .forward).eql(sel_forward)); + try testing.expect(sel.ordered(&s, .reverse).eql(sel_reverse)); + try testing.expect(sel.ordered(&s, .mirrored_reverse).eql(sel_forward)); + } + { + // mirrored_reverse + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + true, + ); + const sel_forward = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + true, + ); + const sel_reverse = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + true, + ); + try testing.expect(sel.ordered(&s, .forward).eql(sel_forward)); + try testing.expect(sel.ordered(&s, .reverse).eql(sel_reverse)); + try testing.expect(sel.ordered(&s, .mirrored_forward).eql(sel_forward)); + } +} + +test "Selection: contains" { + const testing = std.testing; + + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 10, .max_scrollback = 0 }); + defer s.deinit(); + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 2 } }).?, + false, + ); + + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 6, .y = 1 } }).?)); + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 1, .y = 2 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 2 } }).?)); + } + + // Reverse + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + false, + ); + + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 6, .y = 1 } }).?)); + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 1, .y = 2 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 2 } }).?)); + } + + // Single line + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 8, .y = 1 } }).?, + false, + ); + + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 6, .y = 1 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 9, .y = 1 } }).?)); + } +} + +test "Selection: contains, rectangle" { + const testing = std.testing; + + var s = try Screen.init(testing.allocator, .{ .cols = 15, .rows = 15, .max_scrollback = 0 }); + defer s.deinit(); + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 7, .y = 9 } }).?, + true, + ); + + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 6 } }).?)); // Center + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 3, .y = 6 } }).?)); // Left border + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 7, .y = 6 } }).?)); // Right border + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 3 } }).?)); // Top border + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 9 } }).?)); // Bottom border + + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 2 } }).?)); // Above center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 10 } }).?)); // Below center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 2, .y = 6 } }).?)); // Left center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 8, .y = 6 } }).?)); // Right center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 8, .y = 3 } }).?)); // Just right of top right + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 2, .y = 9 } }).?)); // Just left of bottom left + } + + // Reverse + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 7, .y = 9 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + true, + ); + + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 6 } }).?)); // Center + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 3, .y = 6 } }).?)); // Left border + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 7, .y = 6 } }).?)); // Right border + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 3 } }).?)); // Top border + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 9 } }).?)); // Bottom border + + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 2 } }).?)); // Above center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 5, .y = 10 } }).?)); // Below center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 2, .y = 6 } }).?)); // Left center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 8, .y = 6 } }).?)); // Right center + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 8, .y = 3 } }).?)); // Just right of top right + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 2, .y = 9 } }).?)); // Just left of bottom left + } + + // Single line + // NOTE: This is the same as normal selection but we just do it for brevity + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 10, .y = 1 } }).?, + true, + ); + + try testing.expect(sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 6, .y = 1 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?)); + try testing.expect(!sel.contains(&s, s.pages.pin(.{ .screen = .{ .x = 12, .y = 1 } }).?)); + } +} + +test "Selection: containedRow" { + const testing = std.testing; + var s = try Screen.init(testing.allocator, .{ .cols = 10, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 5, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + false, + ); + + // Not contained + try testing.expect(sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 4 } }).?, + ) == null); + + // Start line + try testing.expectEqual(Selection.init( + sel.start(), + s.pages.pin(.{ .screen = .{ .x = s.pages.cols - 1, .y = 1 } }).?, + false, + ), sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + ).?); + + // End line + try testing.expectEqual(Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 3 } }).?, + sel.end(), + false, + ), sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 3 } }).?, + ).?); + + // Middle line + try testing.expectEqual(Selection.init( + s.pages.pin(.{ .screen = .{ .x = 0, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = s.pages.cols - 1, .y = 2 } }).?, + false, + ), sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + ).?); + } + + // Rectangle + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 6, .y = 3 } }).?, + true, + ); + + // Not contained + try testing.expect(sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 4 } }).?, + ) == null); + + // Start line + try testing.expectEqual(Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 6, .y = 1 } }).?, + true, + ), sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + ).?); + + // End line + try testing.expectEqual(Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 3 } }).?, + s.pages.pin(.{ .screen = .{ .x = 6, .y = 3 } }).?, + true, + ), sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 3 } }).?, + ).?); + + // Middle line + try testing.expectEqual(Selection.init( + s.pages.pin(.{ .screen = .{ .x = 3, .y = 2 } }).?, + s.pages.pin(.{ .screen = .{ .x = 6, .y = 2 } }).?, + true, + ), sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 2, .y = 2 } }).?, + ).?); + } + + // Single-line selection + { + const sel = Selection.init( + s.pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?, + s.pages.pin(.{ .screen = .{ .x = 6, .y = 1 } }).?, + false, + ); + + // Not contained + try testing.expect(sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 0 } }).?, + ) == null); + try testing.expect(sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 2 } }).?, + ) == null); + + // Contained + try testing.expectEqual(sel, sel.containedRow( + &s, + s.pages.pin(.{ .screen = .{ .x = 1, .y = 1 } }).?, + ).?); + } +} diff --git a/vendor/libghostty-vt/src/terminal/StringMap.zig b/vendor/libghostty-vt/src/terminal/StringMap.zig new file mode 100644 index 00000000..18dd7b19 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/StringMap.zig @@ -0,0 +1,298 @@ +/// A string along with the mapping of each individual byte in the string +/// to the point in the screen. +const StringMap = @This(); + +const std = @import("std"); +const build_options = @import("terminal_options"); +const oni = @import("oniguruma"); +const point = @import("point.zig"); +const Selection = @import("Selection.zig"); +const Screen = @import("Screen.zig"); +const Pin = @import("PageList.zig").Pin; +const Allocator = std.mem.Allocator; + +// Retry budget for StringMap regex searches. +// +// Units are Oniguruma retry steps (internal backtracking/retry counter), +// not bytes/characters/time. +const oni_search_retry_limit = 100_000; + +string: [:0]const u8, +map: []Pin, + +pub fn deinit(self: StringMap, alloc: Allocator) void { + alloc.free(self.string); + alloc.free(self.map); +} + +/// Returns an iterator that yields the next match of the given regex. +/// Requires Ghostty to be compiled with regex support. +pub const searchIterator = if (build_options.oniguruma) + searchIteratorOni +else + void; + +fn searchIteratorOni( + self: StringMap, + regex: oni.Regex, +) SearchIterator { + return .{ .map = self, .regex = regex }; +} + +/// Iterates over the regular expression matches of the string. +pub const SearchIterator = struct { + map: StringMap, + regex: oni.Regex, + offset: usize = 0, + + /// Returns the next regular expression match or null if there are + /// no more matches. + pub fn next(self: *SearchIterator) !?Match { + if (self.offset >= self.map.string.len) return null; + + // Use per-search match params so we can bound regex retry steps + // (Oniguruma's internal backtracking work counter). + var match_param = try oni.MatchParam.init(); + defer match_param.deinit(); + try match_param.setRetryLimitInSearch(oni_search_retry_limit); + + var region = self.regex.searchWithParam( + self.map.string[self.offset..], + .{}, + &match_param, + ) catch |err| switch (err) { + // Retry/stack-limit errors mean we hit our work budget and + // aborted matching. + // For iterator callers this is equivalent to "no further matches". + error.Mismatch, + error.RetryLimitInMatchOver, + error.RetryLimitInSearchOver, + error.MatchStackLimitOver, + error.SubexpCallLimitInSearchOver, + => { + self.offset = self.map.string.len; + return null; + }, + + else => return err, + }; + errdefer region.deinit(); + + // Increment our offset by the number of bytes in the match. + // We defer this so that we can return the match before + // modifying the offset. + const end_idx: usize = @intCast(region.ends()[0]); + defer self.offset += end_idx; + + return .{ + .map = self.map, + .offset = self.offset, + .region = region, + }; + } +}; + +/// A single regular expression match. +pub const Match = struct { + map: StringMap, + offset: usize, + region: oni.Region, + + pub fn deinit(self: *Match) void { + self.region.deinit(); + } + + /// Returns the selection containing the full match. + pub fn selection(self: Match) Selection { + const start_idx: usize = @intCast(self.region.starts()[0]); + const end_idx: usize = @intCast(self.region.ends()[0] - 1); + const start_pt = self.map.map[self.offset + start_idx]; + const end_pt = self.map.map[self.offset + end_idx]; + return .init(start_pt, end_pt, false); + } +}; + +test "StringMap searchIterator" { + if (comptime !build_options.oniguruma) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + // Initialize our regex + try oni.testing.ensureInit(); + var re = try oni.Regex.init( + "[A-B]{2}", + .{}, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ); + defer re.deinit(); + + // Initialize our screen + var s = try Screen.init(alloc, .{ .cols = 5, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + const str = "1ABCD2EFGH\n3IJKL"; + try s.testWriteString(str); + const line = s.selectLine(.{ + .pin = s.pages.pin(.{ .active = .{ + .x = 2, + .y = 1, + } }).?, + }).?; + var map: StringMap = undefined; + const sel_str = try s.selectionString(alloc, .{ + .sel = line, + .trim = false, + .map = &map, + }); + alloc.free(sel_str); + defer map.deinit(alloc); + + // Get our iterator + var it = map.searchIterator(re); + { + var match = (try it.next()).?; + defer match.deinit(); + + const sel = match.selection(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 2, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + try testing.expect(try it.next() == null); +} + +test "StringMap searchIterator URL detection" { + if (comptime !build_options.oniguruma) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const url = @import("../config/url.zig"); + + // Initialize URL regex + try oni.testing.ensureInit(); + var re = try oni.Regex.init( + url.regex, + .{}, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ); + defer re.deinit(); + + // Initialize our screen with text containing a URL + var s = try Screen.init(alloc, .{ .cols = 40, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello https://example.com/path world"); + + // Get the line + const line = s.selectLine(.{ + .pin = s.pages.pin(.{ .active = .{ + .x = 10, + .y = 0, + } }).?, + }).?; + var map: StringMap = undefined; + const sel_str = try s.selectionString(alloc, .{ + .sel = line, + .trim = false, + .map = &map, + }); + alloc.free(sel_str); + defer map.deinit(alloc); + + // Search for URL match + var it = map.searchIterator(re); + { + var match = (try it.next()).?; + defer match.deinit(); + + const sel = match.selection(); + // URL should start at x=6 ("https://example.com/path" starts after "hello ") + try testing.expectEqual(point.Point{ .screen = .{ + .x = 6, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + // URL should end at x=29 (end of "/path") + try testing.expectEqual(point.Point{ .screen = .{ + .x = 29, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + } + + try testing.expect(try it.next() == null); +} + +test "StringMap searchIterator URL with click position" { + if (comptime !build_options.oniguruma) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + const url = @import("../config/url.zig"); + + // Initialize URL regex + try oni.testing.ensureInit(); + var re = try oni.Regex.init( + url.regex, + .{}, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ); + defer re.deinit(); + + // Initialize our screen with text containing a URL + var s = try Screen.init(alloc, .{ .cols = 40, .rows = 5, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello https://example.com world"); + + // Simulate clicking on "example" (x=14) + const click_pin = s.pages.pin(.{ .active = .{ + .x = 14, + .y = 0, + } }).?; + + // Get the line + const line = s.selectLine(.{ + .pin = click_pin, + }).?; + var map: StringMap = undefined; + const sel_str = try s.selectionString(alloc, .{ + .sel = line, + .trim = false, + .map = &map, + }); + alloc.free(sel_str); + defer map.deinit(alloc); + + // Search for URL match and verify click position is within URL + var it = map.searchIterator(re); + var found_url = false; + while (true) { + var match = (try it.next()) orelse break; + defer match.deinit(); + + const sel = match.selection(); + if (sel.contains(&s, click_pin)) { + found_url = true; + // Verify URL bounds + try testing.expectEqual(point.Point{ .screen = .{ + .x = 6, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.start()).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 24, + .y = 0, + } }, s.pages.pointFromPin(.screen, sel.end()).?); + break; + } + } + try testing.expect(found_url); +} diff --git a/vendor/libghostty-vt/src/terminal/Tabstops.zig b/vendor/libghostty-vt/src/terminal/Tabstops.zig new file mode 100644 index 00000000..68138cbf --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/Tabstops.zig @@ -0,0 +1,271 @@ +//! Keep track of the location of tabstops. +//! +//! This is implemented as a bit set. There is a preallocation segment that +//! is used for almost all screen sizes. Then there is a dynamically allocated +//! segment if the screen is larger than the preallocation amount. +//! +//! In reality, tabstops don't need to be the most performant in any metric. +//! This implementation tries to balance denser memory usage (by using a bitset) +//! and minimizing unnecessary allocations. +const Tabstops = @This(); + +const std = @import("std"); +const tripwire = @import("../tripwire.zig"); +const Allocator = std.mem.Allocator; +const testing = std.testing; +const assert = @import("../quirks.zig").inlineAssert; +const fastmem = @import("../fastmem.zig"); + +/// Unit is the type we use per tabstop unit (see file docs). +const Unit = u8; +const unit_bits = @bitSizeOf(Unit); + +/// The number of columns we preallocate for. This is kind of high which +/// costs us some memory, but this is more columns than my 6k monitor at +/// 12-point font size, so this should prevent allocation in almost all +/// real world scenarios for the price of wasting at most +/// (columns / sizeOf(Unit)) bytes. +const prealloc_columns = 512; + +/// The number of entries we need for our preallocation. +const prealloc_count = prealloc_columns / unit_bits; + +/// We precompute all the possible masks since we never use a huge bit size. +const masks = blk: { + var res: [unit_bits]Unit = undefined; + for (res, 0..) |_, i| { + res[i] = @shlExact(@as(Unit, 1), @as(u3, @intCast(i))); + } + + break :blk res; +}; + +/// The number of columns this tabstop is set to manage. Use resize() +/// to change this number. +cols: usize = 0, + +/// Preallocated tab stops. +prealloc_stops: [prealloc_count]Unit = @splat(0), + +/// Dynamically expanded stops above prealloc stops. +dynamic_stops: []Unit = &[0]Unit{}, + +/// Returns the entry in the stops array that would contain this column. +inline fn entry(col: usize) usize { + return col / unit_bits; +} + +inline fn index(col: usize) usize { + return @mod(col, unit_bits); +} + +pub fn init( + alloc: Allocator, + cols: usize, + interval: usize, +) Allocator.Error!Tabstops { + var res: Tabstops = .{}; + try res.resize(alloc, cols); + res.reset(interval); + return res; +} + +pub fn deinit(self: *Tabstops, alloc: Allocator) void { + if (self.dynamic_stops.len > 0) alloc.free(self.dynamic_stops); + self.* = undefined; +} + +/// Set the tabstop at a certain column. The columns are 0-indexed. +pub fn set(self: *Tabstops, col: usize) void { + const i = entry(col); + const idx = index(col); + if (i < prealloc_count) { + self.prealloc_stops[i] |= masks[idx]; + return; + } + + const dynamic_i = i - prealloc_count; + assert(dynamic_i < self.dynamic_stops.len); + self.dynamic_stops[dynamic_i] |= masks[idx]; +} + +/// Unset the tabstop at a certain column. The columns are 0-indexed. +pub fn unset(self: *Tabstops, col: usize) void { + const i = entry(col); + const idx = index(col); + if (i < prealloc_count) { + self.prealloc_stops[i] ^= masks[idx]; + return; + } + + const dynamic_i = i - prealloc_count; + assert(dynamic_i < self.dynamic_stops.len); + self.dynamic_stops[dynamic_i] ^= masks[idx]; +} + +/// Get the value of a tabstop at a specific column. The columns are 0-indexed. +pub fn get(self: Tabstops, col: usize) bool { + const i = entry(col); + const idx = index(col); + const mask = masks[idx]; + const unit = if (i < prealloc_count) + self.prealloc_stops[i] + else unit: { + const dynamic_i = i - prealloc_count; + assert(dynamic_i < self.dynamic_stops.len); + break :unit self.dynamic_stops[dynamic_i]; + }; + + return unit & mask == mask; +} + +const resize_tw = tripwire.module(enum { + dynamic_alloc, +}, resize); + +/// Resize this to support up to cols columns. +// TODO: needs interval to set new tabstops +pub fn resize( + self: *Tabstops, + alloc: Allocator, + cols: usize, +) Allocator.Error!void { + const tw = resize_tw; + + // Do nothing if it fits. + if (cols <= prealloc_columns) { + self.cols = cols; + return; + } + + // What we need in the dynamic size + const size = cols - prealloc_columns; + if (size < self.dynamic_stops.len) { + self.cols = cols; + return; + } + + // Note: we can probably try to realloc here but I'm not sure it matters. + try tw.check(.dynamic_alloc); + const new = try alloc.alloc(Unit, size); + errdefer comptime unreachable; + @memset(new, 0); + if (self.dynamic_stops.len > 0) { + fastmem.copy(Unit, new, self.dynamic_stops); + alloc.free(self.dynamic_stops); + } + + self.dynamic_stops = new; + self.cols = cols; +} + +/// Return the maximum number of columns this can support currently. +pub fn capacity(self: Tabstops) usize { + return (prealloc_count + self.dynamic_stops.len) * unit_bits; +} + +/// Unset all tabstops and then reset the initial tabstops to the given +/// interval. An interval of 0 sets no tabstops. +pub fn reset(self: *Tabstops, interval: usize) void { + @memset(&self.prealloc_stops, 0); + @memset(self.dynamic_stops, 0); + + if (interval > 0) { + var i: usize = interval; + while (i < self.cols - 1) : (i += interval) { + self.set(i); + } + } +} + +test "Tabstops: basic" { + var t: Tabstops = .{}; + defer t.deinit(testing.allocator); + try testing.expectEqual(@as(usize, 0), entry(4)); + try testing.expectEqual(@as(usize, 1), entry(8)); + try testing.expectEqual(@as(usize, 0), index(0)); + try testing.expectEqual(@as(usize, 1), index(1)); + try testing.expectEqual(@as(usize, 1), index(9)); + + try testing.expectEqual(@as(Unit, 0b00001000), masks[3]); + try testing.expectEqual(@as(Unit, 0b00010000), masks[4]); + + try testing.expect(!t.get(4)); + t.set(4); + try testing.expect(t.get(4)); + try testing.expect(!t.get(3)); + + t.reset(0); + try testing.expect(!t.get(4)); + + t.set(4); + try testing.expect(t.get(4)); + t.unset(4); + try testing.expect(!t.get(4)); +} + +test "Tabstops: dynamic allocations" { + var t: Tabstops = .{}; + defer t.deinit(testing.allocator); + + // Grow the capacity by 2. + const cap = t.capacity(); + try t.resize(testing.allocator, cap * 2); + + // Set something that was out of range of the first + t.set(cap + 5); + try testing.expect(t.get(cap + 5)); + try testing.expect(!t.get(cap + 4)); + + // Prealloc still works + try testing.expect(!t.get(5)); +} + +test "Tabstops: interval" { + var t: Tabstops = try init(testing.allocator, 80, 4); + defer t.deinit(testing.allocator); + try testing.expect(!t.get(0)); + try testing.expect(t.get(4)); + try testing.expect(!t.get(5)); + try testing.expect(t.get(8)); +} + +test "Tabstops: count on 80" { + // https://superuser.com/questions/710019/why-there-are-11-tabstops-on-a-80-column-console + + var t: Tabstops = try init(testing.allocator, 80, 8); + defer t.deinit(testing.allocator); + + // Count the tabstops + const count: usize = count: { + var v: usize = 0; + var i: usize = 0; + while (i < 80) : (i += 1) { + if (t.get(i)) { + v += 1; + } + } + + break :count v; + }; + + try testing.expectEqual(@as(usize, 9), count); +} + +test "Tabstops: resize alloc failure preserves state" { + // This test verifies that if resize() fails during allocation, + // the original cols value is preserved (not corrupted). + var t: Tabstops = try init(testing.allocator, 80, 8); + defer t.deinit(testing.allocator); + + const original_cols = t.cols; + + // Trigger allocation failure when resizing beyond prealloc + resize_tw.errorAlways(.dynamic_alloc, error.OutOfMemory); + const result = t.resize(testing.allocator, prealloc_columns * 2); + try testing.expectError(error.OutOfMemory, result); + try resize_tw.end(.reset); + + // cols should be unchanged after failed resize + try testing.expectEqual(original_cols, t.cols); +} diff --git a/vendor/libghostty-vt/src/terminal/Terminal.zig b/vendor/libghostty-vt/src/terminal/Terminal.zig new file mode 100644 index 00000000..99536e7a --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/Terminal.zig @@ -0,0 +1,13089 @@ +//! The primary terminal emulation structure. This represents a single +//! "terminal" containing a grid of characters and exposes various operations +//! on that grid. This also maintains the scrollback buffer. +const Terminal = @This(); + +const std = @import("std"); +const build_options = @import("terminal_options"); +const lib = @import("lib.zig"); +const assert = @import("../quirks.zig").inlineAssert; +const testing = std.testing; +const Allocator = std.mem.Allocator; +const unicode = @import("../unicode/main.zig"); +const uucode = @import("uucode"); + +const ansi = @import("ansi.zig"); +const modespkg = @import("modes.zig"); +const charsets = @import("charsets.zig"); +const csi = @import("csi.zig"); +const hyperlink = @import("hyperlink.zig"); +const kitty = @import("kitty.zig"); +const osc = @import("osc.zig"); +const point = @import("point.zig"); +const sgr = @import("sgr.zig"); +const Tabstops = @import("Tabstops.zig"); +const color = @import("color.zig"); +const mouse = @import("mouse.zig"); +const Stream = @import("stream_terminal.zig").Stream; + +const size = @import("size.zig"); +const pagepkg = @import("page.zig"); +const style = @import("style.zig"); +const Screen = @import("Screen.zig"); +const ScreenSet = @import("ScreenSet.zig"); +const Page = pagepkg.Page; +const Cell = pagepkg.Cell; +const Row = pagepkg.Row; + +const log = std.log.scoped(.terminal); + +/// Default tabstop interval +const TABSTOP_INTERVAL = 8; + +/// The set of screens behind this terminal (e.g. primary vs alternate). +screens: ScreenSet, + +/// Whether we're currently writing to the status line (DECSASD and DECSSDT). +/// We don't support a status line currently so we just black hole this +/// data so that it doesn't mess up our main display. +status_display: ansi.StatusDisplay = .main, + +/// Where the tabstops are. +tabstops: Tabstops, + +/// The size of the terminal. +rows: size.CellCountInt, +cols: size.CellCountInt, + +/// The size of the screen in pixels. This is used for pty events and images +width_px: u32 = 0, +height_px: u32 = 0, + +/// The current scrolling region. +scrolling_region: ScrollingRegion, + +/// The last reported pwd, if any. +pwd: std.ArrayList(u8), + +/// The title of the terminal as set by escape sequences (e.g. OSC 0/2). +title: std.ArrayList(u8), + +/// The color state for this terminal. +colors: Colors, + +/// The previous printed character. This is used for the repeat previous +/// char CSI (ESC [ b). +previous_char: ?u21 = null, + +/// The modes that this terminal currently has active. +modes: modespkg.ModeState = .{}, + +/// The most recently set mouse shape for the terminal. +mouse_shape: mouse.Shape = .text, + +/// These are just a packed set of flags we may set on the terminal. +flags: packed struct { + // This supports a Kitty extension where programs using semantic + // prompts (OSC133) can annotate their new prompts with `redraw=0` to + // disable clearing the prompt on resize. + shell_redraws_prompt: osc.semantic_prompt.Redraw = .true, + + // This is set via ESC[4;2m. Any other modify key mode just sets + // this to false and we act in mode 1 by default. + modify_other_keys_2: bool = false, + + /// The mouse event mode and format. These are set to the last + /// set mode in modes. You can't get the right event/format to use + /// based on modes alone because modes don't show you what order + /// this was called so we have to track it separately. + mouse_event: mouse.Event = .none, + mouse_format: mouse.Format = .x10, + + /// Set via the XTSHIFTESCAPE sequence. If true (XTSHIFTESCAPE = 1) + /// then we want to capture the shift key for the mouse protocol + /// if the configuration allows it. + mouse_shift_capture: enum(u2) { null, false, true } = .null, + + /// True if the window is focused. + focused: bool = true, + + /// True if the terminal is in a password entry mode. This is set + /// to true based on termios state. This is set + /// to true based on termios state. + password_input: bool = false, + + /// True if the terminal should perform selection scrolling. + selection_scroll: bool = false, + + /// Dirty flag used only by the search thread. The renderer is expected + /// to set this to true if the viewport was dirty as it was rendering. + /// This is used by the search thread to more efficiently re-search the + /// viewport and active area. + /// + /// Since the renderer is going to inspect the viewport/active area ANYWAYS, + /// this lets our search thread do less work and hold the lock less time, + /// resulting in more throughput for everything. + search_viewport_dirty: bool = false, + + /// Dirty flags for the renderer. + dirty: Dirty = .{}, +} = .{}, + +/// The various color configurations a terminal maintains and that can +/// be set dynamically via OSC, with defaults usually coming from a +/// configuration. +pub const Colors = struct { + background: color.DynamicRGB, + foreground: color.DynamicRGB, + cursor: color.DynamicRGB, + palette: color.DynamicPalette, + + pub const default: Colors = .{ + .background = .unset, + .foreground = .unset, + .cursor = .unset, + .palette = .default, + }; +}; + +/// This is a set of dirty flags the renderer can use to determine +/// what parts of the screen need to be redrawn. It is up to the renderer +/// to clear these flags. +/// +/// This only contains dirty flags for terminal state, not for the screen +/// state. The screen state has its own dirty flags. +pub const Dirty = packed struct { + /// Set when the color palette is modified in any way. + palette: bool = false, + + /// Set when the reverse colors mode is modified. + reverse_colors: bool = false, + + /// Screen clear of some kind. This can be due to a screen change, + /// erase display, etc. + clear: bool = false, + + /// Set when the pre-edit is modified. + preedit: bool = false, +}; + +/// Scrolling region is the area of the screen designated where scrolling +/// occurs. When scrolling the screen, only this viewport is scrolled. +pub const ScrollingRegion = struct { + // Top and bottom of the scroll region (0-indexed) + // Precondition: top < bottom + top: size.CellCountInt, + bottom: size.CellCountInt, + + // Left/right scroll regions. + // Precondition: right > left + // Precondition: right <= cols - 1 + left: size.CellCountInt, + right: size.CellCountInt, +}; + +pub const Options = struct { + cols: size.CellCountInt, + rows: size.CellCountInt, + max_scrollback: usize = 10_000, + colors: Colors = .default, + + /// The default mode state. When the terminal gets a reset, it + /// will revert back to this state. + default_modes: modespkg.ModePacked = .{}, +}; + +/// Initialize a new terminal. +pub fn init( + alloc: Allocator, + opts: Options, +) !Terminal { + const cols = opts.cols; + const rows = opts.rows; + + var screen_set: ScreenSet = try .init(alloc, .{ + .cols = cols, + .rows = rows, + .max_scrollback = opts.max_scrollback, + }); + errdefer screen_set.deinit(alloc); + + return .{ + .cols = cols, + .rows = rows, + .screens = screen_set, + .tabstops = try .init(alloc, cols, TABSTOP_INTERVAL), + .scrolling_region = .{ + .top = 0, + .bottom = rows - 1, + .left = 0, + .right = cols - 1, + }, + .pwd = .empty, + .title = .empty, + .colors = opts.colors, + .modes = .{ + .values = opts.default_modes, + .default = opts.default_modes, + }, + }; +} + +pub fn deinit(self: *Terminal, alloc: Allocator) void { + self.tabstops.deinit(alloc); + self.screens.deinit(alloc); + self.pwd.deinit(alloc); + self.title.deinit(alloc); + self.* = undefined; +} + +/// Return a terminal.Stream that can process VT streams and update this +/// terminal state. The streams will only process read-only data that +/// modifies terminal state. +/// +/// Sequences that query or otherwise require output will be ignored. +/// If you want to handle side effects, use `vtHandler` and set the +/// effects field yourself, then initialize a stream. +/// +/// This must be deinitialized by the caller. +/// +/// Important: this creates a new stream each time with fresh parser state. +/// If you need to persist parser state across multiple writes (e.g. +/// for handling escape sequences split across write boundaries), you +/// must store and reuse the returned stream. +pub fn vtStream(self: *Terminal) Stream { + return .initAlloc(self.gpa(), self.vtHandler()); +} + +/// This is the handler-side only for vtStream. +pub fn vtHandler(self: *Terminal) Stream.Handler { + return .init(self); +} + +/// The general allocator we should use for this terminal. +pub fn gpa(self: *Terminal) Allocator { + return self.screens.active.alloc; +} + +/// Print UTF-8 encoded string to the terminal. +pub fn printString(self: *Terminal, str: []const u8) !void { + const view = try std.unicode.Utf8View.init(str); + var it = view.iterator(); + while (it.nextCodepoint()) |cp| { + switch (cp) { + '\n' => { + self.carriageReturn(); + try self.linefeed(); + }, + + else => try self.print(cp), + } + } +} + +/// Print the previous printed character a repeated amount of times. +pub fn printRepeat(self: *Terminal, count_req: usize) !void { + if (self.previous_char) |c| { + const count = @max(count_req, 1); + for (0..count) |_| try self.print(c); + } +} + +pub fn print(self: *Terminal, c: u21) !void { + // log.debug("print={x} y={} x={}", .{ c, self.screens.active.cursor.y, self.screens.active.cursor.x }); + + // If we're not on the main display, do nothing for now + if (self.status_display != .main) { + @branchHint(.cold); + return; + } + + // After doing any printing, wrapping, scrolling, etc. we want to ensure + // that our screen remains in a consistent state. + defer self.screens.active.assertIntegrity(); + + // Our right margin depends where our cursor is now. + const right_limit = if (self.screens.active.cursor.x > self.scrolling_region.right) + self.cols + else + self.scrolling_region.right + 1; + + // Perform grapheme clustering if grapheme support is enabled (mode 2027). + // This is MUCH slower than the normal path so the conditional below is + // purposely ordered in least-likely to most-likely so we can drop out + // as quickly as possible. + if (c > 255 and + self.modes.get(.grapheme_cluster) and + self.screens.active.cursor.x > 0) + grapheme: { + @branchHint(.unlikely); + // We need the previous cell to determine if we're at a grapheme + // break or not. If we are NOT, then we are still combining the + // same grapheme, and will be appending to prev.cell. Otherwise, we are + // in a new cell. + const Prev = struct { cell: *Cell, left: size.CellCountInt }; + var prev: Prev = prev: { + const left: size.CellCountInt = left: { + // If we have wraparound, then we use the prev col unless + // there's a pending wrap, in which case we use the current. + if (self.modes.get(.wraparound)) { + break :left @intFromBool(!self.screens.active.cursor.pending_wrap); + } + + // If we do not have wraparound, the logic is trickier. If + // we're not on the last column, then we just use the previous + // column. Otherwise, we need to check if there is text to + // figure out if we're attaching to the prev or current. + if (self.screens.active.cursor.x != right_limit - 1) break :left 1; + break :left @intFromBool(self.screens.active.cursor.page_cell.codepoint() == 0); + }; + + // If the previous cell is a wide spacer tail, then we actually + // want to use the cell before that because that has the actual + // content. + const immediate = self.screens.active.cursorCellLeft(left); + break :prev switch (immediate.wide) { + else => .{ .cell = immediate, .left = left }, + .spacer_tail => .{ + .cell = self.screens.active.cursorCellLeft(left + 1), + .left = left + 1, + }, + }; + }; + + // If our cell has no content, then this is a new cell and + // necessarily a grapheme break. + if (prev.cell.codepoint() == 0) break :grapheme; + + const grapheme_break = brk: { + var state: uucode.grapheme.BreakState = .default; + var cp1: u21 = prev.cell.content.codepoint; + if (prev.cell.hasGrapheme()) { + const cps = self.screens.active.cursor.page_pin.node.data.lookupGrapheme(prev.cell).?; + for (cps) |cp2| { + // log.debug("cp1={x} cp2={x}", .{ cp1, cp2 }); + assert(!unicode.graphemeBreak(cp1, cp2, &state)); + cp1 = cp2; + } + } + + // log.debug("cp1={x} cp2={x} end", .{ cp1, c }); + break :brk unicode.graphemeBreak(cp1, c, &state); + }; + + // If we can NOT break, this means that "c" is part of a grapheme + // with the previous char. + if (!grapheme_break) { + var desired_wide: enum { no_change, wide, narrow } = .no_change; + + // If this is an emoji variation selector then we need to modify + // the cell width accordingly. VS16 makes the character wide and + // VS15 makes it narrow. + if (c == 0xFE0F or c == 0xFE0E) { + const prev_props = unicode.table.get(prev.cell.content.codepoint); + // Check if it is a valid variation sequence in + // emoji-variation-sequences.txt, and if not, ignore the char. + if (!prev_props.emoji_vs_base) return; + + switch (c) { + 0xFE0F => desired_wide = .wide, + 0xFE0E => desired_wide = .narrow, + else => unreachable, + } + } else if (!unicode.table.get(c).width_zero_in_grapheme) { + // If we have a code point that contributes to the width of a + // grapheme, it necessarily means that we're at least at width + // 2, since the first code point must be at least width 1 to + // start. (Note that Prepend code points could effectively mean + // the first code point should be width 0, but we don't handle + // that yet.) + desired_wide = .wide; + } + + switch (desired_wide) { + .wide => wide: { + if (prev.cell.wide == .wide) break :wide; + + // Move our cursor back to the previous. We'll move + // the cursor within this block to the proper location. + self.screens.active.cursorLeft(prev.left); + + // If we don't have space for the wide char, we need to + // insert spacers and wrap. We need special handling if the + // previous cell has grapheme data. + if (self.screens.active.cursor.x == right_limit - 1) { + if (!self.modes.get(.wraparound)) return; + + // This path can write a spacer_head before printWrap + // which can trigger integrity violations so mark + // the wrap first to keep the intermediary state valid + // if we're wrapping. + const row_wrap = right_limit == self.cols; + if (row_wrap) self.screens.active.cursor.page_row.wrap = true; + + const prev_cp = prev.cell.content.codepoint; + if (prev.cell.hasGrapheme()) { + // This is like printCell but without clearing the + // grapheme data from the cell, so we can move it + // later. + prev.cell.wide = if (row_wrap) .spacer_head else .narrow; + prev.cell.content.codepoint = 0; + + try self.printWrap(); + self.printCell(prev_cp, .wide); + + const new_pin = self.screens.active.cursor.page_pin.*; + const new_rac = new_pin.rowAndCell(); + + transfer_graphemes: { + var old_pin = self.screens.active.cursor.page_pin.up(1) orelse break :transfer_graphemes; + old_pin.x = right_limit - 1; + const old_rac = old_pin.rowAndCell(); + + if (new_pin.node == old_pin.node) { + new_pin.node.data.moveGrapheme(prev.cell, new_rac.cell); + prev.cell.content_tag = .codepoint; + new_rac.cell.content_tag = .codepoint_grapheme; + new_rac.row.grapheme = true; + } else { + const cps = old_pin.node.data.lookupGrapheme(old_rac.cell).?; + for (cps) |cp| { + try self.screens.active.appendGrapheme(new_rac.cell, cp); + } + old_pin.node.data.clearGrapheme(old_rac.cell); + } + + old_pin.node.data.updateRowGraphemeFlag(old_rac.row); + } + + // Point prev.cell to our new previous cell that + // we'll be appending graphemes to + prev.cell = new_rac.cell; + } else { + self.printCell( + 0, + if (row_wrap) .spacer_head else .narrow, + ); + try self.printWrap(); + self.printCell(prev_cp, .wide); + + // Point prev.cell to our new previous cell that + // we'll be appending graphemes to + prev.cell = self.screens.active.cursor.page_cell; + } + } else { + prev.cell.wide = .wide; + } + + // Write our spacer, since prev.cell is now wide + self.screens.active.cursorRight(1); + self.printCell(0, .spacer_tail); + + // Move the cursor again so we're beyond our spacer + if (self.screens.active.cursor.x == right_limit - 1) { + self.screens.active.cursor.pending_wrap = true; + } else { + self.screens.active.cursorRight(1); + } + }, + + .narrow => narrow: { + // Prev cell is no longer wide + if (prev.cell.wide != .wide) break :narrow; + prev.cell.wide = .narrow; + + // Remove the wide spacer tail + const cell = self.screens.active.cursorCellLeft(prev.left - 1); + cell.wide = .narrow; + + // Back track the cursor so that we don't end up with + // an extra space after the character. Since xterm is + // not VS aware, it cannot be used as a reference for + // this behavior; but it does follow the principle of + // least surprise, and also matches the behavior that + // can be observed in Kitty, which is one of the only + // other VS aware terminals. + if (self.screens.active.cursor.x == right_limit - 1) { + // If we're already at the right edge, we stay + // here and set the pending wrap to false since + // when we pend a wrap, we only move our cursor once + // even for wide chars (tests verify). + self.screens.active.cursor.pending_wrap = false; + } else { + // Otherwise, move back. + self.screens.active.cursorLeft(1); + } + + break :narrow; + }, + + else => {}, + } + + log.debug("c={X} grapheme attach to left={} primary_cp={X}", .{ + c, + prev.left, + prev.cell.codepoint(), + }); + self.screens.active.cursorMarkDirty(); + try self.screens.active.appendGrapheme(prev.cell, c); + return; + } + } + + // Determine the width of this character so we can handle + // non-single-width characters properly. We have a fast-path for + // byte-sized characters since they're so common. We can ignore + // control characters because they're always filtered prior. + const width: usize = if (c <= 0xFF) 1 else @intCast(unicode.table.get(c).width); + + // Note: it is possible to have a width of "3" and a width of "-1" from + // uucode.x's wcwidth. We should look into those cases and handle them + // appropriately. + assert(width <= 2); + // log.debug("c={x} width={}", .{ c, width }); + + // Attach zero-width characters to our cell as grapheme data. + if (width == 0) { + @branchHint(.unlikely); + // If we have grapheme clustering enabled, we don't blindly attach + // any zero width character to our cells and we instead just ignore + // it. + if (self.modes.get(.grapheme_cluster)) return; + + // If we're at cell zero, then this is malformed data and we don't + // print anything or even store this. Zero-width characters are ALWAYS + // attached to some other non-zero-width character at the time of + // writing. + if (self.screens.active.cursor.x == 0) { + log.warn("zero-width character with no prior character, ignoring", .{}); + return; + } + + // Find our previous cell + const prev = prev: { + const immediate = self.screens.active.cursorCellLeft(1); + if (immediate.wide != .spacer_tail) break :prev immediate; + break :prev self.screens.active.cursorCellLeft(2); + }; + + // If our previous cell has no text, just ignore the zero-width character + if (!prev.hasText()) { + log.warn("zero-width character with no prior character, ignoring", .{}); + return; + } + + // If this is a emoji variation selector, prev must be an emoji + if (c == 0xFE0F or c == 0xFE0E) { + const prev_props = unicode.table.get(prev.content.codepoint); + const emoji = prev_props.grapheme_break == .extended_pictographic; + if (!emoji) return; + } + + try self.screens.active.appendGrapheme(prev, c); + return; + } + + // We have a printable character, save it + self.previous_char = c; + + // If we're soft-wrapping, then handle that first. + if (self.screens.active.cursor.pending_wrap and self.modes.get(.wraparound)) { + try self.printWrap(); + } + + // If we have insert mode enabled then we need to handle that. We + // only do insert mode if we're not at the end of the line. + if (self.modes.get(.insert) and + self.screens.active.cursor.x + width < self.cols) + { + self.insertBlanks(width); + } + + switch (width) { + // Single cell is very easy: just write in the cell + 1 => { + @branchHint(.likely); + self.screens.active.cursorMarkDirty(); + @call(.always_inline, printCell, .{ self, c, .narrow }); + }, + + // Wide character requires a spacer. We print this by + // using two cells: the first is flagged "wide" and has the + // wide char. The second is guaranteed to be a spacer if + // we're not at the end of the line. + 2 => if ((right_limit - self.scrolling_region.left) > 1) { + // If we don't have space for the wide char, we need + // to insert spacers and wrap. Then we just print the wide + // char as normal. + if (self.screens.active.cursor.x == right_limit - 1) { + // If we don't have wraparound enabled then we don't print + // this character at all and don't move the cursor. This is + // how xterm behaves. + if (!self.modes.get(.wraparound)) return; + + // We only create a spacer head if we're at the real edge + // of the screen. Otherwise, we clear the space with a narrow. + // This allows soft wrapping to work correctly. + if (right_limit == self.cols) { + // Special-case: we need to set wrap to true even + // though we call printWrap below because if there is + // a page resize during printCell then it'll fail + // integrity checks. + self.screens.active.cursor.page_row.wrap = true; + self.printCell(0, .spacer_head); + } else { + self.printCell(0, .narrow); + } + try self.printWrap(); + } + + self.screens.active.cursorMarkDirty(); + self.printCell(c, .wide); + self.screens.active.cursorRight(1); + self.printCell(0, .spacer_tail); + } else { + // This is pretty broken, terminals should never be only 1-wide. + // We should prevent this downstream. + self.screens.active.cursorMarkDirty(); + self.printCell(0, .narrow); + }, + + else => unreachable, + } + + // If we're at the column limit, then we need to wrap the next time. + // In this case, we don't move the cursor. + if (self.screens.active.cursor.x == right_limit - 1) { + self.screens.active.cursor.pending_wrap = true; + return; + } + + // Move the cursor + self.screens.active.cursorRight(1); +} + +fn printCell( + self: *Terminal, + unmapped_c: u21, + wide: Cell.Wide, +) void { + defer self.screens.active.assertIntegrity(); + + // TODO: spacers should use a bgcolor only cell + + const c: u21 = c: { + // TODO: non-utf8 handling, gr + + // If we're single shifting, then we use the key exactly once. + const key = if (self.screens.active.charset.single_shift) |key_once| blk: { + self.screens.active.charset.single_shift = null; + break :blk key_once; + } else self.screens.active.charset.gl; + + const set = self.screens.active.charset.charsets.get(key); + + // UTF-8 or ASCII is used as-is + if (set == .utf8 or set == .ascii) { + @branchHint(.likely); + break :c unmapped_c; + } + + // If we're outside of ASCII range this is an invalid value in + // this table so we just return space. + if (unmapped_c > std.math.maxInt(u8)) break :c ' '; + + // Get our lookup table and map it + const table = charsets.table(set); + break :c @intCast(table[@intCast(unmapped_c)]); + }; + + const cell = self.screens.active.cursor.page_cell; + + // If the wide property of this cell is the same, then we don't + // need to do the special handling here because the structure will + // be the same. If it is NOT the same, then we may need to clear some + // cells. + if (cell.wide != wide) { + switch (cell.wide) { + // Previous cell was narrow. Do nothing. + .narrow => {}, + + // Previous cell was wide. We need to clear the tail and head. + .wide => wide: { + if (self.screens.active.cursor.x >= self.cols - 1) break :wide; + + const spacer_cell = self.screens.active.cursorCellRight(1); + self.screens.active.clearCells( + &self.screens.active.cursor.page_pin.node.data, + self.screens.active.cursor.page_row, + spacer_cell[0..1], + ); + + // If we're near the left edge, a wide char may have + // wrapped from the previous row, leaving a spacer_head + // at the end of that row. Clear it so the previous row + // doesn't keep a stale spacer_head. + if (self.screens.active.cursor.y > 0 and self.screens.active.cursor.x <= 1) { + const head_cell = self.screens.active.cursorCellEndOfPrev(); + if (head_cell.wide == .spacer_head) head_cell.wide = .narrow; + } + }, + + .spacer_tail => { + assert(self.screens.active.cursor.x > 0); + + // So integrity checks pass. We fix this up later so we don't + // need to do this without safety checks. + if (comptime std.debug.runtime_safety) { + cell.wide = .narrow; + } + + const wide_cell = self.screens.active.cursorCellLeft(1); + self.screens.active.clearCells( + &self.screens.active.cursor.page_pin.node.data, + self.screens.active.cursor.page_row, + wide_cell[0..1], + ); + // If we're near the left edge, a wide char may have + // wrapped from the previous row, leaving a spacer_head + // at the end of that row. Clear it so the previous row + // doesn't keep a stale spacer_head. + if (self.screens.active.cursor.y > 0 and self.screens.active.cursor.x <= 1) { + const head_cell = self.screens.active.cursorCellEndOfPrev(); + if (head_cell.wide == .spacer_head) head_cell.wide = .narrow; + } + }, + + // TODO: this case was not handled in the old terminal implementation + // but it feels like we should do something. investigate other + // terminals (xterm mainly) and see what's up. + .spacer_head => {}, + } + } + + // If the prior value had graphemes, clear those + if (cell.hasGrapheme()) { + const page = &self.screens.active.cursor.page_pin.node.data; + page.clearGrapheme(cell); + page.updateRowGraphemeFlag(self.screens.active.cursor.page_row); + } + + // We don't need to update the style refs unless the + // cell's new style will be different after writing. + const style_changed = cell.style_id != self.screens.active.cursor.style_id; + if (style_changed) { + var page = &self.screens.active.cursor.page_pin.node.data; + + // Release the old style. + if (cell.style_id != style.default_id) { + assert(self.screens.active.cursor.page_row.styled); + page.styles.release(page.memory, cell.style_id); + } + } + + // Keep track if we had a hyperlink so we can unset it. + const had_hyperlink = cell.hyperlink; + + // Write + cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = c }, + .style_id = self.screens.active.cursor.style_id, + .wide = wide, + .protected = self.screens.active.cursor.protected, + .semantic_content = self.screens.active.cursor.semantic_content, + }; + + if (style_changed) { + var page = &self.screens.active.cursor.page_pin.node.data; + + // Use the new style. + if (cell.style_id != style.default_id) { + page.styles.use(page.memory, cell.style_id); + self.screens.active.cursor.page_row.styled = true; + } + } + + // If this is a Kitty unicode placeholder then we need to mark the + // row so that the renderer can lookup rows with these much faster. + if (comptime build_options.kitty_graphics) { + if (c == kitty.graphics.unicode.placeholder) { + @branchHint(.unlikely); + self.screens.active.cursor.page_row.kitty_virtual_placeholder = true; + } + } + + // We check for an active hyperlink first because setHyperlink + // handles clearing the old hyperlink and an optimization if we're + // overwriting the same hyperlink. + if (self.screens.active.cursor.hyperlink_id > 0) { + self.screens.active.cursorSetHyperlink() catch |err| { + @branchHint(.unlikely); + log.warn("error reallocating for more hyperlink space, ignoring hyperlink err={}", .{err}); + assert(!cell.hyperlink); + }; + } else if (had_hyperlink) { + // If the previous cell had a hyperlink then we need to clear it. + var page = &self.screens.active.cursor.page_pin.node.data; + page.clearHyperlink(cell); + page.updateRowHyperlinkFlag(self.screens.active.cursor.page_row); + } +} + +fn printWrap(self: *Terminal) !void { + // We only mark that we soft-wrapped if we're at the edge of our + // full screen. We don't mark the row as wrapped if we're in the + // middle due to a right margin. + const cursor: *Screen.Cursor = &self.screens.active.cursor; + const mark_wrap = cursor.x == self.cols - 1; + if (mark_wrap) cursor.page_row.wrap = true; + + // Get the old semantic prompt so we can extend it to the next + // line. We need to do this before we index() because we may + // modify memory. + const old_semantic = cursor.semantic_content; + const old_semantic_clear = cursor.semantic_content_clear_eol; + + // Move to the next line + try self.index(); + self.screens.active.cursorHorizontalAbsolute(self.scrolling_region.left); + + // Our pointer should never move + assert(cursor == &self.screens.active.cursor); + + // We always reset our semantic prompt state + cursor.semantic_content = old_semantic; + cursor.semantic_content_clear_eol = old_semantic_clear; + switch (old_semantic) { + .output, .input => {}, + .prompt => cursor.page_row.semantic_prompt = .prompt_continuation, + } + + if (mark_wrap) { + const row = self.screens.active.cursor.page_row; + // Always mark the row as a continuation + row.wrap_continuation = true; + } + + // Assure that our screen is consistent + self.screens.active.assertIntegrity(); +} + +/// Set the charset into the given slot. +pub fn configureCharset(self: *Terminal, slot: charsets.Slots, set: charsets.Charset) void { + self.screens.active.charset.charsets.set(slot, set); +} + +/// Invoke the charset in slot into the active slot. If single is true, +/// then this will only be invoked for a single character. +pub fn invokeCharset( + self: *Terminal, + active: charsets.ActiveSlot, + slot: charsets.Slots, + single: bool, +) void { + if (single) { + assert(active == .GL); + self.screens.active.charset.single_shift = slot; + return; + } + + switch (active) { + .GL => self.screens.active.charset.gl = slot, + .GR => self.screens.active.charset.gr = slot, + } +} + +/// Carriage return moves the cursor to the first column. +pub fn carriageReturn(self: *Terminal) void { + // Always reset pending wrap state + self.screens.active.cursor.pending_wrap = false; + + // In origin mode we always move to the left margin + self.screens.active.cursorHorizontalAbsolute(if (self.modes.get(.origin)) + self.scrolling_region.left + else if (self.screens.active.cursor.x >= self.scrolling_region.left) + self.scrolling_region.left + else + 0); +} + +/// Linefeed moves the cursor to the next line. +pub fn linefeed(self: *Terminal) !void { + try self.index(); + if (self.modes.get(.linefeed)) self.carriageReturn(); +} + +/// Backspace moves the cursor back a column (but not less than 0). +pub fn backspace(self: *Terminal) void { + self.cursorLeft(1); +} + +/// Move the cursor up amount lines. If amount is greater than the maximum +/// move distance then it is internally adjusted to the maximum. If amount is +/// 0, adjust it to 1. +pub fn cursorUp(self: *Terminal, count_req: usize) void { + // Always resets pending wrap + self.screens.active.cursor.pending_wrap = false; + + // The maximum amount the cursor can move up depends on scrolling regions + const max = if (self.screens.active.cursor.y >= self.scrolling_region.top) + self.screens.active.cursor.y - self.scrolling_region.top + else + self.screens.active.cursor.y; + const count = @min(max, @max(count_req, 1)); + + // We can safely intCast below because of the min/max clamping we did above. + self.screens.active.cursorUp(@intCast(count)); +} + +/// Move the cursor down amount lines. If amount is greater than the maximum +/// move distance then it is internally adjusted to the maximum. This sequence +/// will not scroll the screen or scroll region. If amount is 0, adjust it to 1. +pub fn cursorDown(self: *Terminal, count_req: usize) void { + // Always resets pending wrap + self.screens.active.cursor.pending_wrap = false; + + // The max the cursor can move to depends where the cursor currently is + const max = if (self.screens.active.cursor.y <= self.scrolling_region.bottom) + self.scrolling_region.bottom - self.screens.active.cursor.y + else + self.rows - self.screens.active.cursor.y - 1; + const count = @min(max, @max(count_req, 1)); + self.screens.active.cursorDown(@intCast(count)); +} + +/// Move the cursor right amount columns. If amount is greater than the +/// maximum move distance then it is internally adjusted to the maximum. +/// This sequence will not scroll the screen or scroll region. If amount is +/// 0, adjust it to 1. +pub fn cursorRight(self: *Terminal, count_req: usize) void { + // Always resets pending wrap + self.screens.active.cursor.pending_wrap = false; + + // The max the cursor can move to depends where the cursor currently is + const max = if (self.screens.active.cursor.x <= self.scrolling_region.right) + self.scrolling_region.right - self.screens.active.cursor.x + else + self.cols - self.screens.active.cursor.x - 1; + const count = @min(max, @max(count_req, 1)); + self.screens.active.cursorRight(@intCast(count)); +} + +/// Move the cursor to the left amount cells. If amount is 0, adjust it to 1. +pub fn cursorLeft(self: *Terminal, count_req: usize) void { + // Wrapping behavior depends on various terminal modes + const WrapMode = enum { none, reverse, reverse_extended }; + const wrap_mode: WrapMode = wrap_mode: { + if (!self.modes.get(.wraparound)) break :wrap_mode .none; + if (self.modes.get(.reverse_wrap_extended)) break :wrap_mode .reverse_extended; + if (self.modes.get(.reverse_wrap)) break :wrap_mode .reverse; + break :wrap_mode .none; + }; + + var count = @max(count_req, 1); + + // If we are in no wrap mode, then we move the cursor left and exit + // since this is the fastest and most typical path. + if (wrap_mode == .none) { + self.screens.active.cursorLeft(@min(count, self.screens.active.cursor.x)); + self.screens.active.cursor.pending_wrap = false; + return; + } + + // If we have a pending wrap state and we are in either reverse wrap + // modes then we decrement the amount we move by one to match xterm. + if (self.screens.active.cursor.pending_wrap) { + count -= 1; + self.screens.active.cursor.pending_wrap = false; + } + + // The margins we can move to. + const top = self.scrolling_region.top; + const bottom = self.scrolling_region.bottom; + const right_margin = self.scrolling_region.right; + const left_margin = if (self.screens.active.cursor.x < self.scrolling_region.left) + 0 + else + self.scrolling_region.left; + + // Handle some edge cases when our cursor is already on the left margin. + if (self.screens.active.cursor.x == left_margin) { + switch (wrap_mode) { + // In reverse mode, if we're already before the top margin + // then we just set our cursor to the top-left and we're done. + .reverse => if (self.screens.active.cursor.y <= top) { + self.screens.active.cursorAbsolute(left_margin, top); + return; + }, + + // Handled in while loop + .reverse_extended => {}, + + // Handled above + .none => unreachable, + } + } + + while (true) { + // We can move at most to the left margin. + const max = self.screens.active.cursor.x - left_margin; + + // We want to move at most the number of columns we have left + // or our remaining count. Do the move. + const amount = @min(max, count); + count -= amount; + self.screens.active.cursorLeft(amount); + + // If we have no more to move, then we're done. + if (count == 0) break; + + // If we are at the top, then we are done. + if (self.screens.active.cursor.y == top) { + if (wrap_mode != .reverse_extended) break; + + self.screens.active.cursorAbsolute(right_margin, bottom); + count -= 1; + continue; + } + + // UNDEFINED TERMINAL BEHAVIOR. This situation is not handled in xterm + // and currently results in a crash in xterm. Given no other known + // terminal [to me] implements XTREVWRAP2, I decided to just mimic + // the behavior of xterm up and not including the crash by wrapping + // up to the (0, 0) and stopping there. My reasoning is that for an + // appropriately sized value of "count" this is the behavior that xterm + // would have. This is unit tested. + if (self.screens.active.cursor.y == 0) { + assert(self.screens.active.cursor.x == left_margin); + break; + } + + // If our previous line is not wrapped then we are done. + if (wrap_mode != .reverse_extended) { + const prev_row = self.screens.active.cursorRowUp(1); + if (!prev_row.wrap) break; + } + + self.screens.active.cursorAbsolute(right_margin, self.screens.active.cursor.y - 1); + count -= 1; + } +} + +/// Save cursor position and further state. +/// +/// The primary and alternate screen have distinct save state. One saved state +/// is kept per screen (main / alternative). If for the current screen state +/// was already saved it is overwritten. +pub fn saveCursor(self: *Terminal) void { + self.screens.active.saved_cursor = .{ + .x = self.screens.active.cursor.x, + .y = self.screens.active.cursor.y, + .style = self.screens.active.cursor.style, + .protected = self.screens.active.cursor.protected, + .pending_wrap = self.screens.active.cursor.pending_wrap, + .origin = self.modes.get(.origin), + .charset = self.screens.active.charset, + }; +} + +/// Restore cursor position and other state. +/// +/// The primary and alternate screen have distinct save state. +/// If no save was done before values are reset to their initial values. +pub fn restoreCursor(self: *Terminal) void { + const saved: Screen.SavedCursor = self.screens.active.saved_cursor orelse .{ + .x = 0, + .y = 0, + .style = .{}, + .protected = false, + .pending_wrap = false, + .origin = false, + .charset = .{}, + }; + + // Set the style first because it can fail + self.screens.active.cursor.style = saved.style; + self.screens.active.manualStyleUpdate() catch |err| { + // Regardless of the error here, we revert back to an unstyled + // cursor. It is more important that the restore succeeds in + // other attributes because terminals have no way to communicate + // failure back. + log.warn("restoreCursor error updating style err={}", .{err}); + const screen: *Screen = self.screens.active; + screen.cursor.style = .{}; + self.screens.active.manualStyleUpdate() catch unreachable; + }; + + self.screens.active.charset = saved.charset; + self.modes.set(.origin, saved.origin); + self.screens.active.cursor.pending_wrap = saved.pending_wrap; + self.screens.active.cursor.protected = saved.protected; + self.screens.active.cursorAbsolute( + @min(saved.x, self.cols - 1), + @min(saved.y, self.rows - 1), + ); + + // Ensure our screen is consistent + self.screens.active.assertIntegrity(); +} + +/// Set the character protection mode for the terminal. +pub fn setProtectedMode(self: *Terminal, mode: ansi.ProtectedMode) void { + switch (mode) { + .off => { + self.screens.active.cursor.protected = false; + + // screen.protected_mode is NEVER reset to ".off" because + // logic such as eraseChars depends on knowing what the + // _most recent_ mode was. + }, + + .iso => { + self.screens.active.cursor.protected = true; + self.screens.active.protected_mode = .iso; + }, + + .dec => { + self.screens.active.cursor.protected = true; + self.screens.active.protected_mode = .dec; + }, + } +} + +/// Perform a semantic prompt command. +/// +/// If there is an error, we do our best to get the terminal into +/// some coherent state, since callers typically can't handle errors +/// (since they're sending sequences via the pty). +pub fn semanticPrompt( + self: *Terminal, + cmd: osc.Command.SemanticPrompt, +) !void { + switch (cmd.action) { + .fresh_line => try self.semanticPromptFreshLine(), + + .fresh_line_new_prompt => { + // "First do a fresh-line." + try self.semanticPromptFreshLine(); + + const screen: *Screen = self.screens.active; + + // "Subsequent text (until a OSC "133;B" or OSC "133;I" command) + // is a prompt string (as if followed by OSC 133;P;k=i\007)." + screen.cursorSetSemanticContent(.{ + .prompt = cmd.readOption(.prompt_kind) orelse .initial, + }); + + // This is a kitty-specific flag that notes that the shell + // is NOT capable of redraw. Redraw defaults to true so this + // usually just disables it, but either is possible. + if (cmd.readOption(.redraw)) |v| { + self.flags.shell_redraws_prompt = v; + } + + click: { + // Handle click_events as a priority over cl. click_events + // is another Kitty-specific extension that converts clicks + // within a prompt area to SGR mouse events and defers to the + // shell to handle them. + if (cmd.readOption(.click_events)) |v| { + if (v) { + screen.semantic_prompt.click = .click_events; + break :click; + } + } + + // If click_events was not set or disabled, fallback to `cl`. + if (cmd.readOption(.cl)) |v| { + screen.semantic_prompt.click = .{ .cl = v }; + } + } + + // The "aid" and "cl" options are also valid for this + // command but we don't yet handle these in any meaningful way. + }, + + .new_command => { + // Spec: + // Same as OSC "133;A" but may first implicitly terminate a + // previous command: if the options specify an aid and there + // is an active (open) command with matching aid, finish the + // innermost such command (as well as any other commands + // nested more deeply). If no aid is specified, treat as an + // aid whose value is the empty string. + + // Ghostty: + // We don't currently do explicit command tracking in any way + // so there is no need to terminate prior commands. We just + // perform the `A` action. + try self.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = cmd.options_unvalidated, + }); + }, + + .prompt_start => { + // Explicit start of prompt. Optional after an A or N command. + // The k (kind) option specifies the type of prompt: + // regular primary prompt (k=i or default), + // right-side prompts (k=r), or prompts for continuation lines (k=c or k=s). + self.screens.active.cursorSetSemanticContent(.{ + .prompt = cmd.readOption(.prompt_kind) orelse .initial, + }); + }, + + .end_prompt_start_input => { + // End of prompt and start of user input, terminated by a OSC + // "133;C" or another prompt (OSC "133;P"). + self.screens.active.cursorSetSemanticContent(.{ + .input = .clear_explicit, + }); + }, + + .end_prompt_start_input_terminate_eol => { + // End of prompt and start of user input, terminated by end-of-line. + self.screens.active.cursorSetSemanticContent(.{ + .input = .clear_eol, + }); + }, + + .end_input_start_output => { + // "End of input, and start of output." + self.screens.active.cursorSetSemanticContent(.output); + + // If our current row is marked as a prompt and we're + // at column zero then we assume we're un-prompting. This + // is a heuristic to deal with fish, mostly. The issue that + // fish brings up is that it has no PS2 equivalent and its + // builtin OSC133 marking doesn't output continuation lines + // as k=s. So, we assume when we get a newline with a prompt + // cursor that the new line is also a prompt. But fish changes + // to output on the newline. So if we're at col 0 we just assume + // we're overwriting the prompt. + if (self.screens.active.cursor.page_row.semantic_prompt != .none and + self.screens.active.cursor.x == 0) + { + self.screens.active.cursor.page_row.semantic_prompt = .none; + } + }, + + .end_command => { + // From a terminal state perspective, this doesn't really do + // anything. Other terminals appear to do nothing here. I think + // its reasonable at this point to reset our semantic content + // state but the spec doesn't really say what to do. + self.screens.active.cursorSetSemanticContent(.output); + }, + } +} + +// OSC 133;L +fn semanticPromptFreshLine(self: *Terminal) !void { + const left_margin = if (self.screens.active.cursor.x < self.scrolling_region.left) + 0 + else + self.scrolling_region.left; + + // Spec: "If the cursor is the initial column (left, assuming + // left-to-right writing), do nothing" This specification is very under + // specified. We are taking the liberty to assume that in a left/right + // margin context, if the cursor is outside of the left margin, we treat + // it as being at the left margin for the purposes of this command. + // This is arbitrary. If someone has a better reasonable idea we can + // apply it. + if (self.screens.active.cursor.x == left_margin) return; + + self.carriageReturn(); + try self.index(); +} + +/// The semantic prompt type. This is used when tracking a line type and +/// requires integration with the shell. By default, we mark a line as "none" +/// meaning we don't know what type it is. +/// +/// See: https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md +pub const SemanticPrompt = enum { + prompt, + prompt_continuation, + input, + command, +}; + +/// Returns true if the cursor is currently at a prompt. Another way to look +/// at this is it returns false if the shell is currently outputting something. +/// This requires shell integration (semantic prompt integration). +/// +/// If the shell integration doesn't exist, this will always return false. +pub fn cursorIsAtPrompt(self: *Terminal) bool { + // If we're on the secondary screen, we're never at a prompt. + if (self.screens.active_key == .alternate) return false; + + // If our page row is a prompt then we're always at a prompt + const cursor: *const Screen.Cursor = &self.screens.active.cursor; + if (cursor.page_row.semantic_prompt != .none) return true; + + // Otherwise, determine our cursor state + return switch (cursor.semantic_content) { + .input, .prompt => true, + .output => false, + }; +} + +/// Horizontal tab moves the cursor to the next tabstop, clearing +/// the screen to the left the tabstop. +pub fn horizontalTab(self: *Terminal) void { + while (self.screens.active.cursor.x < self.scrolling_region.right) { + // Move the cursor right + self.screens.active.cursorRight(1); + + // If the last cursor position was a tabstop we return. We do + // "last cursor position" because we want a space to be written + // at the tabstop unless we're at the end (the while condition). + if (self.tabstops.get(self.screens.active.cursor.x)) return; + } +} + +// Same as horizontalTab but moves to the previous tabstop instead of the next. +pub fn horizontalTabBack(self: *Terminal) void { + // With origin mode enabled, our leftmost limit is the left margin. + const left_limit = if (self.modes.get(.origin)) self.scrolling_region.left else 0; + + while (true) { + // If we're already at the edge of the screen, then we're done. + if (self.screens.active.cursor.x <= left_limit) return; + + // Move the cursor left + self.screens.active.cursorLeft(1); + if (self.tabstops.get(self.screens.active.cursor.x)) return; + } +} + +/// Clear tab stops. +pub fn tabClear(self: *Terminal, cmd: csi.TabClear) void { + switch (cmd) { + .current => self.tabstops.unset(self.screens.active.cursor.x), + .all => self.tabstops.reset(0), + else => log.warn("invalid or unknown tab clear setting: {}", .{cmd}), + } +} + +/// Set a tab stop on the current cursor. +/// TODO: test +pub fn tabSet(self: *Terminal) void { + self.tabstops.set(self.screens.active.cursor.x); +} + +/// TODO: test +pub fn tabReset(self: *Terminal) void { + self.tabstops.reset(TABSTOP_INTERVAL); +} + +/// Move the cursor to the next line in the scrolling region, possibly scrolling. +/// +/// If the cursor is outside of the scrolling region: move the cursor one line +/// down if it is not on the bottom-most line of the screen. +/// +/// If the cursor is inside the scrolling region: +/// If the cursor is on the bottom-most line of the scrolling region: +/// invoke scroll up with amount=1 +/// If the cursor is not on the bottom-most line of the scrolling region: +/// move the cursor one line down +/// +/// This unsets the pending wrap state without wrapping. +pub fn index(self: *Terminal) !void { + const screen: *Screen = self.screens.active; + + // Unset pending wrap state + screen.cursor.pending_wrap = false; + + // We handle our cursor semantic prompt state AFTER doing the + // scrolling, because we may need to apply to new rows. + defer if (screen.cursor.semantic_content != .output) { + @branchHint(.unlikely); + + // Always reset any semantic content clear-eol state. + // + // The specification is not clear what "end-of-line" means. If we + // discover that there are more scenarios we should be unsetting + // this we should document and test it. + if (screen.cursor.semantic_content_clear_eol) { + screen.cursor.semantic_content = .output; + screen.cursor.semantic_content_clear_eol = false; + } else { + // If we aren't clearing our state at EOL and we're not output, + // then we mark the new row as a prompt continuation. This is + // to work around shells that don't send OSC 133 k=s sequences + // for continuations. + // + // This can be a false positive if the shell changes content + // type later and outputs something. We handle that in the + // semanticPrompt function. + screen.cursor.page_row.semantic_prompt = .prompt_continuation; + } + } else { + // This should never be set in the output mode. + assert(!screen.cursor.semantic_content_clear_eol); + }; + + // Outside of the scroll region we move the cursor one line down. + if (screen.cursor.y < self.scrolling_region.top or + screen.cursor.y > self.scrolling_region.bottom) + { + // We only move down if we're not already at the bottom of + // the screen. + if (screen.cursor.y < self.rows - 1) { + screen.cursorDown(1); + } + + return; + } + + // If the cursor is inside the scrolling region and on the bottom-most + // line, then we scroll up. If our scrolling region is the full screen + // we create scrollback. + if (screen.cursor.y == self.scrolling_region.bottom and + screen.cursor.x >= self.scrolling_region.left and + screen.cursor.x <= self.scrolling_region.right) + { + if (comptime build_options.kitty_graphics) { + // Scrolling dirties the images because it updates their placements pins. + screen.kitty_images.dirty = true; + } + + // If our scrolling region is at the top, we create scrollback. + if (self.scrolling_region.top == 0 and + self.scrolling_region.left == 0 and + self.scrolling_region.right == self.cols - 1) + { + try screen.cursorScrollAbove(); + return; + } + + // Slow path for left and right scrolling region margins. + if (self.scrolling_region.left != 0 or + self.scrolling_region.right != self.cols - 1 or + + // PERF(mitchellh): If we have an SGR background set then + // we need to preserve that background in our erased rows. + // scrollUp does that but eraseRowBounded below does not. + // However, scrollUp is WAY slower. We should optimize this + // case to work in the eraseRowBounded codepath and remove + // this check. + !screen.blankCell().isZero()) + { + try self.scrollUp(1); + return; + } + + // Otherwise use a fast path function from PageList to efficiently + // scroll the contents of the scrolling region. + + // Preserve old cursor just for assertions + const old_cursor = screen.cursor; + + try screen.pages.eraseRowBounded( + .{ .active = .{ .y = self.scrolling_region.top } }, + self.scrolling_region.bottom - self.scrolling_region.top, + ); + + // eraseRow and eraseRowBounded will end up moving the cursor pin + // up by 1, so we need to move it back down. A `cursorReload` + // would be better option but this is more efficient and this is + // a super hot path so we do this instead. + assert(screen.cursor.x == old_cursor.x); + assert(screen.cursor.y == old_cursor.y); + screen.cursor.y -= 1; + screen.cursorDown(1); + + // The operations above can prune our cursor style so we need to + // update. This should never fail because the above can only FREE + // memory. + screen.manualStyleUpdate() catch |err| { + std.log.warn("deleteLines manualStyleUpdate err={}", .{err}); + screen.cursor.style = .{}; + screen.manualStyleUpdate() catch unreachable; + }; + + return; + } + + // Increase cursor by 1, maximum to bottom of scroll region + if (screen.cursor.y < self.scrolling_region.bottom) { + screen.cursorDown(1); + } +} + +/// Move the cursor to the previous line in the scrolling region, possibly +/// scrolling. +/// +/// If the cursor is outside of the scrolling region, move the cursor one +/// line up if it is not on the top-most line of the screen. +/// +/// If the cursor is inside the scrolling region: +/// +/// * If the cursor is on the top-most line of the scrolling region: +/// invoke scroll down with amount=1 +/// * If the cursor is not on the top-most line of the scrolling region: +/// move the cursor one line up +pub fn reverseIndex(self: *Terminal) void { + if (self.screens.active.cursor.y != self.scrolling_region.top or + self.screens.active.cursor.x < self.scrolling_region.left or + self.screens.active.cursor.x > self.scrolling_region.right) + { + self.cursorUp(1); + return; + } + + self.scrollDown(1); +} + +/// Set Cursor Position. Move cursor to the position indicated +/// by row and column (1-indexed). If column is 0, it is adjusted to 1. +/// If column is greater than the right-most column it is adjusted to +/// the right-most column. If row is 0, it is adjusted to 1. If row is +/// greater than the bottom-most row it is adjusted to the bottom-most +/// row. +pub fn setCursorPos(self: *Terminal, row_req: usize, col_req: usize) void { + // If cursor origin mode is set the cursor row will be moved relative to + // the top margin row and adjusted to be above or at bottom-most row in + // the current scroll region. + // + // If origin mode is set and left and right margin mode is set the cursor + // will be moved relative to the left margin column and adjusted to be on + // or left of the right margin column. + const params: struct { + x_offset: size.CellCountInt = 0, + y_offset: size.CellCountInt = 0, + x_max: size.CellCountInt, + y_max: size.CellCountInt, + } = if (self.modes.get(.origin)) .{ + .x_offset = self.scrolling_region.left, + .y_offset = self.scrolling_region.top, + .x_max = self.scrolling_region.right + 1, // We need this 1-indexed + .y_max = self.scrolling_region.bottom + 1, // We need this 1-indexed + } else .{ + .x_max = self.cols, + .y_max = self.rows, + }; + + // Unset pending wrap state + self.screens.active.cursor.pending_wrap = false; + + // Calculate our new x/y + const row = if (row_req == 0) 1 else row_req; + const col = if (col_req == 0) 1 else col_req; + const x = @min(params.x_max, col + params.x_offset) -| 1; + const y = @min(params.y_max, row + params.y_offset) -| 1; + + // If the y is unchanged then this is fast pointer math + if (y == self.screens.active.cursor.y) { + if (x > self.screens.active.cursor.x) { + self.screens.active.cursorRight(x - self.screens.active.cursor.x); + } else { + self.screens.active.cursorLeft(self.screens.active.cursor.x - x); + } + + return; + } + + // If everything changed we do an absolute change which is slightly slower + self.screens.active.cursorAbsolute(x, y); + // log.info("set cursor position: col={} row={}", .{ self.screens.active.cursor.x, self.screens.active.cursor.y }); +} + +/// Set Top and Bottom Margins If bottom is not specified, 0 or bigger than +/// the number of the bottom-most row, it is adjusted to the number of the +/// bottom most row. +/// +/// If top < bottom set the top and bottom row of the scroll region according +/// to top and bottom and move the cursor to the top-left cell of the display +/// (when in cursor origin mode is set to the top-left cell of the scroll region). +/// +/// Otherwise: Set the top and bottom row of the scroll region to the top-most +/// and bottom-most line of the screen. +/// +/// Top and bottom are 1-indexed. +pub fn setTopAndBottomMargin(self: *Terminal, top_req: usize, bottom_req: usize) void { + const top = @max(1, top_req); + const bottom = @min(self.rows, if (bottom_req == 0) self.rows else bottom_req); + if (top >= bottom) return; + + self.scrolling_region.top = @intCast(top - 1); + self.scrolling_region.bottom = @intCast(bottom - 1); + self.setCursorPos(1, 1); +} + +/// DECSLRM +pub fn setLeftAndRightMargin(self: *Terminal, left_req: usize, right_req: usize) void { + // We must have this mode enabled to do anything + if (!self.modes.get(.enable_left_and_right_margin)) return; + + const left = @max(1, left_req); + const right = @min(self.cols, if (right_req == 0) self.cols else right_req); + if (left >= right) return; + + self.scrolling_region.left = @intCast(left - 1); + self.scrolling_region.right = @intCast(right - 1); + self.setCursorPos(1, 1); +} + +/// Scroll the text down by one row. +pub fn scrollDown(self: *Terminal, count: usize) void { + // Preserve our x/y to restore. + const old_x = self.screens.active.cursor.x; + const old_y = self.screens.active.cursor.y; + const old_wrap = self.screens.active.cursor.pending_wrap; + defer { + self.screens.active.cursorAbsolute(old_x, old_y); + self.screens.active.cursor.pending_wrap = old_wrap; + } + + // Move to the top of the scroll region + self.screens.active.cursorAbsolute(self.scrolling_region.left, self.scrolling_region.top); + self.insertLines(count); +} + +/// Removes amount lines from the top of the scroll region. The remaining lines +/// to the bottom margin are shifted up and space from the bottom margin up +/// is filled with empty lines. +/// +/// The new lines are created according to the current SGR state. +/// +/// Does not change the (absolute) cursor position. +pub fn scrollUp(self: *Terminal, count: usize) !void { + // Preserve our x/y to restore. + const old_x = self.screens.active.cursor.x; + const old_y = self.screens.active.cursor.y; + const old_wrap = self.screens.active.cursor.pending_wrap; + defer { + self.screens.active.cursorAbsolute(old_x, old_y); + self.screens.active.cursor.pending_wrap = old_wrap; + } + + // If our scroll region is at the top and we have no left/right + // margins then we move the scrolled out text into the scrollback. + if (self.scrolling_region.top == 0 and + self.scrolling_region.left == 0 and + self.scrolling_region.right == self.cols - 1) + { + // Scrolling dirties the images because it updates their placements pins. + if (comptime build_options.kitty_graphics) { + self.screens.active.kitty_images.dirty = true; + } + + // Clamp count to the scroll region height. + const region_height = self.scrolling_region.bottom + 1; + const adjusted_count = @min(count, region_height); + + // TODO: Create an optimized version that can scroll N times + // This isn't critical because in most cases, scrollUp is used + // with count=1, but it's still a big optimization opportunity. + + // Move our cursor to the bottom of the scroll region so we can + // use the cursorScrollAbove function to create scrollback + self.screens.active.cursorAbsolute(0, self.scrolling_region.bottom); + for (0..adjusted_count) |_| try self.screens.active.cursorScrollAbove(); + return; + } + + // Move to the top of the scroll region + self.screens.active.cursorAbsolute(self.scrolling_region.left, self.scrolling_region.top); + self.deleteLines(count); +} + +/// Options for scrolling the viewport of the terminal grid. +pub const ScrollViewport = union(Tag) { + /// Scroll to the top of the scrollback + top, + + /// Scroll to the bottom, i.e. the top of the active area + bottom, + + /// Scroll by some delta amount, up is negative. + delta: isize, + + pub const Tag = lib.Enum(lib.target, &.{ + "top", + "bottom", + "delta", + }); + + const c_union = lib.TaggedUnion( + lib.target, + @This(), + // Padding: largest variant is isize (8 bytes on 64-bit). + // Use [2]u64 (16 bytes) for future expansion. + [2]u64, + ); + pub const C = c_union.C; + pub const CValue = c_union.CValue; + pub const cval = c_union.cval; +}; + +/// Scroll the viewport of the terminal grid. +pub fn scrollViewport(self: *Terminal, behavior: ScrollViewport) void { + self.screens.active.scroll(switch (behavior) { + .top => .{ .top = {} }, + .bottom => .{ .active = {} }, + .delta => |delta| .{ .delta_row = delta }, + }); +} + +/// To be called before shifting a row (as in insertLines and deleteLines) +/// +/// Takes care of boundary conditions such as potentially split wide chars +/// across scrolling region boundaries and orphaned spacer heads at line +/// ends. +fn rowWillBeShifted( + self: *Terminal, + page: *Page, + row: *Row, +) void { + const cells = row.cells.ptr(page.memory.ptr); + + // If our scrolling region includes the rightmost column then we + // need to turn any spacer heads in to normal empty cells, since + // once we move them they no longer correspond with soft-wrapped + // wide characters. + // + // If it contains either of the 2 leftmost columns, then the wide + // characters in the first column which may be associated with a + // spacer head will be either moved or cleared, so we also need + // to turn the spacer heads in to empty cells in that case. + if (self.scrolling_region.right == self.cols - 1 or + self.scrolling_region.left < 2) + { + const end_cell: *Cell = &cells[page.size.cols - 1]; + if (end_cell.wide == .spacer_head) { + end_cell.wide = .narrow; + } + } + + // If the leftmost or rightmost cells of our scrolling region + // are parts of wide chars, we need to clear the cells' contents + // since they'd be split by the move. + const left_cell: *Cell = &cells[self.scrolling_region.left]; + const right_cell: *Cell = &cells[self.scrolling_region.right]; + + if (left_cell.wide == .spacer_tail) { + const wide_cell: *Cell = &cells[self.scrolling_region.left - 1]; + if (wide_cell.hasGrapheme()) { + page.clearGrapheme(wide_cell); + page.updateRowGraphemeFlag(row); + } + wide_cell.content.codepoint = 0; + wide_cell.wide = .narrow; + left_cell.wide = .narrow; + } + + if (right_cell.wide == .wide) { + const tail_cell: *Cell = &cells[self.scrolling_region.right + 1]; + if (right_cell.hasGrapheme()) { + page.clearGrapheme(right_cell); + page.updateRowGraphemeFlag(row); + } + right_cell.content.codepoint = 0; + right_cell.wide = .narrow; + tail_cell.wide = .narrow; + } +} + +// TODO(qwerasd): `insertLines` and `deleteLines` are 99% identical, +// the majority of their logic can (and should) be abstracted in to +// a single shared helper function, probably on `Screen` not here. +// I'm just too lazy to do that rn :p + +/// Insert amount lines at the current cursor row. The contents of the line +/// at the current cursor row and below (to the bottom-most line in the +/// scrolling region) are shifted down by amount lines. The contents of the +/// amount bottom-most lines in the scroll region are lost. +/// +/// This unsets the pending wrap state without wrapping. If the current cursor +/// position is outside of the current scroll region it does nothing. +/// +/// If amount is greater than the remaining number of lines in the scrolling +/// region it is adjusted down (still allowing for scrolling out every remaining +/// line in the scrolling region) +/// +/// In left and right margin mode the margins are respected; lines are only +/// scrolled in the scroll region. +/// +/// All cleared space is colored according to the current SGR state. +/// +/// Moves the cursor to the left margin. +pub fn insertLines(self: *Terminal, count: usize) void { + // Rare, but happens + if (count == 0) return; + + // If the cursor is outside the scroll region we do nothing. + if (self.screens.active.cursor.y < self.scrolling_region.top or + self.screens.active.cursor.y > self.scrolling_region.bottom or + self.screens.active.cursor.x < self.scrolling_region.left or + self.screens.active.cursor.x > self.scrolling_region.right) return; + + if (comptime build_options.kitty_graphics) { + // Scrolling dirties the images because it updates their placements pins. + self.screens.active.kitty_images.dirty = true; + } + + // At the end we need to return the cursor to the row it started on. + const start_y = self.screens.active.cursor.y; + defer { + self.screens.active.cursorAbsolute(self.scrolling_region.left, start_y); + + // Always unset pending wrap + self.screens.active.cursor.pending_wrap = false; + } + + // We have a slower path if we have left or right scroll margins. + const left_right = self.scrolling_region.left > 0 or + self.scrolling_region.right < self.cols - 1; + + // Remaining rows from our cursor to the bottom of the scroll region. + const rem = self.scrolling_region.bottom - self.screens.active.cursor.y + 1; + + // We can only insert lines up to our remaining lines in the scroll + // region. So we take whichever is smaller. + const adjusted_count = @min(count, rem); + + // Create a new tracked pin which we'll use to navigate the page list + // so that if we need to adjust capacity it will be properly tracked. + var cur_p = self.screens.active.pages.trackPin( + self.screens.active.cursor.page_pin.down(rem - 1).?, + ) catch |err| { + comptime assert(@TypeOf(err) == error{OutOfMemory}); + + // This error scenario means that our GPA is OOM. This is not a + // situation we can gracefully handle. We can't just ignore insertLines + // because it'll result in a corrupted screen. Ideally in the future + // we flag the state as broken and show an error message to the user. + // For now, we panic. + log.err("insertLines trackPin error err={}", .{err}); + @panic("insertLines trackPin OOM"); + }; + defer self.screens.active.pages.untrackPin(cur_p); + + // Our current y position relative to the cursor + var y: usize = rem; + + // Traverse from the bottom up + while (y > 0) { + const cur_rac = cur_p.rowAndCell(); + const cur_row: *Row = cur_rac.row; + + // If this is one of the lines we need to shift, do so + if (y > adjusted_count) { + const off_p = cur_p.up(adjusted_count).?; + const off_rac = off_p.rowAndCell(); + const off_row: *Row = off_rac.row; + + self.rowWillBeShifted(&cur_p.node.data, cur_row); + self.rowWillBeShifted(&off_p.node.data, off_row); + + // If our scrolling region is full width, then we unset wrap. + if (!left_right) { + off_row.wrap = false; + cur_row.wrap = false; + off_row.wrap_continuation = false; + cur_row.wrap_continuation = false; + } + + const src_p = off_p; + const src_row = off_row; + const dst_p = cur_p; + const dst_row = cur_row; + + // If our page doesn't match, then we need to do a copy from + // one page to another. This is the slow path. + if (src_p.node != dst_p.node) { + dst_p.node.data.clonePartialRowFrom( + &src_p.node.data, + dst_row, + src_row, + self.scrolling_region.left, + self.scrolling_region.right + 1, + ) catch |err| { + // Adjust our page capacity to make + // room for we didn't have space for + _ = self.screens.active.increaseCapacity( + dst_p.node, + switch (err) { + // Rehash the sets + error.StyleSetNeedsRehash, + error.HyperlinkSetNeedsRehash, + => null, + + // Increase style memory + error.StyleSetOutOfMemory, + => .styles, + + // Increase string memory + error.StringAllocOutOfMemory, + => .string_bytes, + + // Increase hyperlink memory + error.HyperlinkSetOutOfMemory, + error.HyperlinkMapOutOfMemory, + => .hyperlink_bytes, + + // Increase grapheme memory + error.GraphemeMapOutOfMemory, + error.GraphemeAllocOutOfMemory, + => .grapheme_bytes, + }, + ) catch |e| switch (e) { + // System OOM. We have no way to recover from this + // currently. We should probably change insertLines + // to raise an error here. + error.OutOfMemory, + => @panic("increaseCapacity system allocator OOM"), + + // The page can't accommodate the managed memory required + // for this operation. We previously just corrupted + // memory here so a crash is better. The right long + // term solution is to allocate a new page here + // move this row to the new page, and start over. + error.OutOfSpace, + => @panic("increaseCapacity OutOfSpace"), + }; + + // Continue the loop to try handling this row again. + continue; + }; + } else { + if (!left_right) { + // Swap the src/dst cells. This ensures that our dst gets the + // proper shifted rows and src gets non-garbage cell data that + // we can clear. + const dst = dst_row.*; + dst_row.* = src_row.*; + src_row.* = dst; + + // Ensure what we did didn't corrupt the page + cur_p.node.data.assertIntegrity(); + } else { + // Left/right scroll margins we have to + // copy cells, which is much slower... + const page = &cur_p.node.data; + page.moveCells( + src_row, + self.scrolling_region.left, + dst_row, + self.scrolling_region.left, + (self.scrolling_region.right - self.scrolling_region.left) + 1, + ); + } + } + } else { + // Clear the cells for this row, it has been shifted. + self.rowWillBeShifted(&cur_p.node.data, cur_row); + const page = &cur_p.node.data; + const cells = page.getCells(cur_row); + self.screens.active.clearCells( + page, + cur_row, + cells[self.scrolling_region.left .. self.scrolling_region.right + 1], + ); + } + + // Mark the row as dirty + cur_p.markDirty(); + + // We have successfully processed a line. + y -= 1; + // Move our pin up to the next row. + if (cur_p.up(1)) |p| cur_p.* = p; + } +} + +/// Removes amount lines from the current cursor row down. The remaining lines +/// to the bottom margin are shifted up and space from the bottom margin up is +/// filled with empty lines. +/// +/// If the current cursor position is outside of the current scroll region it +/// does nothing. If amount is greater than the remaining number of lines in the +/// scrolling region it is adjusted down. +/// +/// In left and right margin mode the margins are respected; lines are only +/// scrolled in the scroll region. +/// +/// If the cell movement splits a multi cell character that character cleared, +/// by replacing it by spaces, keeping its current attributes. All other +/// cleared space is colored according to the current SGR state. +/// +/// Moves the cursor to the left margin. +pub fn deleteLines(self: *Terminal, count: usize) void { + // Rare, but happens + if (count == 0) return; + + // If the cursor is outside the scroll region we do nothing. + if (self.screens.active.cursor.y < self.scrolling_region.top or + self.screens.active.cursor.y > self.scrolling_region.bottom or + self.screens.active.cursor.x < self.scrolling_region.left or + self.screens.active.cursor.x > self.scrolling_region.right) return; + + if (comptime build_options.kitty_graphics) { + // Scrolling dirties the images because it updates their placements pins. + self.screens.active.kitty_images.dirty = true; + } + + // At the end we need to return the cursor to the row it started on. + const start_y = self.screens.active.cursor.y; + defer { + self.screens.active.cursorAbsolute(self.scrolling_region.left, start_y); + // Always unset pending wrap + self.screens.active.cursor.pending_wrap = false; + } + + // We have a slower path if we have left or right scroll margins. + const left_right = self.scrolling_region.left > 0 or + self.scrolling_region.right < self.cols - 1; + + // Remaining rows from our cursor to the bottom of the scroll region. + const rem = self.scrolling_region.bottom - self.screens.active.cursor.y + 1; + + // We can only insert lines up to our remaining lines in the scroll + // region. So we take whichever is smaller. + const adjusted_count = @min(count, rem); + + // Create a new tracked pin which we'll use to navigate the page list + // so that if we need to adjust capacity it will be properly tracked. + var cur_p = self.screens.active.pages.trackPin( + self.screens.active.cursor.page_pin.*, + ) catch |err| { + // See insertLines + comptime assert(@TypeOf(err) == error{OutOfMemory}); + log.err("deleteLines trackPin error err={}", .{err}); + @panic("deleteLines trackPin OOM"); + }; + defer self.screens.active.pages.untrackPin(cur_p); + + // Our current y position relative to the cursor + var y: usize = 0; + + // Traverse from the top down + while (y < rem) { + const cur_rac = cur_p.rowAndCell(); + const cur_row: *Row = cur_rac.row; + + // If this is one of the lines we need to shift, do so + if (y < rem - adjusted_count) { + const off_p = cur_p.down(adjusted_count).?; + const off_rac = off_p.rowAndCell(); + const off_row: *Row = off_rac.row; + + self.rowWillBeShifted(&cur_p.node.data, cur_row); + self.rowWillBeShifted(&off_p.node.data, off_row); + + // If our scrolling region is full width, then we unset wrap. + if (!left_right) { + off_row.wrap = false; + cur_row.wrap = false; + off_row.wrap_continuation = false; + cur_row.wrap_continuation = false; + } + + const src_p = off_p; + const src_row = off_row; + const dst_p = cur_p; + const dst_row = cur_row; + + // If our page doesn't match, then we need to do a copy from + // one page to another. This is the slow path. + if (src_p.node != dst_p.node) { + dst_p.node.data.clonePartialRowFrom( + &src_p.node.data, + dst_row, + src_row, + self.scrolling_region.left, + self.scrolling_region.right + 1, + ) catch |err| { + // Adjust our page capacity to make + // room for we didn't have space for + _ = self.screens.active.increaseCapacity( + dst_p.node, + switch (err) { + // Rehash the sets + error.StyleSetNeedsRehash, + error.HyperlinkSetNeedsRehash, + => null, + + // Increase style memory + error.StyleSetOutOfMemory, + => .styles, + + // Increase string memory + error.StringAllocOutOfMemory, + => .string_bytes, + + // Increase hyperlink memory + error.HyperlinkSetOutOfMemory, + error.HyperlinkMapOutOfMemory, + => .hyperlink_bytes, + + // Increase grapheme memory + error.GraphemeMapOutOfMemory, + error.GraphemeAllocOutOfMemory, + => .grapheme_bytes, + }, + ) catch |e| switch (e) { + // See insertLines + error.OutOfMemory, + => @panic("increaseCapacity system allocator OOM"), + + error.OutOfSpace, + => @panic("increaseCapacity OutOfSpace"), + }; + + // Continue the loop to try handling this row again. + continue; + }; + } else { + if (!left_right) { + // Swap the src/dst cells. This ensures that our dst gets the + // proper shifted rows and src gets non-garbage cell data that + // we can clear. + const dst = dst_row.*; + dst_row.* = src_row.*; + src_row.* = dst; + + // Ensure what we did didn't corrupt the page + cur_p.node.data.assertIntegrity(); + } else { + // Left/right scroll margins we have to + // copy cells, which is much slower... + const page = &cur_p.node.data; + page.moveCells( + src_row, + self.scrolling_region.left, + dst_row, + self.scrolling_region.left, + (self.scrolling_region.right - self.scrolling_region.left) + 1, + ); + } + } + } else { + // Clear the cells for this row, it's from out of bounds. + self.rowWillBeShifted(&cur_p.node.data, cur_row); + const page = &cur_p.node.data; + const cells = page.getCells(cur_row); + self.screens.active.clearCells( + page, + cur_row, + cells[self.scrolling_region.left .. self.scrolling_region.right + 1], + ); + } + + // Mark the row as dirty + cur_p.markDirty(); + + // We have successfully processed a line. + y += 1; + // Move our pin down to the next row. + if (cur_p.down(1)) |p| cur_p.* = p; + } +} + +/// Inserts spaces at current cursor position moving existing cell contents +/// to the right. The contents of the count right-most columns in the scroll +/// region are lost. The cursor position is not changed. +/// +/// This unsets the pending wrap state without wrapping. +/// +/// The inserted cells are colored according to the current SGR state. +pub fn insertBlanks(self: *Terminal, count: usize) void { + // Unset pending wrap state without wrapping. Note: this purposely + // happens BEFORE the scroll region check below, because that's what + // xterm does. + self.screens.active.cursor.pending_wrap = false; + + // If we're given a zero then we do nothing. The rest of this function + // assumes count > 0 and will crash if zero so return early. Note that + // this shouldn't be possible with real CSI sequences because the value + // is clamped to 1 min. + if (count == 0) return; + + // If our cursor is outside the margins then do nothing. We DO reset + // wrap state still so this must remain below the above logic. + if (self.screens.active.cursor.x < self.scrolling_region.left or + self.screens.active.cursor.x > self.scrolling_region.right) return; + + // If our count is larger than the remaining amount, we just erase right. + // We only do this if we can erase the entire line (no right margin). + // if (right_limit == self.cols and + // count > right_limit - self.screens.active.cursor.x) + // { + // self.eraseLine(.right, false); + // return; + // } + + // left is just the cursor position but as a multi-pointer + const left: [*]Cell = @ptrCast(self.screens.active.cursor.page_cell); + var page = &self.screens.active.cursor.page_pin.node.data; + + // If our X is a wide spacer tail then we need to erase the + // previous cell too so we don't split a multi-cell character. + if (self.screens.active.cursor.page_cell.wide == .spacer_tail) { + assert(self.screens.active.cursor.x > 0); + self.screens.active.clearCells(page, self.screens.active.cursor.page_row, (left - 1)[0..2]); + } + + // Remaining cols from our cursor to the right margin. + const rem = self.scrolling_region.right - self.screens.active.cursor.x + 1; + + // If the cell at the right margin is wide, its spacer tail is + // outside the scroll region and would be orphaned by either the + // shift or the clear. Clean up both halves up front. + { + const right_cell: *Cell = @ptrCast(left + (rem - 1)); + if (right_cell.wide == .wide) self.screens.active.clearCells( + page, + self.screens.active.cursor.page_row, + @as([*]Cell, @ptrCast(right_cell))[0..2], + ); + } + + // We can only insert blanks up to our remaining cols + const adjusted_count = @min(count, rem); + + // This is the amount of space at the right of the scroll region + // that will NOT be blank, so we need to shift the correct cols right. + // "scroll_amount" is the number of such cols. + const scroll_amount = rem - adjusted_count; + if (scroll_amount > 0) { + page.pauseIntegrityChecks(true); + defer page.pauseIntegrityChecks(false); + + var x: [*]Cell = left + (scroll_amount - 1); + + // If our last cell we're shifting is wide, then we need to clear + // it to be empty so we don't split the multi-cell char. + const end: *Cell = @ptrCast(x); + if (end.wide == .wide) { + const end_multi: [*]Cell = @ptrCast(end); + assert(end_multi[1].wide == .spacer_tail); + self.screens.active.clearCells( + page, + self.screens.active.cursor.page_row, + end_multi[0..2], + ); + } + + // We work backwards so we don't overwrite data. + while (@intFromPtr(x) >= @intFromPtr(left)) : (x -= 1) { + const src: *Cell = @ptrCast(x); + const dst: *Cell = @ptrCast(x + adjusted_count); + page.swapCells(src, dst); + } + } + + // Insert blanks. The blanks preserve the background color. + self.screens.active.clearCells(page, self.screens.active.cursor.page_row, left[0..adjusted_count]); + + // Our row is always dirty + self.screens.active.cursorMarkDirty(); +} + +/// Removes amount characters from the current cursor position to the right. +/// The remaining characters are shifted to the left and space from the right +/// margin is filled with spaces. +/// +/// If amount is greater than the remaining number of characters in the +/// scrolling region, it is adjusted down. +/// +/// Does not change the cursor position. +pub fn deleteChars(self: *Terminal, count_req: usize) void { + if (count_req == 0) return; + + // If our cursor is outside the margins then do nothing. We DO reset + // wrap state still so this must remain below the above logic. + if (self.screens.active.cursor.x < self.scrolling_region.left or + self.screens.active.cursor.x > self.scrolling_region.right) return; + + // left is just the cursor position but as a multi-pointer + const left: [*]Cell = @ptrCast(self.screens.active.cursor.page_cell); + var page = &self.screens.active.cursor.page_pin.node.data; + + // Remaining cols from our cursor to the right margin. + const rem = self.scrolling_region.right - self.screens.active.cursor.x + 1; + + // We can only insert blanks up to our remaining cols + const count = @min(count_req, rem); + + self.screens.active.splitCellBoundary(self.screens.active.cursor.x); + self.screens.active.splitCellBoundary(self.screens.active.cursor.x + count); + self.screens.active.splitCellBoundary(self.scrolling_region.right + 1); + + // This is the amount of space at the right of the scroll region + // that will NOT be blank, so we need to shift the correct cols right. + // "scroll_amount" is the number of such cols. + const scroll_amount = rem - count; + var x: [*]Cell = left; + if (scroll_amount > 0) { + page.pauseIntegrityChecks(true); + defer page.pauseIntegrityChecks(false); + + const right: [*]Cell = left + (scroll_amount - 1); + + while (@intFromPtr(x) <= @intFromPtr(right)) : (x += 1) { + const src: *Cell = @ptrCast(x + count); + const dst: *Cell = @ptrCast(x); + page.swapCells(src, dst); + } + } + + // Insert blanks. The blanks preserve the background color. + self.screens.active.clearCells(page, self.screens.active.cursor.page_row, x[0 .. rem - scroll_amount]); + + // Our row's soft-wrap is always reset. + self.screens.active.cursorResetWrap(); + + // Our row is always dirty + self.screens.active.cursorMarkDirty(); +} + +pub fn eraseChars(self: *Terminal, count_req: usize) void { + const count = end: { + const remaining = self.cols - self.screens.active.cursor.x; + var end = @min(remaining, @max(count_req, 1)); + + // If our last cell is a wide char then we need to also clear the + // cell beyond it since we can't just split a wide char. + if (end != remaining) { + const last = self.screens.active.cursorCellRight(end - 1); + if (last.wide == .wide) end += 1; + } + + break :end end; + }; + + // Handle any boundary conditions on the edges of the erased area. + // + // TODO(qwerasd): This isn't actually correct if you take in to account + // protected modes. We need to figure out how to make `clearCells` or at + // least `clearUnprotectedCells` handle boundary conditions... + self.screens.active.splitCellBoundary(self.screens.active.cursor.x); + self.screens.active.splitCellBoundary(self.screens.active.cursor.x + count); + + // Reset our row's soft-wrap. + self.screens.active.cursorResetWrap(); + + // Mark our cursor row as dirty + self.screens.active.cursorMarkDirty(); + + // Clear the cells + const cells: [*]Cell = @ptrCast(self.screens.active.cursor.page_cell); + + // If we never had a protection mode, then we can assume no cells + // are protected and go with the fast path. If the last protection + // mode was not ISO we also always ignore protection attributes. + if (self.screens.active.protected_mode != .iso) { + self.screens.active.clearCells( + &self.screens.active.cursor.page_pin.node.data, + self.screens.active.cursor.page_row, + cells[0..count], + ); + return; + } + + self.screens.active.clearUnprotectedCells( + &self.screens.active.cursor.page_pin.node.data, + self.screens.active.cursor.page_row, + cells[0..count], + ); +} + +/// Erase the line. +pub fn eraseLine( + self: *Terminal, + mode: csi.EraseLine, + protected_req: bool, +) void { + // Get our start/end positions depending on mode. + const start, const end = switch (mode) { + .right => right: { + var x = self.screens.active.cursor.x; + + // If our X is a wide spacer tail then we need to erase the + // previous cell too so we don't split a multi-cell character. + if (x > 0 and self.screens.active.cursor.page_cell.wide == .spacer_tail) { + x -= 1; + } + + // Reset our row's soft-wrap. + self.screens.active.cursorResetWrap(); + + break :right .{ x, self.cols }; + }, + + .left => left: { + var x = self.screens.active.cursor.x; + + // If our x is a wide char we need to delete the tail too. + if (self.screens.active.cursor.page_cell.wide == .wide) { + x += 1; + } + + break :left .{ 0, x + 1 }; + }, + + // Note that it seems like complete should reset the soft-wrap + // state of the line but in xterm it does not. + .complete => .{ 0, self.cols }, + + else => { + log.err("unimplemented erase line mode: {}", .{mode}); + return; + }, + }; + + // All modes will clear the pending wrap state and we know we have + // a valid mode at this point. + self.screens.active.cursor.pending_wrap = false; + + // We always mark our row as dirty + self.screens.active.cursorMarkDirty(); + + // Start of our cells + const cells: [*]Cell = cells: { + const cells: [*]Cell = @ptrCast(self.screens.active.cursor.page_cell); + break :cells cells - self.screens.active.cursor.x; + }; + + // We respect protected attributes if explicitly requested (probably + // a DECSEL sequence) or if our last protected mode was ISO even if its + // not currently set. + const protected = self.screens.active.protected_mode == .iso or protected_req; + + // If we're not respecting protected attributes, we can use a fast-path + // to fill the entire line. + if (!protected) { + self.screens.active.clearCells( + &self.screens.active.cursor.page_pin.node.data, + self.screens.active.cursor.page_row, + cells[start..end], + ); + return; + } + + self.screens.active.clearUnprotectedCells( + &self.screens.active.cursor.page_pin.node.data, + self.screens.active.cursor.page_row, + cells[start..end], + ); +} + +/// Erase the display. +pub fn eraseDisplay( + self: *Terminal, + mode: csi.EraseDisplay, + protected_req: bool, +) void { + // We respect protected attributes if explicitly requested (probably + // a DECSEL sequence) or if our last protected mode was ISO even if its + // not currently set. + const protected = self.screens.active.protected_mode == .iso or protected_req; + + switch (mode) { + .scroll_complete => { + self.screens.active.scrollClear() catch |err| { + log.warn("scroll clear failed, doing a normal clear err={}", .{err}); + self.eraseDisplay(.complete, protected_req); + return; + }; + + // Unsets pending wrap state + self.screens.active.cursor.pending_wrap = false; + + if (comptime build_options.kitty_graphics) { + // Clear all Kitty graphics state for this screen + self.screens.active.kitty_images.delete( + self.screens.active.alloc, + self, + .{ .all = true }, + ); + } + }, + + .complete => { + // If we're on the primary screen and our last non-empty row is + // a prompt, then we do a scroll_complete instead. This is a + // heuristic to get the generally desirable behavior that ^L + // at a prompt scrolls the screen contents prior to clearing. + // Most shells send `ESC [ H ESC [ 2 J` so we can't just check + // our current cursor position. See #905 + if (self.screens.active_key == .primary) at_prompt: { + // Go from the bottom of the active up and see if we're + // at a prompt. + const active_br = self.screens.active.pages.getBottomRight( + .active, + ) orelse break :at_prompt; + var it = active_br.rowIterator( + .left_up, + self.screens.active.pages.getTopLeft(.active), + ); + while (it.next()) |p| { + const row = p.rowAndCell().row; + switch (row.semantic_prompt) { + // If we're at a prompt or input area, then we are at a prompt. + .prompt, + .prompt_continuation, + => break, + + // If we have command output, then we're most certainly not + // at a prompt. + .none => break :at_prompt, + } + } else break :at_prompt; + + self.screens.active.scrollClear() catch { + // If we fail, we just fall back to doing a normal clear + // so we don't worry about the error. + }; + } + + // All active area + self.screens.active.clearRows( + .{ .active = .{} }, + null, + protected, + ); + + // Unsets pending wrap state + self.screens.active.cursor.pending_wrap = false; + + if (comptime build_options.kitty_graphics) { + // Clear all Kitty graphics state for this screen + self.screens.active.kitty_images.delete( + self.screens.active.alloc, + self, + .{ .all = true }, + ); + } + + // Cleared screen dirty bit + self.flags.dirty.clear = true; + }, + + .below => { + // All lines to the right (including the cursor) + self.eraseLine(.right, protected_req); + + // All lines below + if (self.screens.active.cursor.y + 1 < self.rows) { + self.screens.active.clearRows( + .{ .active = .{ .y = self.screens.active.cursor.y + 1 } }, + null, + protected, + ); + } + + // Unsets pending wrap state. Should be done by eraseLine. + assert(!self.screens.active.cursor.pending_wrap); + }, + + .above => { + // Erase to the left (including the cursor) + self.eraseLine(.left, protected_req); + + // All lines above + if (self.screens.active.cursor.y > 0) { + self.screens.active.clearRows( + .{ .active = .{ .y = 0 } }, + .{ .active = .{ .y = self.screens.active.cursor.y - 1 } }, + protected, + ); + } + + // Unsets pending wrap state + assert(!self.screens.active.cursor.pending_wrap); + }, + + .scrollback => self.screens.active.eraseHistory(null), + } +} + +/// Resets all margins and fills the whole screen with the character 'E' +/// +/// Sets the cursor to the top left corner. +pub fn decaln(self: *Terminal) !void { + // Clear our stylistic attributes. This is the only thing that can + // fail so we do it first so we can undo it. + const old_style = self.screens.active.cursor.style; + self.screens.active.cursor.style = .{ + .bg_color = self.screens.active.cursor.style.bg_color, + .fg_color = self.screens.active.cursor.style.fg_color, + }; + errdefer self.screens.active.cursor.style = old_style; + try self.screens.active.manualStyleUpdate(); + + // Reset margins, also sets cursor to top-left + self.scrolling_region = .{ + .top = 0, + .bottom = self.rows - 1, + .left = 0, + .right = self.cols - 1, + }; + + // Origin mode is disabled + self.modes.set(.origin, false); + + // Move our cursor to the top-left + self.setCursorPos(1, 1); + + // Use clearRows instead of eraseDisplay because we must NOT respect + // protected attributes here. + self.screens.active.clearRows( + .{ .active = .{} }, + null, + false, + ); + + // Fill with Es by moving the cursor but reset it after. + while (true) { + const page = &self.screens.active.cursor.page_pin.node.data; + const row = self.screens.active.cursor.page_row; + const cells_multi: [*]Cell = row.cells.ptr(page.memory); + const cells = cells_multi[0..page.size.cols]; + @memset(cells, .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 'E' }, + .style_id = self.screens.active.cursor.style_id, + + // DECALN does not respect protected state. Verified with xterm. + .protected = false, + }); + + // If we have a ref-counted style, increase + if (self.screens.active.cursor.style_id != style.default_id) { + page.styles.useMultiple( + page.memory, + self.screens.active.cursor.style_id, + @intCast(cells.len), + ); + row.styled = true; + } + + // We messed with the page so assert its integrity here. + page.assertIntegrity(); + + self.screens.active.cursorMarkDirty(); + if (self.screens.active.cursor.y == self.rows - 1) break; + self.screens.active.cursorDown(1); + } + + // Reset the cursor to the top-left + self.setCursorPos(1, 1); +} + +/// Execute a kitty graphics command. The buf is used to populate with +/// the response that should be sent as an APC sequence. The response will +/// be a full, valid APC sequence. +/// +/// If an error occurs, the caller should response to the pty that a +/// an error occurred otherwise the behavior of the graphics protocol is +/// undefined. +pub fn kittyGraphics( + self: *Terminal, + alloc: Allocator, + cmd: *kitty.graphics.Command, +) ?kitty.graphics.Response { + return kitty.graphics.execute(alloc, self, cmd); +} + +/// Set a style attribute. +pub fn setAttribute(self: *Terminal, attr: sgr.Attribute) !void { + try self.screens.active.setAttribute(attr); +} + +/// Print the active attributes as a string. This is used to respond to DECRQSS +/// requests. +/// +/// Boolean attributes are printed first, followed by foreground color, then +/// background color. Each attribute is separated by a semicolon. +pub fn printAttributes(self: *Terminal, buf: []u8) ![]const u8 { + var stream = std.io.fixedBufferStream(buf); + const writer = stream.writer(); + + // The SGR response always starts with a 0. See https://vt100.net/docs/vt510-rm/DECRPSS + try writer.writeByte('0'); + + const pen = self.screens.active.cursor.style; + var attrs: [8]u8 = @splat(0); + var i: usize = 0; + + if (pen.flags.bold) { + attrs[i] = '1'; + i += 1; + } + + if (pen.flags.faint) { + attrs[i] = '2'; + i += 1; + } + + if (pen.flags.italic) { + attrs[i] = '3'; + i += 1; + } + + if (pen.flags.underline != .none) { + attrs[i] = '4'; + i += 1; + } + + if (pen.flags.blink) { + attrs[i] = '5'; + i += 1; + } + + if (pen.flags.inverse) { + attrs[i] = '7'; + i += 1; + } + + if (pen.flags.invisible) { + attrs[i] = '8'; + i += 1; + } + + if (pen.flags.strikethrough) { + attrs[i] = '9'; + i += 1; + } + + for (attrs[0..i]) |c| { + try writer.print(";{c}", .{c}); + } + + switch (pen.fg_color) { + .none => {}, + .palette => |idx| if (idx >= 16) + try writer.print(";38:5:{}", .{idx}) + else if (idx >= 8) + try writer.print(";9{}", .{idx - 8}) + else + try writer.print(";3{}", .{idx}), + .rgb => |rgb| try writer.print(";38:2::{[r]}:{[g]}:{[b]}", rgb), + } + + switch (pen.bg_color) { + .none => {}, + .palette => |idx| if (idx >= 16) + try writer.print(";48:5:{}", .{idx}) + else if (idx >= 8) + try writer.print(";10{}", .{idx - 8}) + else + try writer.print(";4{}", .{idx}), + .rgb => |rgb| try writer.print(";48:2::{[r]}:{[g]}:{[b]}", rgb), + } + + return stream.getWritten(); +} + +/// The modes for DECCOLM. +pub const DeccolmMode = enum(u1) { + @"80_cols" = 0, + @"132_cols" = 1, +}; + +/// DECCOLM changes the terminal width between 80 and 132 columns. This +/// function call will do NOTHING unless `setDeccolmSupported` has been +/// called with "true". +/// +/// This breaks the expectation around modern terminals that they resize +/// with the window. This will fix the grid at either 80 or 132 columns. +/// The rows will continue to be variable. +pub fn deccolm(self: *Terminal, alloc: Allocator, mode: DeccolmMode) !void { + // If DEC mode 40 isn't enabled, then this is ignored. We also make + // sure that we don't have deccolm set because we want to fully ignore + // set mode. + if (!self.modes.get(.enable_mode_3)) { + self.modes.set(.@"132_column", false); + return; + } + + // Enable it + self.modes.set(.@"132_column", mode == .@"132_cols"); + + // Resize to the requested size + try self.resize( + alloc, + switch (mode) { + .@"132_cols" => 132, + .@"80_cols" => 80, + }, + self.rows, + ); + + // Erase our display and move our cursor. + self.eraseDisplay(.complete, false); + self.setCursorPos(1, 1); +} + +/// Resize the underlying terminal. +pub fn resize( + self: *Terminal, + alloc: Allocator, + cols: size.CellCountInt, + rows: size.CellCountInt, +) !void { + // If our cols/rows didn't change then we're done + if (self.cols == cols and self.rows == rows) return; + + // Resize our tabstops + if (self.cols != cols) { + self.tabstops.deinit(alloc); + self.tabstops = try .init(alloc, cols, 8); + } + + // Resize primary screen, which supports reflow + const primary = self.screens.get(.primary).?; + try primary.resize(.{ + .cols = cols, + .rows = rows, + .reflow = self.modes.get(.wraparound), + .prompt_redraw = self.flags.shell_redraws_prompt, + }); + + // Alternate screen, if it exists, doesn't reflow + if (self.screens.get(.alternate)) |alt| try alt.resize(.{ + .cols = cols, + .rows = rows, + .reflow = false, + }); + + // Whenever we resize we just mark it as a screen clear + self.flags.dirty.clear = true; + + // Set our size + self.cols = cols; + self.rows = rows; + + // Reset the scrolling region + self.scrolling_region = .{ + .top = 0, + .bottom = rows - 1, + .left = 0, + .right = cols - 1, + }; +} + +/// Set the pwd for the terminal. +pub fn setPwd(self: *Terminal, pwd: []const u8) !void { + self.pwd.clearRetainingCapacity(); + if (pwd.len > 0) { + try self.pwd.appendSlice(self.gpa(), pwd); + try self.pwd.append(self.gpa(), 0); + } +} + +/// Returns the pwd for the terminal, if any. The memory is owned by the +/// Terminal and is not copied. It is safe until a reset or setPwd. +pub fn getPwd(self: *const Terminal) ?[:0]const u8 { + if (self.pwd.items.len == 0) return null; + return self.pwd.items[0 .. self.pwd.items.len - 1 :0]; +} + +/// Set the title for the terminal, as set by escape sequences (e.g. OSC 0/2). +pub fn setTitle(self: *Terminal, t: []const u8) !void { + self.title.clearRetainingCapacity(); + if (t.len > 0) { + try self.title.appendSlice(self.gpa(), t); + try self.title.append(self.gpa(), 0); + } +} + +/// Returns the title for the terminal, if any. The memory is owned by the +/// Terminal and is not copied. It is safe until a reset or setTitle. +pub fn getTitle(self: *const Terminal) ?[:0]const u8 { + if (self.title.items.len == 0) return null; + return self.title.items[0 .. self.title.items.len - 1 :0]; +} + +/// Switch to the given screen type (alternate or primary). +/// +/// This does NOT handle behaviors such as clearing the screen, +/// copying the cursor, etc. This should be handled by downstream +/// callers. +/// +/// After calling this function, the `self.screen` field will point +/// to the current screen, and the returned value will be the previous +/// screen. If the return value is null, then the screen was not +/// switched because it was already the active screen. +/// +/// Note: This is written in a generic way so that we can support +/// more than two screens in the future if needed. There isn't +/// currently a spec for this, but it is something I think might +/// be useful in the future. +pub fn switchScreen(self: *Terminal, key: ScreenSet.Key) !?*Screen { + // If we're already on the requested screen we do nothing. + if (self.screens.active_key == key) return null; + const old = self.screens.active; + + // We always end hyperlink state when switching screens. + // We need to do this on the original screen. + old.endHyperlink(); + + // Switch the screens/ + const new = self.screens.get(key) orelse new: { + const primary = self.screens.get(.primary).?; + break :new try self.screens.getInit( + old.alloc, + key, + .{ + .cols = self.cols, + .rows = self.rows, + .max_scrollback = switch (key) { + .primary => primary.pages.explicit_max_size, + .alternate => 0, + }, + + // Inherit our Kitty image storage limit from the primary + // screen if we have to initialize. + .kitty_image_storage_limit = if (comptime build_options.kitty_graphics) + primary.kitty_images.total_limit + else + 0, + }, + ); + }; + + // The new screen should not have any hyperlinks set + assert(new.cursor.hyperlink_id == 0); + + // Bring our charset state with us + new.charset = old.charset; + + // Clear our selection + new.clearSelection(); + + if (comptime build_options.kitty_graphics) { + // Mark kitty images as dirty so they redraw. Without this set + // the images will remain where they were (the dirty bit on + // the screen only tracks the terminal grid, not the images). + new.kitty_images.dirty = true; + } + + // Mark our terminal as dirty to redraw the grid. + self.flags.dirty.clear = true; + + // Finalize the switch + self.screens.switchTo(key); + + return old; +} + +/// Switch screen via a mode switch (e.g. mode 47, 1047, 1049). +/// This is a much more opinionated operation than `switchScreen` +/// since it also handles the behaviors of the specific mode, +/// such as clearing the screen, saving/restoring the cursor, +/// etc. +/// +/// This should be used for legacy compatibility with VT protocols, +/// but more modern usage should use `switchScreen` instead and handle +/// details like clearing the screen, cursor saving, etc. manually. +pub fn switchScreenMode( + self: *Terminal, + mode: SwitchScreenMode, + enabled: bool, +) !void { + // The behavior in this function is completely based on reading + // the xterm source, specifically "charproc.c" for + // `srm_ALTBUF`, `srm_OPT_ALTBUF`, and `srm_OPT_ALTBUF_CURSOR`. + // We shouldn't touch anything in here without adding a unit + // test AND verifying the behavior with xterm. + + switch (mode) { + .@"47" => {}, + + // If we're disabling 1047 and we're on alt screen then + // we clear the screen. + .@"1047" => if (!enabled and self.screens.active_key == .alternate) { + self.eraseDisplay(.complete, false); + }, + + // 1049 unconditionally saves the cursor on enabling, even + // if we're already on the alternate screen. + .@"1049" => if (enabled) self.saveCursor(), + } + + // Switch screens first to whatever we're going to. + const to: ScreenSet.Key = if (enabled) .alternate else .primary; + const old_ = try self.switchScreen(to); + + switch (mode) { + // For these modes, we need to copy the cursor. We only copy + // the cursor if the screen actually changed, otherwise the + // cursor is already copied. The cursor is copied regardless + // of destination screen. + .@"47", .@"1047" => if (old_) |old| { + self.screens.active.cursorCopy(old.cursor, .{ + .hyperlink = false, + }) catch |err| { + log.warn( + "cursor copy failed entering alt screen err={}", + .{err}, + ); + }; + }, + + // Mode 1049 restores cursor on the primary screen when + // we disable it. + .@"1049" => if (enabled) { + assert(self.screens.active_key == .alternate); + self.eraseDisplay(.complete, false); + + // When we enter alt screen with 1049, we always copy the + // cursor from the primary screen (if we weren't already + // on it). + if (old_) |old| { + self.screens.active.cursorCopy(old.cursor, .{ + .hyperlink = false, + }) catch |err| { + log.warn( + "cursor copy failed entering alt screen err={}", + .{err}, + ); + }; + } + } else { + assert(self.screens.active_key == .primary); + self.restoreCursor(); + }, + } +} + +/// Modal screen changes. These map to the literal terminal +/// modes to enable or disable alternate screen modes. They each +/// have subtle behaviors so we define them as an enum here. +pub const SwitchScreenMode = enum { + /// Legacy alternate screen mode. This goes to the alternate + /// screen or primary screen and only copies the cursor. The + /// screen is not erased. + @"47", + + /// Alternate screen mode where the alternate screen is cleared + /// on exit. The primary screen is never cleared. The cursor is + /// copied. + @"1047", + + /// Save primary screen cursor, switch to alternate screen, + /// and clear the alternate screen on entry. On exit, + /// do not clear the screen, and restore the cursor on the + /// primary screen. + @"1049", +}; + +/// Return the current string value of the terminal. Newlines are +/// encoded as "\n". This omits any formatting such as fg/bg. +/// +/// The caller must free the string. +pub fn plainString(self: *Terminal, alloc: Allocator) ![]const u8 { + return try self.screens.active.dumpStringAlloc(alloc, .{ .viewport = .{} }); +} + +/// Same as plainString, but respects row wrap state when building the string. +pub fn plainStringUnwrapped(self: *Terminal, alloc: Allocator) ![]const u8 { + return try self.screens.active.dumpStringAllocUnwrapped(alloc, .{ .viewport = .{} }); +} + +/// Full reset. +/// +/// This will attempt to free the existing screen memory but if that fails +/// this will reuse the existing memory. In the latter case, memory may +/// be wasted (since its unused) but it isn't leaked. +pub fn fullReset(self: *Terminal) void { + // Ensure we're back on primary screen + self.screens.switchTo(.primary); + self.screens.remove( + self.screens.active.alloc, + .alternate, + ); + + // Reset our screens + self.screens.active.reset(); + + // Rest our basic state + self.modes.reset(); + self.flags = .{}; + self.tabstops.reset(TABSTOP_INTERVAL); + self.previous_char = null; + self.pwd.clearRetainingCapacity(); + self.title.clearRetainingCapacity(); + self.status_display = .main; + self.scrolling_region = .{ + .top = 0, + .bottom = self.rows - 1, + .left = 0, + .right = self.cols - 1, + }; + + // Always mark dirty so we redraw everything + self.flags.dirty.clear = true; +} + +/// Returns true if the point is dirty, used for testing. +fn isDirty(t: *const Terminal, pt: point.Point) bool { + return t.screens.active.pages.getCell(pt).?.isDirty(); +} + +/// Clear all dirty bits. Testing only. +fn clearDirty(t: *Terminal) void { + t.screens.active.pages.clearDirty(); +} + +test "Terminal: input with no control characters" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 40, .rows = 40 }); + defer t.deinit(alloc); + + // Basic grid writing + for ("hello") |c| try t.print(c); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + { + const str = try t.plainString(alloc); + defer alloc.free(str); + try testing.expectEqualStrings("hello", str); + } + + // The first row should be dirty + try testing.expect(t.isDirty(.{ .screen = .{ .x = 5, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 5, .y = 1 } })); +} + +test "Terminal: input with basic wraparound" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 40 }); + defer t.deinit(alloc); + + // Basic grid writing + for ("helloworldabc12") |c| try t.print(c); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + { + const str = try t.plainString(alloc); + defer alloc.free(str); + try testing.expectEqualStrings("hello\nworld\nabc12", str); + } +} + +test "Terminal: input with basic wraparound dirty" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 40 }); + defer t.deinit(alloc); + + for ("hello") |c| try t.print(c); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 4, .y = 0 } })); + t.clearDirty(); + try t.print('w'); + + // Old row is dirty because cursor moved from there + try testing.expect(t.isDirty(.{ .screen = .{ .x = 4, .y = 0 } })); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 1 } })); +} + +test "Terminal: input that forces scroll" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 1, .rows = 5 }); + defer t.deinit(alloc); + + // Basic grid writing + for ("abcdef") |c| try t.print(c); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + { + const str = try t.plainString(alloc); + defer alloc.free(str); + try testing.expectEqualStrings("b\nc\nd\ne\nf", str); + } +} + +test "Terminal: input unique style per cell" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 30, .rows = 30 }); + defer t.deinit(alloc); + + for (0..t.rows) |y| { + for (0..t.cols) |x| { + t.setCursorPos(y, x); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = @intCast(x), + .g = @intCast(y), + .b = 0, + } }); + try t.print('x'); + } + } +} + +test "Terminal: input glitch text" { + const glitch = @embedFile("res/glitch.txt"); + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 30, .rows = 30 }); + defer t.deinit(alloc); + + // Get our initial grapheme capacity. + const grapheme_cap = cap: { + const page = t.screens.active.pages.pages.first.?; + break :cap page.data.capacity.grapheme_bytes; + }; + + // Print glitch text until our capacity changes + while (true) { + const page = t.screens.active.pages.pages.first.?; + if (page.data.capacity.grapheme_bytes != grapheme_cap) break; + try t.printString(glitch); + } + + // We're testing to make sure that grapheme capacity gets increased. + const page = t.screens.active.pages.pages.first.?; + try testing.expect(page.data.capacity.grapheme_bytes > grapheme_cap); +} + +test "Terminal: zero-width character at start" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // This used to crash the terminal. This is not allowed so we should + // just ignore it. + try t.print(0x200D); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + + // Should not be dirty since we changed nothing. + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +// https://github.com/mitchellh/ghostty/issues/1400 +test "Terminal: print single very long line" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // This would crash for issue 1400. So the assertion here is + // that we simply do not crash. + for (0..1000) |_| try t.print('x'); +} + +test "Terminal: print wide char" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.print(0x1F600); // Smiley face + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F600), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print wide char at edge creates spacer head" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + t.setCursorPos(1, 10); + try t.print(0x1F600); // Smiley face + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 9, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F600), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } + + // Our first row just had a spacer head added which does not affect + // rendering so only the place where the wide char was printed + // should be marked. + // BUT old row is dirty because cursor moved from there + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 1 } })); +} + +test "Terminal: print wide char with 1-column width" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 1, .rows = 2 }); + defer t.deinit(alloc); + + try t.print('😀'); // 0x1F600 + + // This prints a space so we should be dirty. + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print wide char in single-width terminal" { + var t = try init(testing.allocator, .{ .cols = 1, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.print(0x1F600); // Smiley face + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print over wide char at 0,0" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.print(0x1F600); // Smiley face + t.setCursorPos(0, 0); + try t.print('A'); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'A'), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 1 } })); +} + +test "Terminal: print over wide char at col 0 corrupts previous row" { + // Crash found by AFL++ fuzzer (afl-out/stream/default/crashes/id:000002). + // + // printCell, when overwriting a wide cell with a narrow cell at x<=1 + // and y>0, sets the last cell of the previous row to .narrow — even + // when that cell is a .spacer_tail rather than a .spacer_head. This + // orphans the .wide cell at cols-2. + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 3 }); + defer t.deinit(alloc); + + // Fill rows 0 and 1 with wide chars (5 per row on a 10-col terminal). + for (0..10) |_| try t.print(0x4E2D); + + // Move cursor to row 1, col 0 (on top of a wide char) and print a + // narrow character. This triggers printCell's .wide branch which + // corrupts row 0's last cell: col 9 changes from .spacer_tail to + // .narrow, orphaning the .wide at col 8. + t.setCursorPos(2, 1); + try t.print('A'); + + // Row 1, col 0 should be narrow (we just overwrote the wide char). + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + try testing.expectEqual(Cell.Wide.narrow, list_cell.cell.wide); + } + // Row 0, col 8 should still be .wide (the last wide char on the row). + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 8, .y = 0 } }).?; + try testing.expectEqual(Cell.Wide.wide, list_cell.cell.wide); + } + // Row 0, col 9 must remain .spacer_tail to pair with the .wide at col 8. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 9, .y = 0 } }).?; + try testing.expectEqual(Cell.Wide.spacer_tail, list_cell.cell.wide); + } +} + +test "Terminal: print over wide spacer tail" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + try t.print('橋'); + t.setCursorPos(1, 2); + try t.print('X'); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'X'), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print over wide char with bold" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.setAttribute(.{ .bold = {} }); + try t.print(0x1F600); // Smiley face + // verify we have styles in our style map + { + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + } + + // Go back and overwrite with no style + t.setCursorPos(0, 0); + try t.setAttribute(.{ .unset = {} }); + try t.print('A'); // Smiley face + + // verify our style is gone + { + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 0), page.styles.count()); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print over wide char with bg color" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + try t.print(0x1F600); // Smiley face + // verify we have styles in our style map + { + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + } + + // Go back and overwrite with no style + t.setCursorPos(0, 0); + try t.setAttribute(.{ .unset = {} }); + try t.print('A'); // Smiley face + + // verify our style is gone + { + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 0), page.styles.count()); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print multicodepoint grapheme, disabled mode 2027" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // https://github.com/mitchellh/ghostty/issues/289 + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + // We should have 6 cells taken up + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 6), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F468), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + try testing.expect(list_cell.node.data.lookupGrapheme(cell) == null); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F469), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 3, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + try testing.expect(list_cell.node.data.lookupGrapheme(cell) == null); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 4, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F467), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expect(list_cell.node.data.lookupGrapheme(cell) == null); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 5, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + try testing.expect(list_cell.node.data.lookupGrapheme(cell) == null); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: VS16 doesn't make character with 2027 disabled" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Disable grapheme clustering + t.modes.set(.grapheme_cluster, false); + + try t.print(0x2764); // Heart + try t.print(0xFE0F); // VS16 to make wide + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("❤️", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x2764), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } +} + +test "Terminal: ignored VS16 doesn't mark dirty" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Disable grapheme clustering + t.modes.set(.grapheme_cluster, false); + + try t.print(0x2764); // Heart + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + t.clearDirty(); + try t.print(0xFE0F); // VS16 to make wide + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print invalid VS16 non-grapheme" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // https://github.com/mitchellh/ghostty/issues/1482 + try t.print('x'); + try t.print(0xFE0F); + + // We should have 1 narrow cell. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'x'), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + } +} + +test "Terminal: invalid VS16 doesn't mark dirty" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Disable grapheme clustering + t.modes.set(.grapheme_cluster, false); + + try t.print('x'); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + t.clearDirty(); + try t.print(0xFE0F); // VS16 to make wide + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print multicodepoint grapheme, mode 2027" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/289 + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Row should be dirty + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F468), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 4), cps.len); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: keypad sequence VS15" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // This is: "#︎" (number sign with text presentation selector) + try t.print(0x23); // # Number sign (valid base) + try t.print(0xFE0E); // VS15 (text presentation selector) + + // VS15 should combine with the base character into a single grapheme cluster, + // taking 1 cell (narrow character). + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + // Row should be dirty + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // The base emoji should be in cell 0 with the skin tone as a grapheme + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x23), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: keypad sequence VS16" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // This is: "#️" (number sign with emoji presentation selector) + try t.print(0x23); // # Number sign (valid base) + try t.print(0xFE0F); // VS16 (emoji presentation selector) + + // VS16 should combine with the base character into a single grapheme cluster, + // taking 2 cells (wide character). + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Row should be dirty + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // The base emoji should be in cell 0 with the skin tone as a grapheme + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x23), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } +} + +test "Terminal: Fitzpatrick skin tone next valid base" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // This is: "👋🏿" (waving hand with dark skin tone) + try t.print(0x1F44B); // 👋 Waving hand (valid base) + try t.print(0x1F3FF); // 🏿 Dark skin tone modifier + + // The skin tone should combine with the base emoji into a single grapheme cluster, + // taking 2 cells (wide character). + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Row should be dirty + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // The base emoji should be in cell 0 with the skin tone as a grapheme + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F44B), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } +} + +test "Terminal: Fitzpatrick skin tone next to non-base" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // This is: "🏿" (which may not render correctly in your editor!) + try t.print(0x22); // " + try t.print(0x1F3FF); // Dark skin tone + try t.print(0x22); // " + + // We should have 4 cells taken up. Importantly, the skin tone + // should not join with the quotes. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.x); + + // Row should be dirty + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x22), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F3FF), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 3, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x22), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: multicodepoint grapheme marks dirty on every codepoint" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/289 + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + try t.print(0x200D); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + try t.print(0x1F469); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + try t.print(0x200D); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + try t.print(0x1F467); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); +} + +test "Terminal: VS15 to make narrow character" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print(0x2614); // Umbrella with rain drops, width=2 + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + try t.print(0xFE0E); // VS15 to make narrow + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + // VS15 should send us back a cell since our char is no longer wide. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("☔︎", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x2614), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } +} + +test "Terminal: VS15 on already narrow emoji" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print(0x26C8); // Thunder cloud and rain, width=1 + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + try t.print(0xFE0E); // VS15 to make narrow + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + // Character takes up one cell + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("⛈︎", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x26C8), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } +} + +test "Terminal: print invalid VS15 following emoji is wide" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print('\u{1F9E0}'); // 🧠 + try t.print(0xFE0E); // not valid with U+1F9E0 as base + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '\u{1F9E0}'), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: print invalid VS15 in emoji ZWJ sequence" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print('\u{1F469}'); // 👩 + try t.print(0xFE0E); // not valid with U+1F469 as base + try t.print('\u{200D}'); // ZWJ + try t.print('\u{1F466}'); // 👦 + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '\u{1F469}'), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{ '\u{200D}', '\u{1F466}' }, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: VS15 to make narrow character with pending wrap" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 4 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try testing.expect(t.modes.get(.wraparound)); + + try t.print(0x1F34B); // Lemon, width=2 + try t.print(0x2614); // Umbrella with rain drops, width=2 + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + // We only move to the end of the line because we're in a pending wrap + // state. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 3), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + + try t.print(0xFE0E); // VS15 to make narrow + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + // VS15 should clear the pending wrap state + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 3), t.screens.active.cursor.x); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("🍋☔︎", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x2614), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } + + // VS15 should not affect the previous grapheme + { + const lemon_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?.cell; + try testing.expectEqual(@as(u21, 0x1F34B), lemon_cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, lemon_cell.wide); + const spacer_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?.cell; + try testing.expectEqual(@as(u21, 0), spacer_cell.content.codepoint); + try testing.expectEqual(Cell.Wide.spacer_tail, spacer_cell.wide); + } +} + +test "Terminal: VS16 to make wide character on next line" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 3 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + t.cursorRight(2); + try t.print('#'); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 2, .y = 0 } })); + t.clearDirty(); + + try t.print(0xFE0F); // VS16 to make wide + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 2, .y = 0 } })); + t.clearDirty(); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + { + // Previous cell turns into spacer_head + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + // '#' cell is wide + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '#'), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0xFE0F}, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + // spacer_tail + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: VS16 to make wide character on next line with hyperlink" { + // Regression test for the crash fixed in print's grapheme `.wide` path: + // writing a spacer_head at the screen edge before row.wrap was set. + var t = try init(testing.allocator, .{ .rows = 5, .cols = 3 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering and activate a hyperlink so printCell + // calls cursorSetHyperlink (which runs page integrity checks). + t.modes.set(.grapheme_cluster, true); + try t.screens.active.startHyperlink("http://example.com", null); + + t.cursorRight(2); + try t.print('#'); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + + // Without the fix, this panicked with UnwrappedSpacerHead. + try t.print(0xFE0F); // VS16 to make wide + + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + { + // Previous cell turns into spacer_head and remains hyperlinked. + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + try testing.expect(cell.hyperlink); + try testing.expect(list_cell.row.wrap); + } + { + // '#' cell is now wide and still hyperlinked. + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '#'), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0xFE0F}, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + try testing.expect(cell.hyperlink); + } + { + // spacer_tail inherits hyperlink as part of the same grapheme cell. + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + try testing.expect(cell.hyperlink); + } +} + +test "Terminal: VS16 to make wide character with pending wrap" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 3 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + t.cursorRight(1); + try t.print('#'); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + try t.print(0xFE0F); // VS16 to make wide + + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expect(t.screens.active.cursor.pending_wrap); + + { + // '#' cell is wide + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '#'), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0xFE0F}, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + // spacer_tail + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: VS16 to make wide character with mode 2027" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print(0x2764); // Heart + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + try t.print(0xFE0F); // VS16 to make wide + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("❤️", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x2764), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } +} + +test "Terminal: VS16 repeated with mode 2027" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print(0x2764); // Heart + try t.print(0xFE0F); // VS16 to make wide + try t.print(0x2764); // Heart + try t.print(0xFE0F); // VS16 to make wide + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("❤️❤️", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x2764), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x2764), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + const cps = list_cell.node.data.lookupGrapheme(cell).?; + try testing.expectEqual(@as(usize, 1), cps.len); + } +} + +test "Terminal: print invalid VS16 grapheme" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/1482 + try t.print('x'); + try t.print(0xFE0F); // invalid VS16 + + // We should have 1 cells taken up, and narrow. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'x'), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: print invalid VS16 with second char" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/1482 + try t.print('x'); + try t.print(0xFE0F); + try t.print('y'); + + // We should have 2 cells taken up, from two separate narrow characters. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'x'), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'y'), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: print grapheme ò (o with nonspacing mark) should be narrow" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print('o'); + try t.print(0x0300); // combining grave accent + + // We should have 1 cell taken up. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'o'), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0x0300}, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: print Devanagari grapheme should be wide" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // क्‍ष + try t.print(0x0915); + try t.print(0x094D); + try t.print(0x200D); + try t.print(0x0937); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x0915), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{ 0x094D, 0x200D, 0x0937 }, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: print Devanagari grapheme should be wide on next line" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 3 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + t.cursorRight(2); + + // क्‍ष + try t.print(0x0915); + try t.print(0x094D); + try t.print(0x200D); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + + // This one increases the width to wide + try t.print(0x0937); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + { + // Previous cell turns into spacer_head + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + // Devanagari grapheme is wide + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x0915), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{ 0x094D, 0x200D, 0x0937 }, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: print Devanagari grapheme should be wide on next page" { + const rows = pagepkg.std_capacity.rows; + const cols = pagepkg.std_capacity.cols; + var t = try init(testing.allocator, .{ .rows = rows, .cols = cols }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + t.cursorDown(rows - 1); + + for (rows..t.screens.active.pages.pages.first.?.data.capacity.rows) |_| { + try t.index(); + } + + t.cursorRight(cols - 1); + + try testing.expectEqual(cols - 1, t.screens.active.cursor.x); + try testing.expectEqual(rows - 1, t.screens.active.cursor.y); + + // क्‍ष + try t.print(0x0915); + try t.print(0x094D); + try t.print(0x200D); + try testing.expectEqual(cols - 1, t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.pending_wrap); + + // This one increases the width to wide + try t.print(0x0937); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(rows - 1, t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + { + // Previous cell turns into spacer_head + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = cols - 1, .y = rows - 2 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + } + { + // Devanagari grapheme is wide + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = rows - 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x0915), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{ 0x094D, 0x200D, 0x0937 }, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 1, .y = rows - 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: print invalid VS16 with second char (combining)" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/1482 + try t.print('n'); + try t.print(0xFE0F); // invalid VS16 + try t.print(0x0303); // combining tilde + + // We should have 1 cells taken up, and narrow. + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'n'), cell.content.codepoint); + try testing.expect(cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{'\u{0303}'}, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: overwrite grapheme should clear grapheme data" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.print(0x26C8); // Thunder cloud and rain + try t.print(0xFE0E); // VS15 to make narrow + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + t.clearDirty(); + + t.setCursorPos(1, 1); + try t.print('A'); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'A'), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: overwrite multicodepoint grapheme clears grapheme data" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/289 + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // We should have one cell with graphemes + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.graphemeCount()); + + // Move back and overwrite wide + t.setCursorPos(1, 1); + t.clearDirty(); + try t.print('X'); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), page.graphemeCount()); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X", str); + } +} + +test "Terminal: overwrite multicodepoint grapheme tail clears grapheme data" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + // https://github.com/mitchellh/ghostty/issues/289 + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + // We should have 2 cells taken up. It is one character but "wide". + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // We should have one cell with graphemes + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.graphemeCount()); + + // Move back and overwrite wide + t.setCursorPos(1, 2); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), page.graphemeCount()); +} + +test "Terminal: print breaks valid grapheme cluster with Prepend + ASCII for speed" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Make sure we're not at cursor.x == 0 for the next char. + try t.print('_'); + + // U+0600 ARABIC NUMBER SIGN (Prepend) + try t.print(0x0600); + try t.print('1'); + + // We should have 3 cells taken up, each narrow. Note that this is + // **incorrect** grapheme break behavior, since a Prepend code point should + // not break with the one following it per UAX #29 GB9b. However, as an + // optimization we assume a grapheme break when c <= 255, and note that + // this deviation only affects these very uncommon scenarios (e.g. the + // Arabic number sign should precede Arabic-script digits). + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 3), t.screens.active.cursor.x); + // This is what we'd expect if we did break correctly: + //try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Assert various properties about our screen to verify + // we have all expected cells. + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x0600), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + // This is what we'd expect if we did break correctly: + //try testing.expect(cell.hasGrapheme()); + //try testing.expectEqualSlices(u21, &.{'1'}, list_cell.node.data.lookupGrapheme(cell).?); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '1'), cell.content.codepoint); + // This is what we'd expect if we did break correctly: + //try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expect(!cell.hasGrapheme()); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: print writes to bottom if scrolled" { + var t = try init(testing.allocator, .{ .cols = 5, .rows = 2 }); + defer t.deinit(testing.allocator); + + // Basic grid writing + for ("hello") |c| try t.print(c); + t.setCursorPos(0, 0); + + // Make newlines so we create scrollback + // 3 pushes hello off the screen + try t.index(); + try t.index(); + try t.index(); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + // Scroll to the top + t.screens.active.scroll(.{ .top = {} }); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hello", str); + } + + // Type + try t.print('A'); + t.screens.active.scroll(.{ .active = {} }); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nA", str); + } + + try testing.expect(t.isDirty(.{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } })); +} + +test "Terminal: print charset" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // G1 should have no effect + t.configureCharset(.G1, .dec_special); + t.configureCharset(.G2, .dec_special); + t.configureCharset(.G3, .dec_special); + + // No dirty to configure charset + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // Basic grid writing + try t.print('`'); + t.configureCharset(.G0, .utf8); + try t.print('`'); + t.configureCharset(.G0, .ascii); + try t.print('`'); + t.configureCharset(.G0, .dec_special); + try t.print('`'); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("```◆", str); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print charset outside of ASCII" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // G1 should have no effect + t.configureCharset(.G1, .dec_special); + t.configureCharset(.G2, .dec_special); + t.configureCharset(.G3, .dec_special); + + // No dirty to configure charset + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // Basic grid writing + t.configureCharset(.G0, .dec_special); + try t.print('`'); + try t.print(0x1F600); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("◆ ", str); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print invoke charset" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + t.configureCharset(.G1, .dec_special); + + try t.print('`'); + + // Invokecharset but should not mark dirty on its own + t.clearDirty(); + t.invokeCharset(.GL, .G1, false); + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + try t.print('`'); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + try t.print('`'); + t.invokeCharset(.GL, .G0, false); + try t.print('`'); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("`◆◆`", str); + } +} + +test "Terminal: print invoke charset single" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + t.configureCharset(.G1, .dec_special); + + // Basic grid writing + try t.print('`'); + t.invokeCharset(.GL, .G1, true); + try t.print('`'); + try t.print('`'); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("`◆`", str); + } +} + +test "Terminal: print kitty unicode placeholder" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + try t.print(kitty.graphics.unicode.placeholder); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.x); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, kitty.graphics.unicode.placeholder), cell.content.codepoint); + try testing.expect(list_cell.row.kitty_virtual_placeholder); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: soft wrap" { + var t = try init(testing.allocator, .{ .cols = 3, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Basic grid writing + for ("hello") |c| try t.print(c); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hel\nlo", str); + } +} + +test "Terminal: soft wrap with semantic prompt" { + var t = try init(testing.allocator, .{ .cols = 3, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Mark our prompt. + try t.semanticPrompt(.init(.prompt_start)); + // Should not make anything dirty on its own. + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + // Write and wrap + for ("hello") |c| try t.print(c); + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + try testing.expectEqual(.prompt, list_cell.row.semantic_prompt); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } +} + +test "Terminal: disabled wraparound with wide char and one space" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + t.modes.set(.wraparound, false); + + // This puts our cursor at the end and there is NO SPACE for a + // wide character. + try t.printString("AAAA"); + t.clearDirty(); + try t.print(0x1F6A8); // Police car light + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.x); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AAAA", str); + } + + // Make sure we printed nothing + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 4, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + // Should not be dirty since we didn't modify anything + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: disabled wraparound with wide char and no space" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + t.modes.set(.wraparound, false); + + // This puts our cursor at the end and there is NO SPACE for a + // wide character. + try t.printString("AAAAA"); + t.clearDirty(); + try t.print(0x1F6A8); // Police car light + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.x); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AAAAA", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 4, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'A'), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + // Should not be dirty since we didn't modify anything + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: disabled wraparound with wide grapheme and half space" { + var t = try init(testing.allocator, .{ .rows = 5, .cols = 5 }); + defer t.deinit(testing.allocator); + + t.modes.set(.grapheme_cluster, true); + t.modes.set(.wraparound, false); + + // This puts our cursor at the end and there is NO SPACE for a + // wide character. + try t.printString("AAAA"); + try t.print(0x2764); // Heart + t.clearDirty(); + try t.print(0xFE0F); // VS16 to make wide + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.x); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AAAA❤", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 4, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '❤'), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + + // Should not be dirty since we didn't modify anything + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print right margin wrap" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 5 }); + defer t.deinit(testing.allocator); + + try t.printString("123456789"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setCursorPos(1, 5); + try t.printString("XY"); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1234X6789\n Y", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + const row = list_cell.row; + try testing.expect(!row.wrap); + } +} + +test "Terminal: print right margin wrap dirty tracking" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 5 }); + defer t.deinit(testing.allocator); + + try t.printString("123456789"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setCursorPos(1, 5); + + // Writing our X on the first line should mark only that line dirty. + t.clearDirty(); + try t.print('X'); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 4, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 2, .y = 1 } })); + + // Writing our Y should wrap. It marks both rows dirty because the + // cursor moved. + t.clearDirty(); + try t.print('Y'); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 4, .y = 0 } })); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 2, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1234X6789\n Y", str); + } +} + +test "Terminal: print right margin outside" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 5 }); + defer t.deinit(testing.allocator); + + try t.printString("123456789"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setCursorPos(1, 6); + t.clearDirty(); + try t.printString("XY"); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("12345XY89", str); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 5, .y = 0 } })); +} + +test "Terminal: print right margin outside wrap" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 5 }); + defer t.deinit(testing.allocator); + + try t.printString("123456789"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setCursorPos(1, 10); + try t.printString("XY"); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("123456789X\n Y", str); + } +} + +test "Terminal: print wide char at right margin does not create spacer head" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setCursorPos(1, 5); + try t.print(0x1F600); // Smiley face + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 4), t.screens.active.cursor.x); + + // Both rows dirty because the cursor moved + try testing.expect(t.isDirty(.{ .screen = .{ .x = 4, .y = 0 } })); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 4, .y = 1 } })); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 4, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + + const row = list_cell.row; + try testing.expect(!row.wrap); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 2, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x1F600), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 3, .y = 1 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: print with hyperlink" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Setup our hyperlink and print + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("123456"); + + // Verify all our cells have a hyperlink + for (0..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print over cell with same hyperlink" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Setup our hyperlink and print + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("123456"); + t.setCursorPos(1, 1); + try t.printString("123456"); + + // Verify all our cells have a hyperlink + for (0..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print and end hyperlink" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Setup our hyperlink and print + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("123"); + t.screens.active.endHyperlink(); + try t.printString("456"); + + // Verify all our cells have a hyperlink + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + for (3..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: print and change hyperlink" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Setup our hyperlink and print + try t.screens.active.startHyperlink("http://one.example.com", null); + try t.printString("123"); + try t.screens.active.startHyperlink("http://two.example.com", null); + try t.printString("456"); + + // Verify all our cells have a hyperlink + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + for (3..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 2), id); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +test "Terminal: overwrite hyperlink" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Setup our hyperlink and print + try t.screens.active.startHyperlink("http://one.example.com", null); + try t.printString("123"); + t.setCursorPos(1, 1); + t.screens.active.endHyperlink(); + try t.printString("456"); + + // Verify all our cells have a hyperlink + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const page = &list_cell.node.data; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + try testing.expect(page.lookupHyperlink(cell) == null); + try testing.expectEqual(0, page.hyperlink_set.count()); + } + + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); +} + +// Printing a wide char at the right edge with an active hyperlink causes +// printCell to write a spacer_head before printWrap sets the row wrap +// flag. The integrity check inside setHyperlink (or increaseCapacity) +// sees the unwrapped spacer head and panics. Found via fuzzing. +test "Terminal: print wide char at right edge with hyperlink" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 5 }); + defer t.deinit(testing.allocator); + + try t.screens.active.startHyperlink("http://example.com", null); + + // Move cursor to the last column (1-indexed) + t.setCursorPos(1, 10); + + // Print a wide character; this will call printCell(0, .spacer_head) + // at the right edge before calling printWrap, triggering the + // integrity violation. + try t.print(0x4E2D); // U+4E2D '中' + + // Cursor wraps to row 2, after the wide char + spacer tail + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + + // Row 0, col 9: spacer head with hyperlink + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 9, .y = 0 } }).?; + try testing.expectEqual(Cell.Wide.spacer_head, list_cell.cell.wide); + try testing.expect(list_cell.cell.hyperlink); + try testing.expect(list_cell.row.wrap); + } + // Row 1, col 0: the wide char with hyperlink + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 1 } }).?; + try testing.expectEqual(@as(u21, 0x4E2D), list_cell.cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, list_cell.cell.wide); + try testing.expect(list_cell.cell.hyperlink); + } + // Row 1, col 1: spacer tail with hyperlink + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 1 } }).?; + try testing.expectEqual(Cell.Wide.spacer_tail, list_cell.cell.wide); + try testing.expect(list_cell.cell.hyperlink); + } +} + +test "Terminal: linefeed and carriage return" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Print and CR. + for ("hello") |c| try t.print(c); + t.clearDirty(); + t.carriageReturn(); + + // CR should not mark row dirty because it doesn't change rendering. + try testing.expect(!t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + + try t.linefeed(); + + // LF marks row dirty due to cursor movement + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 1 } })); + + for ("world") |c| try t.print(c); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hello\nworld", str); + } +} + +test "Terminal: linefeed unsets pending wrap" { + var t = try init(testing.allocator, .{ .cols = 5, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Basic grid writing + for ("hello") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap == true); + t.clearDirty(); + try t.linefeed(); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .screen = .{ .x = 0, .y = 1 } })); + try testing.expect(t.screens.active.cursor.pending_wrap == false); +} + +test "Terminal: linefeed mode automatic carriage return" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + // Basic grid writing + t.modes.set(.linefeed, true); + try t.printString("123456"); + try t.linefeed(); + try t.print('X'); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("123456\nX", str); + } +} + +test "Terminal: carriage return unsets pending wrap" { + var t = try init(testing.allocator, .{ .cols = 5, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Basic grid writing + for ("hello") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap == true); + t.carriageReturn(); + try testing.expect(t.screens.active.cursor.pending_wrap == false); +} + +test "Terminal: carriage return origin mode moves to left margin" { + var t = try init(testing.allocator, .{ .cols = 5, .rows = 80 }); + defer t.deinit(testing.allocator); + + t.modes.set(.origin, true); + t.screens.active.cursor.x = 0; + t.scrolling_region.left = 2; + t.carriageReturn(); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); +} + +test "Terminal: carriage return left of left margin moves to zero" { + var t = try init(testing.allocator, .{ .cols = 5, .rows = 80 }); + defer t.deinit(testing.allocator); + + t.screens.active.cursor.x = 1; + t.scrolling_region.left = 2; + t.carriageReturn(); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); +} + +test "Terminal: carriage return right of left margin moves to left margin" { + var t = try init(testing.allocator, .{ .cols = 5, .rows = 80 }); + defer t.deinit(testing.allocator); + + t.screens.active.cursor.x = 3; + t.scrolling_region.left = 2; + t.carriageReturn(); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); +} + +test "Terminal: backspace" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // BS + for ("hello") |c| try t.print(c); + t.backspace(); + try t.print('y'); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("helly", str); + } +} + +test "Terminal: horizontal tabs" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + // HT + try t.print('1'); + t.horizontalTab(); + try testing.expectEqual(@as(usize, 8), t.screens.active.cursor.x); + + // HT + t.horizontalTab(); + try testing.expectEqual(@as(usize, 16), t.screens.active.cursor.x); + + // HT at the end + t.horizontalTab(); + try testing.expectEqual(@as(usize, 19), t.screens.active.cursor.x); + t.horizontalTab(); + try testing.expectEqual(@as(usize, 19), t.screens.active.cursor.x); +} + +test "Terminal: horizontal tabs starting on tabstop" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(t.screens.active.cursor.y, 9); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y, 9); + t.horizontalTab(); + try t.print('A'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X A", str); + } +} + +test "Terminal: horizontal tabs with right margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + t.scrolling_region.left = 2; + t.scrolling_region.right = 5; + t.setCursorPos(t.screens.active.cursor.y, 1); + try t.print('X'); + t.horizontalTab(); + try t.print('A'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X A", str); + } +} + +test "Terminal: horizontal tabs back" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + // Edge of screen + t.setCursorPos(t.screens.active.cursor.y, 20); + + // HT + t.horizontalTabBack(); + try testing.expectEqual(@as(usize, 16), t.screens.active.cursor.x); + + // HT + t.horizontalTabBack(); + try testing.expectEqual(@as(usize, 8), t.screens.active.cursor.x); + + // HT + t.horizontalTabBack(); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + t.horizontalTabBack(); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); +} + +test "Terminal: horizontal tabs back starting on tabstop" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(t.screens.active.cursor.y, 9); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y, 9); + t.horizontalTabBack(); + try t.print('A'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A X", str); + } +} + +test "Terminal: horizontal tabs with left margin in origin mode" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + t.modes.set(.origin, true); + t.scrolling_region.left = 2; + t.scrolling_region.right = 5; + t.setCursorPos(1, 2); + try t.print('X'); + t.horizontalTabBack(); + try t.print('A'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" AX", str); + } +} + +test "Terminal: horizontal tab back with cursor before left margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 20, .rows = 5 }); + defer t.deinit(alloc); + + t.modes.set(.origin, true); + t.saveCursor(); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(5, 0); + t.restoreCursor(); + t.horizontalTabBack(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X", str); + } +} + +test "Terminal: cursorPos resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.setCursorPos(1, 1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("XBCDE", str); + } +} + +test "Terminal: cursorPos off the screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(500, 500); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\n\n X", str); + } +} + +test "Terminal: cursorPos relative to origin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.scrolling_region.top = 2; + t.scrolling_region.bottom = 3; + t.modes.set(.origin, true); + t.setCursorPos(1, 1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\nX", str); + } +} + +test "Terminal: cursorPos relative to origin with left/right" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.scrolling_region.top = 2; + t.scrolling_region.bottom = 3; + t.scrolling_region.left = 2; + t.scrolling_region.right = 4; + t.modes.set(.origin, true); + t.setCursorPos(1, 1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n X", str); + } +} + +test "Terminal: cursorPos limits with full scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.scrolling_region.top = 2; + t.scrolling_region.bottom = 3; + t.scrolling_region.left = 2; + t.scrolling_region.right = 4; + t.modes.set(.origin, true); + t.setCursorPos(500, 500); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\n X", str); + } +} + +// Probably outdated, but dates back to the original terminal implementation. +test "Terminal: setCursorPos (original test)" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + + // Setting it to 0 should keep it zero (1 based) + t.setCursorPos(0, 0); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + + // Should clamp to size + t.setCursorPos(81, 81); + try testing.expectEqual(@as(usize, 79), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 79), t.screens.active.cursor.y); + + // Should reset pending wrap + t.setCursorPos(0, 80); + try t.print('c'); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.setCursorPos(0, 80); + try testing.expect(!t.screens.active.cursor.pending_wrap); + + // Origin mode + t.modes.set(.origin, true); + + // No change without a scroll region + t.setCursorPos(81, 81); + try testing.expectEqual(@as(usize, 79), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 79), t.screens.active.cursor.y); + + // Set the scroll region + t.setTopAndBottomMargin(10, t.rows); + t.setCursorPos(0, 0); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 9), t.screens.active.cursor.y); + + t.setCursorPos(1, 1); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 9), t.screens.active.cursor.y); + + t.setCursorPos(100, 0); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 79), t.screens.active.cursor.y); + + t.setTopAndBottomMargin(10, 11); + t.setCursorPos(2, 0); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 10), t.screens.active.cursor.y); +} + +test "Terminal: setTopAndBottomMargin simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(0, 0); + + t.clearDirty(); + t.scrollDown(1); + + // Mark the rows we moved as dirty. + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nDEF\nGHI", str); + } +} + +test "Terminal: setTopAndBottomMargin top only" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(2, 0); + + t.clearDirty(); + t.scrollDown(1); + + // This is dirty because the cursor moves from this row + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\n\nDEF\nGHI", str); + } +} + +test "Terminal: setTopAndBottomMargin top and bottom" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(1, 2); + + t.clearDirty(); + t.scrollDown(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nGHI", str); + } +} + +test "Terminal: setTopAndBottomMargin top equal to bottom" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(2, 2); + + t.clearDirty(); + t.scrollDown(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nDEF\nGHI", str); + } +} + +test "Terminal: setLeftAndRightMargin simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(0, 0); + + t.clearDirty(); + t.eraseChars(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" BC\nDEF\nGHI", str); + } +} + +test "Terminal: setLeftAndRightMargin left only" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 0); + try testing.expectEqual(@as(usize, 1), t.scrolling_region.left); + try testing.expectEqual(@as(usize, t.cols - 1), t.scrolling_region.right); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nDBC\nGEF\n HI", str); + } +} + +test "Terminal: setLeftAndRightMargin left and right" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(1, 2); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" C\nABF\nDEI\nGH", str); + } +} + +test "Terminal: setLeftAndRightMargin left equal right" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 2); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nDEF\nGHI", str); + } +} + +test "Terminal: setLeftAndRightMargin mode 69 unset" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, false); + t.setLeftAndRightMargin(1, 2); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nDEF\nGHI", str); + } +} + +test "Terminal: insertLines simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\n\nDEF\nGHI", str); + } +} + +test "Terminal: insertLines colors with bg color" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.insertLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\n\nDEF\nGHI", str); + } + + for (0..t.cols) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 1, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: insertLines handles style refs" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + + // For the line being deleted, create a refcounted style + try t.setAttribute(.{ .bold = {} }); + try t.printString("GHI"); + try t.setAttribute(.{ .unset = {} }); + + // verify we have styles in our style map + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + + t.setCursorPos(2, 2); + t.insertLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\n\nDEF", str); + } + + // verify we have no styles in our style map + try testing.expectEqual(@as(usize, 0), page.styles.count()); +} + +test "Terminal: insertLines outside of scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(3, 4); + t.setCursorPos(2, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\nGHI", str); + } +} + +test "Terminal: insertLines top/bottom scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("123"); + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(2, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\n\nDEF\n123", str); + } +} + +test "Terminal: insertLines across page boundary marks all shifted rows dirty" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 10, .max_scrollback = 1024 }); + defer t.deinit(alloc); + + const first_page = t.screens.active.pages.pages.first.?; + const first_page_nrows = first_page.data.capacity.rows; + + // Fill up the first page minus 3 rows + for (0..first_page_nrows - 3) |_| try t.linefeed(); + + // Add content that will cross a page boundary + try t.printString("1AAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("2BBBB"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("3CCCC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("4DDDD"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("5EEEE"); + + // Verify we now have a second page + try testing.expect(first_page.next != null); + + t.setCursorPos(1, 1); + t.clearDirty(); + t.insertLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n1AAAA\n2BBBB\n3CCCC\n4DDDD", str); + } +} + +test "Terminal: insertLines (legacy test)" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + t.carriageReturn(); + try t.linefeed(); + try t.print('E'); + + // Move to row 2 + t.setCursorPos(2, 1); + + // Insert two lines + t.insertLines(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n\n\nB\nC", str); + } +} + +test "Terminal: insertLines zero" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + // This should do nothing + t.setCursorPos(1, 1); + t.insertLines(0); +} + +test "Terminal: insertLines with scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 6 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + t.carriageReturn(); + try t.linefeed(); + try t.print('E'); + + t.setTopAndBottomMargin(1, 2); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X\nA\nC\nD\nE", str); + } +} + +test "Terminal: insertLines more than remaining" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + t.carriageReturn(); + try t.linefeed(); + try t.print('E'); + + // Move to row 2 + t.setCursorPos(2, 1); + + // Insert a bunch of lines + t.clearDirty(); + t.insertLines(20); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A", str); + } +} + +test "Terminal: insertLines resets pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.insertLines(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('B'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("B\nABCDE", str); + } +} + +test "Terminal: insertLines resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + try t.print('1'); + t.carriageReturn(); + try t.linefeed(); + for ("ABCDEF") |c| try t.print(c); + t.setCursorPos(1, 1); + t.insertLines(1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X\n1\nABC", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 2 } }).?; + const row = list_cell.row; + try testing.expect(!row.wrap); + } +} + +test "Terminal: insertLines multi-codepoint graphemes" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Disable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + t.insertLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\n\n👨‍👩‍👧\nGHI", str); + } +} + +test "Terminal: insertLines left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + + t.clearDirty(); + t.insertLines(1); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC123\nD 56\nGEF489\n HI7", str); + } +} + +test "Terminal: scrollUp simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + + const cursor = t.screens.active.cursor; + const viewport_before = t.screens.active.pages.getTopLeft(.viewport); + try t.scrollUp(1); + try testing.expectEqual(cursor.x, t.screens.active.cursor.x); + try testing.expectEqual(cursor.y, t.screens.active.cursor.y); + + // Viewport should have moved. Our entire page should've scrolled! + // The viewport moving will cause our render state to make the full + // frame as dirty. + const viewport_after = t.screens.active.pages.getTopLeft(.viewport); + try testing.expect(!viewport_before.eql(viewport_after)); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("DEF\nGHI", str); + } +} + +test "Terminal: scrollUp moves hyperlink" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("DEF"); + t.screens.active.endHyperlink(); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + try t.scrollUp(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("DEF\nGHI", str); + } + + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: scrollUp clears hyperlink" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("ABC"); + t.screens.active.endHyperlink(); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + try t.scrollUp(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("DEF\nGHI", str); + } + + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: scrollUp top/bottom scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(2, 3); + t.setCursorPos(1, 1); + + t.clearDirty(); + try t.scrollUp(1); + + // This is dirty because the cursor moves from this row + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nGHI", str); + } +} + +test "Terminal: scrollUp left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + + const cursor = t.screens.active.cursor; + t.clearDirty(); + try t.scrollUp(1); + try testing.expectEqual(cursor.x, t.screens.active.cursor.x); + try testing.expectEqual(cursor.y, t.screens.active.cursor.y); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AEF423\nDHI756\nG 89", str); + } +} + +test "Terminal: scrollUp left/right scroll region hyperlink" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("DEF456"); + t.screens.active.endHyperlink(); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + try t.scrollUp(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AEF423\nDHI756\nG 89", str); + } + + // First row gets some hyperlinks + { + for (0..1) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } + for (1..4) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + for (4..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } + } + + // Second row preserves hyperlink where we didn't scroll + { + for (0..1) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + for (1..4) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } + for (4..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + } +} + +test "Terminal: scrollUp preserves pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(1, 5); + try t.print('A'); + t.setCursorPos(2, 5); + try t.print('B'); + t.setCursorPos(3, 5); + try t.print('C'); + try t.scrollUp(1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" B\n C\n\nX", str); + } +} + +test "Terminal: scrollUp full top/bottom region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("top"); + t.setCursorPos(5, 1); + try t.printString("ABCDE"); + t.setTopAndBottomMargin(2, 5); + + t.clearDirty(); + try t.scrollUp(4); + + // This is dirty because the cursor moves from this row + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("top", str); + } +} + +test "Terminal: scrollUp full top/bottomleft/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("top"); + t.setCursorPos(5, 1); + try t.printString("ABCDE"); + t.modes.set(.enable_left_and_right_margin, true); + t.setTopAndBottomMargin(2, 5); + t.setLeftAndRightMargin(2, 4); + + t.clearDirty(); + try t.scrollUp(4); + + // This is dirty because the cursor moves from this row + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + for (1..5) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("top\n\n\n\nA E", str); + } +} + +test "Terminal: scrollUp creates scrollback in primary screen" { + // When in primary screen with full-width scroll region at top, + // scrollUp (CSI S) should push lines into scrollback like xterm. + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5, .max_scrollback = 10 }); + defer t.deinit(alloc); + + // Fill the screen with content + try t.printString("AAAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("BBBBB"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("CCCCC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DDDDD"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("EEEEE"); + + t.clearDirty(); + + // Scroll up by 1, which should push "AAAAA" into scrollback + try t.scrollUp(1); + + // The cursor row (new empty row) should be dirty + try testing.expect(t.screens.active.cursor.page_row.dirty); + + // The active screen should now show BBBBB through EEEEE plus one blank line + { + const str = try t.plainString(alloc); + defer alloc.free(str); + try testing.expectEqualStrings("BBBBB\nCCCCC\nDDDDD\nEEEEE", str); + } + + // Now scroll to the top to see scrollback - AAAAA should be there + t.screens.active.scroll(.{ .top = {} }); + { + const str = try t.plainString(alloc); + defer alloc.free(str); + // Should see AAAAA in scrollback + try testing.expectEqualStrings("AAAAA\nBBBBB\nCCCCC\nDDDDD\nEEEEE", str); + } +} + +test "Terminal: scrollUp with max_scrollback zero" { + // When max_scrollback is 0, scrollUp should still work but not retain history + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5, .max_scrollback = 0 }); + defer t.deinit(alloc); + + try t.printString("AAAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("BBBBB"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("CCCCC"); + + try t.scrollUp(1); + + // Active screen should show scrolled content + { + const str = try t.plainString(alloc); + defer alloc.free(str); + try testing.expectEqualStrings("BBBBB\nCCCCC", str); + } + + // Scroll to top - should be same as active since no scrollback + t.screens.active.scroll(.{ .top = {} }); + { + const str = try t.plainString(alloc); + defer alloc.free(str); + try testing.expectEqualStrings("BBBBB\nCCCCC", str); + } +} + +test "Terminal: scrollUp with max_scrollback zero and top margin" { + // When max_scrollback is 0 and top margin is set, should use deleteLines path + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5, .max_scrollback = 0 }); + defer t.deinit(alloc); + + try t.printString("AAAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("BBBBB"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("CCCCC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DDDDD"); + + // Set top margin (not at row 0) + t.setTopAndBottomMargin(2, 5); + + try t.scrollUp(1); + + { + const str = try t.plainString(alloc); + defer alloc.free(str); + // First row preserved, rest scrolled + try testing.expectEqualStrings("AAAAA\nCCCCC\nDDDDD", str); + } +} + +test "Terminal: scrollUp with max_scrollback zero and left/right margin" { + // When max_scrollback is 0 with left/right margins, uses deleteLines path + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 10, .max_scrollback = 0 }); + defer t.deinit(alloc); + + try t.printString("AAAAABBBBB"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("CCCCCDDDDD"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("EEEEEFFFFF"); + + // Set left/right margins (columns 2-6, 1-indexed = indices 1-5) + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 6); + + try t.scrollUp(1); + + { + const str = try t.plainString(alloc); + defer alloc.free(str); + // cols 1-5 scroll, col 0 and cols 6+ preserved + try testing.expectEqualStrings("ACCCCDBBBB\nCEEEEFDDDD\nE FFFF", str); + } +} + +test "Terminal: scrollDown simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + + const cursor = t.screens.active.cursor; + t.clearDirty(); + t.scrollDown(1); + try testing.expectEqual(cursor.x, t.screens.active.cursor.x); + try testing.expectEqual(cursor.y, t.screens.active.cursor.y); + + for (0..5) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nDEF\nGHI", str); + } +} + +test "Terminal: scrollDown hyperlink moves" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("ABC"); + t.screens.active.endHyperlink(); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + t.scrollDown(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nABC\nDEF\nGHI", str); + } + + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: scrollDown outside of scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setTopAndBottomMargin(3, 4); + t.setCursorPos(2, 2); + + const cursor = t.screens.active.cursor; + t.clearDirty(); + t.scrollDown(1); + try testing.expectEqual(cursor.x, t.screens.active.cursor.x); + try testing.expectEqual(cursor.y, t.screens.active.cursor.y); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + // This is dirty because the cursor moves from this row + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\n\nGHI", str); + } +} + +test "Terminal: scrollDown left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + + const cursor = t.screens.active.cursor; + t.clearDirty(); + t.scrollDown(1); + try testing.expectEqual(cursor.x, t.screens.active.cursor.x); + try testing.expectEqual(cursor.y, t.screens.active.cursor.y); + + for (0..4) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A 23\nDBC156\nGEF489\n HI7", str); + } +} + +test "Terminal: scrollDown left/right scroll region hyperlink" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("ABC123"); + t.screens.active.endHyperlink(); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + t.scrollDown(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A 23\nDBC156\nGEF489\n HI7", str); + } + + // First row preserves hyperlink where we didn't scroll + { + for (0..1) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + for (1..4) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } + for (4..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + } + + // Second row gets some hyperlinks + { + for (0..1) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } + for (1..4) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + const page = &list_cell.node.data; + try testing.expectEqual(1, page.hyperlink_set.count()); + } + for (4..6) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = @intCast(x), + .y = 1, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } + } +} + +test "Terminal: scrollDown outside of left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(1, 1); + + const cursor = t.screens.active.cursor; + t.clearDirty(); + t.scrollDown(1); + try testing.expectEqual(cursor.x, t.screens.active.cursor.x); + try testing.expectEqual(cursor.y, t.screens.active.cursor.y); + + for (0..4) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A 23\nDBC156\nGEF489\n HI7", str); + } +} + +test "Terminal: scrollDown preserves pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 10 }); + defer t.deinit(alloc); + + t.setCursorPos(1, 5); + try t.print('A'); + t.setCursorPos(2, 5); + try t.print('B'); + t.setCursorPos(3, 5); + try t.print('C'); + t.scrollDown(1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n A\n B\nX C", str); + } +} + +test "Terminal: eraseChars simple operation" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.clearDirty(); + t.eraseChars(2); + try t.print('X'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X C", str); + } +} + +test "Terminal: eraseChars minimum one" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.clearDirty(); + t.eraseChars(0); + try t.print('X'); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("XBC", str); + } +} + +test "Terminal: eraseChars beyond screen edge" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for (" ABC") |c| try t.print(c); + t.setCursorPos(1, 4); + t.eraseChars(10); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" A", str); + } +} + +test "Terminal: eraseChars wide character" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('橋'); + for ("BC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.eraseChars(1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X BC", str); + } +} + +test "Terminal: eraseChars resets pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.eraseChars(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX", str); + } +} + +test "Terminal: eraseChars resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE123") |c| try t.print(c); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + const row = list_cell.row; + try testing.expect(row.wrap); + } + + t.setCursorPos(1, 1); + t.eraseChars(1); + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + const row = list_cell.row; + try testing.expect(!row.wrap); + } + + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("XBCDE\n123", str); + } +} + +test "Terminal: eraseChars preserves background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.eraseChars(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" C", str); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 1, .y = 0 } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: eraseChars handles refcounted styles" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .bold = {} }); + try t.print('A'); + try t.print('B'); + try t.setAttribute(.{ .unset = {} }); + try t.print('C'); + + // verify we have styles in our style map + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + + t.setCursorPos(1, 1); + t.eraseChars(2); + + // verify we have no styles in our style map + try testing.expectEqual(@as(usize, 0), page.styles.count()); +} + +test "Terminal: eraseChars protected attributes respected with iso" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.eraseChars(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC", str); + } +} + +test "Terminal: eraseChars protected attributes ignored with dec most recent" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setProtectedMode(.dec); + t.setProtectedMode(.off); + t.setCursorPos(1, 1); + t.eraseChars(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" C", str); + } +} + +test "Terminal: eraseChars protected attributes ignored with dec set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.eraseChars(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" C", str); + } +} + +test "Terminal: eraseChars wide char boundary conditions" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 1, .cols = 8 }); + defer t.deinit(alloc); + + try t.printString("😀a😀b😀"); + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings("😀a😀b😀", str); + } + + t.setCursorPos(1, 2); + t.eraseChars(3); + t.screens.active.cursor.page_pin.node.data.assertIntegrity(); + + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" b😀", str); + } +} + +test "Terminal: eraseChars wide char splits proper cell boundaries" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 1, .cols = 30 }); + defer t.deinit(alloc); + + // This is a test for a bug: https://github.com/ghostty-org/ghostty/issues/2817 + // To explain the setup: + // (1) We need our wide characters starting on an even (1-based) column. + // (2) We need our cursor to be in the middle somewhere. + // (3) We need our count to be less than our cursor X and on a split cell. + // The bug was that we split the wrong cell boundaries. + + try t.printString("x食べて下さい"); + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings("x食べて下さい", str); + } + + t.setCursorPos(1, 6); // At: て + t.eraseChars(4); // Delete: て下 + t.screens.active.cursor.page_pin.node.data.assertIntegrity(); + + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings("x食べ さい", str); + } +} + +test "Terminal: eraseChars wide char wrap boundary conditions" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 3, .cols = 8 }); + defer t.deinit(alloc); + + try t.printString(".......😀abcde😀......"); + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings(".......\n😀abcde\n😀......", str); + + const unwrapped = try t.plainStringUnwrapped(alloc); + defer testing.allocator.free(unwrapped); + try testing.expectEqualStrings(".......😀abcde😀......", unwrapped); + } + + t.setCursorPos(2, 2); + t.eraseChars(3); + t.screens.active.cursor.page_pin.node.data.assertIntegrity(); + + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings(".......\n cde\n😀......", str); + + const unwrapped = try t.plainStringUnwrapped(alloc); + defer testing.allocator.free(unwrapped); + try testing.expectEqualStrings("....... cde\n😀......", unwrapped); + } +} + +test "Terminal: reverseIndex" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.reverseIndex(); + try t.print('D'); + t.carriageReturn(); + try t.linefeed(); + t.carriageReturn(); + try t.linefeed(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nBD\nC", str); + } +} + +test "Terminal: reverseIndex from the top" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + t.carriageReturn(); + try t.linefeed(); + + t.setCursorPos(1, 1); + t.reverseIndex(); + try t.print('D'); + + t.carriageReturn(); + try t.linefeed(); + t.setCursorPos(1, 1); + t.reverseIndex(); + try t.print('E'); + t.carriageReturn(); + try t.linefeed(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("E\nD\nA\nB", str); + } +} + +test "Terminal: reverseIndex top of scrolling region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 10 }); + defer t.deinit(alloc); + + // Initial value + t.setCursorPos(2, 1); + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + t.carriageReturn(); + try t.linefeed(); + + // Set our scroll region + t.setTopAndBottomMargin(2, 5); + t.setCursorPos(2, 1); + t.reverseIndex(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nX\nA\nB\nC", str); + } +} + +test "Terminal: reverseIndex top of screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.setCursorPos(2, 1); + try t.print('B'); + t.setCursorPos(3, 1); + try t.print('C'); + t.setCursorPos(1, 1); + t.reverseIndex(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X\nA\nB\nC", str); + } +} + +test "Terminal: reverseIndex not top of screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.setCursorPos(2, 1); + try t.print('B'); + t.setCursorPos(3, 1); + try t.print('C'); + t.setCursorPos(2, 1); + t.reverseIndex(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X\nB\nC", str); + } +} + +test "Terminal: reverseIndex top/bottom margins" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.setCursorPos(2, 1); + try t.print('B'); + t.setCursorPos(3, 1); + try t.print('C'); + t.setTopAndBottomMargin(2, 3); + t.setCursorPos(2, 1); + t.reverseIndex(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n\nB", str); + } +} + +test "Terminal: reverseIndex outside top/bottom margins" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.setCursorPos(2, 1); + try t.print('B'); + t.setCursorPos(3, 1); + try t.print('C'); + t.setTopAndBottomMargin(2, 3); + t.setCursorPos(1, 1); + t.reverseIndex(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nB\nC", str); + } +} + +test "Terminal: reverseIndex left/right margins" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.setCursorPos(2, 1); + try t.printString("DEF"); + t.setCursorPos(3, 1); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 3); + t.setCursorPos(1, 2); + t.reverseIndex(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nDBC\nGEF\n HI", str); + } +} + +test "Terminal: reverseIndex outside left/right margins" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.setCursorPos(2, 1); + try t.printString("DEF"); + t.setCursorPos(3, 1); + try t.printString("GHI"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 3); + t.setCursorPos(1, 1); + t.reverseIndex(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\nGHI", str); + } +} + +test "Terminal: index" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + try t.index(); + try t.print('A'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nA", str); + } +} + +test "Terminal: index from the bottom" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(5, 1); + try t.print('A'); + t.cursorLeft(1); // undo moving right from 'A' + + t.clearDirty(); + try t.index(); + try t.print('B'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\nA\nB", str); + } +} + +test "Terminal: index scrolling with hyperlink" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(5, 1); + try t.screens.active.startHyperlink("http://example.com", null); + try t.print('A'); + t.screens.active.endHyperlink(); + t.cursorLeft(1); // undo moving right from 'A' + try t.index(); + try t.print('B'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\nA\nB", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = 0, + .y = 3, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = 0, + .y = 4, + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: index outside of scrolling region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + t.setTopAndBottomMargin(2, 5); + try t.index(); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); +} + +test "Terminal: index from the bottom outside of scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 2); + t.setCursorPos(5, 1); + try t.print('A'); + t.clearDirty(); + try t.index(); + try t.print('B'); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\n\nAB", str); + } +} + +test "Terminal: index no scroll region, top of screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.clearDirty(); + try t.index(); + try t.print('X'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n X", str); + } +} + +test "Terminal: index bottom of primary screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(5, 1); + try t.print('A'); + t.clearDirty(); + try t.index(); + try t.print('X'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\nA\n X", str); + } +} + +test "Terminal: index bottom of primary screen background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(5, 1); + try t.print('A'); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + try t.index(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\n\nA", str); + for (0..5) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 4, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: index inside scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + try t.print('A'); + t.clearDirty(); + try t.index(); + try t.print('X'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n X", str); + } +} + +test "Terminal: index bottom of scroll region with hyperlinks" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 2); + try t.print('A'); + try t.index(); + t.carriageReturn(); + try t.screens.active.startHyperlink("http://example.com", null); + try t.print('B'); + t.screens.active.endHyperlink(); + try t.index(); + t.carriageReturn(); + try t.print('C'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("B\nC", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = 0, + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = 0, + .y = 1, + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: index bottom of scroll region clear hyperlinks" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5, .max_scrollback = 0 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(2, 3); + t.setCursorPos(2, 1); + try t.screens.active.startHyperlink("http://example.com", null); + try t.print('A'); + t.screens.active.endHyperlink(); + try t.index(); + t.carriageReturn(); + try t.print('B'); + try t.index(); + t.carriageReturn(); + try t.print('C'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nB\nC", str); + } + + for (1..3) |y| { + const list_cell = t.screens.active.pages.getCell(.{ .viewport = .{ + .x = 0, + .y = @intCast(y), + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + const page = &list_cell.node.data; + try testing.expectEqual(0, page.hyperlink_set.count()); + } +} + +test "Terminal: index bottom of scroll region with background SGR" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(4, 1); + try t.print('B'); + t.setCursorPos(3, 1); + try t.print('A'); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + try t.index(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nA\n\nB", str); + } + + for (0..t.cols) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 2, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: index bottom of primary screen with scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(3, 1); + try t.print('A'); + t.setCursorPos(5, 1); + t.clearDirty(); + try t.index(); + try t.index(); + try t.index(); + try t.print('X'); + + for (0..4) |y| try testing.expect(!t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\nA\n\nX", str); + } +} + +test "Terminal: index outside left/right margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + t.scrolling_region.left = 3; + t.scrolling_region.right = 5; + t.setCursorPos(3, 3); + try t.print('A'); + t.setCursorPos(3, 1); + t.clearDirty(); + try t.index(); + try t.print('X'); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\nX A", str); + } +} + +test "Terminal: index inside left/right margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + try t.printString("AAAAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("AAAAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("AAAAAA"); + t.modes.set(.enable_left_and_right_margin, true); + t.setTopAndBottomMargin(1, 3); + t.setLeftAndRightMargin(1, 3); + t.setCursorPos(3, 1); + + t.clearDirty(); + try t.index(); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AAAAAA\nAAAAAA\n AAA", str); + } +} + +test "Terminal: index bottom of scroll region creates scrollback" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + try t.printString("1\n2\n3"); + t.setCursorPos(4, 1); + try t.print('X'); + t.setCursorPos(3, 1); + try t.index(); + try t.print('Y'); + + { + const str = try t.screens.active.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer testing.allocator.free(str); + try testing.expectEqualStrings("2\n3\nY\nX", str); + } + { + const str = try t.screens.active.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1\n2\n3\nY\nX", str); + } +} + +test "Terminal: index bottom of scroll region no scrollback" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5, .max_scrollback = 0 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(4, 1); + try t.print('B'); + t.setCursorPos(3, 1); + try t.print('A'); + t.clearDirty(); + try t.index(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nA\n X\nB", str); + } +} + +test "Terminal: index bottom of scroll region blank line preserves SGR" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + try t.printString("1\n2\n3"); + t.setCursorPos(4, 1); + try t.print('X'); + t.setCursorPos(3, 1); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + try t.index(); + + { + const str = try t.screens.active.dumpStringAlloc(alloc, .{ .viewport = .{} }); + defer testing.allocator.free(str); + try testing.expectEqualStrings("2\n3\n\nX", str); + } + { + const str = try t.screens.active.dumpStringAlloc(alloc, .{ .screen = .{} }); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1\n2\n3\n\nX", str); + } + for (0..t.cols) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 2, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: cursorUp basic" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(3, 1); + try t.print('A'); + t.cursorUp(10); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X\n\nA", str); + } +} + +test "Terminal: cursorUp below top scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(2, 4); + t.setCursorPos(3, 1); + try t.print('A'); + t.cursorUp(5); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n X\nA", str); + } +} + +test "Terminal: cursorUp above top scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(3, 5); + t.setCursorPos(3, 1); + try t.print('A'); + t.setCursorPos(2, 1); + t.cursorUp(10); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X\n\nA", str); + } +} + +test "Terminal: cursorUp resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorUp(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX", str); + } +} + +test "Terminal: cursorLeft no wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.cursorLeft(10); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nB", str); + } +} + +test "Terminal: cursorLeft unsets pending wrap state" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorLeft(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCXE", str); + } +} + +test "Terminal: cursorLeft unsets pending wrap state with longer jump" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorLeft(3); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AXCDE", str); + } +} + +test "Terminal: cursorLeft reverse wrap with pending wrap state" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap, true); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorLeft(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX", str); + } +} + +test "Terminal: cursorLeft reverse wrap extended with pending wrap state" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap_extended, true); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorLeft(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX", str); + } +} + +test "Terminal: cursorLeft reverse wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap, true); + + for ("ABCDE1") |c| try t.print(c); + t.cursorLeft(2); + try t.print('X'); + try testing.expect(t.screens.active.cursor.pending_wrap); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX\n1", str); + } +} + +test "Terminal: cursorLeft reverse wrap with no soft wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap, true); + + for ("ABCDE") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + try t.print('1'); + t.cursorLeft(2); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDE\nX", str); + } +} + +test "Terminal: cursorLeft reverse wrap before left margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap, true); + t.setTopAndBottomMargin(3, 0); + t.cursorLeft(1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n\nX", str); + } +} + +test "Terminal: cursorLeft extended reverse wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap_extended, true); + + for ("ABCDE") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + try t.print('1'); + t.cursorLeft(2); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX\n1", str); + } +} + +test "Terminal: cursorLeft extended reverse wrap bottom wraparound" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap_extended, true); + + for ("ABCDE") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + try t.print('1'); + t.cursorLeft(1 + t.cols + 1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDE\n1\n X", str); + } +} + +test "Terminal: cursorLeft extended reverse wrap is priority if both set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap, true); + t.modes.set(.reverse_wrap_extended, true); + + for ("ABCDE") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + try t.print('1'); + t.cursorLeft(1 + t.cols + 1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDE\n1\n X", str); + } +} + +test "Terminal: cursorLeft extended reverse wrap above top scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap_extended, true); + + t.setTopAndBottomMargin(3, 0); + t.setCursorPos(2, 1); + t.cursorLeft(1000); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); +} + +test "Terminal: cursorLeft reverse wrap on first row" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + t.modes.set(.reverse_wrap, true); + + t.setTopAndBottomMargin(3, 0); + t.setCursorPos(1, 2); + t.cursorLeft(1000); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); +} + +test "Terminal: cursorDown basic" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.cursorDown(10); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n\n\n\n X", str); + } +} + +test "Terminal: cursorDown above bottom scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + try t.print('A'); + t.cursorDown(10); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n\n X", str); + } +} + +test "Terminal: cursorDown below bottom scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setTopAndBottomMargin(1, 3); + try t.print('A'); + t.setCursorPos(4, 1); + t.cursorDown(10); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n\n\n\nX", str); + } +} + +test "Terminal: cursorDown resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorDown(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDE\n X", str); + } +} + +test "Terminal: cursorRight resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.cursorRight(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX", str); + } +} + +test "Terminal: cursorRight to the edge of screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.cursorRight(100); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } +} + +test "Terminal: cursorRight left of right margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.scrolling_region.right = 2; + t.cursorRight(100); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } +} + +test "Terminal: cursorRight right of right margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.scrolling_region.right = 2; + t.setCursorPos(1, 4); + t.cursorRight(100); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } +} + +test "Terminal: deleteLines simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + + t.clearDirty(); + t.deleteLines(1); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nGHI", str); + } +} + +test "Terminal: deleteLines colors with bg color" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("ABC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI"); + t.setCursorPos(2, 2); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nGHI", str); + } + + for (0..t.cols) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 4, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: deleteLines across page boundary marks all shifted rows dirty" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 10, .max_scrollback = 1024 }); + defer t.deinit(alloc); + + const first_page = t.screens.active.pages.pages.first.?; + const first_page_nrows = first_page.data.capacity.rows; + + // Fill up the first page minus 3 rows + for (0..first_page_nrows - 3) |_| try t.linefeed(); + + // Add content that will cross a page boundary + try t.printString("1AAAA"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("2BBBB"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("3CCCC"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("4DDDD"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("5EEEE"); + + // Verify we now have a second page + try testing.expect(first_page.next != null); + + t.setCursorPos(1, 1); + t.clearDirty(); + t.deleteLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 4 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("2BBBB\n3CCCC\n4DDDD\n5EEEE", str); + } +} + +test "Terminal: deleteLines (legacy)" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 80, .rows = 80 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + + t.cursorUp(2); + t.deleteLines(1); + + try t.print('E'); + t.carriageReturn(); + try t.linefeed(); + + // We should be + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.y); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nE\nD", str); + } +} + +test "Terminal: deleteLines with scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 80, .rows = 80 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.deleteLines(1); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + try t.print('E'); + t.carriageReturn(); + try t.linefeed(); + + // We should be + // try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + // try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.y); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("E\nC\n\nD", str); + } +} + +test "Terminal: deleteLines with scroll region, large count" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 80, .rows = 80 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.deleteLines(5); + + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 3 } })); + + try t.print('E'); + t.carriageReturn(); + try t.linefeed(); + + // We should be + // try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + // try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.y); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("E\n\n\nD", str); + } +} + +test "Terminal: deleteLines with scroll region, cursor outside of region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 80, .rows = 80 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + t.carriageReturn(); + try t.linefeed(); + try t.print('C'); + t.carriageReturn(); + try t.linefeed(); + try t.print('D'); + + t.setTopAndBottomMargin(1, 3); + t.setCursorPos(4, 1); + + t.clearDirty(); + t.deleteLines(1); + + for (0..4) |y| try testing.expect(!t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\nB\nC\nD", str); + } +} + +test "Terminal: deleteLines resets pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.deleteLines(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('B'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("B", str); + } +} + +test "Terminal: deleteLines resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + + try t.print('1'); + t.carriageReturn(); + try t.linefeed(); + for ("ABCDEF") |c| try t.print(c); + + t.setTopAndBottomMargin(1, 2); + t.setCursorPos(1, 1); + t.deleteLines(1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("XBC\n\nDEF", str); + } + + for (0..t.rows) |y| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } }).?; + const row = list_cell.row; + try testing.expect(!row.wrap); + } +} + +test "Terminal: deleteLines left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + + t.clearDirty(); + t.deleteLines(1); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + for (1..3) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC123\nDHI756\nG 89", str); + } +} + +test "Terminal: deleteLines left/right scroll region from top" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(1, 2); + + t.clearDirty(); + t.deleteLines(1); + + for (0..3) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AEF423\nDHI756\nG 89", str); + } +} + +test "Terminal: deleteLines left/right scroll region high count" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DEF456"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GHI789"); + t.scrolling_region.left = 1; + t.scrolling_region.right = 3; + t.setCursorPos(2, 2); + + t.clearDirty(); + t.deleteLines(100); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + for (1..3) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC123\nD 56\nG 89", str); + } +} + +test "Terminal: deleteLines wide character spacer head" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + // +-----+ + // |AAAAA| < Wrapped + // |BBBB*| < Wrapped (continued) + // |WWCCC| < Non-wrapped (continued) + // +-----+ + // where * represents a spacer head cell + // and WW is the wide character. + try t.printString("AAAAABBBB\u{1F600}CCC"); + + // Delete the top line + // +-----+ + // |BBBB | < Non-wrapped + // |WWCCC| < Non-wrapped + // | | < Non-wrapped + // +-----+ + // This should convert the spacer head to + // a regular empty cell, and un-set wrap. + t.setCursorPos(1, 1); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + const unwrapped_str = try t.plainStringUnwrapped(testing.allocator); + defer testing.allocator.free(unwrapped_str); + try testing.expectEqualStrings("BBBB\n\u{1F600}CCC", str); + try testing.expectEqualStrings("BBBB\n\u{1F600}CCC", unwrapped_str); + } +} + +test "Terminal: deleteLines wide character spacer head left scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + // +-----+ + // |AAAAA| < Wrapped + // |BBBB*| < Wrapped (continued) + // |WWCCC| < Non-wrapped (continued) + // +-----+ + // where * represents a spacer head cell + // and WW is the wide character. + try t.printString("AAAAABBBB\u{1F600}CCC"); + + t.scrolling_region.left = 2; + + // Delete the top line + // ### <- scrolling region + // +-----+ + // |AABB | < Wrapped + // |BBCCC| < Wrapped (continued) + // |WW | < Non-wrapped (continued) + // +-----+ + // This should convert the spacer head to + // a regular empty cell, but due to the + // left scrolling margin, wrap state should + // remain. + t.setCursorPos(1, 3); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + const unwrapped_str = try t.plainStringUnwrapped(testing.allocator); + defer testing.allocator.free(unwrapped_str); + try testing.expectEqualStrings("AABB\nBBCCC\n\u{1F600}", str); + try testing.expectEqualStrings("AABB BBCCC\u{1F600}", unwrapped_str); + } +} + +test "Terminal: deleteLines wide character spacer head right scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + // +-----+ + // |AAAAA| < Wrapped + // |BBBB*| < Wrapped (continued) + // |WWCCC| < Non-wrapped (continued) + // +-----+ + // where * represents a spacer head cell + // and WW is the wide character. + try t.printString("AAAAABBBB\u{1F600}CCC"); + + t.scrolling_region.right = 3; + + // Delete the top line + // #### <- scrolling region + // +-----+ + // |BBBBA| < Wrapped + // |WWCC | < Wrapped (continued) + // | C| < Non-wrapped (continued) + // +-----+ + // This should convert the spacer head to + // a regular empty cell, but due to the + // right scrolling margin, wrap state should + // remain. + t.setCursorPos(1, 1); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + const unwrapped_str = try t.plainStringUnwrapped(testing.allocator); + defer testing.allocator.free(unwrapped_str); + try testing.expectEqualStrings("BBBBA\n\u{1F600}CC\n C", str); + try testing.expectEqualStrings("BBBBA\u{1F600}CC C", unwrapped_str); + } +} + +test "Terminal: deleteLines wide character spacer head left and right scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + // +-----+ + // |AAAAA| < Wrapped + // |BBBB*| < Wrapped (continued) + // |WWCCC| < Non-wrapped (continued) + // +-----+ + // where * represents a spacer head cell + // and WW is the wide character. + try t.printString("AAAAABBBB\u{1F600}CCC"); + + t.scrolling_region.right = 3; + t.scrolling_region.left = 2; + + // Delete the top line + // ## <- scrolling region + // +-----+ + // |AABBA| < Wrapped + // |BBCC*| < Wrapped (continued) + // |WW C| < Non-wrapped (continued) + // +-----+ + // Because there is both a left scrolling + // margin > 1 and a right scrolling margin + // the spacer head should remain, and the + // wrap state should be untouched. + t.setCursorPos(1, 3); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + const unwrapped_str = try t.plainStringUnwrapped(testing.allocator); + defer testing.allocator.free(unwrapped_str); + try testing.expectEqualStrings("AABBA\nBBCC\n\u{1F600} C", str); + try testing.expectEqualStrings("AABBABBCC\u{1F600} C", unwrapped_str); + } +} + +test "Terminal: deleteLines wide character spacer head left (< 2) and right scroll margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + // +-----+ + // |AAAAA| < Wrapped + // |BBBB*| < Wrapped (continued) + // |WWCCC| < Non-wrapped (continued) + // +-----+ + // where * represents a spacer head cell + // and WW is the wide character. + try t.printString("AAAAABBBB\u{1F600}CCC"); + + t.scrolling_region.right = 3; + t.scrolling_region.left = 1; + + // Delete the top line + // ### <- scrolling region + // +-----+ + // |ABBBA| < Wrapped + // |B CC | < Wrapped (continued) + // | C| < Non-wrapped (continued) + // +-----+ + // Because the left margin is 1, the wide + // char is split, and therefore removed, + // along with the spacer head - however, + // wrap state should be untouched. + t.setCursorPos(1, 2); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + const unwrapped_str = try t.plainStringUnwrapped(testing.allocator); + defer testing.allocator.free(unwrapped_str); + try testing.expectEqualStrings("ABBBA\nB CC\n C", str); + try testing.expectEqualStrings("ABBBAB CC C", unwrapped_str); + } +} + +test "Terminal: deleteLines wide characters split by left/right scroll region boundaries" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + // Initial value + // +-----+ + // |AAAAA| + // |WWBWW| + // +-----+ + // where WW represents a wide character + try t.printString("AAAAA\n\u{1F600}B\u{1F600}"); + + t.scrolling_region.right = 3; + t.scrolling_region.left = 1; + + // Delete the top line + // ### <- scrolling region + // +-----+ + // |A B A| + // | | + // +-----+ + // The two wide chars, because they're + // split by the edge of the scrolling + // region, get removed. + t.setCursorPos(1, 2); + t.deleteLines(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A B A", str); + } +} + +test "Terminal: deleteLines zero" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 5 }); + defer t.deinit(alloc); + + // This should do nothing + t.setCursorPos(1, 1); + t.deleteLines(0); +} + +test "Terminal: default style is empty" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'A'), cell.content.codepoint); + try testing.expectEqual(@as(style.Id, 0), cell.style_id); + } +} + +test "Terminal: bold style" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .bold = {} }); + try t.print('A'); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'A'), cell.content.codepoint); + try testing.expect(cell.style_id != 0); + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expect(page.styles.refCount(page.memory, t.screens.active.cursor.style_id) > 1); + } +} + +test "Terminal: garbage collect overwritten" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .bold = {} }); + try t.print('A'); + t.setCursorPos(1, 1); + try t.setAttribute(.{ .unset = {} }); + try t.print('B'); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'B'), cell.content.codepoint); + try testing.expect(cell.style_id == 0); + } + + // verify we have no styles in our style map + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 0), page.styles.count()); +} + +test "Terminal: do not garbage collect old styles in use" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .bold = {} }); + try t.print('A'); + try t.setAttribute(.{ .unset = {} }); + try t.print('B'); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 'B'), cell.content.codepoint); + try testing.expect(cell.style_id == 0); + } + + // verify we have no styles in our style map + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); +} + +test "Terminal: print with style marks the row as styled" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .bold = {} }); + try t.print('A'); + try t.setAttribute(.{ .unset = {} }); + try t.print('B'); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.row.styled); + } +} + +test "Terminal: DECALN" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 2 }); + defer t.deinit(alloc); + + // Initial value + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + try t.print('B'); + try t.decaln(); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + + for (0..t.rows) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("EE\nEE", str); + } +} + +test "Terminal: decaln reset margins" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + t.modes.set(.origin, true); + t.setTopAndBottomMargin(2, 3); + try t.decaln(); + t.scrollDown(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nEEE\nEEE", str); + } +} + +test "Terminal: decaln preserves color" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + // Initial value + try t.setAttribute(.{ .direct_color_bg = .{ .r = 0xFF, .g = 0, .b = 0 } }); + t.modes.set(.origin, true); + t.setTopAndBottomMargin(2, 3); + try t.decaln(); + t.scrollDown(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\nEEE\nEEE", str); + } + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: DECALN resets graphemes with protected mode" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + // Add protected mode. A previous version of DECALN accidentally preserved + // protected mode which left dangling managed memory. + t.setProtectedMode(.iso); + + // This is: 👨‍👩‍👧 (which may or may not render correctly) + t.modes.set(.grapheme_cluster, true); + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + try t.decaln(); + + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expect(t.screens.active.cursor.protected); + try testing.expect(t.screens.active.protected_mode == .iso); + + for (0..t.rows) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("EEE\nEEE\nEEE", str); + } +} + +test "Terminal: insertBlanks zero" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + try t.print('A'); + try t.print('B'); + try t.print('C'); + t.setCursorPos(1, 1); + + t.insertBlanks(0); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC", str); + } +} + +test "Terminal: insertBlanks" { + // NOTE: this is not verified with conformance tests, so these + // tests might actually be verifying wrong behavior. + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + try t.print('A'); + try t.print('B'); + try t.print('C'); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.insertBlanks(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" ABC", str); + } +} + +test "Terminal: insertBlanks pushes off end" { + // NOTE: this is not verified with conformance tests, so these + // tests might actually be verifying wrong behavior. + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 2 }); + defer t.deinit(alloc); + + try t.print('A'); + try t.print('B'); + try t.print('C'); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.insertBlanks(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" A", str); + } +} + +test "Terminal: insertBlanks more than size" { + // NOTE: this is not verified with conformance tests, so these + // tests might actually be verifying wrong behavior. + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 2 }); + defer t.deinit(alloc); + + try t.print('A'); + try t.print('B'); + try t.print('C'); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.insertBlanks(5); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +test "Terminal: insertBlanks no scroll region, fits" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + + t.clearDirty(); + t.insertBlanks(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" ABC", str); + } +} + +test "Terminal: insertBlanks preserves background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.insertBlanks(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" ABC", str); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: insertBlanks shift off screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 10 }); + defer t.deinit(alloc); + + for (" ABC") |c| try t.print(c); + t.setCursorPos(1, 3); + t.clearDirty(); + t.insertBlanks(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X A", str); + } +} + +test "Terminal: insertBlanks split multi-cell character" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 10 }); + defer t.deinit(alloc); + + for ("123") |c| try t.print(c); + try t.print('橋'); + t.setCursorPos(1, 1); + t.clearDirty(); + t.insertBlanks(1); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" 123", str); + } +} + +test "Terminal: insertBlanks inside left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + t.scrolling_region.left = 2; + t.scrolling_region.right = 4; + t.setCursorPos(1, 3); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 3); + + t.clearDirty(); + t.insertBlanks(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X A", str); + } +} + +test "Terminal: insertBlanks outside left/right scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 6, .rows = 10 }); + defer t.deinit(alloc); + + t.setCursorPos(1, 4); + for ("ABC") |c| try t.print(c); + t.scrolling_region.left = 2; + t.scrolling_region.right = 4; + try testing.expect(t.screens.active.cursor.pending_wrap); + t.clearDirty(); + t.insertBlanks(2); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" ABX", str); + } +} + +test "Terminal: insertBlanks left/right scroll region large count" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + t.modes.set(.origin, true); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setCursorPos(1, 1); + t.clearDirty(); + t.insertBlanks(140); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } +} + +test "Terminal: insertBlanks deleting graphemes" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Disable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.printString("ABC"); + + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + // We should have one cell with graphemes + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.graphemeCount()); + + t.setCursorPos(1, 1); + t.clearDirty(); + t.insertBlanks(4); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" A", str); + } + + // We should have no graphemes + try testing.expectEqual(@as(usize, 0), page.graphemeCount()); +} + +test "Terminal: insertBlanks shift graphemes" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Enable grapheme clustering + t.modes.set(.grapheme_cluster, true); + + try t.printString("A"); + + // This is: 👨‍👩‍👧 (which may or may not render correctly) + try t.print(0x1F468); + try t.print(0x200D); + try t.print(0x1F469); + try t.print(0x200D); + try t.print(0x1F467); + + // We should have one cell with graphemes + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.graphemeCount()); + + t.setCursorPos(1, 1); + t.clearDirty(); + t.insertBlanks(1); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" A👨‍👩‍👧", str); + } + + // We should have no graphemes + try testing.expectEqual(@as(usize, 1), page.graphemeCount()); +} + +test "Terminal: insertBlanks split multi-cell character from tail" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("橋123"); + t.setCursorPos(1, 2); + t.insertBlanks(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" 12", str); + } +} + +test "Terminal: insertBlanks shifts hyperlinks" { + // osc "8;;http://example.com" + // printf "link" + // printf "\r" + // csi "3@" + // echo + // + // link should be preserved, blanks should not be linked + + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("ABC"); + t.setCursorPos(1, 1); + t.insertBlanks(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" ABC", str); + } + + // Verify all our cells have a hyperlink + for (2..5) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(row.hyperlink); + const cell = list_cell.cell; + try testing.expect(cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell).?; + try testing.expectEqual(@as(hyperlink.Id, 1), id); + } + for (0..2) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: insertBlanks pushes hyperlink off end completely" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 2 }); + defer t.deinit(alloc); + + try t.screens.active.startHyperlink("http://example.com", null); + try t.printString("ABC"); + t.setCursorPos(1, 1); + t.insertBlanks(3); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + for (0..3) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ + .x = @intCast(x), + .y = 0, + } }).?; + const row = list_cell.row; + try testing.expect(!row.hyperlink); + const cell = list_cell.cell; + try testing.expect(!cell.hyperlink); + const id = list_cell.node.data.lookupHyperlink(cell); + try testing.expect(id == null); + } +} + +test "Terminal: insertBlanks wide char straddling right margin" { + // Crash found by AFL++ fuzzer. + // + // When a wide character straddles the right scroll margin (head at the + // margin, spacer_tail just beyond it), insertBlanks shifts the wide head + // away via swapCells but leaves the orphaned spacer_tail in place, + // causing a page integrity violation. + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Fill row: A B C D 橋 _ _ _ _ _ + // Positions: 0 1 2 3 4W 5T 6 7 8 9 + t.setCursorPos(1, 1); + for ("ABCD") |c| try t.print(c); + try t.print('橋'); // wide char: head at 4, spacer_tail at 5 + + // Set right margin so the wide head is AT the boundary and the + // spacer_tail is just outside it. + t.scrolling_region.right = 4; + + // Position cursor at x=2 (1-indexed col 3) and insert one blank. + // This triggers the swap loop which displaces the wide head at + // position 4 without clearing the spacer_tail at position 5. + t.setCursorPos(1, 3); + t.insertBlanks(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AB CD", str); + } +} + +test "Terminal: insertBlanks wide char spacer_tail orphaned beyond right margin" { + // Regression test for AFL++ crash. + // + // When insertBlanks clears the entire region from cursor to the right + // margin (scroll_amount == 0), a wide character whose head is AT the + // right margin gets cleared but its spacer_tail just beyond the margin + // is left behind, causing a page integrity violation: + // "spacer tail not following wide" + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Fill cols 0–9 with wide chars: 中中中中中 + // Positions: 0W 1T 2W 3T 4W 5T 6W 7T 8W 9T + for (0..5) |_| try t.print(0x4E2D); + + // Set left/right margins so that the last wide char (cols 8–9) + // straddles the boundary: head at col 8 (inside), tail at col 9 (outside). + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(1, 9); // 1-indexed: left=0, right=8 + + // Cursor is now at (0, 0) after DECSLRM. Print a narrow char to + // advance cursor to col 1. + try t.print('a'); + + // ICH 8: insert 8 blanks at cursor x=1. + // rem = right(8) - x(1) + 1 = 8, adjusted_count = 8, scroll_amount = 0. + // The code clears cols 1–8 without noticing the spacer_tail at col 9. + t.insertBlanks(8); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("a", str); + } +} + +test "Terminal: insert mode with space" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + for ("hello") |c| try t.print(c); + t.setCursorPos(1, 2); + t.modes.set(.insert, true); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hXello", str); + } +} + +test "Terminal: insert mode doesn't wrap pushed characters" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + for ("hello") |c| try t.print(c); + t.setCursorPos(1, 2); + t.modes.set(.insert, true); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hXell", str); + } +} + +test "Terminal: insert mode does nothing at the end of the line" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + for ("hello") |c| try t.print(c); + t.modes.set(.insert, true); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hello\nX", str); + } +} + +test "Terminal: insert mode with wide characters" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + for ("hello") |c| try t.print(c); + t.setCursorPos(1, 2); + t.modes.set(.insert, true); + try t.print('😀'); // 0x1F600 + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("h😀el", str); + } +} + +test "Terminal: insert mode with wide characters at end" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + for ("well") |c| try t.print(c); + t.modes.set(.insert, true); + try t.print('😀'); // 0x1F600 + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("well\n😀", str); + } +} + +test "Terminal: insert mode pushing off wide character" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 2 }); + defer t.deinit(alloc); + + for ("123") |c| try t.print(c); + try t.print('😀'); // 0x1F600 + t.modes.set(.insert, true); + t.setCursorPos(1, 1); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X123", str); + } +} + +test "Terminal: deleteChars" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.deleteChars(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ADE", str); + } +} + +test "Terminal: deleteChars zero count" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.deleteChars(0); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDE", str); + } +} + +test "Terminal: deleteChars more than half" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.deleteChars(3); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AE", str); + } +} + +test "Terminal: deleteChars more than line width" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.deleteChars(10); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A", str); + } +} + +test "Terminal: deleteChars should shift left" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + + t.clearDirty(); + t.deleteChars(1); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ACDE", str); + } +} + +test "Terminal: deleteChars resets pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.deleteChars(1); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDX", str); + } +} + +test "Terminal: deleteChars resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE123") |c| try t.print(c); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + const row = list_cell.row; + try testing.expect(row.wrap); + } + t.setCursorPos(1, 1); + t.deleteChars(1); + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + const row = list_cell.row; + try testing.expect(!row.wrap); + } + + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("XCDE\n123", str); + } +} + +test "Terminal: deleteChars simple operation" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.setCursorPos(1, 3); + + t.clearDirty(); + t.deleteChars(2); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AB23", str); + } +} + +test "Terminal: deleteChars preserves background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + for ("ABC123") |c| try t.print(c); + t.setCursorPos(1, 3); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.deleteChars(2); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AB23", str); + } + for (t.cols - 2..t.cols) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 0, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: deleteChars outside scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 6, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.scrolling_region.left = 2; + t.scrolling_region.right = 4; + try testing.expect(t.screens.active.cursor.pending_wrap); + t.clearDirty(); + t.deleteChars(2); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.screens.active.cursor.pending_wrap); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC123", str); + } +} + +test "Terminal: deleteChars inside scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 6, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("ABC123"); + t.scrolling_region.left = 2; + t.scrolling_region.right = 4; + t.setCursorPos(1, 4); + + t.clearDirty(); + t.deleteChars(1); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC2 3", str); + } +} + +test "Terminal: deleteChars split wide character from spacer tail" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 6, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("A橋123"); + t.setCursorPos(1, 3); + t.deleteChars(1); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A 123", str); + } +} + +test "Terminal: deleteChars split wide character from wide" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 6, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("橋123"); + t.setCursorPos(1, 1); + t.deleteChars(1); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, '1'), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: deleteChars split wide character from end" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 6, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("A橋123"); + t.setCursorPos(1, 1); + t.deleteChars(1); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 0, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0x6A4B), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.wide, cell.wide); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 1, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.spacer_tail, cell.wide); + } +} + +test "Terminal: deleteChars with a spacer head at the end" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 5, .rows = 10 }); + defer t.deinit(alloc); + + try t.printString("0123橋123"); + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 4, .y = 0 } }).?; + const row = list_cell.row; + const cell = list_cell.cell; + try testing.expectEqual(Cell.Wide.spacer_head, cell.wide); + try testing.expect(row.wrap); + } + + t.setCursorPos(1, 1); + t.deleteChars(1); + + { + const list_cell = t.screens.active.pages.getCell(.{ .screen = .{ .x = 3, .y = 0 } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u21, 0), cell.content.codepoint); + try testing.expectEqual(Cell.Wide.narrow, cell.wide); + } +} + +test "Terminal: deleteChars split wide character tail" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(1, t.cols - 1); + try t.print(0x6A4B); // 橋 + t.carriageReturn(); + t.deleteChars(t.cols - 1); + try t.print('0'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("0", str); + } +} + +test "Terminal: deleteChars wide char boundary conditions" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 1, .cols = 8 }); + defer t.deinit(alloc); + + // EXPLANATION(qwerasd): + // + // There are 3 or 4 boundaries to be concerned with in deleteChars, + // depending on how you count them. Consider the following terminal: + // + // +--------+ + // 0 |.ABCDEF.| + // : ^ : (^ = cursor) + // +--------+ + // + // if we DCH 3 we get + // + // +--------+ + // 0 |.DEF....| + // +--------+ + // + // The boundaries exist at the following points then: + // + // +--------+ + // 0 |.ABCDEF.| + // :11 22 33: + // +--------+ + // + // I'm counting 2 for double since it's both the end of the deleted + // content and the start of the content that is shifted in to place. + // + // Now consider wide characters (represented as `WW`) at these boundaries: + // + // +--------+ + // 0 |WWaWWbWW| + // : ^ : (^ = cursor) + // : ^^^ : (^ = deleted by DCH 3) + // +--------+ + // + // -> DCH 3 + // -> The first 2 wide characters are split & destroyed (verified in xterm) + // + // +--------+ + // 0 |..bWW...| + // +--------+ + + try t.printString("😀a😀b😀"); + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings("😀a😀b😀", str); + } + + t.setCursorPos(1, 2); + t.deleteChars(3); + t.screens.active.cursor.page_pin.node.data.assertIntegrity(); + + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" b😀", str); + } +} + +test "Terminal: deleteChars wide char wrap boundary conditions" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 3, .cols = 8 }); + defer t.deinit(alloc); + + // EXPLANATION(qwerasd): + // (cont. from "Terminal: deleteChars wide char boundary conditions") + // + // Additionally consider soft-wrapped wide chars (`H` = spacer head): + // + // +--------+ + // 0 |.......H… + // 1 …WWabcdeH… + // : ^ : (^ = cursor) + // : ^^^ : (^ = deleted by DCH 3) + // 2 …WW......| + // +--------+ + // + // -> DCH 3 + // -> First wide character split and destroyed, including spacer head, + // second spacer head removed (verified in xterm). + // -> Wrap state of row reset + // + // +--------+ + // 0 |........| + // 1 |.cde....| + // 2 |WW......| + // +--------+ + // + + try t.printString(".......😀abcde😀......"); + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings(".......\n😀abcde\n😀......", str); + + const unwrapped = try t.plainStringUnwrapped(alloc); + defer testing.allocator.free(unwrapped); + try testing.expectEqualStrings(".......😀abcde😀......", unwrapped); + } + + t.setCursorPos(2, 2); + t.deleteChars(3); + t.screens.active.cursor.page_pin.node.data.assertIntegrity(); + + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings(".......\n cde\n😀......", str); + + const unwrapped = try t.plainStringUnwrapped(alloc); + defer testing.allocator.free(unwrapped); + try testing.expectEqualStrings("....... cde\n😀......", unwrapped); + } +} + +test "Terminal: deleteChars wide char across right margin" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 3, .cols = 8 }); + defer t.deinit(alloc); + + // scroll region + // VVVVVV + // +-######-+ + // |.abcdeWW| + // : ^ : (^ = cursor) + // +--------+ + // + // DCH 1 + + try t.printString("123456橋"); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(2, 7); + + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings("123456橋", str); + } + + t.setCursorPos(1, 2); + t.deleteChars(1); + t.screens.active.cursor.page_pin.node.data.assertIntegrity(); + + // NOTE: This behavior is slightly inconsistent with xterm. xterm + // _visually_ splits the wide character (half the wide character shows + // up in col 6 and half in col 8). In all other wide char split scenarios, + // xterm clears the cell. Therefore, we've chosen to clear the cell here. + // Given we have space, we also could actually preserve it, but I haven't + // yet found a terminal that behaves that way. We should be open to + // revisiting this behavior but for now we're going with the simpler + // impl. + { + const str = try t.plainString(alloc); + defer testing.allocator.free(str); + try testing.expectEqualStrings("13456", str); + } +} + +test "Terminal: saveCursor" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .bold = {} }); + t.screens.active.charset.gr = .G3; + t.modes.set(.origin, true); + t.saveCursor(); + t.screens.active.charset.gr = .G0; + try t.setAttribute(.{ .unset = {} }); + t.modes.set(.origin, false); + t.restoreCursor(); + try testing.expect(t.screens.active.cursor.style.flags.bold); + try testing.expect(t.screens.active.charset.gr == .G3); + try testing.expect(t.modes.get(.origin)); +} + +test "Terminal: saveCursor position" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(1, 5); + try t.print('A'); + t.saveCursor(); + t.setCursorPos(1, 1); + try t.print('B'); + t.restoreCursor(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("B AX", str); + } +} + +test "Terminal: saveCursor pending wrap state" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(1, 5); + try t.print('A'); + t.saveCursor(); + t.setCursorPos(1, 1); + try t.print('B'); + t.restoreCursor(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("B A\nX", str); + } +} + +test "Terminal: saveCursor origin mode" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + t.modes.set(.origin, true); + t.saveCursor(); + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(3, 5); + t.setTopAndBottomMargin(2, 4); + t.restoreCursor(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X", str); + } +} + +test "Terminal: saveCursor resize" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + t.setCursorPos(1, 10); + t.saveCursor(); + try t.resize(alloc, 5, 5); + t.restoreCursor(); + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } +} + +test "Terminal: saveCursor protected pen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + try testing.expect(t.screens.active.cursor.protected); + t.setCursorPos(1, 10); + t.saveCursor(); + t.setProtectedMode(.off); + try testing.expect(!t.screens.active.cursor.protected); + t.restoreCursor(); + try testing.expect(t.screens.active.cursor.protected); +} + +test "Terminal: saveCursor doesn't modify hyperlink state" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + try t.screens.active.startHyperlink("http://example.com", null); + const id = t.screens.active.cursor.hyperlink_id; + t.saveCursor(); + try testing.expectEqual(id, t.screens.active.cursor.hyperlink_id); + t.restoreCursor(); + try testing.expectEqual(id, t.screens.active.cursor.hyperlink_id); +} + +test "Terminal: restoreCursor uses default style on OutOfSpace" { + // Tests that restoreCursor falls back to default style when + // manualStyleUpdate fails with OutOfSpace (can't split a 1-row page + // and styles are at max capacity). + const alloc = testing.allocator; + + // Use a single row so the page can't be split + var t = try init(alloc, .{ .cols = 10, .rows = 1 }); + defer t.deinit(alloc); + + // Set a style and save the cursor + try t.setAttribute(.{ .bold = {} }); + t.saveCursor(); + + // Clear the style + try t.setAttribute(.{ .unset = {} }); + try testing.expect(!t.screens.active.cursor.style.flags.bold); + + // Fill the style map to max capacity + const max_styles = std.math.maxInt(size.CellCountInt); + while (t.screens.active.cursor.page_pin.node.data.capacity.styles < max_styles) { + _ = t.screens.active.increaseCapacity( + t.screens.active.cursor.page_pin.node, + .styles, + ) catch break; + } + + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(max_styles, page.capacity.styles); + + // Fill all style slots using the StyleSet's layout capacity which accounts + // for the load factor. The capacity in the layout is the actual max number + // of items that can be stored. + { + page.pauseIntegrityChecks(true); + defer page.pauseIntegrityChecks(false); + defer page.assertIntegrity(); + + const max_items = page.styles.layout.cap; + var n: usize = 1; + while (n < max_items) : (n += 1) { + _ = page.styles.add( + page.memory, + .{ .bg_color = .{ .rgb = @bitCast(@as(u24, @intCast(n))) } }, + ) catch break; + } + } + + // Restore cursor - should fall back to default style since page + // can't be split (1 row) and styles are at max capacity + t.restoreCursor(); + + // The style should be reset to default because OutOfSpace occurred + try testing.expect(!t.screens.active.cursor.style.flags.bold); + try testing.expectEqual(style.default_id, t.screens.active.cursor.style_id); +} + +test "Terminal: setProtectedMode" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + try testing.expect(!t.screens.active.cursor.protected); + t.setProtectedMode(.off); + try testing.expect(!t.screens.active.cursor.protected); + t.setProtectedMode(.iso); + try testing.expect(t.screens.active.cursor.protected); + t.setProtectedMode(.dec); + try testing.expect(t.screens.active.cursor.protected); + t.setProtectedMode(.off); + try testing.expect(!t.screens.active.cursor.protected); +} + +test "Terminal: eraseLine simple erase right" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 3); + t.clearDirty(); + t.eraseLine(.right, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AB", str); + } +} + +test "Terminal: eraseLine resets pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.eraseLine(.right, false); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('B'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABCDB", str); + } +} + +test "Terminal: eraseLine resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE123") |c| try t.print(c); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.row.wrap); + } + + t.setCursorPos(1, 1); + t.eraseLine(.right, false); + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(!list_cell.row.wrap); + } + try t.print('X'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("X\n123", str); + } +} + +test "Terminal: eraseLine right preserves background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.eraseLine(.right, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A", str); + for (1..5) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 0, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: eraseLine right wide character" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + for ("AB") |c| try t.print(c); + try t.print('橋'); + for ("DE") |c| try t.print(c); + t.setCursorPos(1, 4); + t.clearDirty(); + t.eraseLine(.right, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AB", str); + } +} + +test "Terminal: eraseLine right protected attributes respected with iso" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.clearDirty(); + t.eraseLine(.right, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC", str); + } +} + +test "Terminal: eraseLine right protected attributes ignored with dec most recent" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setProtectedMode(.dec); + t.setProtectedMode(.off); + t.setCursorPos(1, 2); + t.clearDirty(); + t.eraseLine(.right, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A", str); + } +} + +test "Terminal: eraseLine right protected attributes ignored with dec set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 2); + t.clearDirty(); + t.eraseLine(.right, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A", str); + } +} + +test "Terminal: eraseLine right protected requested" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + for ("12345678") |c| try t.print(c); + t.setCursorPos(t.screens.active.cursor.y + 1, 6); + t.setProtectedMode(.dec); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y + 1, 4); + t.clearDirty(); + t.eraseLine(.right, true); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("123 X", str); + } +} + +test "Terminal: eraseLine simple erase left" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 3); + t.clearDirty(); + t.eraseLine(.left, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" DE", str); + } +} + +test "Terminal: eraseLine left resets wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + t.clearDirty(); + t.eraseLine(.left, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(!t.screens.active.cursor.pending_wrap); + try t.print('B'); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" B", str); + } +} + +test "Terminal: eraseLine left preserves background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.eraseLine(.left, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" CDE", str); + for (0..2) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 0, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: eraseLine left wide character" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + for ("AB") |c| try t.print(c); + try t.print('橋'); + for ("DE") |c| try t.print(c); + t.setCursorPos(1, 3); + t.clearDirty(); + t.eraseLine(.left, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" DE", str); + } +} + +test "Terminal: eraseLine left protected attributes respected with iso" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.clearDirty(); + t.eraseLine(.left, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC", str); + } +} + +test "Terminal: eraseLine left protected attributes ignored with dec most recent" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setProtectedMode(.dec); + t.setProtectedMode(.off); + t.setCursorPos(1, 2); + t.clearDirty(); + t.eraseLine(.left, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" C", str); + } +} + +test "Terminal: eraseLine left protected attributes ignored with dec set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 2); + t.clearDirty(); + t.eraseLine(.left, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" C", str); + } +} + +test "Terminal: eraseLine left protected requested" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + for ("123456789") |c| try t.print(c); + t.setCursorPos(t.screens.active.cursor.y + 1, 6); + t.setProtectedMode(.dec); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y + 1, 8); + t.clearDirty(); + t.eraseLine(.left, true); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X 9", str); + } +} + +test "Terminal: eraseLine complete preserves background sgr" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + t.setCursorPos(1, 2); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.eraseLine(.complete, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + for (0..5) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 0, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: eraseLine complete protected attributes respected with iso" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 1); + t.clearDirty(); + t.eraseLine(.complete, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC", str); + } +} + +test "Terminal: eraseLine complete protected attributes ignored with dec most recent" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.setProtectedMode(.dec); + t.setProtectedMode(.off); + t.setCursorPos(1, 2); + t.clearDirty(); + t.eraseLine(.complete, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +test "Terminal: eraseLine complete protected attributes ignored with dec set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.setCursorPos(1, 2); + t.clearDirty(); + t.eraseLine(.complete, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +test "Terminal: eraseLine complete protected requested" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + for ("123456789") |c| try t.print(c); + t.setCursorPos(t.screens.active.cursor.y + 1, 6); + t.setProtectedMode(.dec); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y + 1, 8); + t.clearDirty(); + t.eraseLine(.complete, true); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" X", str); + } +} + +test "Terminal: tabClear single" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 30, .rows = 5 }); + defer t.deinit(alloc); + + t.horizontalTab(); + t.tabClear(.current); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + t.setCursorPos(1, 1); + t.horizontalTab(); + try testing.expectEqual(@as(usize, 16), t.screens.active.cursor.x); +} + +test "Terminal: tabClear all" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 30, .rows = 5 }); + defer t.deinit(alloc); + + t.tabClear(.all); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + t.setCursorPos(1, 1); + t.horizontalTab(); + try testing.expectEqual(@as(usize, 29), t.screens.active.cursor.x); +} + +test "Terminal: printRepeat simple" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("A"); + try t.printRepeat(1); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AA", str); + } +} + +test "Terminal: printRepeat wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString(" A"); + try t.printRepeat(1); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" A\nA", str); + } +} + +test "Terminal: printRepeat no previous character" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printRepeat(1); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +test "Terminal: printAttributes" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + var storage: [64]u8 = undefined; + + { + try t.setAttribute(.{ .direct_color_fg = .{ .r = 1, .g = 2, .b = 3 } }); + defer t.setAttribute(.unset) catch unreachable; + const buf = try t.printAttributes(&storage); + try testing.expectEqualStrings("0;38:2::1:2:3", buf); + } + + { + try t.setAttribute(.bold); + try t.setAttribute(.{ .direct_color_bg = .{ .r = 1, .g = 2, .b = 3 } }); + defer t.setAttribute(.unset) catch unreachable; + const buf = try t.printAttributes(&storage); + try testing.expectEqualStrings("0;1;48:2::1:2:3", buf); + } + + { + try t.setAttribute(.bold); + try t.setAttribute(.faint); + try t.setAttribute(.italic); + try t.setAttribute(.{ .underline = .single }); + try t.setAttribute(.blink); + try t.setAttribute(.inverse); + try t.setAttribute(.invisible); + try t.setAttribute(.strikethrough); + try t.setAttribute(.{ .direct_color_fg = .{ .r = 100, .g = 200, .b = 255 } }); + try t.setAttribute(.{ .direct_color_bg = .{ .r = 101, .g = 102, .b = 103 } }); + defer t.setAttribute(.unset) catch unreachable; + const buf = try t.printAttributes(&storage); + try testing.expectEqualStrings("0;1;2;3;4;5;7;8;9;38:2::100:200:255;48:2::101:102:103", buf); + } + + { + try t.setAttribute(.{ .underline = .single }); + defer t.setAttribute(.unset) catch unreachable; + const buf = try t.printAttributes(&storage); + try testing.expectEqualStrings("0;4", buf); + } + + { + const buf = try t.printAttributes(&storage); + try testing.expectEqualStrings("0", buf); + } +} + +test "Terminal: eraseDisplay simple erase below" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + + t.clearDirty(); + t.eraseDisplay(.below, false); + + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nD", str); + } +} + +test "Terminal: eraseDisplay erase below preserves SGR bg" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.eraseDisplay(.below, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nD", str); + for (1..5) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 1, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: eraseDisplay below split multi-cell" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("AB橋C"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DE橋F"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GH橋I"); + t.setCursorPos(2, 4); + t.eraseDisplay(.below, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AB橋C\nDE", str); + } +} + +test "Terminal: eraseDisplay below protected attributes respected with iso" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + t.eraseDisplay(.below, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\nGHI", str); + } +} + +test "Terminal: eraseDisplay below protected attributes ignored with dec most recent" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setProtectedMode(.dec); + t.setProtectedMode(.off); + t.setCursorPos(2, 2); + t.eraseDisplay(.below, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nD", str); + } +} + +test "Terminal: eraseDisplay below protected attributes ignored with dec set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + t.eraseDisplay(.below, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nD", str); + } +} + +test "Terminal: eraseDisplay below protected attributes respected with force" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + t.eraseDisplay(.below, true); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\nGHI", str); + } +} + +test "Terminal: eraseDisplay simple erase above" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + + t.clearDirty(); + t.eraseDisplay(.above, false); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 0 } })); + try testing.expect(t.isDirty(.{ .active = .{ .x = 0, .y = 1 } })); + try testing.expect(!t.isDirty(.{ .active = .{ .x = 0, .y = 2 } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n F\nGHI", str); + } +} + +test "Terminal: eraseDisplay erase above preserves SGR bg" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.eraseDisplay(.above, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n F\nGHI", str); + for (0..2) |x| { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = @intCast(x), + .y = 1, + } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } + } +} + +test "Terminal: eraseDisplay above split multi-cell" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.printString("AB橋C"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("DE橋F"); + t.carriageReturn(); + try t.linefeed(); + try t.printString("GH橋I"); + t.setCursorPos(2, 3); + t.eraseDisplay(.above, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n F\nGH橋I", str); + } +} + +test "Terminal: eraseDisplay above protected attributes respected with iso" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + t.eraseDisplay(.above, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\nGHI", str); + } +} + +test "Terminal: eraseDisplay above protected attributes ignored with dec most recent" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.iso); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setProtectedMode(.dec); + t.setProtectedMode(.off); + t.setCursorPos(2, 2); + t.eraseDisplay(.above, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n F\nGHI", str); + } +} + +test "Terminal: eraseDisplay above protected attributes ignored with dec set" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + t.eraseDisplay(.above, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n F\nGHI", str); + } +} + +test "Terminal: eraseDisplay above protected attributes respected with force" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.setProtectedMode(.dec); + for ("ABC") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("DEF") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("GHI") |c| try t.print(c); + t.setCursorPos(2, 2); + t.eraseDisplay(.above, true); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("ABC\nDEF\nGHI", str); + } +} + +test "Terminal: eraseDisplay protected complete" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + for ("123456789") |c| try t.print(c); + t.setCursorPos(t.screens.active.cursor.y + 1, 6); + t.setProtectedMode(.dec); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y + 1, 4); + + t.clearDirty(); + t.eraseDisplay(.complete, true); + for (0..t.rows) |y| try testing.expect(t.isDirty(.{ .active = .{ + .x = 0, + .y = @intCast(y), + } })); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n X", str); + } +} + +test "Terminal: eraseDisplay protected below" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + for ("123456789") |c| try t.print(c); + t.setCursorPos(t.screens.active.cursor.y + 1, 6); + t.setProtectedMode(.dec); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y + 1, 4); + t.eraseDisplay(.below, true); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A\n123 X", str); + } +} + +test "Terminal: eraseDisplay scroll complete" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + t.eraseDisplay(.scroll_complete, false); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +test "Terminal: eraseDisplay protected above" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 3 }); + defer t.deinit(alloc); + + try t.print('A'); + t.carriageReturn(); + try t.linefeed(); + for ("123456789") |c| try t.print(c); + t.setCursorPos(t.screens.active.cursor.y + 1, 6); + t.setProtectedMode(.dec); + try t.print('X'); + t.setCursorPos(t.screens.active.cursor.y + 1, 8); + t.eraseDisplay(.above, true); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("\n X 9", str); + } +} + +test "Terminal: eraseDisplay complete preserves cursor" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Set our cursur + try t.setAttribute(.{ .bold = {} }); + try t.printString("AAAA"); + try testing.expect(t.screens.active.cursor.style_id != style.default_id); + + // Erasing the display may detect that our style is no longer in use + // and prune our style, which we don't want because its still our + // active cursor. + t.eraseDisplay(.complete, false); + try testing.expect(t.screens.active.cursor.style_id != style.default_id); +} + +test "Terminal: semantic prompt" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Prompt + try t.semanticPrompt(.init(.fresh_line_new_prompt)); + for ("hello") |c| try t.print(c); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x - 1, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(.prompt, cell.semantic_content); + + const row = list_cell.row; + try testing.expectEqual(.prompt, row.semantic_prompt); + } + + // Start input but end it on EOL + try t.semanticPrompt(.init(.end_prompt_start_input_terminate_eol)); + t.carriageReturn(); + try t.linefeed(); + + // Write some output + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + for ("world") |c| try t.print(c); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x - 1, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(.output, cell.semantic_content); + + const row = list_cell.row; + try testing.expectEqual(.none, row.semantic_prompt); + } +} + +test "Terminal: semantic prompt continuations" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Prompt + try t.semanticPrompt(.init(.fresh_line_new_prompt)); + for ("hello") |c| try t.print(c); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x - 1, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(.prompt, cell.semantic_content); + + const row = list_cell.row; + try testing.expectEqual(.prompt, row.semantic_prompt); + } + + // Start input but end it on EOL + t.carriageReturn(); + try t.linefeed(); + try t.semanticPrompt(.{ + .action = .prompt_start, + .options_unvalidated = "k=c", + }); + + // Write some output + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + for ("world") |c| try t.print(c); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x - 1, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(.prompt, cell.semantic_content); + + const row = list_cell.row; + try testing.expectEqual(.prompt_continuation, row.semantic_prompt); + } +} + +test "Terminal: index in prompt mode marks new row as prompt continuation" { + // This tests the Fish shell workaround: when in prompt mode and we get + // a newline, assume the new row is a prompt continuation (since Fish + // doesn't emit OSC133 k=s markers for continuation lines). + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Start a prompt + try t.semanticPrompt(.init(.prompt_start)); + for ("hello") |c| try t.print(c); + + // Verify first row is marked as prompt + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 0, + } }).?; + try testing.expectEqual(.prompt, list_cell.row.semantic_prompt); + } + + // Now do a linefeed while still in prompt mode + t.carriageReturn(); + try t.linefeed(); + + // The new row should automatically be marked as prompt continuation + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } + + // The cursor semantic content should still be prompt + try testing.expectEqual(.prompt, t.screens.active.cursor.semantic_content); +} + +test "Terminal: index in input mode does not mark new row as prompt" { + // Input mode should NOT trigger prompt continuation on newline + // (only prompt mode does, not input mode) + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Start a prompt then switch to input + try t.semanticPrompt(.init(.prompt_start)); + for ("$ ") |c| try t.print(c); + try t.semanticPrompt(.init(.end_prompt_start_input)); + for ("echo \\") |c| try t.print(c); + + // Linefeed while in input mode + t.carriageReturn(); + try t.linefeed(); + + // The new row should be marked as prompt continuation + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } + + // Our cursor should still be in input + try testing.expectEqual(.input, t.screens.active.cursor.semantic_content); +} + +test "Terminal: index in output mode does not mark new row as prompt" { + // Output mode should NOT trigger prompt continuation + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Complete prompt cycle: prompt -> input -> output + try t.semanticPrompt(.init(.prompt_start)); + for ("$ ") |c| try t.print(c); + try t.semanticPrompt(.init(.end_prompt_start_input)); + for ("ls") |c| try t.print(c); + try t.semanticPrompt(.init(.end_input_start_output)); + + // Linefeed while in output mode + t.carriageReturn(); + try t.linefeed(); + + // The new row should NOT be marked as a prompt + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.none, list_cell.row.semantic_prompt); + } +} + +test "Terminal: OSC133C at x=0 on prompt row clears prompt mark" { + // This tests the second Fish heuristic: when Fish emits a newline + // then immediately sends OSC133C (start output) at column 0, we + // should clear the prompt continuation mark we just set. + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Start a prompt + try t.semanticPrompt(.init(.prompt_start)); + for ("$ echo \\") |c| try t.print(c); + + // Simulate Fish behavior: newline first (which marks next row as prompt) + t.carriageReturn(); + try t.linefeed(); + + // Verify the new row is marked as prompt continuation + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } + + // Now Fish sends OSC133C at column 0 (cursor is still at x=0) + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try t.semanticPrompt(.init(.end_input_start_output)); + + // The prompt continuation should be cleared + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.none, list_cell.row.semantic_prompt); + } +} + +test "Terminal: OSC133C at x>0 on prompt row does not clear prompt mark" { + // If we're not at column 0, we shouldn't clear the prompt mark + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Start a prompt on a row + try t.semanticPrompt(.init(.prompt_start)); + for ("$ ") |c| try t.print(c); + + // Move to a new line and mark it as prompt continuation manually + t.carriageReturn(); + try t.linefeed(); + try t.semanticPrompt(.{ + .action = .prompt_start, + .options_unvalidated = "k=c", + }); + for ("> ") |c| try t.print(c); + + // Verify the row is marked as prompt continuation + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } + + // Now send OSC133C but cursor is NOT at column 0 + try testing.expect(t.screens.active.cursor.x > 0); + try t.semanticPrompt(.init(.end_input_start_output)); + + // The prompt continuation should NOT be cleared (we're not at x=0) + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } +} + +test "Terminal: multiple newlines in prompt mode marks all rows" { + // Multiple newlines should each mark their row as prompt continuation + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Start a prompt + try t.semanticPrompt(.init(.prompt_start)); + for ("line1") |c| try t.print(c); + + // Multiple newlines + t.carriageReturn(); + try t.linefeed(); + for ("line2") |c| try t.print(c); + t.carriageReturn(); + try t.linefeed(); + for ("line3") |c| try t.print(c); + + // First row should be prompt + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 0, + } }).?; + try testing.expectEqual(.prompt, list_cell.row.semantic_prompt); + } + + // Second and third rows should be prompt continuation + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 1, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = 0, + .y = 2, + } }).?; + try testing.expectEqual(.prompt_continuation, list_cell.row.semantic_prompt); + } +} + +test "Terminal: OSC133A click_events=1 sets click to click_events" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // Verify default state is none + try testing.expectEqual(.none, t.screens.active.semantic_prompt.click); + + // OSC 133;A with click_events=1 + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "click_events=1", + }); + + try testing.expectEqual(.click_events, t.screens.active.semantic_prompt.click); +} + +test "Terminal: OSC133A click_events=0 does not set click_events" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // OSC 133;A with click_events=0 + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "click_events=0", + }); + + // Should remain none since click_events=0 doesn't activate anything + try testing.expectEqual(.none, t.screens.active.semantic_prompt.click); +} + +test "Terminal: OSC133A cl option sets click to cl value" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // OSC 133;A with cl=m (multiple) + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "cl=m", + }); + + try testing.expectEqual(Screen.SemanticPrompt.SemanticClick{ .cl = .multiple }, t.screens.active.semantic_prompt.click); +} + +test "Terminal: OSC133A cl=line sets click to line" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "cl=line", + }); + + try testing.expectEqual(Screen.SemanticPrompt.SemanticClick{ .cl = .line }, t.screens.active.semantic_prompt.click); +} + +test "Terminal: OSC133A click_events=1 takes priority over cl" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // OSC 133;A with both click_events=1 and cl=m + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "click_events=1;cl=m", + }); + + // click_events should take priority + try testing.expectEqual(.click_events, t.screens.active.semantic_prompt.click); +} + +test "Terminal: OSC133A click_events=0 falls back to cl" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // OSC 133;A with click_events=0 and cl=v + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "click_events=0;cl=v", + }); + + // Should fall back to cl since click_events is disabled + try testing.expectEqual(Screen.SemanticPrompt.SemanticClick{ .cl = .conservative_vertical }, t.screens.active.semantic_prompt.click); +} + +test "Terminal: OSC133A no click options leaves click as none" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + // OSC 133;A with no click-related options + try t.semanticPrompt(.{ + .action = .fresh_line_new_prompt, + .options_unvalidated = "aid=123", + }); + + try testing.expectEqual(.none, t.screens.active.semantic_prompt.click); +} + +test "Terminal: cursorIsAtPrompt" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 10, .rows = 3 }); + defer t.deinit(alloc); + + try testing.expect(!t.cursorIsAtPrompt()); + try t.semanticPrompt(.init(.prompt_start)); + try testing.expect(t.cursorIsAtPrompt()); + for ("$ ") |c| try t.print(c); + + // Input is also a prompt + try t.semanticPrompt(.init(.end_prompt_start_input)); + try testing.expect(t.cursorIsAtPrompt()); + for ("ls") |c| try t.print(c); + + // But once we say we're starting output, we're not a prompt + // (cursor is not at x=0, so the Fish heuristic doesn't trigger) + try t.semanticPrompt(.init(.end_input_start_output)); + // Still a prompt because this line has a prompt + try testing.expect(t.cursorIsAtPrompt()); + try t.linefeed(); + try testing.expect(!t.cursorIsAtPrompt()); + + // Until we know we're at a prompt again + try t.linefeed(); + try t.semanticPrompt(.init(.prompt_start)); + try testing.expect(t.cursorIsAtPrompt()); +} + +test "Terminal: cursorIsAtPrompt alternate screen" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 2 }); + defer t.deinit(alloc); + + try testing.expect(!t.cursorIsAtPrompt()); + try t.semanticPrompt(.init(.prompt_start)); + try testing.expect(t.cursorIsAtPrompt()); + + // Secondary screen is never a prompt + try t.switchScreenMode(.@"1049", true); + try testing.expect(!t.cursorIsAtPrompt()); + try t.semanticPrompt(.init(.prompt_start)); + try testing.expect(!t.cursorIsAtPrompt()); +} + +test "Terminal: fullReset with a non-empty pen" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.setAttribute(.{ .direct_color_fg = .{ .r = 0xFF, .g = 0, .b = 0x7F } }); + try t.setAttribute(.{ .direct_color_bg = .{ .r = 0xFF, .g = 0, .b = 0x7F } }); + t.screens.active.cursor.semantic_content = .input; + t.fullReset(); + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expect(cell.style_id == 0); + } + + try testing.expectEqual(@as(style.Id, 0), t.screens.active.cursor.style_id); + try testing.expectEqual(.output, t.screens.active.cursor.semantic_content); +} + +test "Terminal: fullReset hyperlink" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.screens.active.startHyperlink("http://example.com", null); + t.fullReset(); + try testing.expectEqual(0, t.screens.active.cursor.hyperlink_id); +} + +test "Terminal: fullReset with a non-empty saved cursor" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + try t.setAttribute(.{ .direct_color_fg = .{ .r = 0xFF, .g = 0, .b = 0x7F } }); + try t.setAttribute(.{ .direct_color_bg = .{ .r = 0xFF, .g = 0, .b = 0x7F } }); + t.saveCursor(); + t.fullReset(); + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expect(cell.style_id == 0); + } + + try testing.expectEqual(@as(style.Id, 0), t.screens.active.cursor.style_id); +} + +test "Terminal: fullReset origin mode" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + t.setCursorPos(3, 5); + t.modes.set(.origin, true); + t.fullReset(); + + // Origin mode should be reset and the cursor should be moved + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expect(!t.modes.get(.origin)); +} + +test "Terminal: fullReset status display" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + t.status_display = .status_line; + t.fullReset(); + try testing.expect(t.status_display == .main); +} + +// https://github.com/mitchellh/ghostty/issues/1607 +test "Terminal: fullReset clears alt screen kitty keyboard state" { + var t = try init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + try t.switchScreenMode(.@"1049", true); + t.screens.active.kitty_keyboard.push(.{ + .disambiguate = true, + .report_events = false, + .report_alternates = true, + .report_all = true, + .report_associated = true, + }); + try t.switchScreenMode(.@"1049", false); + + t.fullReset(); + try testing.expect(t.screens.get(.alternate) == null); +} + +test "Terminal: fullReset default modes" { + var t = try init(testing.allocator, .{ + .cols = 10, + .rows = 10, + .default_modes = .{ .grapheme_cluster = true }, + }); + defer t.deinit(testing.allocator); + try testing.expect(t.modes.get(.grapheme_cluster)); + t.fullReset(); + try testing.expect(t.modes.get(.grapheme_cluster)); +} + +test "Terminal: fullReset tracked pins" { + var t = try init(testing.allocator, .{ .cols = 80, .rows = 80 }); + defer t.deinit(testing.allocator); + + // Create a tracked pin + const p = try t.screens.active.pages.trackPin(t.screens.active.cursor.page_pin.*); + t.fullReset(); + try testing.expect(t.screens.active.pages.pinIsValid(p.*)); +} + +// https://github.com/mitchellh/ghostty/issues/272 +// This is also tested in depth in screen resize tests but I want to keep +// this test around to ensure we don't regress at multiple layers. +test "Terminal: resize less cols with wide char then print" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 3, .rows = 3 }); + defer t.deinit(alloc); + + try t.print('x'); + try t.print('😀'); // 0x1F600 + try t.resize(alloc, 2, 3); + t.setCursorPos(1, 2); + try t.print('😀'); // 0x1F600 +} + +// https://github.com/mitchellh/ghostty/issues/723 +// This was found via fuzzing so its highly specific. +test "Terminal: resize with left and right margin set" { + const alloc = testing.allocator; + const cols = 70; + const rows = 23; + var t = try init(alloc, .{ .cols = cols, .rows = rows }); + defer t.deinit(alloc); + + t.modes.set(.enable_left_and_right_margin, true); + try t.print('0'); + t.modes.set(.enable_mode_3, true); + try t.resize(alloc, cols, rows); + t.setLeftAndRightMargin(2, 0); + try t.printRepeat(1850); + _ = t.modes.restore(.enable_mode_3); + try t.resize(alloc, cols, rows); +} + +// https://github.com/mitchellh/ghostty/issues/1343 +test "Terminal: resize with wraparound off" { + const alloc = testing.allocator; + const cols = 4; + const rows = 2; + var t = try init(alloc, .{ .cols = cols, .rows = rows }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, false); + try t.print('0'); + try t.print('1'); + try t.print('2'); + try t.print('3'); + const new_cols = 2; + try t.resize(alloc, new_cols, rows); + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("01", str); +} + +test "Terminal: resize with wraparound on" { + const alloc = testing.allocator; + const cols = 4; + const rows = 2; + var t = try init(alloc, .{ .cols = cols, .rows = rows }); + defer t.deinit(alloc); + + t.modes.set(.wraparound, true); + try t.print('0'); + try t.print('1'); + try t.print('2'); + try t.print('3'); + const new_cols = 2; + try t.resize(alloc, new_cols, rows); + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("01\n23", str); +} + +test "Terminal: resize with high unique style per cell" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 30, .rows = 30 }); + defer t.deinit(alloc); + + for (0..t.rows) |y| { + for (0..t.cols) |x| { + t.setCursorPos(y, x); + try t.setAttribute(.{ .direct_color_bg = .{ + .r = @intCast(x), + .g = @intCast(y), + .b = 0, + } }); + try t.print('x'); + } + } + + try t.resize(alloc, 60, 30); +} + +test "Terminal: resize with high unique style per cell with wrapping" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 30, .rows = 30 }); + defer t.deinit(alloc); + + const cell_count: u16 = @intCast(t.rows * t.cols); + for (0..cell_count) |i| { + const r: u8 = @intCast(i >> 8); + const g: u8 = @intCast(i & 0xFF); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = r, + .g = g, + .b = 0, + } }); + try t.print('x'); + } + + try t.resize(alloc, 60, 30); +} + +test "Terminal: resize with reflow and saved cursor" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 3 }); + defer t.deinit(alloc); + try t.printString("1A2B"); + t.setCursorPos(2, 2); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u32, 'B'), cell.content.codepoint); + } + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A\n2B", str); + } + + t.saveCursor(); + try t.resize(alloc, 5, 3); + t.restoreCursor(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A2B", str); + } + + // Verify our cursor is still in the same place + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u32, 'B'), cell.content.codepoint); + } +} + +test "Terminal: resize with reflow and saved cursor pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 2, .rows = 3 }); + defer t.deinit(alloc); + try t.printString("1A2B"); + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } }).?; + const cell = list_cell.cell; + try testing.expectEqual(@as(u32, 'B'), cell.content.codepoint); + } + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A\n2B", str); + } + + t.saveCursor(); + try t.resize(alloc, 5, 3); + t.restoreCursor(); + + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A2B", str); + } + + // Pending wrap should be reset + try t.print('X'); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A2BX", str); + } +} + +test "Terminal: DECCOLM without DEC mode 40" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.@"132_column", true); + try t.deccolm(alloc, .@"132_cols"); + try testing.expectEqual(@as(usize, 5), t.cols); + try testing.expectEqual(@as(usize, 5), t.rows); + try testing.expect(!t.modes.get(.@"132_column")); +} + +test "Terminal: DECCOLM unset" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.enable_mode_3, true); + try t.deccolm(alloc, .@"80_cols"); + try testing.expectEqual(@as(usize, 80), t.cols); + try testing.expectEqual(@as(usize, 5), t.rows); +} + +test "Terminal: DECCOLM resets pending wrap" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + for ("ABCDE") |c| try t.print(c); + try testing.expect(t.screens.active.cursor.pending_wrap); + + t.modes.set(.enable_mode_3, true); + try t.deccolm(alloc, .@"80_cols"); + try testing.expectEqual(@as(usize, 80), t.cols); + try testing.expectEqual(@as(usize, 5), t.rows); + try testing.expect(!t.screens.active.cursor.pending_wrap); +} + +test "Terminal: DECCOLM preserves SGR bg" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + try t.setAttribute(.{ .direct_color_bg = .{ + .r = 0xFF, + .g = 0, + .b = 0, + } }); + t.modes.set(.enable_mode_3, true); + try t.deccolm(alloc, .@"80_cols"); + + { + const list_cell = t.screens.active.pages.getCell(.{ .active = .{ .x = 0, .y = 0 } }).?; + try testing.expect(list_cell.cell.content_tag == .bg_color_rgb); + try testing.expectEqual(Cell.RGB{ + .r = 0xFF, + .g = 0, + .b = 0, + }, list_cell.cell.content.color_rgb); + } +} + +test "Terminal: DECCOLM resets scroll region" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + t.modes.set(.enable_left_and_right_margin, true); + t.setTopAndBottomMargin(2, 3); + t.setLeftAndRightMargin(3, 5); + + t.modes.set(.enable_mode_3, true); + try t.deccolm(alloc, .@"80_cols"); + + try testing.expect(t.modes.get(.enable_left_and_right_margin)); + try testing.expectEqual(@as(usize, 0), t.scrolling_region.top); + try testing.expectEqual(@as(usize, 4), t.scrolling_region.bottom); + try testing.expectEqual(@as(usize, 0), t.scrolling_region.left); + try testing.expectEqual(@as(usize, 79), t.scrolling_region.right); +} + +test "Terminal: mode 47 alt screen plain" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Print on primary screen + try t.printString("1A"); + + // Go to alt screen with mode 47 + try t.switchScreenMode(.@"47", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Screen should be empty + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + // Print on alt screen. This should be off center because + // we copy the cursor over from the primary screen + try t.printString("2B"); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" 2B", str); + } + + // Go back to primary + try t.switchScreenMode(.@"47", false); + try testing.expectEqual(.primary, t.screens.active_key); + + // Primary screen should still have the original content + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A", str); + } + + // Go back to alt screen with mode 47 + try t.switchScreenMode(.@"47", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Screen should retain content + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" 2B", str); + } +} + +test "Terminal: mode 47 copies cursor both directions" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Color our cursor red + try t.setAttribute(.{ .direct_color_fg = .{ .r = 0xFF, .g = 0, .b = 0x7F } }); + + // Go to alt screen with mode 47 + try t.switchScreenMode(.@"47", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Verify that our style is set + { + try testing.expect(t.screens.active.cursor.style_id != style.default_id); + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(page.styles.refCount(page.memory, t.screens.active.cursor.style_id) > 0); + } + + // Set a new style + try t.setAttribute(.{ .direct_color_fg = .{ .r = 0, .g = 0xFF, .b = 0 } }); + + // Go back to primary + try t.switchScreenMode(.@"47", false); + try testing.expectEqual(.primary, t.screens.active_key); + + // Verify that our style is still set + { + try testing.expect(t.screens.active.cursor.style_id != style.default_id); + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(page.styles.refCount(page.memory, t.screens.active.cursor.style_id) > 0); + } +} + +test "Terminal: mode 1047 alt screen plain" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Print on primary screen + try t.printString("1A"); + + // Go to alt screen with mode 47 + try t.switchScreenMode(.@"1047", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Screen should be empty + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + // Print on alt screen. This should be off center because + // we copy the cursor over from the primary screen + try t.printString("2B"); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" 2B", str); + } + + // Go back to primary + try t.switchScreenMode(.@"1047", false); + try testing.expectEqual(.primary, t.screens.active_key); + + // Primary screen should still have the original content + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A", str); + } + + // Go back to alt screen with mode 1047 + try t.switchScreenMode(.@"1047", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Screen should be empty + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +test "Terminal: mode 1047 copies cursor both directions" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Color our cursor red + try t.setAttribute(.{ .direct_color_fg = .{ .r = 0xFF, .g = 0, .b = 0x7F } }); + + // Go to alt screen with mode 47 + try t.switchScreenMode(.@"1047", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Verify that our style is set + { + try testing.expect(t.screens.active.cursor.style_id != style.default_id); + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(page.styles.refCount(page.memory, t.screens.active.cursor.style_id) > 0); + } + + // Set a new style + try t.setAttribute(.{ .direct_color_fg = .{ .r = 0, .g = 0xFF, .b = 0 } }); + + // Go back to primary + try t.switchScreenMode(.@"1047", false); + try testing.expectEqual(.primary, t.screens.active_key); + + // Verify that our style is still set + { + try testing.expect(t.screens.active.cursor.style_id != style.default_id); + const page = &t.screens.active.cursor.page_pin.node.data; + try testing.expectEqual(@as(usize, 1), page.styles.count()); + try testing.expect(page.styles.refCount(page.memory, t.screens.active.cursor.style_id) > 0); + } +} + +test "Terminal: mode 1049 alt screen plain" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Print on primary screen + try t.printString("1A"); + + // Go to alt screen with mode 47 + try t.switchScreenMode(.@"1049", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Screen should be empty + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + // Print on alt screen. This should be off center because + // we copy the cursor over from the primary screen + try t.printString("2B"); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings(" 2B", str); + } + + // Go back to primary + try t.switchScreenMode(.@"1049", false); + try testing.expectEqual(.primary, t.screens.active_key); + + // Primary screen should still have the original content + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1A", str); + } + + // Write, our cursor should be restored back. + try t.printString("C"); + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("1AC", str); + } + + // Go back to alt screen with mode 1049 + try t.switchScreenMode(.@"1049", true); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Screen should be empty + { + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } +} + +// Reproduces a crash found by AFL++ fuzzer (afl-out/stream/default/crashes/ +// id:000007,sig:06,src:004522). The crash is a page integrity violation +// "spacer tail not following wide" triggered during scrollUp -> deleteLines +// -> clearCells. When deleteLines count >= scroll region height, all rows +// are cleared (no shifting), so rowWillBeShifted is never called and wide +// characters straddling the right margin boundary leave orphaned spacer_tails. +test "Terminal: deleteLines wide char at right margin with full clear" { + const alloc = testing.allocator; + var t = try init(alloc, .{ .cols = 80, .rows = 24 }); + defer t.deinit(alloc); + + // Place a wide character at col 39 (1-indexed) on several rows. + // The wide cell lands at col 38 (0-indexed) with spacer_tail at col 39. + t.setCursorPos(10, 39); + try t.print(0x4E2D); // '中' + + // Set left/right scroll margins so scrolling_region.right = 38. + // clearCells will clear cells[4..39], which includes the wide cell + // at col 38 but NOT the spacer_tail at col 39. + t.modes.set(.enable_left_and_right_margin, true); + t.setLeftAndRightMargin(5, 39); + + // scrollUp with count >= region height causes deleteLines to clear + // ALL rows without any shifting, so rowWillBeShifted is never called + // and the orphaned spacer_tail at col 39 triggers a page integrity + // violation in clearCells. + try t.scrollUp(t.rows); +} diff --git a/vendor/libghostty-vt/src/terminal/UTF8Decoder.zig b/vendor/libghostty-vt/src/terminal/UTF8Decoder.zig new file mode 100644 index 00000000..716dac40 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/UTF8Decoder.zig @@ -0,0 +1,142 @@ +//! DFA-based non-allocating error-replacing UTF-8 decoder. +//! +//! This implementation is based largely on the excellent work of +//! Bjoern Hoehrmann, with slight modifications to support error- +//! replacement. +//! +//! For details on Bjoern's DFA-based UTF-8 decoder, see +//! http://bjoern.hoehrmann.de/utf-8/decoder/dfa (MIT licensed) +const UTF8Decoder = @This(); + +const std = @import("std"); +const testing = std.testing; + +const log = std.log.scoped(.utf8decoder); + +// zig fmt: off +const char_classes = [_]u4{ + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, +}; + +const transitions = [_]u8 { + 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, + 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, + 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, + 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, + 12,36,12,12,12,12,12,12,12,12,12,12, +}; +// zig fmt: on + +// DFA states +const ACCEPT_STATE = 0; +const REJECT_STATE = 12; + +// This is where we accumulate our current codepoint. +accumulator: u21 = 0, +// The internal state of the DFA. +state: u8 = ACCEPT_STATE, + +/// Takes the next byte in the utf-8 sequence and emits a tuple of +/// - The codepoint that was generated, if there is one. +/// - A boolean that indicates whether the provided byte was consumed. +/// +/// The only case where the byte is not consumed is if an ill-formed +/// sequence is reached, in which case a replacement character will be +/// emitted and the byte will not be consumed. +/// +/// If the byte is not consumed, the caller is responsible for calling +/// again with the same byte before continuing. +pub inline fn next(self: *UTF8Decoder, byte: u8) struct { ?u21, bool } { + const char_class = char_classes[byte]; + + const initial_state = self.state; + + if (self.state != ACCEPT_STATE) { + self.accumulator <<= 6; + self.accumulator |= (byte & 0x3F); + } else { + self.accumulator = (@as(u21, 0xFF) >> char_class) & (byte); + } + + self.state = transitions[self.state + char_class]; + + if (self.state == ACCEPT_STATE) { + defer self.accumulator = 0; + + // Emit the fully decoded codepoint. + return .{ self.accumulator, true }; + } else if (self.state == REJECT_STATE) { + self.accumulator = 0; + self.state = ACCEPT_STATE; + // Emit a replacement character. If we rejected the first byte + // in a sequence, then it was consumed, otherwise it was not. + return .{ 0xFFFD, initial_state == ACCEPT_STATE }; + } else { + // Emit nothing, we're in the middle of a sequence. + return .{ null, true }; + } +} + +test "ASCII" { + var d: UTF8Decoder = .{}; + var out: [13]u8 = undefined; + for ("Hello, World!", 0..) |byte, i| { + const res = d.next(byte); + try testing.expect(res[1]); + if (res[0]) |codepoint| { + out[i] = @intCast(codepoint); + } + } + + try testing.expectEqualStrings(&out, "Hello, World!"); +} + +test "Well formed utf-8" { + var d: UTF8Decoder = .{}; + var out: [4]u21 = undefined; + var i: usize = 0; + // 4 bytes, 3 bytes, 2 bytes, 1 byte + for ("😄✤ÁA") |byte| { + var consumed = false; + while (!consumed) { + const res = d.next(byte); + consumed = res[1]; + // There are no errors in this sequence, so + // every byte should be consumed first try. + try testing.expect(consumed == true); + if (res[0]) |codepoint| { + out[i] = codepoint; + i += 1; + } + } + } + + try testing.expect(std.mem.eql(u21, &out, &[_]u21{ 0x1F604, 0x2724, 0xC1, 0x41 })); +} + +test "Partially invalid utf-8" { + var d: UTF8Decoder = .{}; + var out: [5]u21 = undefined; + var i: usize = 0; + // Illegally terminated sequence, valid sequence, illegal surrogate pair. + for ("\xF0\x9F😄\xED\xA0\x80") |byte| { + var consumed = false; + while (!consumed) { + const res = d.next(byte); + consumed = res[1]; + if (res[0]) |codepoint| { + out[i] = codepoint; + i += 1; + } + } + } + + try testing.expect(std.mem.eql(u21, &out, &[_]u21{ 0xFFFD, 0x1F604, 0xFFFD, 0xFFFD, 0xFFFD })); +} diff --git a/vendor/libghostty-vt/src/terminal/ansi.zig b/vendor/libghostty-vt/src/terminal/ansi.zig new file mode 100644 index 00000000..4e777b7c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/ansi.zig @@ -0,0 +1,106 @@ +const lib = @import("lib.zig"); + +/// C0 (7-bit) control characters from ANSI. +/// +/// This is not complete, control characters are only added to this +/// as the terminal emulator handles them. +pub const C0 = enum(u7) { + /// Null + NUL = 0x00, + /// Start of heading + SOH = 0x01, + /// Start of text + STX = 0x02, + /// Enquiry + ENQ = 0x05, + /// Bell + BEL = 0x07, + /// Backspace + BS = 0x08, + // Horizontal tab + HT = 0x09, + /// Line feed + LF = 0x0A, + /// Vertical Tab + VT = 0x0B, + /// Form feed + FF = 0x0C, + /// Carriage return + CR = 0x0D, + /// Shift out + SO = 0x0E, + /// Shift in + SI = 0x0F, + + // Non-exhaustive so that @intToEnum never fails since the inputs are + // user-generated. + _, +}; + +/// The SGR rendition aspects that can be set, sometimes known as attributes. +/// The value corresponds to the parameter value for the SGR command (ESC [ m). +pub const RenditionAspect = enum(u16) { + default = 0, + bold = 1, + default_fg = 39, + default_bg = 49, + + // Non-exhaustive so that @intToEnum never fails since the inputs are + // user-generated. + _, +}; + +/// Possible cursor styles (ESC [ q) +pub const CursorStyle = lib.Enum( + lib.target, + &.{ + "default", + "blinking_block", + "steady_block", + "blinking_underline", + "steady_underline", + "blinking_bar", + "steady_bar", + }, +); + +/// The status line type for DECSSDT. +pub const StatusLineType = enum(u16) { + none = 0, + indicator = 1, + host_writable = 2, + + // Non-exhaustive so that @intToEnum never fails for unsupported values. + _, +}; + +/// The display to target for status updates (DECSASD). +pub const StatusDisplay = lib.Enum( + lib.target, + &.{ + "main", + "status_line", + }, +); + +/// The possible modify key formats to ESC[>{a};{b}m +/// Note: this is not complete, we should add more as we support more +pub const ModifyKeyFormat = lib.Enum( + lib.target, + &.{ + "legacy", + "cursor_keys", + "function_keys", + "other_keys_none", + "other_keys_numeric_except", + "other_keys_numeric", + }, +); + +/// The protection modes that can be set for the terminal. See DECSCA and +/// ESC V, W. +pub const ProtectedMode = enum { + off, + iso, // ESC V, W + dec, // CSI Ps " q +}; diff --git a/vendor/libghostty-vt/src/terminal/apc.zig b/vendor/libghostty-vt/src/terminal/apc.zig new file mode 100644 index 00000000..3ebacbbf --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/apc.zig @@ -0,0 +1,186 @@ +const std = @import("std"); +const build_options = @import("terminal_options"); +const Allocator = std.mem.Allocator; + +const kitty_gfx = @import("kitty/graphics.zig"); + +const log = std.log.scoped(.terminal_apc); + +/// APC command handler. This should be hooked into a terminal.Stream handler. +/// The start/feed/end functions are meant to be called from the terminal.Stream +/// apcStart, apcPut, and apcEnd functions, respectively. +pub const Handler = struct { + state: State = .{ .inactive = {} }, + + pub fn deinit(self: *Handler) void { + self.state.deinit(); + } + + pub fn start(self: *Handler) void { + self.state.deinit(); + self.state = .{ .identify = {} }; + } + + pub fn feed(self: *Handler, alloc: Allocator, byte: u8) void { + switch (self.state) { + .inactive => unreachable, + + // We're ignoring this APC command, likely because we don't + // recognize it so there is no need to store the data in memory. + .ignore => return, + + // We identify the APC command by the first byte. + .identify => { + switch (byte) { + // Kitty graphics protocol + 'G' => self.state = if (comptime build_options.kitty_graphics) + .{ .kitty = kitty_gfx.CommandParser.init(alloc) } + else + .{ .ignore = {} }, + + // Unknown + else => self.state = .{ .ignore = {} }, + } + }, + + .kitty => |*p| if (comptime build_options.kitty_graphics) { + p.feed(byte) catch |err| { + log.warn("kitty graphics protocol error: {}", .{err}); + self.state = .{ .ignore = {} }; + }; + } else unreachable, + } + } + + pub fn end(self: *Handler) ?Command { + defer { + self.state.deinit(); + self.state = .{ .inactive = {} }; + } + + return switch (self.state) { + .inactive => unreachable, + .ignore, .identify => null, + .kitty => |*p| kitty: { + if (comptime !build_options.kitty_graphics) unreachable; + + // Use the same allocator that was used to create the parser. + const alloc = p.arena.child_allocator; + const command = p.complete(alloc) catch |err| { + log.warn("kitty graphics protocol error: {}", .{err}); + break :kitty null; + }; + + break :kitty .{ .kitty = command }; + }, + }; + } +}; + +pub const State = union(enum) { + /// We're not in the middle of an APC command yet. + inactive: void, + + /// We got an unrecognized APC sequence or the APC sequence we + /// recognized became invalid. We're just dropping bytes. + ignore: void, + + /// We're waiting to identify the APC sequence. This is done by + /// inspecting the first byte of the sequence. + identify: void, + + /// Kitty graphics protocol + kitty: if (build_options.kitty_graphics) + kitty_gfx.CommandParser + else + void, + + pub fn deinit(self: *State) void { + switch (self.*) { + .inactive, .ignore, .identify => {}, + .kitty => |*v| if (comptime build_options.kitty_graphics) + v.deinit() + else + unreachable, + } + } +}; + +/// Possible APC commands. +pub const Command = union(enum) { + kitty: if (build_options.kitty_graphics) + kitty_gfx.Command + else + void, + + pub fn deinit(self: *Command, alloc: Allocator) void { + switch (self.*) { + .kitty => |*v| if (comptime build_options.kitty_graphics) + v.deinit(alloc) + else + unreachable, + } + } +}; + +test "unknown APC command" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + h.start(); + for ("Xabcdef1234") |c| h.feed(alloc, c); + try testing.expect(h.end() == null); +} + +test "garbage Kitty command" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + h.start(); + for ("Gabcdef1234") |c| h.feed(alloc, c); + try testing.expect(h.end() == null); +} + +test "Kitty command with overflow u32" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + h.start(); + for ("Ga=p,i=10000000000") |c| h.feed(alloc, c); + try testing.expect(h.end() == null); +} + +test "Kitty command with overflow i32" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + h.start(); + for ("Ga=p,i=1,z=-9999999999") |c| h.feed(alloc, c); + try testing.expect(h.end() == null); +} + +test "valid Kitty command" { + if (comptime !build_options.kitty_graphics) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + h.start(); + const input = "Gf=24,s=10,v=20,hello=world"; + for (input) |c| h.feed(alloc, c); + + var cmd = h.end().?; + defer cmd.deinit(alloc); + try testing.expect(cmd == .kitty); +} diff --git a/vendor/libghostty-vt/src/terminal/bitmap_allocator.zig b/vendor/libghostty-vt/src/terminal/bitmap_allocator.zig new file mode 100644 index 00000000..deeecf55 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/bitmap_allocator.zig @@ -0,0 +1,1021 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const size = @import("size.zig"); +const getOffset = size.getOffset; +const Offset = size.Offset; +const OffsetBuf = size.OffsetBuf; +const alignForward = std.mem.alignForward; + +/// A relatively naive bitmap allocator that uses memory offsets against +/// a fixed backing buffer so that the backing buffer can be easily moved +/// without having to update pointers. +/// +/// The chunk size determines the size of each chunk in bytes. This is the +/// minimum distributed unit of memory. For example, if you request a +/// 1-byte allocation, you'll use a chunk of chunk_size bytes. Likewise, +/// if your chunk size is 4, and you request a 5-byte allocation, you'll +/// use 2 chunks. +/// +/// The allocator is susceptible to fragmentation. If you allocate and free +/// memory in a way that leaves small holes in the memory, you may not be +/// able to allocate large chunks of memory even if there is enough free +/// memory in aggregate. To avoid fragmentation, use a chunk size that is +/// large enough to cover most of your allocations. +/// +// Notes for contributors: this is highly contributor friendly part of +// the code. If you can improve this, add tests, show benchmarks, then +// please do so! +pub fn BitmapAllocator(comptime chunk_size: comptime_int) type { + return struct { + const Self = @This(); + + comptime { + assert(std.math.isPowerOfTwo(chunk_size)); + } + + pub const base_align: std.mem.Alignment = .fromByteUnits(@alignOf(u64)); + pub const bitmap_bit_size = @bitSizeOf(u64); + + /// The bitmap of available chunks. Each bit represents a chunk. A + /// 1 means the chunk is free and a 0 means it's used. We use 1 + /// for free since it makes it very slightly faster to find free + /// chunks. + bitmap: Offset(u64), + bitmap_count: usize, + + /// The contiguous buffer of chunks. + chunks: Offset(u8), + + /// Initialize the allocator map with a given buf and memory layout. + pub fn init(buf: OffsetBuf, l: Layout) Self { + assert(base_align.check(@intFromPtr(buf.start()))); + + // Initialize our bitmaps to all 1s to note that all chunks are free. + const bitmap = buf.member(u64, l.bitmap_start); + const bitmap_ptr = bitmap.ptr(buf); + @memset(bitmap_ptr[0..l.bitmap_count], std.math.maxInt(u64)); + + return .{ + .bitmap = bitmap, + .bitmap_count = l.bitmap_count, + .chunks = buf.member(u8, l.chunks_start), + }; + } + + /// Returns the number of bytes required to allocate n elements of + /// type T. This accounts for the chunk size alignment used by the + /// bitmap allocator. + pub fn bytesRequired(comptime T: type, n: usize) usize { + const byte_count = @sizeOf(T) * n; + return alignForward(usize, byte_count, chunk_size); + } + + /// Allocate n elements of type T. This will return error.OutOfMemory + /// if there isn't enough space in the backing buffer. + /// + /// Use (size.zig).getOffset to get the base offset from the backing + /// memory for portable storage. + pub fn alloc( + self: *Self, + comptime T: type, + base: anytype, + n: usize, + ) Allocator.Error![]T { + // note: we don't handle alignment yet, we just require that all + // types are properly aligned. This is a limitation that should be + // fixed but we haven't needed it. Contributor friendly: add tests + // and fix this. + assert(chunk_size % @alignOf(T) == 0); + assert(n > 0); + + const byte_count = std.math.mul(usize, @sizeOf(T), n) catch + return error.OutOfMemory; + const chunk_count = std.math.divCeil(usize, byte_count, chunk_size) catch + return error.OutOfMemory; + + // Find the index of the free chunk. This also marks it as used. + const bitmaps = self.bitmap.ptr(base); + const idx = findFreeChunks(bitmaps[0..self.bitmap_count], chunk_count) orelse + return error.OutOfMemory; + + const chunks = self.chunks.ptr(base); + const ptr: [*]T = @ptrCast(@alignCast(&chunks[idx * chunk_size])); + return ptr[0..n]; + } + + pub fn free(self: *Self, base: anytype, slice: anytype) void { + // Convert the slice of whatever type to a slice of bytes. We + // can then use the byte len and chunk size to determine the + // number of chunks that were allocated. + const bytes = std.mem.sliceAsBytes(slice); + const aligned_len = std.mem.alignForward(usize, bytes.len, chunk_size); + const chunk_count = @divExact(aligned_len, chunk_size); + + // From the pointer, we can calculate the exact index. + const chunks = self.chunks.ptr(base); + const chunk_idx = @divExact(@intFromPtr(slice.ptr) - @intFromPtr(chunks), chunk_size); + + const bitmaps = self.bitmap.ptr(base); + + // Current bitmap index. + var i: usize = @divFloor(chunk_idx, 64); + // Number of chunks we still have to mark as free. + var rem: usize = chunk_count; + + // Mark any bits in the starting bitmap that need to be marked. + { + // Bit index. + const bit = chunk_idx % 64; + // Number of bits we need to mark in this bitmap. + const bits = @min(rem, 64 - bit); + + bitmaps[i] |= ~@as(u64, 0) >> @intCast(64 - bits) << @intCast(bit); + rem -= bits; + } + + // Mark any full bitmaps worth of bits that need to be marked. + i += 1; + while (rem > 64) : (i += 1) { + bitmaps[i] = std.math.maxInt(u64); + rem -= 64; + } + + // Mark any bits at the start of this last bitmap if it needs it. + if (rem > 0) { + bitmaps[i] |= ~@as(u64, 0) >> @intCast(64 - rem); + } + } + + /// Returns the total capacity in bytes. + pub fn capacityBytes(self: Self) usize { + return self.bitmap_count * bitmap_bit_size * chunk_size; + } + + /// Returns the number of bytes currently in use. + pub fn usedBytes(self: Self, base: anytype) usize { + const bitmaps = self.bitmap.ptr(base); + var free_chunks: usize = 0; + for (bitmaps[0..self.bitmap_count]) |bitmap| free_chunks += @popCount(bitmap); + const total_chunks = self.bitmap_count * bitmap_bit_size; + return (total_chunks - free_chunks) * chunk_size; + } + + /// For testing only. + fn isAllocated(self: *Self, base: anytype, slice: anytype) bool { + comptime assert(@import("builtin").is_test); + + const bytes = std.mem.sliceAsBytes(slice); + const aligned_len = std.mem.alignForward(usize, bytes.len, chunk_size); + const chunk_count = @divExact(aligned_len, chunk_size); + + const chunks = self.chunks.ptr(base); + const chunk_idx = @divExact(@intFromPtr(slice.ptr) - @intFromPtr(chunks), chunk_size); + + const bitmaps = self.bitmap.ptr(base); + + for (chunk_idx..chunk_idx + chunk_count) |i| { + const bitmap = @divFloor(i, bitmap_bit_size); + const bit = i % bitmap_bit_size; + if (bitmaps[bitmap] & (@as(u64, 1) << @intCast(bit)) != 0) { + return false; + } + } + + return true; + } + + /// For debugging + fn dumpBitmaps(self: *Self, base: anytype) void { + const bitmaps = self.bitmap.ptr(base); + for (bitmaps[0..self.bitmap_count], 0..) |bitmap, idx| { + std.log.warn("bm={b} idx={}", .{ bitmap, idx }); + } + } + + pub const Layout = struct { + total_size: usize, + bitmap_count: usize, + bitmap_start: usize, + chunks_start: usize, + }; + + /// Get the layout for the given capacity. The capacity is in + /// number of bytes, not chunks. The capacity will likely be + /// rounded up to the nearest chunk size and bitmap size so + /// everything is perfectly divisible. + pub fn layout(cap: usize) Layout { + // Align the cap forward to our chunk size so we always have + // a full chunk at the end. + const aligned_cap = alignForward(usize, cap, chunk_size); + + // Calculate the number of bitmaps. We need 1 bitmap per 64 chunks. + // We align the chunk count forward so our bitmaps are full so we + // don't have to handle the case where we have a partial bitmap. + const chunk_count = @divExact(aligned_cap, chunk_size); + const aligned_chunk_count = alignForward(usize, chunk_count, 64); + const bitmap_count = @divExact(aligned_chunk_count, 64); + + const bitmap_start = 0; + const bitmap_end = @sizeOf(u64) * bitmap_count; + const chunks_start = alignForward(usize, bitmap_end, @alignOf(u8)); + const chunks_end = chunks_start + (aligned_cap * chunk_size); + const total_size = chunks_end; + + return Layout{ + .total_size = total_size, + .bitmap_count = bitmap_count, + .bitmap_start = bitmap_start, + .chunks_start = chunks_start, + }; + } + }; +} + +/// Find `n` sequential free chunks in the given bitmaps and return the index +/// of the first chunk. If no chunks are found, return `null`. This also updates +/// the bitmap to mark the chunks as used. +fn findFreeChunks(bitmaps: []u64, n: usize) ?usize { + // NOTE: This is a naive implementation that just iterates through the + // bitmaps. There is very likely a more efficient way to do this but + // I'm not a bit twiddling expert. Perhaps even SIMD could be used here + // but unsure. Contributor friendly: let's benchmark and improve this! + + // Large chunks require special handling. + if (n > @bitSizeOf(u64)) { + var i: usize = 0; + search: while (i < bitmaps.len) { + // Number of chunks available at the end of this bitmap. + const prefix = @clz(~bitmaps[i]); + + // If there are no chunks available at the end of this bitmap + // then we can't start in it, so we'll try the next one. + if (prefix == 0) { + i += 1; + continue; + } + + // Starting position if we manage to find the span we need here. + const start_bitmap = i; + const start_bit = 64 - prefix; + + // The remaining number of sequential free chunks we need to find. + var rem: usize = n - prefix; + + i += 1; + while (rem > 64) : (i += 1) { + // We ran out of bitmaps, there's no sufficiently large gap. + if (i >= bitmaps.len) return null; + + // There's more than 64 remaining chunks and this bitmap has + // content in it, so we try starting again with this bitmap. + if (bitmaps[i] != std.math.maxInt(u64)) continue :search; + + // This bitmap is completely free, we can subtract 64 from + // our remaining number. + rem -= 64; + } + + // If the number of available chunks at the start of this bitmap + // is less than the remaining required, we have to try again. + if (@ctz(~bitmaps[i]) < rem) continue; + + const suffix = (n - prefix) % 64; + + // Found! Mark everything between our start and end as full. + bitmaps[start_bitmap] ^= ~@as(u64, 0) >> @intCast(start_bit) << @intCast(start_bit); + const full_bitmaps = @divFloor(n - prefix - suffix, 64); + for (bitmaps[start_bitmap + 1 ..][0..full_bitmaps]) |*bitmap| { + bitmap.* = 0; + } + if (suffix > 0) bitmaps[i] ^= ~@as(u64, 0) >> @intCast(64 - suffix); + + return start_bitmap * 64 + start_bit; + } + + return null; + } + + assert(n <= @bitSizeOf(u64)); + for (bitmaps, 0..) |*bitmap, idx| { + // Shift the bitmap to find `n` sequential free chunks. + // EXAMPLE: + // n = 4 + // shifted = 001111001011110010 + // & 000111100101111001 + // & 000011110010111100 + // & 000001111001011110 + // = 000001000000010000 + // ^ ^ + // In this example there are 2 places with at least 4 sequential 1s. + var shifted: u64 = bitmap.*; + for (1..n) |i| shifted &= bitmap.* >> @intCast(i); + + // If we have zero then we have no matches + if (shifted == 0) continue; + + // Trailing zeroes gets us the index of the first bit index with at + // least `n` sequential 1s. In the example above, that would be `4`. + const bit = @ctz(shifted); + + // Calculate the mask so we can mark it as used + const mask = (@as(u64, std.math.maxInt(u64)) >> @intCast(64 - n)) << @intCast(bit); + bitmap.* ^= mask; + + return (idx * 64) + bit; + } + + return null; +} + +test "findFreeChunks single found" { + const testing = std.testing; + + var bitmaps = [_]u64{ + 0b10000000_00000000_00000000_00000000_00000000_00000000_00001110_00000000, + }; + const idx = findFreeChunks(&bitmaps, 2).?; + try testing.expectEqual(@as(usize, 9), idx); + try testing.expectEqual( + 0b10000000_00000000_00000000_00000000_00000000_00000000_00001000_00000000, + bitmaps[0], + ); +} + +test "findFreeChunks single not found" { + const testing = std.testing; + + var bitmaps = [_]u64{0b10000111_00000000_00000000_00000000_00000000_00000000_00000000_00000000}; + const idx = findFreeChunks(&bitmaps, 4); + try testing.expect(idx == null); +} + +test "findFreeChunks multiple found" { + const testing = std.testing; + + var bitmaps = [_]u64{ + 0b10000111_00000000_00000000_00000000_00000000_00000000_00000000_01110000, + 0b10000000_00111110_00000000_00000000_00000000_00000000_00111110_00000000, + }; + const idx = findFreeChunks(&bitmaps, 4).?; + try testing.expectEqual(@as(usize, 73), idx); + try testing.expectEqual( + 0b10000000_00111110_00000000_00000000_00000000_00000000_00100000_00000000, + bitmaps[1], + ); +} + +test "findFreeChunks exactly 64 chunks" { + const testing = std.testing; + + var bitmaps = [_]u64{ + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + }; + const idx = findFreeChunks(&bitmaps, 64).?; + try testing.expectEqual( + 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + bitmaps[0], + ); + try testing.expectEqual(@as(usize, 0), idx); +} + +test "findFreeChunks larger than 64 chunks" { + const testing = std.testing; + + var bitmaps = [_]u64{ + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + }; + const idx = findFreeChunks(&bitmaps, 65).?; + try testing.expectEqual( + 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + bitmaps[0], + ); + try testing.expectEqual( + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111110, + bitmaps[1], + ); + try testing.expectEqual(@as(usize, 0), idx); +} + +test "findFreeChunks larger than 64 chunks not at beginning" { + const testing = std.testing; + + var bitmaps = [_]u64{ + 0b11111111_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + }; + const idx = findFreeChunks(&bitmaps, 65).?; + try testing.expectEqual( + 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + bitmaps[0], + ); + try testing.expectEqual( + 0b11111110_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + bitmaps[1], + ); + try testing.expectEqual( + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + bitmaps[2], + ); + try testing.expectEqual(@as(usize, 56), idx); +} + +test "findFreeChunks larger than 64 chunks exact" { + const testing = std.testing; + + var bitmaps = [_]u64{ + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + 0b11111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111, + }; + const idx = findFreeChunks(&bitmaps, 128).?; + try testing.expectEqual( + 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + bitmaps[0], + ); + try testing.expectEqual( + 0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_00000000, + bitmaps[1], + ); + try testing.expectEqual(@as(usize, 0), idx); +} + +test "BitmapAllocator layout" { + const Alloc = BitmapAllocator(4); + const cap = 64 * 4; + + const testing = std.testing; + const layout = Alloc.layout(cap); + + // We expect to use one bitmap since the cap is bytes. + try testing.expectEqual(@as(usize, 1), layout.bitmap_count); +} + +test "BitmapAllocator alloc sequentially" { + const Alloc = BitmapAllocator(4); + const cap = 64; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + const ptr = try bm.alloc(u8, buf, 1); + ptr[0] = 'A'; + + const ptr2 = try bm.alloc(u8, buf, 1); + try testing.expect(@intFromPtr(ptr.ptr) != @intFromPtr(ptr2.ptr)); + + // Should grab the next chunk + try testing.expectEqual(@intFromPtr(ptr.ptr) + 4, @intFromPtr(ptr2.ptr)); + + // Free ptr and next allocation should be back + bm.free(buf, ptr); + const ptr3 = try bm.alloc(u8, buf, 1); + try testing.expectEqual(@intFromPtr(ptr.ptr), @intFromPtr(ptr3.ptr)); +} + +test "BitmapAllocator alloc non-byte" { + const Alloc = BitmapAllocator(4); + const cap = 128; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + const ptr = try bm.alloc(u21, buf, 1); + ptr[0] = 'A'; + + const ptr2 = try bm.alloc(u21, buf, 1); + try testing.expect(@intFromPtr(ptr.ptr) != @intFromPtr(ptr2.ptr)); + try testing.expectEqual(@intFromPtr(ptr.ptr) + 4, @intFromPtr(ptr2.ptr)); + + // Free ptr and next allocation should be back + bm.free(buf, ptr); + const ptr3 = try bm.alloc(u21, buf, 1); + try testing.expectEqual(@intFromPtr(ptr.ptr), @intFromPtr(ptr3.ptr)); +} + +test "BitmapAllocator alloc non-byte multi-chunk" { + const Alloc = BitmapAllocator(4 * @sizeOf(u21)); + const cap = 128; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + const ptr = try bm.alloc(u21, buf, 6); + try testing.expectEqual(@as(usize, 6), ptr.len); + for (ptr) |*v| v.* = 'A'; + + const ptr2 = try bm.alloc(u21, buf, 1); + try testing.expect(@intFromPtr(ptr.ptr) != @intFromPtr(ptr2.ptr)); + try testing.expectEqual(@intFromPtr(ptr.ptr) + (@sizeOf(u21) * 4 * 2), @intFromPtr(ptr2.ptr)); + + // Free ptr and next allocation should be back + bm.free(buf, ptr); + const ptr3 = try bm.alloc(u21, buf, 1); + try testing.expectEqual(@intFromPtr(ptr.ptr), @intFromPtr(ptr3.ptr)); +} + +test "BitmapAllocator alloc large" { + const Alloc = BitmapAllocator(2); + const cap = 256; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + const ptr = try bm.alloc(u8, buf, 129); + ptr[0] = 'A'; + bm.free(buf, ptr); +} + +test "BitmapAllocator alloc and free one bitmap" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate exactly one bitmap worth of bytes. + const slice = try bm.alloc(u8, buf, Alloc.bitmap_bit_size); + try testing.expectEqual(Alloc.bitmap_bit_size, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([Alloc.bitmap_bit_size]u8, @splat(0x11)), + slice, + ); + + // Free it + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free half bitmap" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate exactly half a bitmap worth of bytes. + const slice = try bm.alloc(u8, buf, Alloc.bitmap_bit_size / 2); + try testing.expectEqual(Alloc.bitmap_bit_size / 2, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([Alloc.bitmap_bit_size / 2]u8, @splat(0x11)), + slice, + ); + + // Free it + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free two half bitmaps" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate exactly one bitmap worth of bytes across two allocations. + const slice = try bm.alloc(u8, buf, Alloc.bitmap_bit_size / 2); + try testing.expectEqual(Alloc.bitmap_bit_size / 2, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([Alloc.bitmap_bit_size / 2]u8, @splat(0x11)), + slice, + ); + + const slice2 = try bm.alloc(u8, buf, Alloc.bitmap_bit_size / 2); + try testing.expectEqual(Alloc.bitmap_bit_size / 2, slice2.len); + + @memset(slice2, 0x22); + try testing.expectEqualSlices( + u8, + &@as([Alloc.bitmap_bit_size / 2]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([Alloc.bitmap_bit_size / 2]u8, @splat(0x11)), + slice, + ); + + // Free them + try testing.expect(bm.isAllocated(buf, slice2)); + bm.free(buf, slice2); + try testing.expect(!bm.isAllocated(buf, slice2)); + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free 1.5 bitmaps" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate exactly 1.5 bitmaps worth of bytes. + const slice = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 2); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 2, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x11)), + slice, + ); + + // Free them + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free two 1.5 bitmaps" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate exactly 3 bitmaps worth of bytes across two allocations. + const slice = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 2); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 2, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x11)), + slice, + ); + + const slice2 = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 2); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 2, slice2.len); + + @memset(slice2, 0x22); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x11)), + slice, + ); + + // Free them + try testing.expect(bm.isAllocated(buf, slice2)); + bm.free(buf, slice2); + try testing.expect(!bm.isAllocated(buf, slice2)); + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free 1.5 bitmaps offset by 0.75" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate three quarters of a bitmap first. + const slice = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 4); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 4, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + // Then a 1.5 bitmap sized allocation, so that it spans + // from 0.75 to 2.25, occupying bits in 3 different bitmaps. + const slice2 = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 2); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 2, slice2.len); + + @memset(slice2, 0x22); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + // Free them + try testing.expect(bm.isAllocated(buf, slice2)); + bm.free(buf, slice2); + try testing.expect(!bm.isAllocated(buf, slice2)); + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free three 0.75 bitmaps" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 3 bitmaps. + const cap = Alloc.bitmap_bit_size * 3; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // Allocate three quarters of a bitmap three times. + const slice = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 4); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 4, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + const slice2 = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 4); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 4, slice2.len); + + @memset(slice2, 0x22); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + const slice3 = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 4); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 4, slice3.len); + + @memset(slice3, 0x33); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x33)), + slice3, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + // Free them + try testing.expect(bm.isAllocated(buf, slice2)); + bm.free(buf, slice2); + try testing.expect(!bm.isAllocated(buf, slice2)); + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + try testing.expect(bm.isAllocated(buf, slice3)); + bm.free(buf, slice3); + try testing.expect(!bm.isAllocated(buf, slice3)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([3]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..3], + ); +} + +test "BitmapAllocator alloc and free two 1.5 bitmaps offset 0.75" { + const Alloc = BitmapAllocator(1); + // Capacity such that we'll have 4 bitmaps. + const cap = Alloc.bitmap_bit_size * 4; + + const testing = std.testing; + const alloc = testing.allocator; + const layout = Alloc.layout(cap); + const buf = try alloc.alignedAlloc(u8, Alloc.base_align, layout.total_size); + defer alloc.free(buf); + + var bm = Alloc.init(.init(buf), layout); + + // First allocate a 0.75 bitmap + const slice = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 4); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 4, slice.len); + + @memset(slice, 0x11); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + // Then two 1.5 bitmaps + const slice2 = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 2); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 2, slice2.len); + + @memset(slice2, 0x22); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + const slice3 = try bm.alloc(u8, buf, 3 * Alloc.bitmap_bit_size / 2); + try testing.expectEqual(3 * Alloc.bitmap_bit_size / 2, slice3.len); + + @memset(slice3, 0x33); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x33)), + slice3, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 2]u8, @splat(0x22)), + slice2, + ); + try testing.expectEqualSlices( + u8, + &@as([3 * Alloc.bitmap_bit_size / 4]u8, @splat(0x11)), + slice, + ); + + // Free them + try testing.expect(bm.isAllocated(buf, slice2)); + bm.free(buf, slice2); + try testing.expect(!bm.isAllocated(buf, slice2)); + try testing.expect(bm.isAllocated(buf, slice)); + bm.free(buf, slice); + try testing.expect(!bm.isAllocated(buf, slice)); + try testing.expect(bm.isAllocated(buf, slice3)); + bm.free(buf, slice3); + try testing.expect(!bm.isAllocated(buf, slice3)); + + // All of our bitmaps should be free. + try testing.expectEqualSlices( + u64, + &@as([4]u64, @splat(~@as(u64, 0))), + bm.bitmap.ptr(buf)[0..4], + ); +} + +test "BitmapAllocator bytesRequired" { + const testing = std.testing; + + // Chunk size of 16 bytes (like grapheme_chunk in page.zig) + { + const Alloc = BitmapAllocator(16); + + // Single byte rounds up to chunk size + try testing.expectEqual(16, Alloc.bytesRequired(u8, 1)); + try testing.expectEqual(16, Alloc.bytesRequired(u8, 16)); + try testing.expectEqual(32, Alloc.bytesRequired(u8, 17)); + + // u21 (4 bytes each) + try testing.expectEqual(16, Alloc.bytesRequired(u21, 1)); // 4 bytes -> 16 + try testing.expectEqual(16, Alloc.bytesRequired(u21, 4)); // 16 bytes -> 16 + try testing.expectEqual(32, Alloc.bytesRequired(u21, 5)); // 20 bytes -> 32 + try testing.expectEqual(32, Alloc.bytesRequired(u21, 6)); // 24 bytes -> 32 + } + + // Chunk size of 4 bytes + { + const Alloc = BitmapAllocator(4); + + try testing.expectEqual(4, Alloc.bytesRequired(u8, 1)); + try testing.expectEqual(4, Alloc.bytesRequired(u8, 4)); + try testing.expectEqual(8, Alloc.bytesRequired(u8, 5)); + + // u32 (4 bytes each) - exactly one chunk per element + try testing.expectEqual(4, Alloc.bytesRequired(u32, 1)); + try testing.expectEqual(8, Alloc.bytesRequired(u32, 2)); + } + + // Chunk size of 32 bytes (like string_chunk in page.zig) + { + const Alloc = BitmapAllocator(32); + + try testing.expectEqual(32, Alloc.bytesRequired(u8, 1)); + try testing.expectEqual(32, Alloc.bytesRequired(u8, 32)); + try testing.expectEqual(64, Alloc.bytesRequired(u8, 33)); + } +} diff --git a/vendor/libghostty-vt/src/terminal/build_options.zig b/vendor/libghostty-vt/src/terminal/build_options.zig new file mode 100644 index 00000000..6c0a4df6 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/build_options.zig @@ -0,0 +1,80 @@ +const std = @import("std"); + +/// Options set by Zig build.zig and exposed via `terminal_options`. +pub const Options = struct { + /// The target artifact to build. This will gate some functionality. + artifact: Artifact, + + /// Whether Oniguruma regex support is available. If this isn't + /// available, some features will be disabled. This may be outdated, + /// but the specific disabled features are: + /// + /// - Kitty graphics protocol + /// - Tmux control mode + /// + oniguruma: bool, + + /// Whether to build SIMD-accelerated code paths. This pulls in more + /// build-time dependencies and adds libc as a runtime dependency, + /// but results in significant performance improvements. + simd: bool, + + /// True if we should enable the "slow" runtime safety checks. These + /// are runtime safety checks that are slower than typical and should + /// generally be disabled in production builds. + slow_runtime_safety: bool, + + /// Force C ABI mode on or off. If not set, then it will be set based on + /// Options. + c_abi: bool, + + /// The version of the application. + version: std.SemanticVersion, + + /// Add the required build options for the terminal module. + /// + /// The memory referenced by self is expected to stick around (it isn't + /// copied), since we expect we're in a build environment. + pub fn add( + self: Options, + b: *std.Build, + m: *std.Build.Module, + ) void { + const opts = b.addOptions(); + opts.addOption(Artifact, "artifact", self.artifact); + opts.addOption(bool, "c_abi", self.c_abi); + opts.addOption(bool, "oniguruma", self.oniguruma); + opts.addOption(bool, "simd", self.simd); + opts.addOption(bool, "slow_runtime_safety", self.slow_runtime_safety); + + // These are synthesized based on other options. + opts.addOption(bool, "kitty_graphics", self.oniguruma); + opts.addOption(bool, "tmux_control_mode", self.oniguruma); + + // Version information. + var buf: [1024]u8 = undefined; + opts.addOption( + []const u8, + "version_string", + std.fmt.bufPrint( + &buf, + "{f}", + .{self.version}, + ) catch @panic("version string too long"), + ); + opts.addOption(usize, "version_major", self.version.major); + opts.addOption(usize, "version_minor", self.version.minor); + opts.addOption(usize, "version_patch", self.version.patch); + opts.addOption(?[]const u8, "version_build", self.version.build); + + m.addOptions("terminal_options", opts); + } +}; + +pub const Artifact = enum { + /// Ghostty application + ghostty, + + /// libghostty-vt, Zig module + lib, +}; diff --git a/vendor/libghostty-vt/src/terminal/c/AGENTS.md b/vendor/libghostty-vt/src/terminal/c/AGENTS.md new file mode 100644 index 00000000..63f7fc6c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/AGENTS.md @@ -0,0 +1,22 @@ +# libghostty-vt C API + +- C API must be designed with ABI compatibility in mind +- Zig tagged unions must be converted to C ABI compatible unions + via `lib.TaggedUnion`. +- Any functions must be updated all the way through from here to + `src/terminal/c/main.zig` to `src/lib_vt.zig` and the headers + in `include/ghostty/vt.h`. +- In `include/ghostty/vt.h`, always sort the header contents by: + (1) macros, (2) forward declarations, (3) types, (4) functions + +## ABI Compatibility + +- Prefer opaque pointers for long-lived objects, such as + `GhosttyTerminal`. +- Structs: + - May contain padding bytes if we're confident we'll never grow + beyond a certain size. + - May use the "sized struct" pattern: an `extern struct` with + `size: usize = @sizeOf(Self)` as the first field. In the C header, + callers use `GHOSTTY_INIT_SIZED` from `types.h` to zero-initialize and + set the size. diff --git a/vendor/libghostty-vt/src/terminal/c/allocator.zig b/vendor/libghostty-vt/src/terminal/c/allocator.zig new file mode 100644 index 00000000..ca698f3c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/allocator.zig @@ -0,0 +1,67 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; + +/// Allocate a buffer of `len` bytes using the given allocator +/// (or the default allocator if NULL). +/// +/// Returns a pointer to the allocated buffer, or NULL if the +/// allocation failed. +pub fn alloc( + alloc_: ?*const CAllocator, + len: usize, +) callconv(lib.calling_conv) ?[*]u8 { + const allocator = lib.alloc.default(alloc_); + const buf = allocator.alloc(u8, len) catch return null; + return buf.ptr; +} + +/// Free memory that was allocated by a libghostty-vt function. +/// +/// This must be used to free buffers returned by functions like +/// `format_alloc`. Pass the same allocator (or NULL for the default) +/// that was used for the allocation. +pub fn free( + alloc_: ?*const CAllocator, + ptr: ?[*]u8, + len: usize, +) callconv(lib.calling_conv) void { + const mem = ptr orelse return; + const allocator = lib.alloc.default(alloc_); + allocator.free(mem[0..len]); +} + +test "alloc returns non-null" { + const ptr = alloc(&lib.alloc.test_allocator, 16); + try testing.expect(ptr != null); + free(&lib.alloc.test_allocator, ptr, 16); +} + +test "alloc with null allocator" { + const ptr = alloc(null, 8); + try testing.expect(ptr != null); + free(null, ptr, 8); +} + +test "alloc zero length" { + const ptr = alloc(&lib.alloc.test_allocator, 0); + defer free(&lib.alloc.test_allocator, ptr, 0); +} + +test "free null pointer" { + free(&lib.alloc.test_allocator, null, 0); +} + +test "free allocated memory" { + const allocator = lib.alloc.default(&lib.alloc.test_allocator); + const mem = try allocator.alloc(u8, 16); + free(&lib.alloc.test_allocator, mem.ptr, mem.len); +} + +test "free with null allocator" { + // null allocator falls back to the default (test allocator in tests) + const allocator = lib.alloc.default(null); + const mem = try allocator.alloc(u8, 8); + free(null, mem.ptr, mem.len); +} diff --git a/vendor/libghostty-vt/src/terminal/c/build_info.zig b/vendor/libghostty-vt/src/terminal/c/build_info.zig new file mode 100644 index 00000000..bef6760f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/build_info.zig @@ -0,0 +1,162 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const lib = @import("../lib.zig"); +const build_options = @import("terminal_options"); +const Result = @import("result.zig").Result; + +const log = std.log.scoped(.build_info_c); + +/// C: GhosttyOptimizeMode +pub const OptimizeMode = enum(c_int) { + debug = 0, + release_safe = 1, + release_small = 2, + release_fast = 3, +}; + +/// C: GhosttyBuildInfo +pub const BuildInfo = enum(c_int) { + invalid = 0, + simd = 1, + kitty_graphics = 2, + tmux_control_mode = 3, + optimize = 4, + version_string = 5, + version_major = 6, + version_minor = 7, + version_patch = 8, + version_build = 9, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: BuildInfo) type { + return switch (self) { + .invalid => void, + .simd, .kitty_graphics, .tmux_control_mode => bool, + .optimize => OptimizeMode, + .version_string, .version_build => lib.String, + .version_major, .version_minor, .version_patch => usize, + }; + } +}; + +pub fn get( + data: BuildInfo, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(BuildInfo, @intFromEnum(data)) catch { + log.warn("build_info invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| getTyped( + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn getTyped( + comptime data: BuildInfo, + out: *data.OutType(), +) Result { + switch (data) { + .invalid => return .invalid_value, + .simd => out.* = build_options.simd, + .kitty_graphics => out.* = build_options.kitty_graphics, + .tmux_control_mode => out.* = build_options.tmux_control_mode, + .optimize => out.* = switch (builtin.mode) { + .Debug => .debug, + .ReleaseSafe => .release_safe, + .ReleaseSmall => .release_small, + .ReleaseFast => .release_fast, + }, + .version_string => out.* = .{ .ptr = build_options.version_string.ptr, .len = build_options.version_string.len }, + .version_major => out.* = build_options.version_major, + .version_minor => out.* = build_options.version_minor, + .version_patch => out.* = build_options.version_patch, + .version_build => { + if (build_options.version_build) |b| { + out.* = .{ .ptr = b.ptr, .len = b.len }; + } else { + out.* = .{ .ptr = "", .len = 0 }; + } + }, + } + + return .success; +} + +test "get simd" { + const testing = std.testing; + var value: bool = undefined; + try testing.expectEqual(Result.success, get(.simd, @ptrCast(&value))); + try testing.expectEqual(build_options.simd, value); +} + +test "get kitty_graphics" { + const testing = std.testing; + var value: bool = undefined; + try testing.expectEqual(Result.success, get(.kitty_graphics, @ptrCast(&value))); + try testing.expectEqual(build_options.kitty_graphics, value); +} + +test "get tmux_control_mode" { + const testing = std.testing; + var value: bool = undefined; + try testing.expectEqual(Result.success, get(.tmux_control_mode, @ptrCast(&value))); + try testing.expectEqual(build_options.tmux_control_mode, value); +} + +test "get optimize" { + const testing = std.testing; + var value: OptimizeMode = undefined; + try testing.expectEqual(Result.success, get(.optimize, @ptrCast(&value))); + try testing.expectEqual(switch (builtin.mode) { + .Debug => .debug, + .ReleaseSafe => .release_safe, + .ReleaseSmall => .release_small, + .ReleaseFast => .release_fast, + }, value); +} + +test "get version_string" { + const testing = std.testing; + var value: lib.String = undefined; + try testing.expectEqual(Result.success, get(.version_string, @ptrCast(&value))); + try testing.expect(value.len > 0); +} + +test "get version_major" { + const testing = std.testing; + var value: usize = undefined; + try testing.expectEqual(Result.success, get(.version_major, @ptrCast(&value))); + try testing.expectEqual(build_options.version_major, value); +} + +test "get version_minor" { + const testing = std.testing; + var value: usize = undefined; + try testing.expectEqual(Result.success, get(.version_minor, @ptrCast(&value))); + try testing.expectEqual(build_options.version_minor, value); +} + +test "get version_patch" { + const testing = std.testing; + var value: usize = undefined; + try testing.expectEqual(Result.success, get(.version_patch, @ptrCast(&value))); + try testing.expectEqual(build_options.version_patch, value); +} + +test "get version_build" { + const testing = std.testing; + var value: lib.String = undefined; + try testing.expectEqual(Result.success, get(.version_build, @ptrCast(&value))); +} + +test "get invalid" { + try std.testing.expectEqual(Result.invalid_value, get(.invalid, null)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/cell.zig b/vendor/libghostty-vt/src/terminal/c/cell.zig new file mode 100644 index 00000000..c9746da7 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/cell.zig @@ -0,0 +1,178 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const page = @import("../page.zig"); +const Cell = page.Cell; +const color = @import("../color.zig"); +const style_c = @import("style.zig"); +const Result = @import("result.zig").Result; + +/// C: GhosttyCell +pub const CCell = u64; + +/// C: GhosttyCellContentTag +pub const ContentTag = enum(c_int) { + codepoint = 0, + codepoint_grapheme = 1, + bg_color_palette = 2, + bg_color_rgb = 3, +}; + +/// C: GhosttyCellWide +pub const Wide = enum(c_int) { + narrow = 0, + wide = 1, + spacer_tail = 2, + spacer_head = 3, +}; + +/// C: GhosttyCellSemanticContent +pub const SemanticContent = enum(c_int) { + output = 0, + input = 1, + prompt = 2, +}; + +/// C: GhosttyCellData +pub const CellData = enum(c_int) { + invalid = 0, + + /// The codepoint of the cell (0 if empty or bg-color-only). + /// Output type: uint32_t * (stored as u21, zero-extended) + codepoint = 1, + + /// The content tag describing what kind of content is in the cell. + /// Output type: GhosttyCellContentTag * + content_tag = 2, + + /// The wide property of the cell. + /// Output type: GhosttyCellWide * + wide = 3, + + /// Whether the cell has text to render. + /// Output type: bool * + has_text = 4, + + /// Whether the cell has styling (non-default style). + /// Output type: bool * + has_styling = 5, + + /// The style ID for the cell (for use with style lookups). + /// Output type: uint16_t * + style_id = 6, + + /// Whether the cell has a hyperlink. + /// Output type: bool * + has_hyperlink = 7, + + /// Whether the cell is protected. + /// Output type: bool * + protected = 8, + + /// The semantic content type of the cell (from OSC 133). + /// Output type: GhosttyCellSemanticContent * + semantic_content = 9, + + /// The palette index for the cell's background color. + /// Only valid when content_tag is bg_color_palette. + /// Output type: GhosttyColorPaletteIndex * + color_palette = 10, + + /// The RGB value for the cell's background color. + /// Only valid when content_tag is bg_color_rgb. + /// Output type: GhosttyColorRgb * + color_rgb = 11, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: CellData) type { + return switch (self) { + .invalid => void, + .codepoint => u32, + .content_tag => ContentTag, + .wide => Wide, + .has_text, .has_styling, .has_hyperlink, .protected => bool, + .style_id => u16, + .semantic_content => SemanticContent, + .color_palette => u8, + .color_rgb => color.RGB.C, + }; + } +}; + +pub fn get( + cell_: CCell, + data: CellData, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(CellData, @intFromEnum(data)) catch { + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| getTyped( + cell_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn getTyped( + cell_: CCell, + comptime data: CellData, + out: *data.OutType(), +) Result { + const cell: Cell = @bitCast(cell_); + switch (data) { + .invalid => return .invalid_value, + .codepoint => out.* = @intCast(cell.codepoint()), + .content_tag => out.* = @enumFromInt(@intFromEnum(cell.content_tag)), + .wide => out.* = @enumFromInt(@intFromEnum(cell.wide)), + .has_text => out.* = cell.hasText(), + .has_styling => out.* = cell.hasStyling(), + .style_id => out.* = cell.style_id, + .has_hyperlink => out.* = cell.hyperlink, + .protected => out.* = cell.protected, + .semantic_content => out.* = @enumFromInt(@intFromEnum(cell.semantic_content)), + .color_palette => out.* = cell.content.color_palette, + .color_rgb => { + const rgb = cell.content.color_rgb; + out.* = .{ .r = rgb.r, .g = rgb.g, .b = rgb.b }; + }, + } + + return .success; +} + +test "get codepoint" { + const cell: CCell = @bitCast(Cell.init('A')); + var cp: u32 = 0; + try testing.expectEqual(Result.success, get(cell, .codepoint, @ptrCast(&cp))); + try testing.expectEqual(@as(u32, 'A'), cp); +} + +test "get has_text" { + const cell: CCell = @bitCast(Cell.init('A')); + var has: bool = false; + try testing.expectEqual(Result.success, get(cell, .has_text, @ptrCast(&has))); + try testing.expect(has); +} + +test "get empty cell" { + const cell: CCell = @bitCast(Cell.init(0)); + var has: bool = true; + try testing.expectEqual(Result.success, get(cell, .has_text, @ptrCast(&has))); + try testing.expect(!has); +} + +test "get wide" { + var zig_cell = Cell.init('A'); + zig_cell.wide = .wide; + const cell: CCell = @bitCast(zig_cell); + var w: Wide = .narrow; + try testing.expectEqual(Result.success, get(cell, .wide, @ptrCast(&w))); + try testing.expectEqual(Wide.wide, w); +} diff --git a/vendor/libghostty-vt/src/terminal/c/color.zig b/vendor/libghostty-vt/src/terminal/c/color.zig new file mode 100644 index 00000000..3d244a19 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/color.zig @@ -0,0 +1,13 @@ +const lib = @import("../lib.zig"); +const color = @import("../color.zig"); + +pub fn rgb_get( + c: color.RGB.C, + r: *u8, + g: *u8, + b: *u8, +) callconv(lib.calling_conv) void { + r.* = c.r; + g.* = c.g; + b.* = c.b; +} diff --git a/vendor/libghostty-vt/src/terminal/c/focus.zig b/vendor/libghostty-vt/src/terminal/c/focus.zig new file mode 100644 index 00000000..2c53191d --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/focus.zig @@ -0,0 +1,55 @@ +const std = @import("std"); +const lib = @import("../lib.zig"); +const terminal_focus = @import("../focus.zig"); +const Result = @import("result.zig").Result; + +pub fn encode( + event: terminal_focus.Event, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{}); + terminal_focus.encode(&writer, event) catch |err| switch (err) { + error.WriteFailed => { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + terminal_focus.encode(&discarding.writer, event) catch unreachable; + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + }; + + out_written.* = writer.end; + return .success; +} + +test "encode focus gained" { + var buf: [terminal_focus.max_encode_size]u8 = undefined; + var written: usize = 0; + const result = encode(.gained, &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[I", buf[0..written]); +} + +test "encode focus lost" { + var buf: [terminal_focus.max_encode_size]u8 = undefined; + var written: usize = 0; + const result = encode(.lost, &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[O", buf[0..written]); +} + +test "encode with insufficient buffer" { + var buf: [1]u8 = undefined; + var written: usize = 0; + const result = encode(.gained, &buf, buf.len, &written); + try std.testing.expectEqual(.out_of_space, result); + try std.testing.expectEqual(terminal_focus.max_encode_size, written); +} + +test "encode with null buffer" { + var written: usize = 0; + const result = encode(.gained, null, 0, &written); + try std.testing.expectEqual(.out_of_space, result); + try std.testing.expectEqual(terminal_focus.max_encode_size, written); +} diff --git a/vendor/libghostty-vt/src/terminal/c/formatter.zig b/vendor/libghostty-vt/src/terminal/c/formatter.zig new file mode 100644 index 00000000..11717bc2 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/formatter.zig @@ -0,0 +1,417 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const terminal_c = @import("terminal.zig"); +const ZigTerminal = @import("../Terminal.zig"); +const formatterpkg = @import("../formatter.zig"); +const Result = @import("result.zig").Result; + +/// Wrapper around formatter that tracks the allocator for C API usage. +const FormatterWrapper = struct { + kind: Kind, + alloc: std.mem.Allocator, + + const Kind = union(enum) { + terminal: formatterpkg.TerminalFormatter, + }; +}; + +/// C: GhosttyFormatter +pub const Formatter = ?*FormatterWrapper; + +/// C: GhosttyFormatterFormat +pub const Format = formatterpkg.Format; + +/// C: GhosttyFormatterScreenOptions +pub const ScreenOptions = extern struct { + /// C: GhosttyFormatterScreenExtra + pub const Extra = extern struct { + size: usize = @sizeOf(Extra), + cursor: bool, + style: bool, + hyperlink: bool, + protection: bool, + kitty_keyboard: bool, + charsets: bool, + + comptime { + for (std.meta.fieldNames(formatterpkg.ScreenFormatter.Extra)) |name| { + if (!@hasField(Extra, name)) + @compileError("ScreenOptions.Extra missing field: " ++ name); + } + } + + fn toZig(self: Extra) formatterpkg.ScreenFormatter.Extra { + return .{ + .cursor = self.cursor, + .style = self.style, + .hyperlink = self.hyperlink, + .protection = self.protection, + .kitty_keyboard = self.kitty_keyboard, + .charsets = self.charsets, + }; + } + }; +}; + +/// C: GhosttyFormatterTerminalOptions +pub const TerminalOptions = extern struct { + size: usize = @sizeOf(TerminalOptions), + emit: Format, + unwrap: bool, + trim: bool, + extra: Extra, + + /// C: GhosttyFormatterTerminalExtra + pub const Extra = extern struct { + size: usize = @sizeOf(Extra), + palette: bool, + modes: bool, + scrolling_region: bool, + tabstops: bool, + pwd: bool, + keyboard: bool, + screen: ScreenOptions.Extra, + + comptime { + for (std.meta.fieldNames(formatterpkg.TerminalFormatter.Extra)) |name| { + if (!@hasField(Extra, name)) + @compileError("TerminalOptions.Extra missing field: " ++ name); + } + } + + fn toZig(self: Extra) formatterpkg.TerminalFormatter.Extra { + return .{ + .palette = self.palette, + .modes = self.modes, + .scrolling_region = self.scrolling_region, + .tabstops = self.tabstops, + .pwd = self.pwd, + .keyboard = self.keyboard, + .screen = self.screen.toZig(), + }; + } + }; +}; + +pub fn terminal_new( + alloc_: ?*const CAllocator, + result: *Formatter, + terminal_: terminal_c.Terminal, + opts: TerminalOptions, +) callconv(lib.calling_conv) Result { + result.* = terminal_new_( + alloc_, + terminal_, + opts, + ) catch |err| { + result.* = null; + return switch (err) { + error.InvalidValue => .invalid_value, + error.OutOfMemory => .out_of_memory, + }; + }; + + return .success; +} + +fn terminal_new_( + alloc_: ?*const CAllocator, + terminal_: terminal_c.Terminal, + opts: TerminalOptions, +) error{ + InvalidValue, + OutOfMemory, +}!*FormatterWrapper { + const t: *ZigTerminal = (terminal_ orelse return error.InvalidValue).terminal; + + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(FormatterWrapper) catch + return error.OutOfMemory; + errdefer alloc.destroy(ptr); + + var formatter: formatterpkg.TerminalFormatter = .init(t, .{ + .emit = opts.emit, + .unwrap = opts.unwrap, + .trim = opts.trim, + }); + formatter.extra = opts.extra.toZig(); + + ptr.* = .{ + .kind = .{ .terminal = formatter }, + .alloc = alloc, + }; + + return ptr; +} + +pub fn format_buf( + formatter_: Formatter, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + const wrapper = formatter_ orelse return .invalid_value; + + var writer: std.Io.Writer = .fixed(if (out_) |out| + out[0..out_len] + else + &.{}); + + switch (wrapper.kind) { + .terminal => |*t| t.format(&writer) catch |err| switch (err) { + error.WriteFailed => { + // On write failed we always report how much + // space we actually needed. + var discarding: std.Io.Writer.Discarding = .init(&.{}); + t.format(&discarding.writer) catch unreachable; + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + }, + } + + out_written.* = writer.end; + return .success; +} + +pub fn format_alloc( + formatter_: Formatter, + alloc_: ?*const CAllocator, + out_ptr: *?[*]u8, + out_len: *usize, +) callconv(lib.calling_conv) Result { + const wrapper = formatter_ orelse return .invalid_value; + const alloc = lib.alloc.default(alloc_); + + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + + switch (wrapper.kind) { + .terminal => |*t| t.format(&aw.writer) catch return .out_of_memory, + } + + const buf = aw.toOwnedSlice() catch return .out_of_memory; + out_ptr.* = buf.ptr; + out_len.* = buf.len; + return .success; +} + +pub fn free(formatter_: Formatter) callconv(lib.calling_conv) void { + const wrapper = formatter_ orelse return; + const alloc = wrapper.alloc; + alloc.destroy(wrapper); +} + +test "terminal_new/free" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + try testing.expect(f != null); + free(f); +} + +test "terminal_new invalid_value on null terminal" { + var f: Formatter = null; + try testing.expectEqual(Result.invalid_value, terminal_new( + &lib.alloc.test_allocator, + &f, + null, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + try testing.expect(f == null); +} + +test "free null" { + free(null); +} + +test "format plain" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Hello", 5); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + var buf: [1024]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, format_buf(f, &buf, buf.len, &written)); + try testing.expectEqualStrings("Hello", buf[0..written]); +} + +test "format reflects terminal changes" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Hello", 5); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + var buf: [1024]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, format_buf(f, &buf, buf.len, &written)); + try testing.expectEqualStrings("Hello", buf[0..written]); + + // Write more data and re-format + terminal_c.vt_write(t, "\r\nWorld", 7); + + try testing.expectEqual(Result.success, format_buf(f, &buf, buf.len, &written)); + try testing.expectEqualStrings("Hello\nWorld", buf[0..written]); +} + +test "format null returns required size" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Hello", 5); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + // Pass null buffer to query required size + var required: usize = 0; + try testing.expectEqual(Result.out_of_space, format_buf(f, null, 0, &required)); + try testing.expect(required > 0); + + // Now allocate and format + var buf: [1024]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, format_buf(f, &buf, buf.len, &written)); + try testing.expectEqual(required, written); +} + +test "format buffer too small" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Hello", 5); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .plain, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + // Buffer too small + var buf: [2]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.out_of_space, format_buf(f, &buf, buf.len, &written)); + // written contains the required size + try testing.expectEqual(@as(usize, 5), written); +} + +test "format null formatter" { + var written: usize = 0; + try testing.expectEqual(Result.invalid_value, format_buf(null, null, 0, &written)); +} + +test "format vt" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Test", 4); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .vt, .unwrap = false, .trim = true, .extra = .{ .palette = true, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = true, .hyperlink = true, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + var buf: [65536]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, format_buf(f, &buf, buf.len, &written)); + try testing.expect(written > 0); + try testing.expect(std.mem.indexOf(u8, buf[0..written], "Test") != null); +} + +test "format html" { + var t: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 10_000 }, + )); + defer terminal_c.free(t); + + terminal_c.vt_write(t, "Html", 4); + + var f: Formatter = null; + try testing.expectEqual(Result.success, terminal_new( + &lib.alloc.test_allocator, + &f, + t, + .{ .emit = .html, .unwrap = false, .trim = true, .extra = .{ .palette = false, .modes = false, .scrolling_region = false, .tabstops = false, .pwd = false, .keyboard = false, .screen = .{ .cursor = false, .style = false, .hyperlink = false, .protection = false, .kitty_keyboard = false, .charsets = false } } }, + )); + defer free(f); + + var buf: [65536]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, format_buf(f, &buf, buf.len, &written)); + try testing.expect(written > 0); + try testing.expect(std.mem.indexOf(u8, buf[0..written], "Html") != null); +} diff --git a/vendor/libghostty-vt/src/terminal/c/grid_ref.zig b/vendor/libghostty-vt/src/terminal/c/grid_ref.zig new file mode 100644 index 00000000..d029c595 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/grid_ref.zig @@ -0,0 +1,156 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const page = @import("../page.zig"); +const PageList = @import("../PageList.zig"); +const size = @import("../size.zig"); +const stylepkg = @import("../style.zig"); +const cell_c = @import("cell.zig"); +const row_c = @import("row.zig"); +const style_c = @import("style.zig"); +const Result = @import("result.zig").Result; + +/// C: GhosttyGridRef +/// +/// A sized struct that holds a reference to a position in the terminal grid. +/// The ref points to a specific cell position within the terminal's +/// internal page structure. +pub const CGridRef = extern struct { + size: usize = @sizeOf(CGridRef), + node: ?*PageList.List.Node = null, + x: size.CellCountInt = 0, + y: size.CellCountInt = 0, + + pub fn fromPin(pin: PageList.Pin) CGridRef { + return .{ + .node = pin.node, + .x = pin.x, + .y = pin.y, + }; + } + + fn toPin(self: CGridRef) ?PageList.Pin { + return .{ + .node = self.node orelse return null, + .x = self.x, + .y = self.y, + }; + } +}; + +pub fn grid_ref_cell( + ref: *const CGridRef, + out: ?*cell_c.CCell, +) callconv(lib.calling_conv) Result { + const p = ref.toPin() orelse return .invalid_value; + if (out) |o| o.* = @bitCast(p.rowAndCell().cell.*); + return .success; +} + +pub fn grid_ref_row( + ref: *const CGridRef, + out: ?*row_c.CRow, +) callconv(lib.calling_conv) Result { + const p = ref.toPin() orelse return .invalid_value; + if (out) |o| o.* = @bitCast(p.rowAndCell().row.*); + return .success; +} + +pub fn grid_ref_graphemes( + ref: *const CGridRef, + out_buf: ?[*]u32, + buf_len: usize, + out_len: *usize, +) callconv(lib.calling_conv) Result { + const p = ref.toPin() orelse return .invalid_value; + const cell = p.rowAndCell().cell; + + if (!cell.hasText()) { + out_len.* = 0; + return .success; + } + + const cp = cell.codepoint(); + const extra = if (cell.hasGrapheme()) p.grapheme(cell) else null; + const total = 1 + if (extra) |e| e.len else 0; + + if (out_buf == null or buf_len < total) { + out_len.* = total; + return .out_of_space; + } + + const buf = out_buf.?[0..buf_len]; + buf[0] = cp; + if (extra) |e| for (e, 1..) |c, i| { + buf[i] = c; + }; + + out_len.* = total; + return .success; +} + +pub fn grid_ref_style( + ref: *const CGridRef, + out: ?*style_c.Style, +) callconv(lib.calling_conv) Result { + const p = ref.toPin() orelse return .invalid_value; + if (out) |o| { + const cell = p.rowAndCell().cell; + if (cell.style_id == stylepkg.default_id) { + o.* = .fromStyle(.{}); + } else { + o.* = .fromStyle(p.node.data.styles.get( + p.node.data.memory, + cell.style_id, + ).*); + } + } + return .success; +} + +test "grid_ref_cell null node" { + const ref = CGridRef{}; + var out: cell_c.CCell = undefined; + try testing.expectEqual(Result.invalid_value, grid_ref_cell(&ref, &out)); +} + +test "grid_ref_row null node" { + const ref = CGridRef{}; + var out: row_c.CRow = undefined; + try testing.expectEqual(Result.invalid_value, grid_ref_row(&ref, &out)); +} + +test "grid_ref_cell null out" { + const ref = CGridRef{}; + try testing.expectEqual(Result.invalid_value, grid_ref_cell(&ref, null)); +} + +test "grid_ref_row null out" { + const ref = CGridRef{}; + try testing.expectEqual(Result.invalid_value, grid_ref_row(&ref, null)); +} + +test "grid_ref_graphemes null node" { + const ref = CGridRef{}; + var len: usize = undefined; + try testing.expectEqual(Result.invalid_value, grid_ref_graphemes(&ref, null, 0, &len)); +} + +test "grid_ref_graphemes null buf returns out_of_space" { + const ref = CGridRef{}; + var len: usize = undefined; + // With null node this returns invalid_value before checking the buffer, + // so we can only test null node here. Full buffer tests require a real page. + try testing.expectEqual(Result.invalid_value, grid_ref_graphemes(&ref, null, 0, &len)); +} + +test "grid_ref_style null node" { + const ref = CGridRef{}; + var out: style_c.Style = undefined; + try testing.expectEqual(Result.invalid_value, grid_ref_style(&ref, &out)); +} + +test "grid_ref_style null out" { + const ref = CGridRef{}; + try testing.expectEqual(Result.invalid_value, grid_ref_style(&ref, null)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/key_encode.zig b/vendor/libghostty-vt/src/terminal/c/key_encode.zig new file mode 100644 index 00000000..15fa74dd --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/key_encode.zig @@ -0,0 +1,356 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const key_encode = @import("../../input/key_encode.zig"); +const key_event = @import("key_event.zig"); +const KittyFlags = @import("../../terminal/kitty/key.zig").Flags; +const OptionAsAlt = @import("../../input/config.zig").OptionAsAlt; +const Result = @import("result.zig").Result; +const KeyEvent = @import("key_event.zig").Event; +const Terminal = @import("terminal.zig").Terminal; +const ZigTerminal = @import("../Terminal.zig"); + +const log = std.log.scoped(.key_encode); + +/// Wrapper around key encoding options that tracks the allocator for C API usage. +const KeyEncoderWrapper = struct { + opts: key_encode.Options, + alloc: Allocator, +}; + +/// C: GhosttyKeyEncoder +pub const Encoder = ?*KeyEncoderWrapper; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Encoder, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(KeyEncoderWrapper) catch + return .out_of_memory; + ptr.* = .{ + .opts = .{}, + .alloc = alloc, + }; + result.* = ptr; + return .success; +} + +pub fn free(encoder_: Encoder) callconv(lib.calling_conv) void { + const wrapper = encoder_ orelse return; + const alloc = wrapper.alloc; + alloc.destroy(wrapper); +} + +/// C: GhosttyKeyEncoderOption +pub const Option = enum(c_int) { + cursor_key_application = 0, + keypad_key_application = 1, + ignore_keypad_with_numlock = 2, + alt_esc_prefix = 3, + modify_other_keys_state_2 = 4, + kitty_flags = 5, + macos_option_as_alt = 6, + + /// Input type expected for setting the option. + pub fn InType(comptime self: Option) type { + return switch (self) { + .cursor_key_application, + .keypad_key_application, + .ignore_keypad_with_numlock, + .alt_esc_prefix, + .modify_other_keys_state_2, + => bool, + .kitty_flags => u8, + .macos_option_as_alt => OptionAsAlt, + }; + } +}; + +pub fn setopt( + encoder_: Encoder, + option: Option, + value: ?*const anyopaque, +) callconv(lib.calling_conv) void { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + log.warn("setopt invalid option value={d}", .{@intFromEnum(option)}); + return; + }; + } + + return switch (option) { + inline else => |comptime_option| setoptTyped( + encoder_, + comptime_option, + @ptrCast(@alignCast(value orelse return)), + ), + }; +} + +fn setoptTyped( + encoder_: Encoder, + comptime option: Option, + value: *const option.InType(), +) void { + const opts = &encoder_.?.opts; + switch (option) { + .cursor_key_application => opts.cursor_key_application = value.*, + .keypad_key_application => opts.keypad_key_application = value.*, + .ignore_keypad_with_numlock => opts.ignore_keypad_with_numlock = value.*, + .alt_esc_prefix => opts.alt_esc_prefix = value.*, + .modify_other_keys_state_2 => opts.modify_other_keys_state_2 = value.*, + .kitty_flags => opts.kitty_flags = flags: { + const bits: u5 = @truncate(value.*); + break :flags @bitCast(bits); + }, + .macos_option_as_alt => { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(OptionAsAlt, @intFromEnum(value.*)) catch { + log.warn("setopt invalid OptionAsAlt value={d}", .{@intFromEnum(value.*)}); + return; + }; + } + opts.macos_option_as_alt = value.*; + }, + } +} + +pub fn setopt_from_terminal( + encoder_: Encoder, + terminal_: Terminal, +) callconv(lib.calling_conv) void { + const wrapper = encoder_ orelse return; + const t: *ZigTerminal = (terminal_ orelse return).terminal; + wrapper.opts = .fromTerminal(t); +} + +pub fn encode( + encoder_: Encoder, + event_: KeyEvent, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + // Attempt to write to this buffer + var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{}); + key_encode.encode( + &writer, + event_.?.event, + encoder_.?.opts, + ) catch |err| switch (err) { + error.WriteFailed => { + // If we don't have space, use a discarding writer to count + // how much space we would have needed. + var discarding: std.Io.Writer.Discarding = .init(&.{}); + key_encode.encode( + &discarding.writer, + event_.?.event, + encoder_.?.opts, + ) catch unreachable; + + // Discarding always uses a u64. If we're on 32-bit systems + // we cast down. We should make this safer in the future. + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + }; + + out_written.* = writer.end; + return .success; +} + +test "alloc" { + const testing = std.testing; + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + free(e); +} + +test "setopt bool" { + const testing = std.testing; + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Test setting bool options + const val_true: bool = true; + setopt(e, .cursor_key_application, &val_true); + try testing.expect(e.?.opts.cursor_key_application); + + const val_false: bool = false; + setopt(e, .cursor_key_application, &val_false); + try testing.expect(!e.?.opts.cursor_key_application); + + setopt(e, .keypad_key_application, &val_true); + try testing.expect(e.?.opts.keypad_key_application); +} + +test "setopt kitty flags" { + const testing = std.testing; + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Test setting kitty flags + const flags: KittyFlags = .{ + .disambiguate = true, + .report_events = true, + }; + const flags_int: u8 = @intCast(flags.int()); + setopt(e, .kitty_flags, &flags_int); + try testing.expect(e.?.opts.kitty_flags.disambiguate); + try testing.expect(e.?.opts.kitty_flags.report_events); + try testing.expect(!e.?.opts.kitty_flags.report_alternates); +} + +test "setopt macos option as alt" { + const testing = std.testing; + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Test setting option as alt + const opt_left: OptionAsAlt = .left; + setopt(e, .macos_option_as_alt, &opt_left); + try testing.expectEqual(OptionAsAlt.left, e.?.opts.macos_option_as_alt); + + const opt_true: OptionAsAlt = .true; + setopt(e, .macos_option_as_alt, &opt_true); + try testing.expectEqual(OptionAsAlt.true, e.?.opts.macos_option_as_alt); +} + +test "setopt_from_terminal" { + const testing = std.testing; + const terminal_c = @import("terminal.zig"); + + // Create encoder + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Create terminal + var t: Terminal = undefined; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + )); + defer terminal_c.free(t); + + // Apply terminal state to encoder + setopt_from_terminal(e, t); + + // Options should reflect defaults from a fresh terminal + try testing.expect(!e.?.opts.cursor_key_application); + try testing.expect(e.?.opts.alt_esc_prefix); + try testing.expectEqual(KittyFlags.disabled, e.?.opts.kitty_flags); + try testing.expectEqual(OptionAsAlt.false, e.?.opts.macos_option_as_alt); +} + +test "setopt_from_terminal null" { + // Both null should be no-ops + setopt_from_terminal(null, null); + + const testing = std.testing; + + // Encoder null with valid terminal + const terminal_c = @import("terminal.zig"); + var t: Terminal = undefined; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + )); + defer terminal_c.free(t); + setopt_from_terminal(null, t); + + // Valid encoder with null terminal + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + setopt_from_terminal(e, null); +} + +test "encode: kitty ctrl release with ctrl mod set" { + const testing = std.testing; + + // Create encoder + var encoder: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &encoder, + )); + defer free(encoder); + + // Set kitty flags with all features enabled + { + const flags: KittyFlags = .{ + .disambiguate = true, + .report_events = true, + .report_alternates = true, + .report_all = true, + .report_associated = true, + }; + const flags_int: u8 = @intCast(flags.int()); + setopt(encoder, .kitty_flags, &flags_int); + } + + // Create key event + var event: key_event.Event = undefined; + try testing.expectEqual(Result.success, key_event.new( + &lib.alloc.test_allocator, + &event, + )); + defer key_event.free(event); + + // Set event properties: release action, ctrl key, ctrl modifier + key_event.set_action(event, .release); + key_event.set_key(event, .control_left); + key_event.set_mods(event, .{ .ctrl = true }); + + // Encode null should give us the length required + var required: usize = 0; + try testing.expectEqual(Result.out_of_space, encode( + encoder, + event, + null, + 0, + &required, + )); + + // Encode the key event + var buf: [128]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, encode( + encoder, + event, + &buf, + buf.len, + &written, + )); + try testing.expectEqual(required, written); + + // Expected: ESC[57442;5:3u (ctrl key code with mods and release event) + const actual = buf[0..written]; + try testing.expectEqualStrings("\x1b[57442;5:3u", actual); +} diff --git a/vendor/libghostty-vt/src/terminal/c/key_event.zig b/vendor/libghostty-vt/src/terminal/c/key_event.zig new file mode 100644 index 00000000..1feac9ac --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/key_event.zig @@ -0,0 +1,268 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const key = @import("../../input/key.zig"); +const Result = @import("result.zig").Result; + +const log = std.log.scoped(.key_event); + +/// Wrapper around KeyEvent that tracks the allocator for C API usage. +/// The UTF-8 text is not owned by this wrapper - the caller is responsible +/// for ensuring the lifetime of any UTF-8 text set via set_utf8. +const KeyEventWrapper = struct { + event: key.KeyEvent = .{}, + alloc: Allocator, +}; + +/// C: GhosttyKeyEvent +pub const Event = ?*KeyEventWrapper; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Event, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(KeyEventWrapper) catch + return .out_of_memory; + ptr.* = .{ .alloc = alloc }; + result.* = ptr; + return .success; +} + +pub fn free(event_: Event) callconv(lib.calling_conv) void { + const wrapper = event_ orelse return; + const alloc = wrapper.alloc; + alloc.destroy(wrapper); +} + +pub fn set_action(event_: Event, action: key.Action) callconv(lib.calling_conv) void { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(key.Action, @intFromEnum(action)) catch { + log.warn("set_action invalid action value={d}", .{@intFromEnum(action)}); + return; + }; + } + + const event: *key.KeyEvent = &event_.?.event; + event.action = action; +} + +pub fn get_action(event_: Event) callconv(lib.calling_conv) key.Action { + const event: *key.KeyEvent = &event_.?.event; + return event.action; +} + +pub fn set_key(event_: Event, k: key.Key) callconv(lib.calling_conv) void { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(key.Key, @intFromEnum(k)) catch { + log.warn("set_key invalid key value={d}", .{@intFromEnum(k)}); + return; + }; + } + + const event: *key.KeyEvent = &event_.?.event; + event.key = k; +} + +pub fn get_key(event_: Event) callconv(lib.calling_conv) key.Key { + const event: *key.KeyEvent = &event_.?.event; + return event.key; +} + +pub fn set_mods(event_: Event, mods: key.Mods) callconv(lib.calling_conv) void { + const event: *key.KeyEvent = &event_.?.event; + event.mods = mods; +} + +pub fn get_mods(event_: Event) callconv(lib.calling_conv) key.Mods { + const event: *key.KeyEvent = &event_.?.event; + return event.mods; +} + +pub fn set_consumed_mods(event_: Event, consumed_mods: key.Mods) callconv(lib.calling_conv) void { + const event: *key.KeyEvent = &event_.?.event; + event.consumed_mods = consumed_mods; +} + +pub fn get_consumed_mods(event_: Event) callconv(lib.calling_conv) key.Mods { + const event: *key.KeyEvent = &event_.?.event; + return event.consumed_mods; +} + +pub fn set_composing(event_: Event, composing: bool) callconv(lib.calling_conv) void { + const event: *key.KeyEvent = &event_.?.event; + event.composing = composing; +} + +pub fn get_composing(event_: Event) callconv(lib.calling_conv) bool { + const event: *key.KeyEvent = &event_.?.event; + return event.composing; +} + +pub fn set_utf8(event_: Event, utf8: ?[*]const u8, len: usize) callconv(lib.calling_conv) void { + const event: *key.KeyEvent = &event_.?.event; + event.utf8 = if (utf8) |ptr| ptr[0..len] else ""; +} + +pub fn get_utf8(event_: Event, len: ?*usize) callconv(lib.calling_conv) ?[*]const u8 { + const event: *key.KeyEvent = &event_.?.event; + if (len) |l| l.* = event.utf8.len; + return if (event.utf8.len == 0) null else event.utf8.ptr; +} + +pub fn set_unshifted_codepoint(event_: Event, codepoint: u32) callconv(lib.calling_conv) void { + const event: *key.KeyEvent = &event_.?.event; + event.unshifted_codepoint = @truncate(codepoint); +} + +pub fn get_unshifted_codepoint(event_: Event) callconv(lib.calling_conv) u32 { + const event: *key.KeyEvent = &event_.?.event; + return event.unshifted_codepoint; +} + +test "alloc" { + const testing = std.testing; + var e: Event = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + free(e); +} + +test "set" { + const testing = std.testing; + var e: Event = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Test action + set_action(e, .press); + try testing.expectEqual(key.Action.press, e.?.event.action); + + // Test key + set_key(e, .key_a); + try testing.expectEqual(key.Key.key_a, e.?.event.key); + + // Test mods + const mods: key.Mods = .{ .shift = true, .ctrl = true }; + set_mods(e, mods); + try testing.expect(e.?.event.mods.shift); + try testing.expect(e.?.event.mods.ctrl); + + // Test consumed mods + const consumed: key.Mods = .{ .shift = true }; + set_consumed_mods(e, consumed); + try testing.expect(e.?.event.consumed_mods.shift); + try testing.expect(!e.?.event.consumed_mods.ctrl); + + // Test composing + set_composing(e, true); + try testing.expect(e.?.event.composing); + + // Test UTF-8 + const text = "hello"; + set_utf8(e, text.ptr, text.len); + try testing.expectEqualStrings(text, e.?.event.utf8); + + // Test UTF-8 null + set_utf8(e, null, 0); + try testing.expectEqualStrings("", e.?.event.utf8); + + // Test unshifted codepoint + set_unshifted_codepoint(e, 'a'); + try testing.expectEqual(@as(u21, 'a'), e.?.event.unshifted_codepoint); +} + +test "get" { + const testing = std.testing; + var e: Event = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Set some values + set_action(e, .repeat); + set_key(e, .key_z); + + const mods: key.Mods = .{ .alt = true, .super = true }; + set_mods(e, mods); + + const consumed: key.Mods = .{ .alt = true }; + set_consumed_mods(e, consumed); + + set_composing(e, true); + + const text = "test"; + set_utf8(e, text.ptr, text.len); + + set_unshifted_codepoint(e, 'z'); + + // Get them back + try testing.expectEqual(key.Action.repeat, get_action(e)); + try testing.expectEqual(key.Key.key_z, get_key(e)); + + const got_mods = get_mods(e); + try testing.expect(got_mods.alt); + try testing.expect(got_mods.super); + + const got_consumed = get_consumed_mods(e); + try testing.expect(got_consumed.alt); + try testing.expect(!got_consumed.super); + + try testing.expect(get_composing(e)); + + var utf8_len: usize = undefined; + const got_utf8 = get_utf8(e, &utf8_len); + try testing.expect(got_utf8 != null); + try testing.expectEqual(@as(usize, 4), utf8_len); + try testing.expectEqualStrings("test", got_utf8.?[0..utf8_len]); + + try testing.expectEqual(@as(u32, 'z'), get_unshifted_codepoint(e)); +} + +test "complete key event" { + const testing = std.testing; + var e: Event = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Build a complete key event for shift+a + set_action(e, .press); + set_key(e, .key_a); + + const mods: key.Mods = .{ .shift = true }; + set_mods(e, mods); + + const consumed: key.Mods = .{ .shift = true }; + set_consumed_mods(e, consumed); + + const text = "A"; + set_utf8(e, text.ptr, text.len); + + set_unshifted_codepoint(e, 'a'); + + // Verify all fields + try testing.expectEqual(key.Action.press, e.?.event.action); + try testing.expectEqual(key.Key.key_a, e.?.event.key); + try testing.expect(e.?.event.mods.shift); + try testing.expect(e.?.event.consumed_mods.shift); + try testing.expectEqualStrings("A", e.?.event.utf8); + try testing.expectEqual(@as(u21, 'a'), e.?.event.unshifted_codepoint); + + // Also test the getter + var utf8_len: usize = undefined; + const got_utf8 = get_utf8(e, &utf8_len); + try testing.expect(got_utf8 != null); + try testing.expectEqual(@as(usize, 1), utf8_len); + try testing.expectEqualStrings("A", got_utf8.?[0..utf8_len]); +} diff --git a/vendor/libghostty-vt/src/terminal/c/main.zig b/vendor/libghostty-vt/src/terminal/c/main.zig new file mode 100644 index 00000000..17056779 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/main.zig @@ -0,0 +1,178 @@ +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; + +const buildpkg = @import("build_info.zig"); +pub const allocator = @import("allocator.zig"); +pub const cell = @import("cell.zig"); +pub const color = @import("color.zig"); +pub const focus = @import("focus.zig"); +pub const formatter = @import("formatter.zig"); +pub const grid_ref = @import("grid_ref.zig"); +pub const types = @import("types.zig"); +pub const modes = @import("modes.zig"); +pub const osc = @import("osc.zig"); +pub const render = @import("render.zig"); +pub const key_event = @import("key_event.zig"); +pub const key_encode = @import("key_encode.zig"); +pub const mouse_event = @import("mouse_event.zig"); +pub const mouse_encode = @import("mouse_encode.zig"); +pub const paste = @import("paste.zig"); +pub const row = @import("row.zig"); +pub const sgr = @import("sgr.zig"); +pub const size_report = @import("size_report.zig"); +pub const style = @import("style.zig"); +pub const terminal = @import("terminal.zig"); + +// The full C API, unexported. +pub const build_info = buildpkg.get; + +pub const osc_new = osc.new; +pub const osc_free = osc.free; +pub const osc_reset = osc.reset; +pub const osc_next = osc.next; +pub const osc_end = osc.end; +pub const osc_command_type = osc.commandType; +pub const osc_command_data = osc.commandData; + +pub const color_rgb_get = color.rgb_get; + +pub const focus_encode = focus.encode; + +pub const mode_report_encode = modes.report_encode; + +pub const formatter_terminal_new = formatter.terminal_new; +pub const formatter_format_buf = formatter.format_buf; +pub const formatter_format_alloc = formatter.format_alloc; +pub const formatter_free = formatter.free; + +pub const render_state_new = render.new; +pub const render_state_free = render.free; +pub const render_state_update = render.update; +pub const render_state_get = render.get; +pub const render_state_set = render.set; +pub const render_state_colors_get = render.colors_get; +pub const render_state_row_iterator_new = render.row_iterator_new; +pub const render_state_row_iterator_next = render.row_iterator_next; +pub const render_state_row_get = render.row_get; +pub const render_state_row_set = render.row_set; +pub const render_state_row_iterator_free = render.row_iterator_free; +pub const render_state_row_cells_new = render.row_cells_new; +pub const render_state_row_cells_next = render.row_cells_next; +pub const render_state_row_cells_select = render.row_cells_select; +pub const render_state_row_cells_get = render.row_cells_get; +pub const render_state_row_cells_free = render.row_cells_free; + +pub const sgr_new = sgr.new; +pub const sgr_free = sgr.free; +pub const sgr_reset = sgr.reset; +pub const sgr_set_params = sgr.setParams; +pub const sgr_next = sgr.next; +pub const sgr_unknown_full = sgr.unknown_full; +pub const sgr_unknown_partial = sgr.unknown_partial; +pub const sgr_attribute_tag = sgr.attribute_tag; +pub const sgr_attribute_value = sgr.attribute_value; +pub const wasm_alloc_sgr_attribute = sgr.wasm_alloc_attribute; +pub const wasm_free_sgr_attribute = sgr.wasm_free_attribute; + +pub const key_event_new = key_event.new; +pub const key_event_free = key_event.free; +pub const key_event_set_action = key_event.set_action; +pub const key_event_get_action = key_event.get_action; +pub const key_event_set_key = key_event.set_key; +pub const key_event_get_key = key_event.get_key; +pub const key_event_set_mods = key_event.set_mods; +pub const key_event_get_mods = key_event.get_mods; +pub const key_event_set_consumed_mods = key_event.set_consumed_mods; +pub const key_event_get_consumed_mods = key_event.get_consumed_mods; +pub const key_event_set_composing = key_event.set_composing; +pub const key_event_get_composing = key_event.get_composing; +pub const key_event_set_utf8 = key_event.set_utf8; +pub const key_event_get_utf8 = key_event.get_utf8; +pub const key_event_set_unshifted_codepoint = key_event.set_unshifted_codepoint; +pub const key_event_get_unshifted_codepoint = key_event.get_unshifted_codepoint; + +pub const key_encoder_new = key_encode.new; +pub const key_encoder_free = key_encode.free; +pub const key_encoder_setopt = key_encode.setopt; +pub const key_encoder_setopt_from_terminal = key_encode.setopt_from_terminal; +pub const key_encoder_encode = key_encode.encode; + +pub const mouse_event_new = mouse_event.new; +pub const mouse_event_free = mouse_event.free; +pub const mouse_event_set_action = mouse_event.set_action; +pub const mouse_event_get_action = mouse_event.get_action; +pub const mouse_event_set_button = mouse_event.set_button; +pub const mouse_event_clear_button = mouse_event.clear_button; +pub const mouse_event_get_button = mouse_event.get_button; +pub const mouse_event_set_mods = mouse_event.set_mods; +pub const mouse_event_get_mods = mouse_event.get_mods; +pub const mouse_event_set_position = mouse_event.set_position; +pub const mouse_event_get_position = mouse_event.get_position; + +pub const mouse_encoder_new = mouse_encode.new; +pub const mouse_encoder_free = mouse_encode.free; +pub const mouse_encoder_setopt = mouse_encode.setopt; +pub const mouse_encoder_setopt_from_terminal = mouse_encode.setopt_from_terminal; +pub const mouse_encoder_reset = mouse_encode.reset; +pub const mouse_encoder_encode = mouse_encode.encode; + +pub const paste_is_safe = paste.is_safe; +pub const paste_encode = paste.encode; + +pub const alloc_alloc = allocator.alloc; +pub const alloc_free = allocator.free; + +pub const size_report_encode = size_report.encode; + +pub const cell_get = cell.get; + +pub const row_get = row.get; + +pub const style_default = style.default_style; +pub const style_is_default = style.style_is_default; + +pub const terminal_new = terminal.new; +pub const terminal_free = terminal.free; +pub const terminal_reset = terminal.reset; +pub const terminal_resize = terminal.resize; +pub const terminal_set = terminal.set; +pub const terminal_vt_write = terminal.vt_write; +pub const terminal_scroll_viewport = terminal.scroll_viewport; +pub const terminal_mode_get = terminal.mode_get; +pub const terminal_mode_set = terminal.mode_set; +pub const terminal_get = terminal.get; +pub const terminal_grid_ref = terminal.grid_ref; + +pub const type_json = types.get_json; + +pub const grid_ref_cell = grid_ref.grid_ref_cell; +pub const grid_ref_row = grid_ref.grid_ref_row; +pub const grid_ref_graphemes = grid_ref.grid_ref_graphemes; +pub const grid_ref_style = grid_ref.grid_ref_style; + +test { + _ = allocator; + _ = buildpkg; + _ = cell; + _ = color; + _ = grid_ref; + _ = row; + _ = focus; + _ = formatter; + _ = modes; + _ = osc; + _ = render; + _ = key_event; + _ = key_encode; + _ = mouse_event; + _ = mouse_encode; + _ = paste; + _ = sgr; + _ = size_report; + _ = style; + _ = terminal; + _ = types; + + // We want to make sure we run the tests for the C allocator interface. + _ = @import("../../lib/allocator.zig"); +} diff --git a/vendor/libghostty-vt/src/terminal/c/modes.zig b/vendor/libghostty-vt/src/terminal/c/modes.zig new file mode 100644 index 00000000..449ce63e --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/modes.zig @@ -0,0 +1,104 @@ +const std = @import("std"); +const lib = @import("../lib.zig"); +const modes = @import("../modes.zig"); +const Result = @import("result.zig").Result; + +/// C: GhosttyModeReportState +pub const ReportState = enum(c_int) { + _, + + fn toZig(self: ReportState) ?modes.Report.State { + return std.meta.intToEnum( + modes.Report.State, + @intFromEnum(self), + ) catch null; + } +}; + +pub fn report_encode( + tag: modes.ModeTag.Backing, + state: ReportState, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + const mode_tag: modes.ModeTag = @bitCast(tag); + const report: modes.Report = .{ + .tag = mode_tag, + .state = state.toZig() orelse return .invalid_value, + }; + + var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{}); + report.encode(&writer) catch |err| switch (err) { + error.WriteFailed => { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + report.encode(&discarding.writer) catch unreachable; + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + }; + + out_written.* = writer.end; + return .success; +} + +test "encode DEC mode set" { + var buf: [modes.Report.max_size]u8 = undefined; + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1, .ansi = false }); + const result = report_encode(tag, @enumFromInt(1), &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[?1;1$y", buf[0..written]); +} + +test "encode DEC mode reset" { + var buf: [modes.Report.max_size]u8 = undefined; + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1, .ansi = false }); + const result = report_encode(tag, @enumFromInt(2), &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[?1;2$y", buf[0..written]); +} + +test "encode ANSI mode" { + var buf: [modes.Report.max_size]u8 = undefined; + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 4, .ansi = true }); + const result = report_encode(tag, @enumFromInt(1), &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[4;1$y", buf[0..written]); +} + +test "encode not recognized" { + var buf: [modes.Report.max_size]u8 = undefined; + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }); + const result = report_encode(tag, @enumFromInt(0), &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[?9999;0$y", buf[0..written]); +} + +test "encode with insufficient buffer" { + var buf: [1]u8 = undefined; + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1, .ansi = false }); + const result = report_encode(tag, @enumFromInt(1), &buf, buf.len, &written); + try std.testing.expectEqual(.out_of_space, result); + try std.testing.expect(written > 1); +} + +test "encode with invalid state" { + var buf: [modes.Report.max_size]u8 = undefined; + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1, .ansi = false }); + const result = report_encode(tag, @enumFromInt(99), &buf, buf.len, &written); + try std.testing.expectEqual(.invalid_value, result); +} + +test "encode with null buffer" { + var written: usize = 0; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1, .ansi = false }); + const result = report_encode(tag, @enumFromInt(1), null, 0, &written); + try std.testing.expectEqual(.out_of_space, result); + try std.testing.expect(written > 0); +} diff --git a/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig b/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig new file mode 100644 index 00000000..331dd606 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/mouse_encode.zig @@ -0,0 +1,530 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const input_mouse_encode = @import("../../input/mouse_encode.zig"); +const renderer_size = @import("../../renderer/size.zig"); +const point = @import("../point.zig"); +const terminal_mouse = @import("../mouse.zig"); +const mouse_event = @import("mouse_event.zig"); +const Result = @import("result.zig").Result; +const Event = mouse_event.Event; +const Terminal = @import("terminal.zig").Terminal; +const ZigTerminal = @import("../Terminal.zig"); + +const log = std.log.scoped(.mouse_encode); + +/// Wrapper around mouse encoding options that tracks the allocator for C API usage. +const MouseEncoderWrapper = struct { + opts: input_mouse_encode.Options, + track_last_cell: bool = false, + last_cell: ?point.Coordinate = null, + alloc: Allocator, +}; + +/// C: GhosttyMouseEncoder +pub const Encoder = ?*MouseEncoderWrapper; + +/// C: GhosttyMouseTrackingMode +pub const TrackingMode = terminal_mouse.Event; + +/// C: GhosttyMouseFormat +pub const Format = terminal_mouse.Format; + +/// C: GhosttyMouseEncoderSize +pub const Size = extern struct { + size: usize = @sizeOf(Size), + screen_width: u32, + screen_height: u32, + cell_width: u32, + cell_height: u32, + padding_top: u32, + padding_bottom: u32, + padding_right: u32, + padding_left: u32, + + fn toRenderer(self: Size) ?renderer_size.Size { + if (self.cell_width == 0 or self.cell_height == 0) return null; + return .{ + .screen = .{ + .width = self.screen_width, + .height = self.screen_height, + }, + .cell = .{ + .width = self.cell_width, + .height = self.cell_height, + }, + .padding = .{ + .top = self.padding_top, + .bottom = self.padding_bottom, + .right = self.padding_right, + .left = self.padding_left, + }, + }; + } +}; + +/// C: GhosttyMouseEncoderOption +pub const Option = enum(c_int) { + event = 0, + format = 1, + size = 2, + any_button_pressed = 3, + track_last_cell = 4, + + /// Input type expected for setting the option. + pub fn InType(comptime self: Option) type { + return switch (self) { + .event => TrackingMode, + .format => Format, + .size => Size, + .any_button_pressed, + .track_last_cell, + => bool, + }; + } +}; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Encoder, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(MouseEncoderWrapper) catch + return .out_of_memory; + ptr.* = .{ + .opts = .{ .size = defaultSize() }, + .alloc = alloc, + }; + result.* = ptr; + return .success; +} + +pub fn free(encoder_: Encoder) callconv(lib.calling_conv) void { + const wrapper = encoder_ orelse return; + const alloc = wrapper.alloc; + alloc.destroy(wrapper); +} + +pub fn setopt( + encoder_: Encoder, + option: Option, + value: ?*const anyopaque, +) callconv(lib.calling_conv) void { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + log.warn("setopt invalid option value={d}", .{@intFromEnum(option)}); + return; + }; + } + + return switch (option) { + inline else => |comptime_option| setoptTyped( + encoder_, + comptime_option, + @ptrCast(@alignCast(value orelse return)), + ), + }; +} + +fn setoptTyped( + encoder_: Encoder, + comptime option: Option, + value: *const option.InType(), +) void { + const wrapper = encoder_.?; + switch (option) { + .event => { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(TrackingMode, @intFromEnum(value.*)) catch { + log.warn("setopt invalid TrackingMode value={d}", .{@intFromEnum(value.*)}); + return; + }; + } + + if (wrapper.opts.event != value.*) wrapper.last_cell = null; + wrapper.opts.event = value.*; + }, + + .format => { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Format, @intFromEnum(value.*)) catch { + log.warn("setopt invalid Format value={d}", .{@intFromEnum(value.*)}); + return; + }; + } + + if (wrapper.opts.format != value.*) wrapper.last_cell = null; + wrapper.opts.format = value.*; + }, + + .size => { + if (value.size < @sizeOf(Size)) { + log.warn("setopt size struct too small size={d} expected>={d}", .{ + value.size, + @sizeOf(Size), + }); + return; + } + + wrapper.opts.size = value.toRenderer() orelse { + log.warn("setopt invalid size values (cell width and height must be non-zero)", .{}); + return; + }; + wrapper.last_cell = null; + }, + + .any_button_pressed => wrapper.opts.any_button_pressed = value.*, + + .track_last_cell => { + wrapper.track_last_cell = value.*; + if (!value.*) wrapper.last_cell = null; + }, + } +} + +pub fn setopt_from_terminal( + encoder_: Encoder, + terminal_: Terminal, +) callconv(lib.calling_conv) void { + const wrapper = encoder_ orelse return; + const t: *ZigTerminal = (terminal_ orelse return).terminal; + wrapper.opts.event = t.flags.mouse_event; + wrapper.opts.format = t.flags.mouse_format; + wrapper.last_cell = null; +} + +pub fn reset(encoder_: Encoder) callconv(lib.calling_conv) void { + const wrapper = encoder_ orelse return; + wrapper.last_cell = null; +} + +pub fn encode( + encoder_: Encoder, + event_: Event, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + const wrapper = encoder_ orelse return .invalid_value; + const event = event_ orelse return .invalid_value; + + const prev_last_cell = wrapper.last_cell; + + var opts = wrapper.opts; + opts.last_cell = if (wrapper.track_last_cell) &wrapper.last_cell else null; + + var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{}); + input_mouse_encode.encode( + &writer, + event.event, + opts, + ) catch |err| switch (err) { + error.WriteFailed => { + // Failed writes should not mutate motion dedupe state because no + // complete sequence was produced. + wrapper.last_cell = prev_last_cell; + + // Use a discarding writer to count how much space we would have needed. + var count_last_cell = prev_last_cell; + var count_opts = wrapper.opts; + count_opts.last_cell = if (wrapper.track_last_cell) &count_last_cell else null; + + var discarding: std.Io.Writer.Discarding = .init(&.{}); + input_mouse_encode.encode( + &discarding.writer, + event.event, + count_opts, + ) catch unreachable; + + // Discarding always uses a u64. If we're on 32-bit systems + // we cast down. We should make this safer in the future. + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + }; + + out_written.* = writer.end; + return .success; +} + +fn defaultSize() renderer_size.Size { + return .{ + .screen = .{ .width = 1, .height = 1 }, + .cell = .{ .width = 1, .height = 1 }, + .padding = .{}, + }; +} + +fn testSize() Size { + return .{ + .size = @sizeOf(Size), + .screen_width = 1_000, + .screen_height = 1_000, + .cell_width = 1, + .cell_height = 1, + .padding_top = 0, + .padding_bottom = 0, + .padding_right = 0, + .padding_left = 0, + }; +} + +test "alloc" { + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + free(e); +} + +test "setopt" { + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + const event_mode: TrackingMode = .any; + setopt(e, .event, &event_mode); + try testing.expectEqual(TrackingMode.any, e.?.opts.event); + + const format_mode: Format = .sgr; + setopt(e, .format, &format_mode); + try testing.expectEqual(Format.sgr, e.?.opts.format); + + const size = testSize(); + setopt(e, .size, &size); + try testing.expectEqual(size.screen_width, e.?.opts.size.screen.width); + try testing.expectEqual(size.screen_height, e.?.opts.size.screen.height); + + const any_button_pressed = true; + setopt(e, .any_button_pressed, &any_button_pressed); + try testing.expect(e.?.opts.any_button_pressed); + + const track_last_cell = true; + setopt(e, .track_last_cell, &track_last_cell); + try testing.expect(e.?.track_last_cell); +} + +test "setopt_from_terminal" { + const terminal_c = @import("terminal.zig"); + + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + var t: Terminal = undefined; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + )); + defer terminal_c.free(t); + + const event_mode: TrackingMode = .any; + setopt(e, .event, &event_mode); + const format_mode: Format = .sgr; + setopt(e, .format, &format_mode); + + setopt_from_terminal(e, t); + try testing.expectEqual(TrackingMode.none, e.?.opts.event); + try testing.expectEqual(Format.x10, e.?.opts.format); +} + +test "setopt_from_terminal null" { + setopt_from_terminal(null, null); + + const terminal_c = @import("terminal.zig"); + var t: Terminal = undefined; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &t, + .{ .cols = 80, .rows = 24, .max_scrollback = 0 }, + )); + defer terminal_c.free(t); + setopt_from_terminal(null, t); + + var e: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + setopt_from_terminal(e, null); +} + +test "encode: sgr press left" { + var encoder: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &encoder, + )); + defer free(encoder); + + const event_mode: TrackingMode = .any; + setopt(encoder, .event, &event_mode); + const format_mode: Format = .sgr; + setopt(encoder, .format, &format_mode); + const size = testSize(); + setopt(encoder, .size, &size); + + var event: Event = undefined; + try testing.expectEqual(Result.success, mouse_event.new( + &lib.alloc.test_allocator, + &event, + )); + defer mouse_event.free(event); + + mouse_event.set_action(event, .press); + mouse_event.set_button(event, .left); + mouse_event.set_position(event, .{ .x = 0, .y = 0 }); + + var required: usize = 0; + try testing.expectEqual(Result.out_of_space, encode( + encoder, + event, + null, + 0, + &required, + )); + try testing.expectEqual(@as(usize, 9), required); + + var buf: [32]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, encode( + encoder, + event, + &buf, + buf.len, + &written, + )); + try testing.expectEqual(required, written); + try testing.expectEqualStrings("\x1b[<0;1;1M", buf[0..written]); +} + +test "encode: motion dedupe and reset" { + var encoder: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &encoder, + )); + defer free(encoder); + + const event_mode: TrackingMode = .any; + setopt(encoder, .event, &event_mode); + const format_mode: Format = .sgr; + setopt(encoder, .format, &format_mode); + const size = testSize(); + setopt(encoder, .size, &size); + const track_last_cell = true; + setopt(encoder, .track_last_cell, &track_last_cell); + + var event: Event = undefined; + try testing.expectEqual(Result.success, mouse_event.new( + &lib.alloc.test_allocator, + &event, + )); + defer mouse_event.free(event); + + mouse_event.set_action(event, .motion); + mouse_event.set_button(event, .left); + mouse_event.set_position(event, .{ .x = 5, .y = 6 }); + + { + var buf: [32]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, encode( + encoder, + event, + &buf, + buf.len, + &written, + )); + try testing.expect(written > 0); + } + + { + var buf: [32]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, encode( + encoder, + event, + &buf, + buf.len, + &written, + )); + try testing.expectEqual(@as(usize, 0), written); + } + + reset(encoder); + + { + var buf: [32]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, encode( + encoder, + event, + &buf, + buf.len, + &written, + )); + try testing.expect(written > 0); + } +} + +test "encode: querying required size doesn't update dedupe state" { + var encoder: Encoder = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &encoder, + )); + defer free(encoder); + + const event_mode: TrackingMode = .any; + setopt(encoder, .event, &event_mode); + const format_mode: Format = .sgr; + setopt(encoder, .format, &format_mode); + const size = testSize(); + setopt(encoder, .size, &size); + const track_last_cell = true; + setopt(encoder, .track_last_cell, &track_last_cell); + + var event: Event = undefined; + try testing.expectEqual(Result.success, mouse_event.new( + &lib.alloc.test_allocator, + &event, + )); + defer mouse_event.free(event); + + mouse_event.set_action(event, .motion); + mouse_event.set_button(event, .left); + mouse_event.set_position(event, .{ .x = 5, .y = 6 }); + + var required: usize = 0; + try testing.expectEqual(Result.out_of_space, encode( + encoder, + event, + null, + 0, + &required, + )); + try testing.expect(required > 0); + + var buf: [32]u8 = undefined; + var written: usize = 0; + try testing.expectEqual(Result.success, encode( + encoder, + event, + &buf, + buf.len, + &written, + )); + try testing.expect(written > 0); +} diff --git a/vendor/libghostty-vt/src/terminal/c/mouse_event.zig b/vendor/libghostty-vt/src/terminal/c/mouse_event.zig new file mode 100644 index 00000000..b3c19dd3 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/mouse_event.zig @@ -0,0 +1,155 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const key = @import("../../input/key.zig"); +const mouse = @import("../../input/mouse.zig"); +const mouse_encode = @import("../../input/mouse_encode.zig"); +const Result = @import("result.zig").Result; + +const log = std.log.scoped(.mouse_event); + +/// Wrapper around mouse event that tracks the allocator for C API usage. +const MouseEventWrapper = struct { + event: mouse_encode.Event = .{}, + alloc: Allocator, +}; + +/// C: GhosttyMouseEvent +pub const Event = ?*MouseEventWrapper; + +/// C: GhosttyMouseAction +pub const Action = mouse.Action; + +/// C: GhosttyMouseButton +pub const Button = mouse.Button; + +/// C: GhosttyMousePosition +pub const Position = mouse_encode.Event.Pos; + +/// C: GhosttyMods +pub const Mods = key.Mods; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Event, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(MouseEventWrapper) catch + return .out_of_memory; + ptr.* = .{ .alloc = alloc }; + result.* = ptr; + return .success; +} + +pub fn free(event_: Event) callconv(lib.calling_conv) void { + const wrapper = event_ orelse return; + const alloc = wrapper.alloc; + alloc.destroy(wrapper); +} + +pub fn set_action(event_: Event, action: Action) callconv(lib.calling_conv) void { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Action, @intFromEnum(action)) catch { + log.warn("set_action invalid action value={d}", .{@intFromEnum(action)}); + return; + }; + } + + event_.?.event.action = action; +} + +pub fn get_action(event_: Event) callconv(lib.calling_conv) Action { + return event_.?.event.action; +} + +pub fn set_button(event_: Event, button: Button) callconv(lib.calling_conv) void { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Button, @intFromEnum(button)) catch { + log.warn("set_button invalid button value={d}", .{@intFromEnum(button)}); + return; + }; + } + + event_.?.event.button = button; +} + +pub fn clear_button(event_: Event) callconv(lib.calling_conv) void { + event_.?.event.button = null; +} + +pub fn get_button(event_: Event, out: ?*Button) callconv(lib.calling_conv) bool { + if (event_.?.event.button) |button| { + if (out) |ptr| ptr.* = button; + return true; + } + + return false; +} + +pub fn set_mods(event_: Event, mods: Mods) callconv(lib.calling_conv) void { + event_.?.event.mods = mods; +} + +pub fn get_mods(event_: Event) callconv(lib.calling_conv) Mods { + return event_.?.event.mods; +} + +pub fn set_position(event_: Event, pos: Position) callconv(lib.calling_conv) void { + event_.?.event.pos = pos; +} + +pub fn get_position(event_: Event) callconv(lib.calling_conv) Position { + return event_.?.event.pos; +} + +test "alloc" { + var e: Event = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + free(e); +} + +test "free null" { + free(null); +} + +test "set/get" { + var e: Event = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &e, + )); + defer free(e); + + // Action + set_action(e, .motion); + try testing.expectEqual(Action.motion, get_action(e)); + + // Button + set_button(e, .left); + var button: Button = .unknown; + try testing.expect(get_button(e, &button)); + try testing.expectEqual(Button.left, button); + try testing.expect(get_button(e, null)); + + clear_button(e); + try testing.expect(!get_button(e, &button)); + + // Mods + const mods: Mods = .{ .shift = true, .ctrl = true }; + set_mods(e, mods); + const got_mods = get_mods(e); + try testing.expect(got_mods.shift); + try testing.expect(got_mods.ctrl); + try testing.expect(!got_mods.alt); + + // Position + set_position(e, .{ .x = 12.5, .y = -4.0 }); + const pos = get_position(e); + try testing.expectEqual(@as(f32, 12.5), pos.x); + try testing.expectEqual(@as(f32, -4.0), pos.y); +} diff --git a/vendor/libghostty-vt/src/terminal/c/osc.zig b/vendor/libghostty-vt/src/terminal/c/osc.zig new file mode 100644 index 00000000..7ba32300 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/osc.zig @@ -0,0 +1,140 @@ +const std = @import("std"); +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const osc = @import("../osc.zig"); +const Result = @import("result.zig").Result; + +const log = std.log.scoped(.osc); + +/// C: GhosttyOscParser +pub const Parser = ?*osc.Parser; + +/// C: GhosttyOscCommand +pub const Command = ?*osc.Command; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Parser, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(osc.Parser) catch + return .out_of_memory; + ptr.* = .init(alloc); + result.* = ptr; + return .success; +} + +pub fn free(parser_: Parser) callconv(lib.calling_conv) void { + // C-built parsers always have an associated allocator. + const parser = parser_ orelse return; + const alloc = parser.alloc.?; + parser.deinit(); + alloc.destroy(parser); +} + +pub fn reset(parser_: Parser) callconv(lib.calling_conv) void { + parser_.?.reset(); +} + +pub fn next(parser_: Parser, byte: u8) callconv(lib.calling_conv) void { + parser_.?.next(byte); +} + +pub fn end(parser_: Parser, terminator: u8) callconv(lib.calling_conv) Command { + return parser_.?.end(terminator); +} + +pub fn commandType(command_: Command) callconv(lib.calling_conv) osc.Command.Key { + const command = command_ orelse return .invalid; + return command.*; +} + +/// C: GhosttyOscCommandData +pub const CommandData = enum(c_int) { + invalid = 0, + change_window_title_str = 1, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: CommandData) type { + return switch (self) { + .invalid => void, + .change_window_title_str => [*:0]const u8, + }; + } +}; + +pub fn commandData( + command_: Command, + data: CommandData, + out: ?*anyopaque, +) callconv(lib.calling_conv) bool { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(CommandData, @intFromEnum(data)) catch { + log.warn("commandData invalid data value={d}", .{@intFromEnum(data)}); + return false; + }; + } + + return switch (data) { + .invalid => false, + inline else => |comptime_data| commandDataTyped( + command_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn commandDataTyped( + command_: Command, + comptime data: CommandData, + out: *data.OutType(), +) bool { + const command = command_.?; + switch (data) { + .invalid => return false, + .change_window_title_str => switch (command.*) { + .change_window_title => |v| out.* = v.ptr, + else => return false, + }, + } + + return true; +} + +test "alloc" { + const testing = std.testing; + var p: Parser = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &p, + )); + free(p); +} + +test "command type null" { + const testing = std.testing; + try testing.expectEqual(.invalid, commandType(null)); +} + +test "change window title" { + const testing = std.testing; + var p: Parser = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &p, + )); + defer free(p); + + // Parse it + next(p, '0'); + next(p, ';'); + next(p, 'a'); + const cmd = end(p, 0); + try testing.expectEqual(.change_window_title, commandType(cmd)); + + // Extract the title + var title: [*:0]const u8 = undefined; + try testing.expect(commandData(cmd, .change_window_title_str, @ptrCast(&title))); + try testing.expectEqualStrings("a", std.mem.span(title)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/paste.zig b/vendor/libghostty-vt/src/terminal/c/paste.zig new file mode 100644 index 00000000..bce6a565 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/paste.zig @@ -0,0 +1,129 @@ +const std = @import("std"); +const lib = @import("../lib.zig"); +const paste = @import("../../input/paste.zig"); +const Result = @import("result.zig").Result; + +pub fn is_safe(data: ?[*]const u8, len: usize) callconv(lib.calling_conv) bool { + const slice: []const u8 = if (data) |v| v[0..len] else &.{}; + return paste.isSafe(slice); +} + +pub fn encode( + data: ?[*]u8, + data_len: usize, + bracketed: bool, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + const slice: []u8 = if (data) |v| v[0..data_len] else &.{}; + const result = paste.encode(slice, .{ .bracketed = bracketed }); + + const total = result[0].len + result[1].len + result[2].len; + out_written.* = total; + + const out: []u8 = if (out_) |o| o[0..out_len] else &.{}; + if (out.len < total) return .out_of_space; + + var offset: usize = 0; + for (result) |segment| { + @memcpy(out[offset..][0..segment.len], segment); + offset += segment.len; + } + + return .success; +} + +test "encode bracketed" { + const testing = std.testing; + const input = try testing.allocator.dupe(u8, "hello"); + defer testing.allocator.free(input); + var buf: [64]u8 = undefined; + var written: usize = 0; + const result = encode(input.ptr, input.len, true, &buf, buf.len, &written); + try testing.expectEqual(.success, result); + try testing.expectEqualStrings("\x1b[200~hello\x1b[201~", buf[0..written]); +} + +test "encode unbracketed no newlines" { + const testing = std.testing; + const input = try testing.allocator.dupe(u8, "hello"); + defer testing.allocator.free(input); + var buf: [64]u8 = undefined; + var written: usize = 0; + const result = encode(input.ptr, input.len, false, &buf, buf.len, &written); + try testing.expectEqual(.success, result); + try testing.expectEqualStrings("hello", buf[0..written]); +} + +test "encode unbracketed newlines" { + const testing = std.testing; + const input = try testing.allocator.dupe(u8, "hello\nworld"); + defer testing.allocator.free(input); + var buf: [64]u8 = undefined; + var written: usize = 0; + const result = encode(input.ptr, input.len, false, &buf, buf.len, &written); + try testing.expectEqual(.success, result); + try testing.expectEqualStrings("hello\rworld", buf[0..written]); +} + +test "encode strip unsafe bytes" { + const testing = std.testing; + const input = try testing.allocator.dupe(u8, "hel\x1blo\x00world"); + defer testing.allocator.free(input); + var buf: [64]u8 = undefined; + var written: usize = 0; + const result = encode(input.ptr, input.len, true, &buf, buf.len, &written); + try testing.expectEqual(.success, result); + try testing.expectEqualStrings("\x1b[200~hel lo world\x1b[201~", buf[0..written]); +} + +test "encode with insufficient buffer" { + const testing = std.testing; + const input = try testing.allocator.dupe(u8, "hello"); + defer testing.allocator.free(input); + var buf: [1]u8 = undefined; + var written: usize = 0; + const result = encode(input.ptr, input.len, true, &buf, buf.len, &written); + try testing.expectEqual(.out_of_space, result); + try testing.expectEqual(17, written); +} + +test "encode with null buffer" { + const testing = std.testing; + const input = try testing.allocator.dupe(u8, "hello"); + defer testing.allocator.free(input); + var written: usize = 0; + const result = encode(input.ptr, input.len, true, null, 0, &written); + try testing.expectEqual(.out_of_space, result); + try testing.expectEqual(17, written); +} + +test "is_safe with safe data" { + const testing = std.testing; + const safe = "hello world"; + try testing.expect(is_safe(safe.ptr, safe.len)); +} + +test "is_safe with newline" { + const testing = std.testing; + const unsafe = "hello\nworld"; + try testing.expect(!is_safe(unsafe.ptr, unsafe.len)); +} + +test "is_safe with bracketed paste end" { + const testing = std.testing; + const unsafe = "hello\x1b[201~world"; + try testing.expect(!is_safe(unsafe.ptr, unsafe.len)); +} + +test "is_safe with empty data" { + const testing = std.testing; + const empty = ""; + try testing.expect(is_safe(empty.ptr, 0)); +} + +test "is_safe with null empty data" { + const testing = std.testing; + try testing.expect(is_safe(null, 0)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/render.zig b/vendor/libghostty-vt/src/terminal/c/render.zig new file mode 100644 index 00000000..b95bedd5 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/render.zig @@ -0,0 +1,1382 @@ +const std = @import("std"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const colorpkg = @import("../color.zig"); +const cursorpkg = @import("../cursor.zig"); +const page = @import("../page.zig"); +const size = @import("../size.zig"); +const Style = @import("../style.zig").Style; +const terminal_c = @import("terminal.zig"); +const ZigTerminal = @import("../Terminal.zig"); +const renderpkg = @import("../render.zig"); +const Result = @import("result.zig").Result; +const row = @import("row.zig"); +const style_c = @import("style.zig"); + +const log = std.log.scoped(.render_state_c); + +const RenderStateWrapper = struct { + alloc: std.mem.Allocator, + state: renderpkg.RenderState = .empty, +}; + +const RowIteratorWrapper = struct { + alloc: std.mem.Allocator, + + /// The current index (also y value) into the row list. + y: ?size.CellCountInt, + + /// These are the raw pointers into the render state data. + raws: []const page.Row, + cells: []const std.MultiArrayList(renderpkg.RenderState.Cell), + dirty: []bool, + + /// The color palette from the render state, needed to resolve + /// palette-indexed background colors on cells. + palette: *const colorpkg.Palette, +}; + +const RowCellsWrapper = struct { + alloc: std.mem.Allocator, + x: ?size.CellCountInt, + raws: []const page.Cell, + graphemes: []const []const u21, + styles: []const Style, + + /// The color palette, needed to resolve palette-indexed background colors. + palette: *const colorpkg.Palette, +}; + +/// C: GhosttyRenderState +pub const RenderState = ?*RenderStateWrapper; + +/// C: GhosttyRenderStateRowIterator +pub const RowIterator = ?*RowIteratorWrapper; + +/// C: GhosttyRenderStateRowCells +pub const RowCells = ?*RowCellsWrapper; + +/// C: GhosttyRenderStateDirty +pub const Dirty = renderpkg.RenderState.Dirty; + +/// C: GhosttyRenderStateCursorVisualStyle +pub const CursorVisualStyle = enum(c_int) { + bar = 0, + block = 1, + underline = 2, + block_hollow = 3, + + pub fn fromCursorStyle(s: cursorpkg.Style) CursorVisualStyle { + return switch (s) { + .bar => .bar, + .block => .block, + .underline => .underline, + .block_hollow => .block_hollow, + }; + } +}; + +/// C: GhosttyRenderStateData +pub const Data = enum(c_int) { + invalid = 0, + cols = 1, + rows = 2, + dirty = 3, + row_iterator = 4, + color_background = 5, + color_foreground = 6, + color_cursor = 7, + color_cursor_has_value = 8, + color_palette = 9, + cursor_visual_style = 10, + cursor_visible = 11, + cursor_blinking = 12, + cursor_password_input = 13, + cursor_viewport_has_value = 14, + cursor_viewport_x = 15, + cursor_viewport_y = 16, + cursor_viewport_wide_tail = 17, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: Data) type { + return switch (self) { + .invalid => void, + .cols, .rows => size.CellCountInt, + .dirty => Dirty, + .row_iterator => RowIterator, + .color_background, .color_foreground, .color_cursor => colorpkg.RGB.C, + .color_cursor_has_value => bool, + .color_palette => colorpkg.PaletteC, + .cursor_visual_style => CursorVisualStyle, + .cursor_visible, .cursor_blinking, .cursor_password_input => bool, + .cursor_viewport_has_value, .cursor_viewport_wide_tail => bool, + .cursor_viewport_x, .cursor_viewport_y => size.CellCountInt, + }; + } +}; + +/// C: GhosttyRenderStateOption +pub const SetOption = enum(c_int) { + dirty = 0, + + /// Input type expected for setting the option. + pub fn InType(comptime self: SetOption) type { + return switch (self) { + .dirty => Dirty, + }; + } +}; + +/// C: GhosttyRenderStateColors +pub const Colors = extern struct { + size: usize = @sizeOf(Colors), + background: colorpkg.RGB.C, + foreground: colorpkg.RGB.C, + cursor: colorpkg.RGB.C, + cursor_has_value: bool, + palette: colorpkg.PaletteC, +}; + +pub fn new( + alloc_: ?*const CAllocator, + result: *RenderState, +) callconv(lib.calling_conv) Result { + result.* = new_(alloc_) catch |err| { + result.* = null; + return switch (err) { + error.OutOfMemory => .out_of_memory, + }; + }; + + return .success; +} + +fn new_(alloc_: ?*const CAllocator) error{OutOfMemory}!*RenderStateWrapper { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(RenderStateWrapper) catch + return error.OutOfMemory; + ptr.* = .{ .alloc = alloc }; + return ptr; +} + +pub fn free(state_: RenderState) callconv(lib.calling_conv) void { + const state = state_ orelse return; + const alloc = state.alloc; + state.state.deinit(alloc); + alloc.destroy(state); +} + +pub fn update( + state_: RenderState, + terminal_: terminal_c.Terminal, +) callconv(lib.calling_conv) Result { + const state = state_ orelse return .invalid_value; + const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; + + state.state.update(state.alloc, t) catch return .out_of_memory; + return .success; +} + +pub fn get( + state_: RenderState, + data: Data, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Data, @intFromEnum(data)) catch { + log.warn("render_state_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| getTyped( + state_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn getTyped( + state_: RenderState, + comptime data: Data, + out: *data.OutType(), +) Result { + const state = state_ orelse return .invalid_value; + switch (data) { + .invalid => return .invalid_value, + .cols => out.* = state.state.cols, + .rows => out.* = state.state.rows, + .dirty => out.* = state.state.dirty, + .row_iterator => { + const it = out.* orelse return .invalid_value; + const row_data = state.state.row_data.slice(); + it.* = .{ + .alloc = it.alloc, + .y = null, + .raws = row_data.items(.raw), + .cells = row_data.items(.cells), + .dirty = row_data.items(.dirty), + .palette = &state.state.colors.palette, + }; + }, + .color_background => out.* = state.state.colors.background.cval(), + .color_foreground => out.* = state.state.colors.foreground.cval(), + .color_cursor => { + const cursor = state.state.colors.cursor orelse return .invalid_value; + out.* = cursor.cval(); + }, + .color_cursor_has_value => out.* = state.state.colors.cursor != null, + .color_palette => out.* = colorpkg.paletteCval(&state.state.colors.palette), + .cursor_visual_style => out.* = CursorVisualStyle.fromCursorStyle(state.state.cursor.visual_style), + .cursor_visible => out.* = state.state.cursor.visible, + .cursor_blinking => out.* = state.state.cursor.blinking, + .cursor_password_input => out.* = state.state.cursor.password_input, + .cursor_viewport_has_value => out.* = state.state.cursor.viewport != null, + .cursor_viewport_x => { + const vp = state.state.cursor.viewport orelse return .invalid_value; + out.* = vp.x; + }, + .cursor_viewport_y => { + const vp = state.state.cursor.viewport orelse return .invalid_value; + out.* = vp.y; + }, + .cursor_viewport_wide_tail => { + const vp = state.state.cursor.viewport orelse return .invalid_value; + out.* = vp.wide_tail; + }, + } + + return .success; +} + +pub fn set( + state_: RenderState, + option: SetOption, + value: ?*const anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(SetOption, @intFromEnum(option)) catch { + log.warn("render_state_set invalid option value={d}", .{@intFromEnum(option)}); + return .invalid_value; + }; + } + + return switch (option) { + inline else => |comptime_option| setTyped( + state_, + comptime_option, + @ptrCast(@alignCast(value orelse return .invalid_value)), + ), + }; +} + +fn setTyped( + state_: RenderState, + comptime option: SetOption, + value: *const option.InType(), +) Result { + const state = state_ orelse return .invalid_value; + switch (option) { + .dirty => state.state.dirty = value.*, + } + + return .success; +} + +pub fn colors_get( + state_: RenderState, + out_colors_: ?*Colors, +) callconv(lib.calling_conv) Result { + const state = state_ orelse return .invalid_value; + const out_colors = out_colors_ orelse return .invalid_value; + const out_size = out_colors.size; + if (out_size < @sizeOf(usize)) return .invalid_value; + + const colors = state.state.colors; + if (lib.structSizedFieldFits( + Colors, + out_size, + "background", + )) { + out_colors.background = colors.background.cval(); + } + + if (lib.structSizedFieldFits( + Colors, + out_size, + "foreground", + )) { + out_colors.foreground = colors.foreground.cval(); + } + + if (colors.cursor) |cursor| { + if (lib.structSizedFieldFits( + Colors, + out_size, + "cursor", + )) { + out_colors.cursor = cursor.cval(); + } + } + + if (lib.structSizedFieldFits( + Colors, + out_size, + "cursor_has_value", + )) { + out_colors.cursor_has_value = colors.cursor != null; + } + + { + const palette_offset = @offsetOf(Colors, "palette"); + if (out_size > palette_offset) { + const available = out_size - palette_offset; + const max_entries = @min(colors.palette.len, available / @sizeOf(colorpkg.RGB.C)); + for (0..max_entries) |i| { + out_colors.palette[i] = colors.palette[i].cval(); + } + } + } + + return .success; +} + +pub fn row_iterator_new( + alloc_: ?*const CAllocator, + result: *RowIterator, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(RowIteratorWrapper) catch { + result.* = null; + return .out_of_memory; + }; + ptr.* = .{ + .alloc = alloc, + .y = undefined, + .raws = undefined, + .cells = undefined, + .dirty = undefined, + .palette = undefined, + }; + result.* = ptr; + return .success; +} + +pub fn row_iterator_free(iterator_: RowIterator) callconv(lib.calling_conv) void { + const iterator = iterator_ orelse return; + const alloc = iterator.alloc; + alloc.destroy(iterator); +} + +pub fn row_iterator_next(iterator_: RowIterator) callconv(lib.calling_conv) bool { + const it = iterator_ orelse return false; + const next_y: size.CellCountInt = if (it.y) |y| y + 1 else 0; + if (next_y >= it.raws.len) return false; + it.y = next_y; + return true; +} + +pub fn row_cells_new( + alloc_: ?*const CAllocator, + result: *RowCells, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(RowCellsWrapper) catch { + result.* = null; + return .out_of_memory; + }; + ptr.* = .{ + .alloc = alloc, + .x = undefined, + .raws = undefined, + .graphemes = undefined, + .styles = undefined, + .palette = undefined, + }; + result.* = ptr; + return .success; +} + +pub fn row_cells_next(cells_: RowCells) callconv(lib.calling_conv) bool { + const cells = cells_ orelse return false; + const next_x: size.CellCountInt = if (cells.x) |x| x + 1 else 0; + if (next_x >= cells.raws.len) return false; + cells.x = next_x; + return true; +} + +pub fn row_cells_select(cells_: RowCells, x: size.CellCountInt) callconv(lib.calling_conv) Result { + const cells = cells_ orelse return .invalid_value; + if (x >= cells.raws.len) return .invalid_value; + cells.x = x; + return .success; +} + +pub fn row_cells_free(cells_: RowCells) callconv(lib.calling_conv) void { + const cells = cells_ orelse return; + const alloc = cells.alloc; + alloc.destroy(cells); +} + +/// C: GhosttyRenderStateRowCellsData +pub const RowCellsData = enum(c_int) { + invalid = 0, + raw = 1, + style = 2, + graphemes_len = 3, + graphemes_buf = 4, + bg_color = 5, + fg_color = 6, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: RowCellsData) type { + return switch (self) { + .invalid => void, + .raw => page.Cell.C, + .style => style_c.Style, + .graphemes_len => u32, + .graphemes_buf => u32, + .bg_color, .fg_color => colorpkg.RGB.C, + }; + } +}; + +pub fn row_cells_get( + cells_: RowCells, + data: RowCellsData, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(RowCellsData, @intFromEnum(data)) catch { + log.warn("render_state_row_cells_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| rowCellsGetTyped( + cells_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn rowCellsGetTyped( + cells_: RowCells, + comptime data: RowCellsData, + out: *data.OutType(), +) Result { + const cells = cells_ orelse return .invalid_value; + const x = cells.x orelse return .invalid_value; + const cell = cells.raws[x]; + switch (data) { + .invalid => return .invalid_value, + .raw => out.* = cell.cval(), + .style => out.* = if (cell.hasStyling()) + style_c.Style.fromStyle(cells.styles[x]) + else + style_c.Style.fromStyle(.{}), + .graphemes_len => { + if (!cell.hasText()) { + out.* = 0; + return .success; + } + const extra = if (cell.hasGrapheme()) cells.graphemes[x] else &[_]u21{}; + out.* = @intCast(1 + extra.len); + }, + .graphemes_buf => { + if (!cell.hasText()) return .success; + const extra = if (cell.hasGrapheme()) cells.graphemes[x] else &[_]u21{}; + const buf: [*]u32 = @ptrCast(out); + buf[0] = cell.codepoint(); + for (extra, 1..) |cp, i| { + buf[i] = cp; + } + }, + .bg_color => { + const s: Style = if (cell.hasStyling()) cells.styles[x] else .{}; + const bg = s.bg(&cell, cells.palette) orelse return .invalid_value; + out.* = bg.cval(); + }, + .fg_color => { + const s: Style = if (cell.hasStyling()) cells.styles[x] else .{}; + if (s.fg_color == .none) return .invalid_value; + const fg = s.fg(.{ .default = .{}, .palette = cells.palette }); + out.* = fg.cval(); + }, + } + + return .success; +} + +/// C: GhosttyRenderStateRowData +pub const RowData = enum(c_int) { + invalid = 0, + dirty = 1, + raw = 2, + cells = 3, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: RowData) type { + return switch (self) { + .invalid => void, + .dirty => bool, + .raw => row.CRow, + .cells => RowCells, + }; + } +}; + +/// C: GhosttyRenderStateRowOption +pub const RowOption = enum(c_int) { + dirty = 0, + + /// Input type expected for setting the option. + pub fn InType(comptime self: RowOption) type { + return switch (self) { + .dirty => bool, + }; + } +}; + +pub fn row_get( + iterator_: RowIterator, + data: RowData, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(RowData, @intFromEnum(data)) catch { + log.warn("render_state_row_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| rowGetTyped( + iterator_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn rowGetTyped( + iterator_: RowIterator, + comptime data: RowData, + out: *data.OutType(), +) Result { + const it = iterator_ orelse return .invalid_value; + const y = it.y orelse return .invalid_value; + switch (data) { + .invalid => return .invalid_value, + .dirty => out.* = it.dirty[y], + .raw => out.* = it.raws[y].cval(), + .cells => { + const cells = out.* orelse return .invalid_value; + const cell_data = it.cells[y].slice(); + cells.* = .{ + .alloc = cells.alloc, + .x = null, + .raws = cell_data.items(.raw), + .graphemes = cell_data.items(.grapheme), + .styles = cell_data.items(.style), + .palette = it.palette, + }; + }, + } + + return .success; +} + +pub fn row_set( + iterator_: RowIterator, + option: RowOption, + value: ?*const anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(RowOption, @intFromEnum(option)) catch { + log.warn("render_state_row_set invalid option value={d}", .{@intFromEnum(option)}); + return .invalid_value; + }; + } + + return switch (option) { + inline else => |comptime_option| rowSetTyped( + iterator_, + comptime_option, + @ptrCast(@alignCast(value orelse return .invalid_value)), + ), + }; +} + +fn rowSetTyped( + iterator_: RowIterator, + comptime option: RowOption, + value: *const option.InType(), +) Result { + const it = iterator_ orelse return .invalid_value; + const y = it.y orelse return .invalid_value; + switch (option) { + .dirty => it.dirty[y] = value.*, + } + + return .success; +} + +test "render: new/free" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + try testing.expect(state != null); + free(state); +} + +test "render: free null" { + free(null); +} + +test "render: update invalid value" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.invalid_value, update(null, null)); + try testing.expectEqual(Result.invalid_value, update(state, null)); +} + +test "render: get invalid value" { + var cols: size.CellCountInt = 0; + try testing.expectEqual(Result.invalid_value, get(null, .cols, @ptrCast(&cols))); +} + +test "render: get invalid data" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.invalid_value, get(state, .invalid, null)); +} + +test "render: colors get invalid value" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + var colors: Colors = std.mem.zeroes(Colors); + colors.size = @sizeOf(Colors); + + try testing.expectEqual(Result.invalid_value, colors_get(null, &colors)); + try testing.expectEqual(Result.invalid_value, colors_get(state, null)); + + colors.size = @sizeOf(usize) - 1; + try testing.expectEqual(Result.invalid_value, colors_get(state, &colors)); +} + +test "render: get/set dirty invalid value" { + var dirty: Dirty = .false; + try testing.expectEqual(Result.invalid_value, get(null, .dirty, @ptrCast(&dirty))); + const dirty_full: Dirty = .full; + try testing.expectEqual(Result.invalid_value, set(null, .dirty, @ptrCast(&dirty_full))); +} + +test "render: get/set dirty" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + var dirty: Dirty = undefined; + try testing.expectEqual(Result.success, get(state, .dirty, @ptrCast(&dirty))); + try testing.expectEqual(Dirty.false, dirty); + + const dirty_partial: Dirty = .partial; + try testing.expectEqual(Result.success, set(state, .dirty, @ptrCast(&dirty_partial))); + try testing.expectEqual(Result.success, get(state, .dirty, @ptrCast(&dirty))); + try testing.expectEqual(Dirty.partial, dirty); + + const dirty_full: Dirty = .full; + try testing.expectEqual(Result.success, set(state, .dirty, @ptrCast(&dirty_full))); + try testing.expectEqual(Result.success, get(state, .dirty, @ptrCast(&dirty))); + try testing.expectEqual(Dirty.full, dirty); +} + +test "render: set null value" { + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.invalid_value, set(state, .dirty, null)); +} + +test "render: row iterator get invalid value" { + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + try testing.expectEqual(Result.invalid_value, get(null, .row_iterator, @ptrCast(&iterator))); +} + +test "render: row iterator new/free" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + try testing.expect(iterator != null); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + + const iterator_ptr = iterator.?; + const row_data = state.?.state.row_data.slice(); + + try testing.expectEqual(@as(?size.CellCountInt, null), iterator_ptr.y); + try testing.expectEqual(row_data.items(.raw).len, iterator_ptr.raws.len); + try testing.expectEqual(row_data.items(.cells).len, iterator_ptr.cells.len); + try testing.expectEqual(row_data.items(.dirty).len, iterator_ptr.dirty.len); +} + +test "render: row iterator free null" { + row_iterator_free(null); +} + +test "render: row iterator next null" { + try testing.expect(!row_iterator_next(null)); +} + +test "render: row get null" { + var dirty: bool = undefined; + try testing.expectEqual(Result.invalid_value, row_get(null, .dirty, @ptrCast(&dirty))); +} + +test "render: row get invalid data" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + try testing.expect(row_iterator_next(iterator)); + try testing.expectEqual(Result.invalid_value, row_get(iterator, .invalid, null)); +} + +test "render: row set null" { + const dirty = false; + try testing.expectEqual(Result.invalid_value, row_set(null, .dirty, @ptrCast(&dirty))); +} + +test "render: row set before iteration" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + const dirty = false; + try testing.expectEqual(Result.invalid_value, row_set(iterator, .dirty, @ptrCast(&dirty))); +} + +test "render: row get before iteration" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + var dirty: bool = undefined; + try testing.expectEqual(Result.invalid_value, row_get(iterator, .dirty, @ptrCast(&dirty))); +} + +test "render: row get/set dirty" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + // Dirty the first row so the iterator has at least one dirty row to observe. + terminal_c.vt_write(terminal, "hello", 5); + try testing.expectEqual(Result.success, update(state, terminal)); + + // Create an iterator and verify it is dirty. + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + try testing.expect(row_iterator_next(it)); + var dirty: bool = undefined; + try testing.expectEqual(Result.success, row_get(it, .dirty, @ptrCast(&dirty))); + try testing.expect(dirty); + + // Clear dirty on this row. + const dirty_false = false; + try testing.expectEqual(Result.success, row_set(it, .dirty, @ptrCast(&dirty_false))); + + // It should not be dirty anymore. + var it2: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it2, + )); + defer row_iterator_free(it2); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it2))); + try testing.expect(row_iterator_next(it2)); + try testing.expectEqual(Result.success, row_get(it2, .dirty, @ptrCast(&dirty))); + try testing.expect(!dirty); +} + +test "render: row iterator next" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var iterator: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &iterator, + )); + defer row_iterator_free(iterator); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&iterator))); + + const rows = state.?.state.rows; + if (rows == 0) { + try testing.expect(!row_iterator_next(iterator)); + return; + } + + try testing.expect(row_iterator_next(iterator)); + try testing.expectEqual(@as(?size.CellCountInt, 0), iterator.?.y); + + var i: size.CellCountInt = 1; + while (i < rows) : (i += 1) { + try testing.expect(row_iterator_next(iterator)); + try testing.expectEqual(@as(?size.CellCountInt, i), iterator.?.y); + } + + try testing.expect(!row_iterator_next(iterator)); + try testing.expectEqual(@as(?size.CellCountInt, rows - 1), iterator.?.y); +} + +test "render: update" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + terminal_c.vt_write(terminal, "hello", 5); + try testing.expectEqual(Result.success, update(state, terminal)); + + var cols: size.CellCountInt = 0; + var rows_val: size.CellCountInt = 0; + try testing.expectEqual(Result.success, get(state, .cols, @ptrCast(&cols))); + try testing.expectEqual(Result.success, get(state, .rows, @ptrCast(&rows_val))); + try testing.expectEqual(@as(size.CellCountInt, 80), cols); + try testing.expectEqual(@as(size.CellCountInt, 24), rows_val); +} + +test "render: colors get" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var colors: Colors = std.mem.zeroes(Colors); + colors.size = @sizeOf(Colors); + try testing.expectEqual(Result.success, colors_get(state, &colors)); + + const state_colors = &state.?.state.colors; + try testing.expectEqual(state_colors.background.cval(), colors.background); + try testing.expectEqual(state_colors.foreground.cval(), colors.foreground); + + if (state_colors.cursor) |cursor| { + try testing.expect(colors.cursor_has_value); + try testing.expectEqual(cursor.cval(), colors.cursor); + } else { + try testing.expect(!colors.cursor_has_value); + } + + for (state_colors.palette, colors.palette) |expected, actual| { + try testing.expectEqual(expected.cval(), actual); + } +} + +test "render: row cells bg_color no background" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + // Write plain text (no background color set). + terminal_c.vt_write(terminal, "hello", 5); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + try testing.expect(row_iterator_next(it)); + + var cells: RowCells = null; + try testing.expectEqual(Result.success, row_cells_new( + &lib.alloc.test_allocator, + &cells, + )); + defer row_cells_free(cells); + + try testing.expectEqual(Result.success, row_get(it, .cells, @ptrCast(&cells))); + try testing.expect(row_cells_next(cells)); + + // No background set, should return invalid_value. + var bg: colorpkg.RGB.C = undefined; + try testing.expectEqual(Result.invalid_value, row_cells_get(cells, .bg_color, @ptrCast(&bg))); +} + +test "render: row cells bg_color from style" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + // Set an RGB background via SGR 48;2;R;G;B and write text. + terminal_c.vt_write(terminal, "\x1b[48;2;10;20;30mA", 18); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + try testing.expect(row_iterator_next(it)); + + var cells: RowCells = null; + try testing.expectEqual(Result.success, row_cells_new( + &lib.alloc.test_allocator, + &cells, + )); + defer row_cells_free(cells); + + try testing.expectEqual(Result.success, row_get(it, .cells, @ptrCast(&cells))); + try testing.expect(row_cells_next(cells)); + + var bg: colorpkg.RGB.C = undefined; + try testing.expectEqual(Result.success, row_cells_get(cells, .bg_color, @ptrCast(&bg))); + try testing.expectEqual(@as(u8, 10), bg.r); + try testing.expectEqual(@as(u8, 20), bg.g); + try testing.expectEqual(@as(u8, 30), bg.b); +} + +test "render: row cells bg_color from content tag" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + // Set an RGB background and then erase the line. The erased cells + // should carry the background color via the content tag (bg_color_rgb) + // rather than through the style. + terminal_c.vt_write(terminal, "\x1b[48;2;10;20;30m\x1b[2K", 21); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + try testing.expect(row_iterator_next(it)); + + var cells: RowCells = null; + try testing.expectEqual(Result.success, row_cells_new( + &lib.alloc.test_allocator, + &cells, + )); + defer row_cells_free(cells); + + try testing.expectEqual(Result.success, row_get(it, .cells, @ptrCast(&cells))); + try testing.expect(row_cells_next(cells)); + + var bg: colorpkg.RGB.C = undefined; + try testing.expectEqual(Result.success, row_cells_get(cells, .bg_color, @ptrCast(&bg))); + try testing.expectEqual(@as(u8, 10), bg.r); + try testing.expectEqual(@as(u8, 20), bg.g); + try testing.expectEqual(@as(u8, 30), bg.b); +} + +test "render: row cells fg_color no foreground" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + // Write plain text (no foreground color set). + terminal_c.vt_write(terminal, "hello", 5); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + try testing.expect(row_iterator_next(it)); + + var cells: RowCells = null; + try testing.expectEqual(Result.success, row_cells_new( + &lib.alloc.test_allocator, + &cells, + )); + defer row_cells_free(cells); + + try testing.expectEqual(Result.success, row_get(it, .cells, @ptrCast(&cells))); + try testing.expect(row_cells_next(cells)); + + // No foreground set, should return invalid_value. + var fg: colorpkg.RGB.C = undefined; + try testing.expectEqual(Result.invalid_value, row_cells_get(cells, .fg_color, @ptrCast(&fg))); +} + +test "render: row cells fg_color from style" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + // Set an RGB foreground via SGR 38;2;R;G;B and write text. + terminal_c.vt_write(terminal, "\x1b[38;2;10;20;30mA", 18); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var it: RowIterator = null; + try testing.expectEqual(Result.success, row_iterator_new( + &lib.alloc.test_allocator, + &it, + )); + defer row_iterator_free(it); + + try testing.expectEqual(Result.success, get(state, .row_iterator, @ptrCast(&it))); + try testing.expect(row_iterator_next(it)); + + var cells: RowCells = null; + try testing.expectEqual(Result.success, row_cells_new( + &lib.alloc.test_allocator, + &cells, + )); + defer row_cells_free(cells); + + try testing.expectEqual(Result.success, row_get(it, .cells, @ptrCast(&cells))); + try testing.expect(row_cells_next(cells)); + + var fg: colorpkg.RGB.C = undefined; + try testing.expectEqual(Result.success, row_cells_get(cells, .fg_color, @ptrCast(&fg))); + try testing.expectEqual(@as(u8, 10), fg.r); + try testing.expectEqual(@as(u8, 20), fg.g); + try testing.expectEqual(@as(u8, 30), fg.b); +} + +test "render: colors get supports truncated sized struct" { + var terminal: terminal_c.Terminal = null; + try testing.expectEqual(Result.success, terminal_c.new( + &lib.alloc.test_allocator, + &terminal, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer terminal_c.free(terminal); + + var state: RenderState = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &state, + )); + defer free(state); + + try testing.expectEqual(Result.success, update(state, terminal)); + + var colors: Colors = std.mem.zeroes(Colors); + const sentinel: colorpkg.RGB.C = .{ .r = 0xAA, .g = 0xBB, .b = 0xCC }; + for (&colors.palette) |*entry| entry.* = sentinel; + + colors.size = @offsetOf(Colors, "palette") + @sizeOf(colorpkg.RGB.C) * 2; + try testing.expectEqual(Result.success, colors_get(state, &colors)); + + const state_colors = &state.?.state.colors; + try testing.expectEqual(state_colors.palette[0].cval(), colors.palette[0]); + try testing.expectEqual(state_colors.palette[1].cval(), colors.palette[1]); + try testing.expectEqual(sentinel, colors.palette[2]); +} diff --git a/vendor/libghostty-vt/src/terminal/c/result.zig b/vendor/libghostty-vt/src/terminal/c/result.zig new file mode 100644 index 00000000..32866328 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/result.zig @@ -0,0 +1,8 @@ +/// C: GhosttyResult +pub const Result = enum(c_int) { + success = 0, + out_of_memory = -1, + invalid_value = -2, + out_of_space = -3, + no_value = -4, +}; diff --git a/vendor/libghostty-vt/src/terminal/c/row.zig b/vendor/libghostty-vt/src/terminal/c/row.zig new file mode 100644 index 00000000..d4532706 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/row.zig @@ -0,0 +1,132 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const page = @import("../page.zig"); +const Row = page.Row; +const Result = @import("result.zig").Result; + +/// C: GhosttyRow +pub const CRow = Row.C; + +/// C: GhosttyRowSemanticPrompt +pub const SemanticPrompt = enum(c_int) { + none = 0, + prompt = 1, + prompt_continuation = 2, +}; + +/// C: GhosttyRowData +pub const RowData = enum(c_int) { + invalid = 0, + + /// Whether this row is soft-wrapped. + /// Output type: bool * + wrap = 1, + + /// Whether this row is a continuation of a soft-wrapped row. + /// Output type: bool * + wrap_continuation = 2, + + /// Whether any cells in this row have grapheme clusters. + /// Output type: bool * + grapheme = 3, + + /// Whether any cells in this row have styling (may have false positives). + /// Output type: bool * + styled = 4, + + /// Whether any cells in this row have hyperlinks (may have false positives). + /// Output type: bool * + hyperlink = 5, + + /// The semantic prompt state of this row. + /// Output type: GhosttyRowSemanticPrompt * + semantic_prompt = 6, + + /// Whether this row contains a Kitty virtual placeholder. + /// Output type: bool * + kitty_virtual_placeholder = 7, + + /// Whether this row is dirty and requires a redraw. + /// Output type: bool * + dirty = 8, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: RowData) type { + return switch (self) { + .invalid => void, + .wrap, .wrap_continuation, .grapheme, .styled, .hyperlink => bool, + .kitty_virtual_placeholder, .dirty => bool, + .semantic_prompt => SemanticPrompt, + }; + } +}; + +pub fn get( + row_: CRow, + data: RowData, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(RowData, @intFromEnum(data)) catch { + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| getTyped( + row_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn getTyped( + row_: CRow, + comptime data: RowData, + out: *data.OutType(), +) Result { + const row: Row = @bitCast(row_); + switch (data) { + .invalid => return .invalid_value, + .wrap => out.* = row.wrap, + .wrap_continuation => out.* = row.wrap_continuation, + .grapheme => out.* = row.grapheme, + .styled => out.* = row.styled, + .hyperlink => out.* = row.hyperlink, + .semantic_prompt => out.* = @enumFromInt(@intFromEnum(row.semantic_prompt)), + .kitty_virtual_placeholder => out.* = row.kitty_virtual_placeholder, + .dirty => out.* = row.dirty, + } + + return .success; +} + +test "get wrap" { + var zig_row: Row = @bitCast(@as(u64, 0)); + zig_row.wrap = true; + const row: CRow = @bitCast(zig_row); + var wrap: bool = false; + try testing.expectEqual(Result.success, get(row, .wrap, @ptrCast(&wrap))); + try testing.expect(wrap); +} + +test "get semantic_prompt" { + var zig_row: Row = @bitCast(@as(u64, 0)); + zig_row.semantic_prompt = .prompt; + const row: CRow = @bitCast(zig_row); + var sp: SemanticPrompt = .none; + try testing.expectEqual(Result.success, get(row, .semantic_prompt, @ptrCast(&sp))); + try testing.expectEqual(SemanticPrompt.prompt, sp); +} + +test "get dirty" { + var zig_row: Row = @bitCast(@as(u64, 0)); + zig_row.dirty = true; + const row: CRow = @bitCast(zig_row); + var dirty: bool = false; + try testing.expectEqual(Result.success, get(row, .dirty, @ptrCast(&dirty))); + try testing.expect(dirty); +} diff --git a/vendor/libghostty-vt/src/terminal/c/sgr.zig b/vendor/libghostty-vt/src/terminal/c/sgr.zig new file mode 100644 index 00000000..b0ef23d0 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/sgr.zig @@ -0,0 +1,179 @@ +const std = @import("std"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const sgr = @import("../sgr.zig"); +const Result = @import("result.zig").Result; + +const log = std.log.scoped(.sgr); + +/// Wrapper around parser that tracks the allocator for C API usage. +const ParserWrapper = struct { + parser: sgr.Parser, + alloc: Allocator, +}; + +/// C: GhosttySgrParser +pub const Parser = ?*ParserWrapper; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Parser, +) callconv(lib.calling_conv) Result { + const alloc = lib.alloc.default(alloc_); + const ptr = alloc.create(ParserWrapper) catch + return .out_of_memory; + ptr.* = .{ + .parser = .empty, + .alloc = alloc, + }; + result.* = ptr; + return .success; +} + +pub fn free(parser_: Parser) callconv(lib.calling_conv) void { + const wrapper = parser_ orelse return; + const alloc = wrapper.alloc; + const parser: *sgr.Parser = &wrapper.parser; + if (parser.params.len > 0) alloc.free(parser.params); + alloc.destroy(wrapper); +} + +pub fn reset(parser_: Parser) callconv(lib.calling_conv) void { + const wrapper = parser_ orelse return; + const parser: *sgr.Parser = &wrapper.parser; + parser.idx = 0; +} + +pub fn setParams( + parser_: Parser, + params: [*]const u16, + seps_: ?[*]const u8, + len: usize, +) callconv(lib.calling_conv) Result { + const wrapper = parser_ orelse return .invalid_value; + const alloc = wrapper.alloc; + const parser: *sgr.Parser = &wrapper.parser; + + // Copy our new parameters + const params_slice = alloc.dupe(u16, params[0..len]) catch + return .out_of_memory; + if (parser.params.len > 0) alloc.free(parser.params); + parser.params = params_slice; + + // If we have separators, set that state too. + parser.params_sep = .initEmpty(); + if (seps_) |seps| { + if (len > @TypeOf(parser.params_sep).bit_length) { + log.warn("ghostty_sgr_set_params: separators length {} exceeds max supported length {}", .{ + len, + @TypeOf(parser.params_sep).bit_length, + }); + return .invalid_value; + } + + for (seps[0..len], 0..) |sep, i| { + if (sep == ':') parser.params_sep.set(i); + } + } + + // Reset our parsing state + parser.idx = 0; + + return .success; +} + +pub fn next( + parser_: Parser, + result: *sgr.Attribute.C, +) callconv(lib.calling_conv) bool { + const wrapper = parser_ orelse return false; + const parser: *sgr.Parser = &wrapper.parser; + if (parser.next()) |attr| { + result.* = attr.cval(); + return true; + } + + return false; +} + +pub fn unknown_full( + unknown: sgr.Attribute.Unknown.C, + ptr: ?*[*]const u16, +) callconv(lib.calling_conv) usize { + if (ptr) |p| p.* = unknown.full_ptr; + return unknown.full_len; +} + +pub fn unknown_partial( + unknown: sgr.Attribute.Unknown.C, + ptr: ?*[*]const u16, +) callconv(lib.calling_conv) usize { + if (ptr) |p| p.* = unknown.partial_ptr; + return unknown.partial_len; +} + +pub fn attribute_tag( + attr: sgr.Attribute.C, +) callconv(lib.calling_conv) sgr.Attribute.Tag { + return attr.tag; +} + +pub fn attribute_value( + attr: *sgr.Attribute.C, +) callconv(lib.calling_conv) *sgr.Attribute.CValue { + return &attr.value; +} + +pub fn wasm_alloc_attribute() callconv(lib.calling_conv) *sgr.Attribute.C { + const alloc = std.heap.wasm_allocator; + const ptr = alloc.create(sgr.Attribute.C) catch @panic("out of memory"); + return ptr; +} + +pub fn wasm_free_attribute(attr: *sgr.Attribute.C) callconv(lib.calling_conv) void { + const alloc = std.heap.wasm_allocator; + alloc.destroy(attr); +} + +test "alloc" { + var p: Parser = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &p, + )); + free(p); +} + +test "simple params, no seps" { + var p: Parser = undefined; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &p, + )); + defer free(p); + + try testing.expectEqual(Result.success, setParams( + p, + &.{1}, + null, + 1, + )); + + // Set it twice on purpose to make sure we don't leak. + try testing.expectEqual(Result.success, setParams( + p, + &.{1}, + null, + 1, + )); + + // Verify we get bold + var attr: sgr.Attribute.C = undefined; + try testing.expect(next(p, &attr)); + try testing.expectEqual(.bold, attr.tag); + + // Nothing else + try testing.expect(!next(p, &attr)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/size_report.zig b/vendor/libghostty-vt/src/terminal/c/size_report.zig new file mode 100644 index 00000000..1c350c8f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/size_report.zig @@ -0,0 +1,82 @@ +const std = @import("std"); +const lib = @import("../lib.zig"); +const terminal_size_report = @import("../size_report.zig"); +const Result = @import("result.zig").Result; + +/// C: GhosttySizeReportStyle +pub const Style = terminal_size_report.Style; + +/// C: GhosttySizeReportSize +pub const Size = terminal_size_report.Size; + +pub fn encode( + style: Style, + size: Size, + out_: ?[*]u8, + out_len: usize, + out_written: *usize, +) callconv(lib.calling_conv) Result { + var writer: std.Io.Writer = .fixed(if (out_) |out| out[0..out_len] else &.{}); + terminal_size_report.encode(&writer, style, size) catch |err| switch (err) { + error.WriteFailed => { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + terminal_size_report.encode(&discarding.writer, style, size) catch unreachable; + out_written.* = @intCast(discarding.count); + return .out_of_space; + }, + }; + + out_written.* = writer.end; + return .success; +} + +test "encode mode 2048" { + var buf: [64]u8 = undefined; + var written: usize = 0; + const result = encode(.mode_2048, .{ + .rows = 24, + .columns = 80, + .cell_width = 9, + .cell_height = 18, + }, &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1B[48;24;80;432;720t", buf[0..written]); +} + +test "encode csi 14 t" { + var buf: [64]u8 = undefined; + var written: usize = 0; + const result = encode(.csi_14_t, .{ + .rows = 24, + .columns = 80, + .cell_width = 9, + .cell_height = 18, + }, &buf, buf.len, &written); + try std.testing.expectEqual(.success, result); + try std.testing.expectEqualStrings("\x1b[4;432;720t", buf[0..written]); +} + +test "encode with insufficient buffer" { + var buf: [1]u8 = undefined; + var written: usize = 0; + const result = encode(.csi_18_t, .{ + .rows = 24, + .columns = 80, + .cell_width = 9, + .cell_height = 18, + }, &buf, buf.len, &written); + try std.testing.expectEqual(.out_of_space, result); + try std.testing.expect(written > 1); +} + +test "encode with null buffer" { + var written: usize = 0; + const result = encode(.csi_18_t, .{ + .rows = 24, + .columns = 80, + .cell_width = 9, + .cell_height = 18, + }, null, 0, &written); + try std.testing.expectEqual(.out_of_space, result); + try std.testing.expect(written > 0); +} diff --git a/vendor/libghostty-vt/src/terminal/c/style.zig b/vendor/libghostty-vt/src/terminal/c/style.zig new file mode 100644 index 00000000..82729fa9 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/style.zig @@ -0,0 +1,134 @@ +const std = @import("std"); +const assert = std.debug.assert; +const testing = std.testing; +const lib = @import("../lib.zig"); +const style = @import("../style.zig"); +const color = @import("../color.zig"); +const sgr = @import("../sgr.zig"); + +/// C: GhosttyStyleColorTag +pub const ColorTag = enum(c_int) { + none = 0, + palette = 1, + rgb = 2, +}; + +/// C: GhosttyStyleColorValue +pub const ColorValue = extern union { + palette: u8, + rgb: color.RGB.C, + _padding: u64, +}; + +/// C: GhosttyStyleColor +pub const Color = extern struct { + tag: ColorTag, + value: ColorValue, + + pub fn fromColor(c: style.Style.Color) Color { + return switch (c) { + .none => .{ + .tag = .none, + .value = .{ ._padding = 0 }, + }, + .palette => |idx| .{ + .tag = .palette, + .value = .{ .palette = idx }, + }, + .rgb => |rgb| .{ + .tag = .rgb, + .value = .{ .rgb = rgb.cval() }, + }, + }; + } +}; + +/// C: GhosttyStyle +pub const Style = extern struct { + size: usize = @sizeOf(Style), + fg_color: Color, + bg_color: Color, + underline_color: Color, + bold: bool, + italic: bool, + faint: bool, + blink: bool, + inverse: bool, + invisible: bool, + strikethrough: bool, + overline: bool, + underline: c_int, + + pub fn fromStyle(s: style.Style) Style { + return .{ + .fg_color = .fromColor(s.fg_color), + .bg_color = .fromColor(s.bg_color), + .underline_color = .fromColor(s.underline_color), + .bold = s.flags.bold, + .italic = s.flags.italic, + .faint = s.flags.faint, + .blink = s.flags.blink, + .inverse = s.flags.inverse, + .invisible = s.flags.invisible, + .strikethrough = s.flags.strikethrough, + .overline = s.flags.overline, + .underline = @intFromEnum(s.flags.underline), + }; + } +}; + +/// Returns the default style. +pub fn default_style(result: *Style) callconv(lib.calling_conv) void { + result.* = .fromStyle(.{}); + assert(result.size == @sizeOf(Style)); +} + +/// Returns true if the style is the default style. +pub fn style_is_default(s: *const Style) callconv(lib.calling_conv) bool { + assert(s.size == @sizeOf(Style)); + return s.fg_color.tag == .none and + s.bg_color.tag == .none and + s.underline_color.tag == .none and + s.bold == false and + s.italic == false and + s.faint == false and + s.blink == false and + s.inverse == false and + s.invisible == false and + s.strikethrough == false and + s.overline == false and + s.underline == 0; +} + +test "default style" { + var s: Style = undefined; + default_style(&s); + try testing.expect(style_is_default(&s)); + try testing.expectEqual(ColorTag.none, s.fg_color.tag); + try testing.expectEqual(ColorTag.none, s.bg_color.tag); + try testing.expectEqual(ColorTag.none, s.underline_color.tag); + try testing.expect(!s.bold); + try testing.expect(!s.italic); + try testing.expectEqual(@as(c_int, 0), s.underline); +} + +test "convert style with colors" { + const zig_style: style.Style = .{ + .fg_color = .{ .palette = 42 }, + .bg_color = .{ .rgb = .{ .r = 255, .g = 128, .b = 64 } }, + .underline_color = .none, + .flags = .{ .bold = true, .underline = .curly }, + }; + + const c_style: Style = .fromStyle(zig_style); + try testing.expectEqual(ColorTag.palette, c_style.fg_color.tag); + try testing.expectEqual(@as(u8, 42), c_style.fg_color.value.palette); + try testing.expectEqual(ColorTag.rgb, c_style.bg_color.tag); + try testing.expectEqual(@as(u8, 255), c_style.bg_color.value.rgb.r); + try testing.expectEqual(@as(u8, 128), c_style.bg_color.value.rgb.g); + try testing.expectEqual(@as(u8, 64), c_style.bg_color.value.rgb.b); + try testing.expectEqual(ColorTag.none, c_style.underline_color.tag); + try testing.expect(c_style.bold); + try testing.expectEqual(@as(c_int, 3), c_style.underline); + try testing.expect(!style_is_default(&c_style)); +} diff --git a/vendor/libghostty-vt/src/terminal/c/terminal.zig b/vendor/libghostty-vt/src/terminal/c/terminal.zig new file mode 100644 index 00000000..ec749ffa --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/terminal.zig @@ -0,0 +1,2358 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("../lib.zig"); +const CAllocator = lib.alloc.Allocator; +const ZigTerminal = @import("../Terminal.zig"); +const Stream = @import("../stream_terminal.zig").Stream; +const ScreenSet = @import("../ScreenSet.zig"); +const PageList = @import("../PageList.zig"); +const kitty = @import("../kitty/key.zig"); +const modes = @import("../modes.zig"); +const point = @import("../point.zig"); +const size = @import("../size.zig"); +const device_attributes = @import("../device_attributes.zig"); +const device_status = @import("../device_status.zig"); +const size_report = @import("../size_report.zig"); +const cell_c = @import("cell.zig"); +const row_c = @import("row.zig"); +const grid_ref_c = @import("grid_ref.zig"); +const style_c = @import("style.zig"); +const color = @import("../color.zig"); +const Result = @import("result.zig").Result; + +const Handler = @import("../stream_terminal.zig").Handler; + +const log = std.log.scoped(.terminal_c); + +/// Wrapper around ZigTerminal that tracks additional state for C API usage, +/// such as the persistent VT stream needed to handle escape sequences split +/// across multiple vt_write calls. +const TerminalWrapper = struct { + terminal: *ZigTerminal, + stream: Stream, + effects: Effects = .{}, +}; + +/// C callback state for terminal effects. Trampolines are always +/// installed on the stream handler; they check these fields and +/// no-op when the corresponding callback is null. +const Effects = struct { + userdata: ?*anyopaque = null, + write_pty: ?WritePtyFn = null, + bell: ?BellFn = null, + color_scheme: ?ColorSchemeFn = null, + device_attributes_cb: ?DeviceAttributesFn = null, + enquiry: ?EnquiryFn = null, + xtversion: ?XtversionFn = null, + title_changed: ?TitleChangedFn = null, + size_cb: ?SizeFn = null, + + /// Scratch buffer for DA1 feature codes. The device attributes + /// trampoline converts C feature codes into this buffer and returns + /// a slice pointing into it. Storing it here ensures the slice + /// remains valid after the trampoline returns, since the caller + /// (`reportDeviceAttributes`) reads it before any re-entrant call. + da_features_buf: [64]device_attributes.Primary.Feature = undefined, + + /// C function pointer type for the write_pty callback. + pub const WritePtyFn = *const fn (Terminal, ?*anyopaque, [*]const u8, usize) callconv(lib.calling_conv) void; + + /// C function pointer type for the bell callback. + pub const BellFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) void; + + /// C function pointer type for the color_scheme callback. + /// Returns true and fills out_scheme if a color scheme is available, + /// or returns false to silently ignore the query. + pub const ColorSchemeFn = *const fn (Terminal, ?*anyopaque, *device_status.ColorScheme) callconv(lib.calling_conv) bool; + + /// C function pointer type for the enquiry callback. + /// Returns the response bytes. The memory must remain valid + /// until the callback returns. + pub const EnquiryFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) lib.String; + + /// C function pointer type for the xtversion callback. + /// Returns the version string (e.g. "ghostty 1.2.3"). The memory + /// must remain valid until the callback returns. An empty string + /// (len=0) causes the default "libghostty" to be reported. + pub const XtversionFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) lib.String; + + /// C function pointer type for the title_changed callback. + pub const TitleChangedFn = *const fn (Terminal, ?*anyopaque) callconv(lib.calling_conv) void; + + /// C function pointer type for the size callback. + /// Returns true and fills out_size if size is available, + /// or returns false to silently ignore the query. + pub const SizeFn = *const fn (Terminal, ?*anyopaque, *size_report.Size) callconv(lib.calling_conv) bool; + + /// C function pointer type for the device_attributes callback. + /// Returns true and fills out_attrs if attributes are available, + /// or returns false to silently ignore the query. + pub const DeviceAttributesFn = *const fn (Terminal, ?*anyopaque, *CDeviceAttributes) callconv(lib.calling_conv) bool; + + /// C-compatible device attributes struct. + /// C: GhosttyDeviceAttributes + pub const CDeviceAttributes = extern struct { + primary: Primary, + secondary: Secondary, + tertiary: Tertiary, + + pub const Primary = extern struct { + conformance_level: u16, + features: [64]u16, + num_features: usize, + }; + + pub const Secondary = extern struct { + device_type: u16, + firmware_version: u16, + rom_cartridge: u16, + }; + + pub const Tertiary = extern struct { + unit_id: u32, + }; + }; + + fn writePtyTrampoline(handler: *Handler, data: [:0]const u8) void { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.write_pty orelse return; + func(@ptrCast(wrapper), wrapper.effects.userdata, data.ptr, data.len); + } + + fn bellTrampoline(handler: *Handler) void { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.bell orelse return; + func(@ptrCast(wrapper), wrapper.effects.userdata); + } + + fn colorSchemeTrampoline(handler: *Handler) ?device_status.ColorScheme { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.color_scheme orelse return null; + var scheme: device_status.ColorScheme = undefined; + if (func(@ptrCast(wrapper), wrapper.effects.userdata, &scheme)) return scheme; + return null; + } + + fn deviceAttributesTrampoline(handler: *Handler) device_attributes.Attributes { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.device_attributes_cb orelse return .{}; + + // Get our attributes from the callback. + var c_attrs: CDeviceAttributes = undefined; + if (!func(@ptrCast(wrapper), wrapper.effects.userdata, &c_attrs)) return .{}; + + // Note below we use a lot of enumFromInt but its always safe + // because all our types are non-exhaustive enums. + + const n: usize = @min(c_attrs.primary.num_features, 64); + for (0..n) |i| wrapper.effects.da_features_buf[i] = @enumFromInt(c_attrs.primary.features[i]); + + return .{ + .primary = .{ + .conformance_level = @enumFromInt(c_attrs.primary.conformance_level), + .features = wrapper.effects.da_features_buf[0..n], + }, + .secondary = .{ + .device_type = @enumFromInt(c_attrs.secondary.device_type), + .firmware_version = c_attrs.secondary.firmware_version, + .rom_cartridge = c_attrs.secondary.rom_cartridge, + }, + .tertiary = .{ + .unit_id = c_attrs.tertiary.unit_id, + }, + }; + } + + fn enquiryTrampoline(handler: *Handler) []const u8 { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.enquiry orelse return ""; + const result = func(@ptrCast(wrapper), wrapper.effects.userdata); + if (result.len == 0) return ""; + return result.ptr[0..result.len]; + } + + fn xtversionTrampoline(handler: *Handler) []const u8 { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.xtversion orelse return ""; + const result = func(@ptrCast(wrapper), wrapper.effects.userdata); + if (result.len == 0) return ""; + return result.ptr[0..result.len]; + } + + fn titleChangedTrampoline(handler: *Handler) void { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.title_changed orelse return; + func(@ptrCast(wrapper), wrapper.effects.userdata); + } + + fn sizeTrampoline(handler: *Handler) ?size_report.Size { + const stream_ptr: *Stream = @fieldParentPtr("handler", handler); + const wrapper: *TerminalWrapper = @fieldParentPtr("stream", stream_ptr); + const func = wrapper.effects.size_cb orelse return null; + var s: size_report.Size = undefined; + if (func(@ptrCast(wrapper), wrapper.effects.userdata, &s)) return s; + return null; + } +}; + +/// C: GhosttyTerminal +pub const Terminal = ?*TerminalWrapper; + +/// C: GhosttyTerminalOptions +pub const Options = extern struct { + cols: size.CellCountInt, + rows: size.CellCountInt, + max_scrollback: usize, +}; + +const NewError = error{ + InvalidValue, + OutOfMemory, +}; + +pub fn new( + alloc_: ?*const CAllocator, + result: *Terminal, + opts: Options, +) callconv(lib.calling_conv) Result { + result.* = new_(alloc_, opts) catch |err| { + result.* = null; + return switch (err) { + error.InvalidValue => .invalid_value, + error.OutOfMemory => .out_of_memory, + }; + }; + + return .success; +} + +fn new_( + alloc_: ?*const CAllocator, + opts: Options, +) NewError!*TerminalWrapper { + if (opts.cols == 0 or opts.rows == 0) return error.InvalidValue; + + const alloc = lib.alloc.default(alloc_); + const t = alloc.create(ZigTerminal) catch + return error.OutOfMemory; + errdefer alloc.destroy(t); + + const wrapper = alloc.create(TerminalWrapper) catch + return error.OutOfMemory; + errdefer alloc.destroy(wrapper); + + // Setup our terminal + t.* = try .init(alloc, .{ + .cols = opts.cols, + .rows = opts.rows, + .max_scrollback = opts.max_scrollback, + }); + errdefer t.deinit(alloc); + + // Setup our stream with trampolines always installed so that + // setting C callbacks at any time takes effect immediately. + var handler: Stream.Handler = t.vtHandler(); + handler.effects = .{ + .write_pty = &Effects.writePtyTrampoline, + .bell = &Effects.bellTrampoline, + .color_scheme = &Effects.colorSchemeTrampoline, + .device_attributes = &Effects.deviceAttributesTrampoline, + .enquiry = &Effects.enquiryTrampoline, + .xtversion = &Effects.xtversionTrampoline, + .title_changed = &Effects.titleChangedTrampoline, + .size = &Effects.sizeTrampoline, + }; + + wrapper.* = .{ + .terminal = t, + .stream = .initAlloc(alloc, handler), + }; + + return wrapper; +} + +pub fn vt_write( + terminal_: Terminal, + ptr: [*]const u8, + len: usize, +) callconv(lib.calling_conv) void { + const wrapper = terminal_ orelse return; + wrapper.stream.nextSlice(ptr[0..len]); +} + +/// C: GhosttyTerminalOption +pub const Option = enum(c_int) { + userdata = 0, + write_pty = 1, + bell = 2, + enquiry = 3, + xtversion = 4, + title_changed = 5, + size_cb = 6, + color_scheme = 7, + device_attributes = 8, + title = 9, + pwd = 10, + color_foreground = 11, + color_background = 12, + color_cursor = 13, + color_palette = 14, + + /// Input type expected for setting the option. + pub fn InType(comptime self: Option) type { + return switch (self) { + .userdata => ?*const anyopaque, + .write_pty => ?Effects.WritePtyFn, + .bell => ?Effects.BellFn, + .color_scheme => ?Effects.ColorSchemeFn, + .device_attributes => ?Effects.DeviceAttributesFn, + .enquiry => ?Effects.EnquiryFn, + .xtversion => ?Effects.XtversionFn, + .title_changed => ?Effects.TitleChangedFn, + .size_cb => ?Effects.SizeFn, + .title, .pwd => ?*const lib.String, + .color_foreground, .color_background, .color_cursor => ?*const color.RGB.C, + .color_palette => ?*const color.PaletteC, + }; + } +}; + +pub fn set( + terminal_: Terminal, + option: Option, + value: ?*const anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(Option, @intFromEnum(option)) catch { + log.warn("terminal_set invalid option value={d}", .{@intFromEnum(option)}); + return .invalid_value; + }; + } + + const wrapper = terminal_ orelse return .invalid_value; + + return switch (option) { + inline else => |comptime_option| setTyped( + wrapper, + comptime_option, + @ptrCast(@alignCast(value)), + ), + }; +} + +fn setTyped( + wrapper: *TerminalWrapper, + comptime option: Option, + value: option.InType(), +) Result { + switch (option) { + .userdata => wrapper.effects.userdata = @constCast(value), + .write_pty => wrapper.effects.write_pty = value, + .bell => wrapper.effects.bell = value, + .color_scheme => wrapper.effects.color_scheme = value, + .device_attributes => wrapper.effects.device_attributes_cb = value, + .enquiry => wrapper.effects.enquiry = value, + .xtversion => wrapper.effects.xtversion = value, + .title_changed => wrapper.effects.title_changed = value, + .size_cb => wrapper.effects.size_cb = value, + .title => { + const str = if (value) |v| v.ptr[0..v.len] else ""; + wrapper.terminal.setTitle(str) catch return .out_of_memory; + }, + .pwd => { + const str = if (value) |v| v.ptr[0..v.len] else ""; + wrapper.terminal.setPwd(str) catch return .out_of_memory; + }, + .color_foreground => { + wrapper.terminal.colors.foreground.default = if (value) |v| .fromC(v.*) else null; + wrapper.terminal.flags.dirty.palette = true; + }, + .color_background => { + wrapper.terminal.colors.background.default = if (value) |v| .fromC(v.*) else null; + wrapper.terminal.flags.dirty.palette = true; + }, + .color_cursor => { + wrapper.terminal.colors.cursor.default = if (value) |v| .fromC(v.*) else null; + wrapper.terminal.flags.dirty.palette = true; + }, + .color_palette => { + wrapper.terminal.colors.palette.changeDefault( + if (value) |v| color.paletteZval(v) else color.default, + ); + wrapper.terminal.flags.dirty.palette = true; + }, + } + return .success; +} + +/// C: GhosttyDeviceAttributes +pub const DeviceAttributes = Effects.CDeviceAttributes; + +/// C: GhosttyTerminalScrollViewport +pub const ScrollViewport = ZigTerminal.ScrollViewport.C; + +pub fn scroll_viewport( + terminal_: Terminal, + behavior: ScrollViewport, +) callconv(lib.calling_conv) void { + const t: *ZigTerminal = (terminal_ orelse return).terminal; + t.scrollViewport(switch (behavior.tag) { + .top => .top, + .bottom => .bottom, + .delta => .{ .delta = behavior.value.delta }, + }); +} + +pub fn resize( + terminal_: Terminal, + cols: size.CellCountInt, + rows: size.CellCountInt, + cell_width_px: u32, + cell_height_px: u32, +) callconv(lib.calling_conv) Result { + const wrapper = terminal_ orelse return .invalid_value; + const t = wrapper.terminal; + if (cols == 0 or rows == 0) return .invalid_value; + t.resize(t.gpa(), cols, rows) catch return .out_of_memory; + + // Update pixel sizes + t.width_px = std.math.mul(u32, cols, cell_width_px) catch std.math.maxInt(u32); + t.height_px = std.math.mul(u32, rows, cell_height_px) catch std.math.maxInt(u32); + + // Disable synchronized output mode so that we show changes + // immediately for a resize. This is allowed by the spec. + t.modes.set(.synchronized_output, false); + + // If we have in-band size reporting enabled, send a report. + if (t.modes.get(.in_band_size_reports)) in_band: { + const func = wrapper.effects.write_pty orelse break :in_band; + + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + size_report.encode(&writer, .mode_2048, .{ + .rows = rows, + .columns = cols, + .cell_width = cell_width_px, + .cell_height = cell_height_px, + }) catch break :in_band; + + const data = writer.buffered(); + func(@ptrCast(wrapper), wrapper.effects.userdata, data.ptr, data.len); + } + + return .success; +} + +pub fn reset(terminal_: Terminal) callconv(lib.calling_conv) void { + const t: *ZigTerminal = (terminal_ orelse return).terminal; + t.fullReset(); +} + +pub fn mode_get( + terminal_: Terminal, + tag: modes.ModeTag.Backing, + out_value: *bool, +) callconv(lib.calling_conv) Result { + const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; + const mode_tag: modes.ModeTag = @bitCast(tag); + const mode = modes.modeFromInt(mode_tag.value, mode_tag.ansi) orelse return .invalid_value; + out_value.* = t.modes.get(mode); + return .success; +} + +pub fn mode_set( + terminal_: Terminal, + tag: modes.ModeTag.Backing, + value: bool, +) callconv(lib.calling_conv) Result { + const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; + const mode_tag: modes.ModeTag = @bitCast(tag); + const mode = modes.modeFromInt(mode_tag.value, mode_tag.ansi) orelse return .invalid_value; + t.modes.set(mode, value); + return .success; +} + +/// C: GhosttyTerminalScreen +pub const TerminalScreen = ScreenSet.Key; + +/// C: GhosttyTerminalScrollbar +pub const TerminalScrollbar = PageList.Scrollbar.C; + +/// C: GhosttyTerminalData +pub const TerminalData = enum(c_int) { + invalid = 0, + cols = 1, + rows = 2, + cursor_x = 3, + cursor_y = 4, + cursor_pending_wrap = 5, + active_screen = 6, + cursor_visible = 7, + kitty_keyboard_flags = 8, + scrollbar = 9, + cursor_style = 10, + mouse_tracking = 11, + title = 12, + pwd = 13, + total_rows = 14, + scrollback_rows = 15, + width_px = 16, + height_px = 17, + color_foreground = 18, + color_background = 19, + color_cursor = 20, + color_palette = 21, + color_foreground_default = 22, + color_background_default = 23, + color_cursor_default = 24, + color_palette_default = 25, + + /// Output type expected for querying the data of the given kind. + pub fn OutType(comptime self: TerminalData) type { + return switch (self) { + .invalid => void, + .cols, .rows, .cursor_x, .cursor_y => size.CellCountInt, + .cursor_pending_wrap, .cursor_visible, .mouse_tracking => bool, + .active_screen => TerminalScreen, + .kitty_keyboard_flags => u8, + .scrollbar => TerminalScrollbar, + .cursor_style => style_c.Style, + .title, .pwd => lib.String, + .total_rows, .scrollback_rows => usize, + .width_px, .height_px => u32, + .color_foreground, + .color_background, + .color_cursor, + .color_foreground_default, + .color_background_default, + .color_cursor_default, + => color.RGB.C, + .color_palette, .color_palette_default => color.PaletteC, + }; + } +}; + +pub fn get( + terminal_: Terminal, + data: TerminalData, + out: ?*anyopaque, +) callconv(lib.calling_conv) Result { + if (comptime std.debug.runtime_safety) { + _ = std.meta.intToEnum(TerminalData, @intFromEnum(data)) catch { + log.warn("terminal_get invalid data value={d}", .{@intFromEnum(data)}); + return .invalid_value; + }; + } + + return switch (data) { + .invalid => .invalid_value, + inline else => |comptime_data| getTyped( + terminal_, + comptime_data, + @ptrCast(@alignCast(out)), + ), + }; +} + +fn getTyped( + terminal_: Terminal, + comptime data: TerminalData, + out: *data.OutType(), +) Result { + const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; + switch (data) { + .invalid => return .invalid_value, + .cols => out.* = t.cols, + .rows => out.* = t.rows, + .cursor_x => out.* = t.screens.active.cursor.x, + .cursor_y => out.* = t.screens.active.cursor.y, + .cursor_pending_wrap => out.* = t.screens.active.cursor.pending_wrap, + .active_screen => out.* = t.screens.active_key, + .cursor_visible => out.* = t.modes.get(.cursor_visible), + .kitty_keyboard_flags => out.* = @as(u8, t.screens.active.kitty_keyboard.current().int()), + .scrollbar => out.* = t.screens.active.pages.scrollbar().cval(), + .cursor_style => out.* = .fromStyle(t.screens.active.cursor.style), + .mouse_tracking => out.* = t.modes.get(.mouse_event_x10) or + t.modes.get(.mouse_event_normal) or + t.modes.get(.mouse_event_button) or + t.modes.get(.mouse_event_any), + .title => { + const title = t.getTitle() orelse ""; + out.* = .{ .ptr = title.ptr, .len = title.len }; + }, + .pwd => { + const pwd = t.getPwd() orelse ""; + out.* = .{ .ptr = pwd.ptr, .len = pwd.len }; + }, + .total_rows => out.* = t.screens.active.pages.total_rows, + .scrollback_rows => out.* = t.screens.active.pages.total_rows - t.rows, + .width_px => out.* = t.width_px, + .height_px => out.* = t.height_px, + .color_foreground => out.* = (t.colors.foreground.get() orelse return .no_value).cval(), + .color_background => out.* = (t.colors.background.get() orelse return .no_value).cval(), + .color_cursor => out.* = (t.colors.cursor.get() orelse return .no_value).cval(), + .color_foreground_default => out.* = (t.colors.foreground.default orelse return .no_value).cval(), + .color_background_default => out.* = (t.colors.background.default orelse return .no_value).cval(), + .color_cursor_default => out.* = (t.colors.cursor.default orelse return .no_value).cval(), + .color_palette => out.* = color.paletteCval(&t.colors.palette.current), + .color_palette_default => out.* = color.paletteCval(&t.colors.palette.original), + } + + return .success; +} + +pub fn grid_ref( + terminal_: Terminal, + pt: point.Point.C, + out_ref: ?*grid_ref_c.CGridRef, +) callconv(lib.calling_conv) Result { + const t: *ZigTerminal = (terminal_ orelse return .invalid_value).terminal; + const zig_pt: point.Point = switch (pt.tag) { + .active => .{ .active = pt.value.active }, + .viewport => .{ .viewport = pt.value.viewport }, + .screen => .{ .screen = pt.value.screen }, + .history => .{ .history = pt.value.history }, + }; + const p = t.screens.active.pages.pin(zig_pt) orelse + return .invalid_value; + if (out_ref) |out| out.* = grid_ref_c.CGridRef.fromPin(p); + return .success; +} + +pub fn free(terminal_: Terminal) callconv(lib.calling_conv) void { + const wrapper = terminal_ orelse return; + const t = wrapper.terminal; + + wrapper.stream.deinit(); + const alloc = t.gpa(); + t.deinit(alloc); + alloc.destroy(t); + alloc.destroy(wrapper); +} + +test "new/free" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + + try testing.expect(t != null); + free(t); +} + +test "new invalid value" { + var t: Terminal = null; + + try testing.expectEqual(Result.invalid_value, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 0, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + try testing.expect(t == null); + + try testing.expectEqual(Result.invalid_value, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 0, + .max_scrollback = 10_000, + }, + )); + try testing.expect(t == null); +} + +test "free null" { + free(null); +} + +test "scroll_viewport" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 5, + .rows = 2, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + const zt = t.?.terminal; + + // Write "hello" on the first line + vt_write(t, "hello", 5); + + // Push "hello" into scrollback with 3 newlines (index = ESC D) + vt_write(t, "\x1bD\x1bD\x1bD", 6); + { + // Viewport should be empty now since hello scrolled off + const str = try zt.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + // Scroll to top: "hello" should be visible again + scroll_viewport(t, .{ .tag = .top, .value = undefined }); + { + const str = try zt.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hello", str); + } + + // Scroll to bottom: viewport should be empty again + scroll_viewport(t, .{ .tag = .bottom, .value = undefined }); + { + const str = try zt.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + + // Scroll up by delta to bring "hello" back into view + scroll_viewport(t, .{ .tag = .delta, .value = .{ .delta = -3 } }); + { + const str = try zt.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("hello", str); + } +} + +test "scroll_viewport null" { + scroll_viewport(null, .{ .tag = .top, .value = undefined }); +} + +test "reset" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + vt_write(t, "Hello", 5); + reset(t); + + const str = try t.?.terminal.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); +} + +test "reset null" { + reset(null); +} + +test "resize" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + try testing.expectEqual(Result.success, resize(t, 40, 12, 9, 18)); + try testing.expectEqual(40, t.?.terminal.cols); + try testing.expectEqual(12, t.?.terminal.rows); +} + +test "resize null" { + try testing.expectEqual(Result.invalid_value, resize(null, 80, 24, 9, 18)); +} + +test "resize invalid value" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + try testing.expectEqual(Result.invalid_value, resize(t, 0, 24, 9, 18)); + try testing.expectEqual(Result.invalid_value, resize(t, 80, 0, 9, 18)); +} + +test "mode_get and mode_set" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var value: bool = undefined; + + // DEC mode 25 (cursor_visible) defaults to true + const cursor_visible: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); + try testing.expectEqual(Result.success, mode_get(t, cursor_visible, &value)); + try testing.expect(value); + + // Set it to false + try testing.expectEqual(Result.success, mode_set(t, cursor_visible, false)); + try testing.expectEqual(Result.success, mode_get(t, cursor_visible, &value)); + try testing.expect(!value); + + // ANSI mode 4 (insert) defaults to false + const insert: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 4, .ansi = true }); + try testing.expectEqual(Result.success, mode_get(t, insert, &value)); + try testing.expect(!value); + + try testing.expectEqual(Result.success, mode_set(t, insert, true)); + try testing.expectEqual(Result.success, mode_get(t, insert, &value)); + try testing.expect(value); +} + +test "mode_get null" { + var value: bool = undefined; + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); + try testing.expectEqual(Result.invalid_value, mode_get(null, tag, &value)); +} + +test "mode_set null" { + const tag: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); + try testing.expectEqual(Result.invalid_value, mode_set(null, tag, true)); +} + +test "mode_get unknown mode" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var value: bool = undefined; + const unknown: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }); + try testing.expectEqual(Result.invalid_value, mode_get(t, unknown, &value)); +} + +test "mode_set unknown mode" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const unknown: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9999, .ansi = false }); + try testing.expectEqual(Result.invalid_value, mode_set(t, unknown, true)); +} + +test "vt_write" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + vt_write(t, "Hello", 5); + + const str = try t.?.terminal.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Hello", str); +} + +test "vt_write split escape sequence" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + // Write "Hello" in bold by splitting the CSI bold sequence across two writes. + // ESC [ 1 m = bold on, ESC [ 0 m = reset + // Split ESC from the rest of the CSI sequence. + vt_write(t, "Hello \x1b", 7); + vt_write(t, "[1mBold\x1b[0m", 10); + + const str = try t.?.terminal.plainString(testing.allocator); + defer testing.allocator.free(str); + // If the escape sequence leaked, we'd see "[1mBold" as literal text. + try testing.expectEqualStrings("Hello Bold", str); +} + +test "get cols and rows" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var cols: size.CellCountInt = undefined; + var rows: size.CellCountInt = undefined; + try testing.expectEqual(Result.success, get(t, .cols, @ptrCast(&cols))); + try testing.expectEqual(Result.success, get(t, .rows, @ptrCast(&rows))); + try testing.expectEqual(80, cols); + try testing.expectEqual(24, rows); +} + +test "get cursor position" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + vt_write(t, "Hello", 5); + + var x: size.CellCountInt = undefined; + var y: size.CellCountInt = undefined; + try testing.expectEqual(Result.success, get(t, .cursor_x, @ptrCast(&x))); + try testing.expectEqual(Result.success, get(t, .cursor_y, @ptrCast(&y))); + try testing.expectEqual(5, x); + try testing.expectEqual(0, y); +} + +test "get null" { + var cols: size.CellCountInt = undefined; + try testing.expectEqual(Result.invalid_value, get(null, .cols, @ptrCast(&cols))); +} + +test "get cursor_visible" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var visible: bool = undefined; + try testing.expectEqual(Result.success, get(t, .cursor_visible, @ptrCast(&visible))); + try testing.expect(visible); + + // DEC mode 25 controls cursor visibility + const cursor_visible_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 25, .ansi = false }); + try testing.expectEqual(Result.success, mode_set(t, cursor_visible_mode, false)); + try testing.expectEqual(Result.success, get(t, .cursor_visible, @ptrCast(&visible))); + try testing.expect(!visible); +} + +test "get active_screen" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var screen: TerminalScreen = undefined; + try testing.expectEqual(Result.success, get(t, .active_screen, @ptrCast(&screen))); + try testing.expectEqual(.primary, screen); +} + +test "get kitty_keyboard_flags" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var flags: u8 = undefined; + try testing.expectEqual(Result.success, get(t, .kitty_keyboard_flags, @ptrCast(&flags))); + try testing.expectEqual(0, flags); + + // Push kitty flags via VT sequence: CSI > 3 u (push disambiguate | report_events) + vt_write(t, "\x1b[>3u", 5); + + try testing.expectEqual(Result.success, get(t, .kitty_keyboard_flags, @ptrCast(&flags))); + try testing.expectEqual(3, flags); +} + +test "get mouse_tracking" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var tracking: bool = undefined; + try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); + try testing.expect(!tracking); + + // Enable X10 mouse (DEC mode 9) + const x10_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 9, .ansi = false }); + try testing.expectEqual(Result.success, mode_set(t, x10_mode, true)); + try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); + try testing.expect(tracking); + + // Disable X10, enable normal mouse (DEC mode 1000) + try testing.expectEqual(Result.success, mode_set(t, x10_mode, false)); + const normal_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1000, .ansi = false }); + try testing.expectEqual(Result.success, mode_set(t, normal_mode, true)); + try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); + try testing.expect(tracking); + + // Disable normal, enable button mouse (DEC mode 1002) + try testing.expectEqual(Result.success, mode_set(t, normal_mode, false)); + const button_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1002, .ansi = false }); + try testing.expectEqual(Result.success, mode_set(t, button_mode, true)); + try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); + try testing.expect(tracking); + + // Disable button, enable any mouse (DEC mode 1003) + try testing.expectEqual(Result.success, mode_set(t, button_mode, false)); + const any_mode: modes.ModeTag.Backing = @bitCast(modes.ModeTag{ .value = 1003, .ansi = false }); + try testing.expectEqual(Result.success, mode_set(t, any_mode, true)); + try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); + try testing.expect(tracking); + + // Disable all - should be false again + try testing.expectEqual(Result.success, mode_set(t, any_mode, false)); + try testing.expectEqual(Result.success, get(t, .mouse_tracking, @ptrCast(&tracking))); + try testing.expect(!tracking); +} + +test "get total_rows" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + var total: usize = undefined; + try testing.expectEqual(Result.success, get(t, .total_rows, @ptrCast(&total))); + try testing.expect(total >= 24); +} + +test "get scrollback_rows" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 3, + .max_scrollback = 10_000, + }, + )); + defer free(t); + + var scrollback: usize = undefined; + try testing.expectEqual(Result.success, get(t, .scrollback_rows, @ptrCast(&scrollback))); + try testing.expectEqual(@as(usize, 0), scrollback); + + // Write enough lines to push content into scrollback + vt_write(t, "line1\r\nline2\r\nline3\r\nline4\r\nline5\r\n", 34); + + try testing.expectEqual(Result.success, get(t, .scrollback_rows, @ptrCast(&scrollback))); + try testing.expectEqual(@as(usize, 2), scrollback); +} + +test "get invalid" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + try testing.expectEqual(Result.invalid_value, get(t, .invalid, null)); +} + +test "grid_ref" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + vt_write(t, "Hello", 5); + + var out_ref: grid_ref_c.CGridRef = .{}; + try testing.expectEqual(Result.success, grid_ref(t, .{ + .tag = .active, + .value = .{ .active = .{ .x = 0, .y = 0 } }, + }, &out_ref)); + + // Extract cell from grid ref and verify it contains 'H' + var out_cell: cell_c.CCell = undefined; + try testing.expectEqual(Result.success, grid_ref_c.grid_ref_cell(&out_ref, &out_cell)); + + var cp: u32 = 0; + try testing.expectEqual(Result.success, cell_c.get(out_cell, .codepoint, @ptrCast(&cp))); + try testing.expectEqual(@as(u32, 'H'), cp); +} + +test "grid_ref null terminal" { + var out_ref: grid_ref_c.CGridRef = .{}; + try testing.expectEqual(Result.invalid_value, grid_ref(null, .{ + .tag = .active, + .value = .{ .active = .{ .x = 0, .y = 0 } }, + }, &out_ref)); +} + +test "set write_pty callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + var last_userdata: ?*anyopaque = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + last_userdata = null; + } + + fn writePty(_: Terminal, ud: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + last_userdata = ud; + } + }; + defer S.deinit(); + + // Set userdata and write_pty callback + var sentinel: u8 = 42; + try testing.expectEqual(Result.success, set(t, .userdata, @ptrCast(&sentinel))); + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + // DECRQM for wraparound mode (mode 7, set by default) should trigger write_pty + vt_write(t, "\x1B[?7$p", 6); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1B[?7;1$y", S.last_data.?); + try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); +} + +test "set write_pty without callback ignores queries" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // Without setting a callback, DECRQM should be silently ignored (no crash) + vt_write(t, "\x1B[?7$p", 6); +} + +test "set write_pty null clears callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var called: bool = false; + fn writePty(_: Terminal, _: ?*anyopaque, _: [*]const u8, _: usize) callconv(lib.calling_conv) void { + called = true; + } + }; + S.called = false; + + // Set then clear the callback + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .write_pty, null)); + + vt_write(t, "\x1B[?7$p", 6); + try testing.expect(!S.called); +} + +test "set bell callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var bell_count: usize = 0; + var last_userdata: ?*anyopaque = null; + + fn bell(_: Terminal, ud: ?*anyopaque) callconv(lib.calling_conv) void { + bell_count += 1; + last_userdata = ud; + } + }; + S.bell_count = 0; + S.last_userdata = null; + + // Set userdata and bell callback + var sentinel: u8 = 99; + try testing.expectEqual(Result.success, set(t, .userdata, @ptrCast(&sentinel))); + try testing.expectEqual(Result.success, set(t, .bell, @ptrCast(&S.bell))); + + // Single BEL + vt_write(t, "\x07", 1); + try testing.expectEqual(@as(usize, 1), S.bell_count); + try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); + + // Multiple BELs + vt_write(t, "\x07\x07", 2); + try testing.expectEqual(@as(usize, 3), S.bell_count); +} + +test "bell without callback is silent" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // BEL without a callback should not crash + vt_write(t, "\x07", 1); +} + +test "set enquiry callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + const response = "OK"; + fn enquiry(_: Terminal, _: ?*anyopaque) callconv(lib.calling_conv) lib.String { + return .{ .ptr = response, .len = response.len }; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .enquiry, @ptrCast(&S.enquiry))); + + // ENQ (0x05) should trigger the enquiry callback and write response via write_pty + vt_write(t, "\x05", 1); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("OK", S.last_data.?); +} + +test "enquiry without callback is silent" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // ENQ without a callback should not crash + vt_write(t, "\x05", 1); +} + +test "set xtversion callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + const version = "myterm 1.0"; + fn xtversion(_: Terminal, _: ?*anyopaque) callconv(lib.calling_conv) lib.String { + return .{ .ptr = version, .len = version.len }; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .xtversion, @ptrCast(&S.xtversion))); + + // XTVERSION: CSI > q + vt_write(t, "\x1B[>q", 4); + try testing.expect(S.last_data != null); + // Response should be DCS >| version ST + try testing.expectEqualStrings("\x1BP>|myterm 1.0\x1B\\", S.last_data.?); +} + +test "xtversion without callback reports default" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + }; + defer S.deinit(); + + // Set write_pty but not xtversion — should get default "libghostty" + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + vt_write(t, "\x1B[>q", 4); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1BP>|libghostty\x1B\\", S.last_data.?); +} + +test "set title_changed callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var title_count: usize = 0; + var last_userdata: ?*anyopaque = null; + + fn titleChanged(_: Terminal, ud: ?*anyopaque) callconv(lib.calling_conv) void { + title_count += 1; + last_userdata = ud; + } + }; + S.title_count = 0; + S.last_userdata = null; + + var sentinel: u8 = 77; + try testing.expectEqual(Result.success, set(t, .userdata, @ptrCast(&sentinel))); + try testing.expectEqual(Result.success, set(t, .title_changed, @ptrCast(&S.titleChanged))); + + // OSC 2 ; title ST — set window title + vt_write(t, "\x1B]2;Hello\x1B\\", 10); + try testing.expectEqual(@as(usize, 1), S.title_count); + try testing.expectEqual(@as(?*anyopaque, @ptrCast(&sentinel)), S.last_userdata); + + // Another title change + vt_write(t, "\x1B]2;World\x1B\\", 10); + try testing.expectEqual(@as(usize, 2), S.title_count); +} + +test "title_changed without callback is silent" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // OSC 2 without a callback should not crash + vt_write(t, "\x1B]2;Hello\x1B\\", 10); +} + +test "set size callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + fn sizeCb(_: Terminal, _: ?*anyopaque, out_size: *size_report.Size) callconv(lib.calling_conv) bool { + out_size.* = .{ + .rows = 24, + .columns = 80, + .cell_width = 8, + .cell_height = 16, + }; + return true; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .size_cb, @ptrCast(&S.sizeCb))); + + // CSI 18 t — report text area size in characters + vt_write(t, "\x1B[18t", 5); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1b[8;24;80t", S.last_data.?); +} + +test "size without callback is silent" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // CSI 18 t without a size callback should not crash + vt_write(t, "\x1B[18t", 5); +} + +test "set device_attributes callback primary" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + fn da(_: Terminal, _: ?*anyopaque, out: *Effects.CDeviceAttributes) callconv(lib.calling_conv) bool { + out.* = .{ + .primary = .{ + .conformance_level = 64, + .features = .{ 22, 52 } ++ .{0} ** 62, + .num_features = 2, + }, + .secondary = .{ + .device_type = 1, + .firmware_version = 10, + .rom_cartridge = 0, + }, + .tertiary = .{ .unit_id = 0 }, + }; + return true; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .device_attributes, @ptrCast(&S.da))); + + // CSI c — primary DA + vt_write(t, "\x1B[c", 3); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1b[?64;22;52c", S.last_data.?); +} + +test "set device_attributes callback secondary" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + fn da(_: Terminal, _: ?*anyopaque, out: *Effects.CDeviceAttributes) callconv(lib.calling_conv) bool { + out.* = .{ + .primary = .{ + .conformance_level = 62, + .features = .{22} ++ .{0} ** 63, + .num_features = 1, + }, + .secondary = .{ + .device_type = 1, + .firmware_version = 10, + .rom_cartridge = 0, + }, + .tertiary = .{ .unit_id = 0 }, + }; + return true; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .device_attributes, @ptrCast(&S.da))); + + // CSI > c — secondary DA + vt_write(t, "\x1B[>c", 4); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1b[>1;10;0c", S.last_data.?); +} + +test "set device_attributes callback tertiary" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + fn da(_: Terminal, _: ?*anyopaque, out: *Effects.CDeviceAttributes) callconv(lib.calling_conv) bool { + out.* = .{ + .primary = .{ + .conformance_level = 62, + .features = .{0} ** 64, + .num_features = 0, + }, + .secondary = .{ + .device_type = 1, + .firmware_version = 0, + .rom_cartridge = 0, + }, + .tertiary = .{ .unit_id = 0xAABBCCDD }, + }; + return true; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .device_attributes, @ptrCast(&S.da))); + + // CSI = c — tertiary DA + vt_write(t, "\x1B[=c", 4); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1bP!|AABBCCDD\x1b\\", S.last_data.?); +} + +test "device_attributes without callback uses default" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + // Without setting a device_attributes callback, DA1 should return the default + vt_write(t, "\x1B[c", 3); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1b[?62;22c", S.last_data.?); +} + +test "device_attributes callback returns false uses default" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + + fn da(_: Terminal, _: ?*anyopaque, _: *Effects.CDeviceAttributes) callconv(lib.calling_conv) bool { + return false; + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + try testing.expectEqual(Result.success, set(t, .device_attributes, @ptrCast(&S.da))); + + // Callback returns false, should use default response + vt_write(t, "\x1B[c", 3); + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1b[?62;22c", S.last_data.?); +} + +test "set and get title" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // No title set yet — should return empty string + var title: lib.String = undefined; + try testing.expectEqual(Result.success, get(t, .title, @ptrCast(&title))); + try testing.expectEqual(@as(usize, 0), title.len); + + // Set title via option + const hello: lib.String = .{ .ptr = "Hello", .len = 5 }; + try testing.expectEqual(Result.success, set(t, .title, @ptrCast(&hello))); + + try testing.expectEqual(Result.success, get(t, .title, @ptrCast(&title))); + try testing.expectEqualStrings("Hello", title.ptr[0..title.len]); + + // Overwrite title + const world: lib.String = .{ .ptr = "World", .len = 5 }; + try testing.expectEqual(Result.success, set(t, .title, @ptrCast(&world))); + + try testing.expectEqual(Result.success, get(t, .title, @ptrCast(&title))); + try testing.expectEqualStrings("World", title.ptr[0..title.len]); + + // Clear title with NULL + try testing.expectEqual(Result.success, set(t, .title, null)); + + try testing.expectEqual(Result.success, get(t, .title, @ptrCast(&title))); + try testing.expectEqual(@as(usize, 0), title.len); +} + +test "set and get pwd" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // No pwd set yet — should return empty string + var pwd: lib.String = undefined; + try testing.expectEqual(Result.success, get(t, .pwd, @ptrCast(&pwd))); + try testing.expectEqual(@as(usize, 0), pwd.len); + + // Set pwd via option + const home: lib.String = .{ .ptr = "/home/user", .len = 10 }; + try testing.expectEqual(Result.success, set(t, .pwd, @ptrCast(&home))); + + try testing.expectEqual(Result.success, get(t, .pwd, @ptrCast(&pwd))); + try testing.expectEqualStrings("/home/user", pwd.ptr[0..pwd.len]); + + // Clear pwd with NULL + try testing.expectEqual(Result.success, set(t, .pwd, null)); + + try testing.expectEqual(Result.success, get(t, .pwd, @ptrCast(&pwd))); + try testing.expectEqual(@as(usize, 0), pwd.len); +} + +test "get title set via vt_write" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // Set title via OSC 2 + vt_write(t, "\x1B]2;VT Title\x1B\\", 14); + + var title: lib.String = undefined; + try testing.expectEqual(Result.success, get(t, .title, @ptrCast(&title))); + try testing.expectEqualStrings("VT Title", title.ptr[0..title.len]); +} + +test "resize updates pixel dimensions" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); + + const zt = t.?.terminal; + try testing.expectEqual(@as(u32, 100 * 9), zt.width_px); + try testing.expectEqual(@as(u32, 40 * 18), zt.height_px); +} + +test "resize pixel overflow saturates" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + try testing.expectEqual(Result.success, resize(t, 100, 40, std.math.maxInt(u32), std.math.maxInt(u32))); + + const zt = t.?.terminal; + try testing.expectEqual(std.math.maxInt(u32), zt.width_px); + try testing.expectEqual(std.math.maxInt(u32), zt.height_px); +} + +test "resize disables synchronized output" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const zt = t.?.terminal; + zt.modes.set(.synchronized_output, true); + + try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); + try testing.expect(!zt.modes.get(.synchronized_output)); +} + +test "resize sends in-band size report" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var last_data: ?[]u8 = null; + + fn deinit() void { + if (last_data) |d| testing.allocator.free(d); + last_data = null; + } + + fn writePty(_: Terminal, _: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(lib.calling_conv) void { + if (last_data) |d| testing.allocator.free(d); + last_data = testing.allocator.dupe(u8, ptr[0..len]) catch @panic("OOM"); + } + }; + defer S.deinit(); + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + // Enable in-band size reports (mode 2048) + t.?.terminal.modes.set(.in_band_size_reports, true); + + try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); + + // Expected: \x1B[48;rows;cols;height_px;width_pxt + // height_px = 40*18 = 720, width_px = 100*9 = 900 + try testing.expect(S.last_data != null); + try testing.expectEqualStrings("\x1B[48;40;100;720;900t", S.last_data.?); +} + +test "resize no size report without mode 2048" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const S = struct { + var called: bool = false; + fn writePty(_: Terminal, _: ?*anyopaque, _: [*]const u8, _: usize) callconv(lib.calling_conv) void { + called = true; + } + }; + S.called = false; + + try testing.expectEqual(Result.success, set(t, .write_pty, @ptrCast(&S.writePty))); + + // in_band_size_reports is off by default + try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); + try testing.expect(!S.called); +} + +test "resize in-band report without write_pty callback" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // Enable mode 2048 but don't set a write_pty callback — should not crash + t.?.terminal.modes.set(.in_band_size_reports, true); + try testing.expectEqual(Result.success, resize(t, 100, 40, 9, 18)); +} + +test "resize null terminal" { + try testing.expectEqual(Result.invalid_value, resize(null, 100, 40, 9, 18)); +} + +test "resize zero cols" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + try testing.expectEqual(Result.invalid_value, resize(t, 0, 40, 9, 18)); +} + +test "resize zero rows" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + try testing.expectEqual(Result.invalid_value, resize(t, 100, 0, 9, 18)); +} + +test "grid_ref out of bounds" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var out_ref: grid_ref_c.CGridRef = .{}; + try testing.expectEqual(Result.invalid_value, grid_ref(t, .{ + .tag = .active, + .value = .{ .active = .{ .x = 100, .y = 0 } }, + }, &out_ref)); +} + +test "set and get color_foreground" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // Initially unset + var rgb: color.RGB.C = undefined; + try testing.expectEqual(Result.no_value, get(t, .color_foreground, @ptrCast(&rgb))); + + // Set a value + const fg: color.RGB.C = .{ .r = 0xAA, .g = 0xBB, .b = 0xCC }; + try testing.expectEqual(Result.success, set(t, .color_foreground, @ptrCast(&fg))); + try testing.expectEqual(Result.success, get(t, .color_foreground, @ptrCast(&rgb))); + try testing.expectEqual(fg, rgb); + + // Clear with null + try testing.expectEqual(Result.success, set(t, .color_foreground, null)); + try testing.expectEqual(Result.no_value, get(t, .color_foreground, @ptrCast(&rgb))); +} + +test "set and get color_background" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var rgb: color.RGB.C = undefined; + try testing.expectEqual(Result.no_value, get(t, .color_background, @ptrCast(&rgb))); + + const bg: color.RGB.C = .{ .r = 0x11, .g = 0x22, .b = 0x33 }; + try testing.expectEqual(Result.success, set(t, .color_background, @ptrCast(&bg))); + try testing.expectEqual(Result.success, get(t, .color_background, @ptrCast(&rgb))); + try testing.expectEqual(bg, rgb); + + try testing.expectEqual(Result.success, set(t, .color_background, null)); + try testing.expectEqual(Result.no_value, get(t, .color_background, @ptrCast(&rgb))); +} + +test "set and get color_cursor" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var rgb: color.RGB.C = undefined; + try testing.expectEqual(Result.no_value, get(t, .color_cursor, @ptrCast(&rgb))); + + const cur: color.RGB.C = .{ .r = 0xFF, .g = 0x00, .b = 0x88 }; + try testing.expectEqual(Result.success, set(t, .color_cursor, @ptrCast(&cur))); + try testing.expectEqual(Result.success, get(t, .color_cursor, @ptrCast(&rgb))); + try testing.expectEqual(cur, rgb); + + try testing.expectEqual(Result.success, set(t, .color_cursor, null)); + try testing.expectEqual(Result.no_value, get(t, .color_cursor, @ptrCast(&rgb))); +} + +test "set and get color_palette" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + // Get default palette + var palette: color.PaletteC = undefined; + try testing.expectEqual(Result.success, get(t, .color_palette, @ptrCast(&palette))); + try testing.expectEqual(color.default[0].cval(), palette[0]); + + // Set custom palette + var custom: color.PaletteC = color.paletteCval(&color.default); + custom[0] = .{ .r = 0x12, .g = 0x34, .b = 0x56 }; + try testing.expectEqual(Result.success, set(t, .color_palette, @ptrCast(&custom))); + try testing.expectEqual(Result.success, get(t, .color_palette, @ptrCast(&palette))); + try testing.expectEqual(custom[0], palette[0]); + + // Reset with null restores default + try testing.expectEqual(Result.success, set(t, .color_palette, null)); + try testing.expectEqual(Result.success, get(t, .color_palette, @ptrCast(&palette))); + try testing.expectEqual(color.default[0].cval(), palette[0]); +} + +test "get color default vs effective with override" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const zt = t.?.terminal; + var rgb: color.RGB.C = undefined; + + // Set defaults + const fg: color.RGB.C = .{ .r = 0xAA, .g = 0xBB, .b = 0xCC }; + const bg: color.RGB.C = .{ .r = 0x11, .g = 0x22, .b = 0x33 }; + const cur: color.RGB.C = .{ .r = 0xFF, .g = 0x00, .b = 0x88 }; + try testing.expectEqual(Result.success, set(t, .color_foreground, @ptrCast(&fg))); + try testing.expectEqual(Result.success, set(t, .color_background, @ptrCast(&bg))); + try testing.expectEqual(Result.success, set(t, .color_cursor, @ptrCast(&cur))); + + // Simulate OSC overrides + const override: color.RGB = .{ .r = 0x00, .g = 0x00, .b = 0x00 }; + zt.colors.foreground.override = override; + zt.colors.background.override = override; + zt.colors.cursor.override = override; + + // Effective returns override + try testing.expectEqual(Result.success, get(t, .color_foreground, @ptrCast(&rgb))); + try testing.expectEqual(override.cval(), rgb); + try testing.expectEqual(Result.success, get(t, .color_background, @ptrCast(&rgb))); + try testing.expectEqual(override.cval(), rgb); + try testing.expectEqual(Result.success, get(t, .color_cursor, @ptrCast(&rgb))); + try testing.expectEqual(override.cval(), rgb); + + // Default returns original + try testing.expectEqual(Result.success, get(t, .color_foreground_default, @ptrCast(&rgb))); + try testing.expectEqual(fg, rgb); + try testing.expectEqual(Result.success, get(t, .color_background_default, @ptrCast(&rgb))); + try testing.expectEqual(bg, rgb); + try testing.expectEqual(Result.success, get(t, .color_cursor_default, @ptrCast(&rgb))); + try testing.expectEqual(cur, rgb); +} + +test "get color default returns no_value when unset" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + var rgb: color.RGB.C = undefined; + try testing.expectEqual(Result.no_value, get(t, .color_foreground_default, @ptrCast(&rgb))); + try testing.expectEqual(Result.no_value, get(t, .color_background_default, @ptrCast(&rgb))); + try testing.expectEqual(Result.no_value, get(t, .color_cursor_default, @ptrCast(&rgb))); +} + +test "get color_palette_default vs current" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const zt = t.?.terminal; + + // Set a custom default palette + var custom: color.PaletteC = color.paletteCval(&color.default); + custom[0] = .{ .r = 0x12, .g = 0x34, .b = 0x56 }; + try testing.expectEqual(Result.success, set(t, .color_palette, @ptrCast(&custom))); + + // Simulate OSC override on index 0 + zt.colors.palette.set(0, .{ .r = 0xFF, .g = 0xFF, .b = 0xFF }); + + // Current palette returns the override + var palette: color.PaletteC = undefined; + try testing.expectEqual(Result.success, get(t, .color_palette, @ptrCast(&palette))); + try testing.expectEqual(color.RGB.C{ .r = 0xFF, .g = 0xFF, .b = 0xFF }, palette[0]); + + // Default palette returns the original + try testing.expectEqual(Result.success, get(t, .color_palette_default, @ptrCast(&palette))); + try testing.expectEqual(custom[0], palette[0]); +} + +test "set color sets dirty flag" { + var t: Terminal = null; + try testing.expectEqual(Result.success, new( + &lib.alloc.test_allocator, + &t, + .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }, + )); + defer free(t); + + const zt = t.?.terminal; + zt.flags.dirty.palette = false; + + const fg: color.RGB.C = .{ .r = 0xFF, .g = 0xFF, .b = 0xFF }; + try testing.expectEqual(Result.success, set(t, .color_foreground, @ptrCast(&fg))); + try testing.expect(zt.flags.dirty.palette); +} diff --git a/vendor/libghostty-vt/src/terminal/c/types.zig b/vendor/libghostty-vt/src/terminal/c/types.zig new file mode 100644 index 00000000..b808bf38 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/c/types.zig @@ -0,0 +1,215 @@ +//! Comptime-generated metadata describing the layout of all C API +//! extern structs for the current target. +//! +//! This is embedded in the binary as a const string and exposed via +//! `ghostty_type_json` so that WASM (and other FFI) consumers can +//! build structs without hardcoding byte offsets. +const std = @import("std"); +const lib = @import("../lib.zig"); +const color = @import("../color.zig"); +const mouse_event = @import("mouse_event.zig"); +const point = @import("../point.zig"); +const size_report = @import("size_report.zig"); + +const terminal = @import("terminal.zig"); +const formatter = @import("formatter.zig"); +const render = @import("render.zig"); +const style_c = @import("style.zig"); +const mouse_encode = @import("mouse_encode.zig"); +const grid_ref = @import("grid_ref.zig"); + +/// All C API structs and their Ghostty C names. +pub const structs: std.StaticStringMap(StructInfo) = .initComptime(.{ + .{ "GhosttyColorRgb", StructInfo.init(color.RGB.C) }, + .{ "GhosttyDeviceAttributes", StructInfo.init(terminal.DeviceAttributes) }, + .{ "GhosttyDeviceAttributesPrimary", StructInfo.init(terminal.DeviceAttributes.Primary) }, + .{ "GhosttyDeviceAttributesSecondary", StructInfo.init(terminal.DeviceAttributes.Secondary) }, + .{ "GhosttyDeviceAttributesTertiary", StructInfo.init(terminal.DeviceAttributes.Tertiary) }, + .{ "GhosttyFormatterTerminalOptions", StructInfo.init(formatter.TerminalOptions) }, + .{ "GhosttyFormatterTerminalExtra", StructInfo.init(formatter.TerminalOptions.Extra) }, + .{ "GhosttyFormatterScreenExtra", StructInfo.init(formatter.ScreenOptions.Extra) }, + .{ "GhosttyGridRef", StructInfo.init(grid_ref.CGridRef) }, + .{ "GhosttyMouseEncoderSize", StructInfo.init(mouse_encode.Size) }, + .{ "GhosttyMousePosition", StructInfo.init(mouse_event.Position) }, + .{ "GhosttyPoint", StructInfo.init(point.Point.C) }, + .{ "GhosttyPointCoordinate", StructInfo.init(point.Coordinate) }, + .{ "GhosttyRenderStateColors", StructInfo.init(render.Colors) }, + .{ "GhosttySizeReportSize", StructInfo.init(size_report.Size) }, + .{ "GhosttyString", StructInfo.init(lib.String) }, + .{ "GhosttyStyle", StructInfo.init(style_c.Style) }, + .{ "GhosttyStyleColor", StructInfo.init(style_c.Color) }, + .{ "GhosttyTerminalOptions", StructInfo.init(terminal.Options) }, + .{ "GhosttyTerminalScrollbar", StructInfo.init(terminal.TerminalScrollbar) }, + .{ "GhosttyTerminalScrollViewport", StructInfo.init(terminal.ScrollViewport) }, +}); + +/// The comptime-generated JSON string of all structs. +pub const json: [:0]const u8 = json: { + @setEvalBranchQuota(100000); + var counter: std.Io.Writer.Discarding = .init(&.{}); + jsonWriteAll(&counter.writer) catch unreachable; + + var buf: [counter.count:0]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + jsonWriteAll(&writer) catch unreachable; + const final = buf; + break :json final[0..writer.end :0]; +}; + +/// Returns a pointer to the comptime-generated JSON string describing +/// the layout of all C API extern structs, and writes its length to `len`. +/// Exported as `ghostty_type_json` for FFI consumers. +pub fn get_json() callconv(lib.calling_conv) [*:0]const u8 { + return json.ptr; +} + +/// Meta information about a struct that we expose to ease writing +/// bindings in some languages, particularly WASM where we can't +/// easily share struct definitions and need to hardcode byte offsets. +pub const StructInfo = struct { + name: []const u8, + size: usize, + @"align": usize, + fields: []const FieldInfo, + + pub const FieldInfo = struct { + name: []const u8, + offset: usize, + size: usize, + type: []const u8, + }; + + pub fn init(comptime T: type) StructInfo { + comptime { + const fields = @typeInfo(T).@"struct".fields; + const field_infos: [fields.len]FieldInfo = blk: { + var infos: [fields.len]FieldInfo = undefined; + for (fields, 0..) |field, i| infos[i] = .{ + .name = field.name, + .offset = @offsetOf(T, field.name), + .size = @sizeOf(field.type), + .type = typeName(field.type), + }; + break :blk infos; + }; + + return .{ + .name = @typeName(T), + .size = @sizeOf(T), + .@"align" = @alignOf(T), + .fields = &field_infos, + }; + } + } + + pub fn jsonStringify( + self: *const StructInfo, + jws: anytype, + ) std.Io.Writer.Error!void { + try jws.beginObject(); + try jws.objectField("size"); + try jws.write(self.size); + try jws.objectField("align"); + try jws.write(self.@"align"); + try jws.objectField("fields"); + try jws.beginObject(); + for (self.fields) |field| { + try jws.objectField(field.name); + try jws.beginObject(); + try jws.objectField("offset"); + try jws.write(field.offset); + try jws.objectField("size"); + try jws.write(field.size); + try jws.objectField("type"); + try jws.write(field.type); + try jws.endObject(); + } + try jws.endObject(); + try jws.endObject(); + } +}; + +fn jsonWriteAll(writer: *std.Io.Writer) std.Io.Writer.Error!void { + var jws: std.json.Stringify = .{ .writer = writer }; + try jws.beginObject(); + for (structs.keys(), structs.values()) |name, *info| { + try jws.objectField(name); + try info.jsonStringify(&jws); + } + try jws.endObject(); +} + +fn typeName(comptime T: type) []const u8 { + return switch (@typeInfo(T)) { + .bool => "bool", + .int => |info| switch (info.signedness) { + .signed => switch (info.bits) { + 8 => "i8", + 16 => "i16", + 32 => "i32", + 64 => "i64", + else => @compileError("unsupported signed int size"), + }, + .unsigned => switch (info.bits) { + 8 => "u8", + 16 => "u16", + 32 => "u32", + 64 => "u64", + else => @compileError("unsupported unsigned int size"), + }, + }, + .@"enum" => "enum", + .@"struct" => "struct", + .pointer => "pointer", + .array => "array", + else => "opaque", + }; +} + +test "json parses" { + const parsed = try std.json.parseFromSlice( + std.json.Value, + std.testing.allocator, + json, + .{}, + ); + defer parsed.deinit(); + + const root = parsed.value.object; + + // Verify we have all expected structs + try std.testing.expect(root.contains("GhosttyTerminalOptions")); + try std.testing.expect(root.contains("GhosttyFormatterTerminalOptions")); + + // Verify GhosttyTerminalOptions fields + const term_opts = root.get("GhosttyTerminalOptions").?.object; + try std.testing.expect(term_opts.contains("size")); + try std.testing.expect(term_opts.contains("align")); + try std.testing.expect(term_opts.contains("fields")); + + const fields = term_opts.get("fields").?.object; + try std.testing.expect(fields.contains("cols")); + try std.testing.expect(fields.contains("rows")); + try std.testing.expect(fields.contains("max_scrollback")); + + // Verify field offsets make sense (cols should be at 0) + const cols = fields.get("cols").?.object; + try std.testing.expectEqual(0, cols.get("offset").?.integer); +} + +test "struct sizes are non-zero" { + const parsed = try std.json.parseFromSlice( + std.json.Value, + std.testing.allocator, + json, + .{}, + ); + defer parsed.deinit(); + + var it = parsed.value.object.iterator(); + while (it.next()) |entry| { + const struct_info = entry.value_ptr.object; + const size = struct_info.get("size").?.integer; + try std.testing.expect(size > 0); + } +} diff --git a/vendor/libghostty-vt/src/terminal/charsets.zig b/vendor/libghostty-vt/src/terminal/charsets.zig new file mode 100644 index 00000000..00a2d8d1 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/charsets.zig @@ -0,0 +1,115 @@ +const std = @import("std"); +const build_options = @import("terminal_options"); +const assert = @import("../quirks.zig").inlineAssert; +const LibEnum = @import("../lib/enum.zig").Enum; + +/// The available charset slots for a terminal. +pub const Slots = LibEnum( + if (build_options.c_abi) .c else .zig, + &.{ "G0", "G1", "G2", "G3" }, +); + +/// The name of the active slots. +pub const ActiveSlot = LibEnum( + if (build_options.c_abi) .c else .zig, + &.{ "GL", "GR" }, +); + +/// The list of supported character sets and their associated tables. +pub const Charset = LibEnum( + if (build_options.c_abi) .c else .zig, + &.{ "utf8", "ascii", "british", "dec_special" }, +); + +/// The table for the given charset. This returns a pointer to a +/// slice that is guaranteed to be 255 chars that can be used to map +/// ASCII to the given charset. +pub inline fn table(set: Charset) []const u16 { + return switch (set) { + .british => &british, + .dec_special => &dec_special, + + // utf8 is not a table, callers should double-check if the + // charset is utf8 and NOT use tables. + .utf8 => unreachable, + + // recommended that callers just map ascii directly but we can + // support a table + .ascii => &ascii, + }; +} + +/// Just a basic c => c ascii table +const ascii = initTable(); + +/// https://vt100.net/docs/vt220-rm/chapter2.html +const british = british: { + var tbl = initTable(); + tbl[0x23] = 0x00a3; + break :british tbl; +}; + +/// https://en.wikipedia.org/wiki/DEC_Special_Graphics +const dec_special = tech: { + var tbl = initTable(); + tbl[0x60] = 0x25C6; + tbl[0x61] = 0x2592; + tbl[0x62] = 0x2409; + tbl[0x63] = 0x240C; + tbl[0x64] = 0x240D; + tbl[0x65] = 0x240A; + tbl[0x66] = 0x00B0; + tbl[0x67] = 0x00B1; + tbl[0x68] = 0x2424; + tbl[0x69] = 0x240B; + tbl[0x6a] = 0x2518; + tbl[0x6b] = 0x2510; + tbl[0x6c] = 0x250C; + tbl[0x6d] = 0x2514; + tbl[0x6e] = 0x253C; + tbl[0x6f] = 0x23BA; + tbl[0x70] = 0x23BB; + tbl[0x71] = 0x2500; + tbl[0x72] = 0x23BC; + tbl[0x73] = 0x23BD; + tbl[0x74] = 0x251C; + tbl[0x75] = 0x2524; + tbl[0x76] = 0x2534; + tbl[0x77] = 0x252C; + tbl[0x78] = 0x2502; + tbl[0x79] = 0x2264; + tbl[0x7a] = 0x2265; + tbl[0x7b] = 0x03C0; + tbl[0x7c] = 0x2260; + tbl[0x7d] = 0x00A3; + tbl[0x7e] = 0x00B7; + break :tech tbl; +}; + +/// Our table length is 256 so we can contain all ASCII chars. +const table_len = std.math.maxInt(u8) + 1; + +/// Creates a table that maps ASCII to ASCII as a getting started point. +fn initTable() [table_len]u16 { + var result: [table_len]u16 = undefined; + var i: usize = 0; + while (i < table_len) : (i += 1) result[i] = @intCast(i); + assert(i == table_len); + return result; +} + +test { + const testing = std.testing; + const info = @typeInfo(Charset).@"enum"; + inline for (info.fields) |field| { + // utf8 has no table + if (@field(Charset, field.name) == .utf8) continue; + + const tbl = table(@field(Charset, field.name)); + + // Yes, I could use `table_len` here, but I want to explicitly use a + // hardcoded constant so that if there are miscompilations or a comptime + // issue, we catch it. + try testing.expectEqual(@as(usize, 256), tbl.len); + } +} diff --git a/vendor/libghostty-vt/src/terminal/color.zig b/vendor/libghostty-vt/src/terminal/color.zig new file mode 100644 index 00000000..cb1511c3 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/color.zig @@ -0,0 +1,1146 @@ +const colorpkg = @This(); + +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const x11_color = @import("x11_color.zig"); + +/// The default palette. +pub const default: Palette = default: { + var result: Palette = undefined; + + // Named values + var i: u8 = 0; + while (i < 16) : (i += 1) { + result[i] = Name.default(@enumFromInt(i)) catch unreachable; + } + + // Cube + assert(i == 16); + var r: u8 = 0; + while (r < 6) : (r += 1) { + var g: u8 = 0; + while (g < 6) : (g += 1) { + var b: u8 = 0; + while (b < 6) : (b += 1) { + result[i] = .{ + .r = if (r == 0) 0 else (r * 40 + 55), + .g = if (g == 0) 0 else (g * 40 + 55), + .b = if (b == 0) 0 else (b * 40 + 55), + }; + + i += 1; + } + } + } + + // Gray ramp + assert(i == 232); + assert(@TypeOf(i) == u8); + while (i > 0) : (i +%= 1) { + const value = ((i - 232) * 10) + 8; + result[i] = .{ .r = value, .g = value, .b = value }; + } + + break :default result; +}; + +/// Palette is the 256 color palette. +pub const Palette = [256]RGB; + +/// C-compatible palette type using the extern RGB struct. +pub const PaletteC = [256]RGB.C; + +/// Convert a Palette to a PaletteC. +pub fn paletteCval(palette: *const Palette) PaletteC { + var result: PaletteC = undefined; + for (&result, palette) |*dst, src| dst.* = src.cval(); + return result; +} + +/// Convert a PaletteC to a Palette. +pub fn paletteZval(palette: *const PaletteC) Palette { + var result: Palette = undefined; + for (&result, palette) |*dst, src| dst.* = .fromC(src); + return result; +} + +/// Mask that can be used to set which palette indexes were set. +pub const PaletteMask = std.StaticBitSet(@typeInfo(Palette).array.len); + +/// Generate the 256-color palette from the user's base16 theme colors, +/// terminal background, and terminal foreground. +/// +/// Motivation: The default 256-color palette uses fixed, fully-saturated +/// colors that clash with custom base16 themes, have poor readability in +/// dark shades (the first non-black shade jumps to 37% intensity instead +/// of the expected 20%), and exhibit inconsistent perceived brightness +/// across hues of the same shade (e.g., blue appears darker than green). +/// By generating the extended palette from the user's chosen colors, +/// programs can use the richer 256-color range without requiring their +/// own theme configuration, and light/dark switching works automatically. +/// +/// The 216-color cube (indices 16–231) is built via trilinear +/// interpolation in CIELAB space over the 8 base colors. The base16 +/// palette maps to the 8 corners of a 6×6×6 RGB cube as follows: +/// +/// R=0 edge: bg → base[1] (red) +/// R=5 edge: base[6] → fg +/// G=0 edge: bg/base[6] (via R) → base[2]/base[4] (green/blue via R) +/// G=5 edge: base[1]/fg (via R) → base[3]/base[5] (yellow/magenta via R) +/// +/// For each R slice, four corner colors (c0–c3) are interpolated along +/// the R axis, then for each G row two edge colors (c4–c5) are +/// interpolated along G, and finally each B cell is interpolated along B +/// to produce the final color. CIELAB interpolation ensures perceptually +/// uniform brightness transitions across different hues. +/// +/// The 24-step grayscale ramp (indices 232–255) is a simple linear +/// interpolation in CIELAB from the background to the foreground, +/// excluding pure black and white (available in the cube at (0,0,0) +/// and (5,5,5)). The interpolation parameter runs from 1/25 to 24/25. +/// +/// Fill `skip` with user-defined color indexes to avoid replacing them. +/// +/// Reference: https://gist.github.com/jake-stewart/0a8ea46159a7da2c808e5be2177e1783 +pub fn generate256Color( + base: Palette, + skip: PaletteMask, + bg: RGB, + fg: RGB, + harmonious: bool, +) Palette { + // Convert the background, foreground, and 8 base theme colors into + // CIELAB space so that all interpolation is perceptually uniform. + const base8_lab: [8]LAB = base8: { + var base8: [8]LAB = .{ + .fromRgb(bg), + LAB.fromRgb(base[1]), + LAB.fromRgb(base[2]), + LAB.fromRgb(base[3]), + LAB.fromRgb(base[4]), + LAB.fromRgb(base[5]), + LAB.fromRgb(base[6]), + .fromRgb(fg), + }; + + // For light themes (where the foreground is darker than the + // background), the cube's dark-to-light orientation is inverted + // relative to the base color mapping. When `harmonious` is false, + // swap bg and fg so the cube still runs from black (16) to + // white (231). + const is_light_theme = base8[7].l < base8[0].l; + const invert = is_light_theme and !harmonious; + if (invert) std.mem.swap(LAB, &base8[0], &base8[7]); + + break :base8 base8; + }; + + // Start from the base palette so indices 0–15 are preserved as-is. + var result = base; + + // Build the 216-color cube (indices 16–231) via trilinear interpolation + // in CIELAB. The three nested loops correspond to the R, G, and B axes + // of a 6×6×6 cube. For each R slice, four corner colors (c0–c3) are + // interpolated along R from the 8 base colors, mapping the cube corners + // to theme-aware anchors (see doc comment for the mapping). Then for + // each G row, two edge colors (c4–c5) blend along G, and finally each + // B cell interpolates along B to produce the final color. + var idx: usize = 16; + for (0..6) |ri| { + // R-axis corners: blend base colors along the red dimension. + const tr = @as(f32, @floatFromInt(ri)) / 5.0; + const c0: LAB = .lerp(tr, base8_lab[0], base8_lab[1]); + const c1: LAB = .lerp(tr, base8_lab[2], base8_lab[3]); + const c2: LAB = .lerp(tr, base8_lab[4], base8_lab[5]); + const c3: LAB = .lerp(tr, base8_lab[6], base8_lab[7]); + for (0..6) |gi| { + // G-axis edges: blend the R-interpolated corners along green. + const tg = @as(f32, @floatFromInt(gi)) / 5.0; + const c4: LAB = .lerp(tg, c0, c1); + const c5: LAB = .lerp(tg, c2, c3); + for (0..6) |bi| { + // B-axis: final interpolation along blue, then convert back to RGB. + if (!skip.isSet(idx)) { + const c6: LAB = .lerp( + @as(f32, @floatFromInt(bi)) / 5.0, + c4, + c5, + ); + result[idx] = c6.toRgb(); + } + + idx += 1; + } + } + } + + // Build the 24-step grayscale ramp (indices 232–255) by linearly + // interpolating in CIELAB from background to foreground. The parameter + // runs from 1/25 to 24/25, excluding the endpoints which are already + // available in the cube at (0,0,0) and (5,5,5). + for (0..24) |i| { + const t = @as(f32, @floatFromInt(i + 1)) / 25.0; + if (!skip.isSet(idx)) { + const c: LAB = .lerp(t, base8_lab[0], base8_lab[7]); + result[idx] = c.toRgb(); + } + idx += 1; + } + + return result; +} + +/// A palette that can have its colors changed and reset. Purposely built +/// for terminal color operations. +pub const DynamicPalette = struct { + /// The current palette including any user modifications. + current: Palette, + + /// The original/default palette values. + original: Palette, + + /// A bitset where each bit represents whether the corresponding + /// palette index has been modified from its default value. + mask: PaletteMask, + + pub const default: DynamicPalette = .init(colorpkg.default); + + /// Initialize a dynamic palette with a default palette. + pub fn init(def: Palette) DynamicPalette { + return .{ + .current = def, + .original = def, + .mask = .initEmpty(), + }; + } + + /// Set a custom color at the given palette index. + pub fn set(self: *DynamicPalette, idx: u8, color: RGB) void { + self.current[idx] = color; + self.mask.set(idx); + } + + /// Reset the color at the given palette index to its original value. + pub fn reset(self: *DynamicPalette, idx: u8) void { + self.current[idx] = self.original[idx]; + self.mask.unset(idx); + } + + /// Reset all colors to their original values. + pub fn resetAll(self: *DynamicPalette) void { + self.* = .init(self.original); + } + + /// Change the default palette, but preserve the changed values. + pub fn changeDefault(self: *DynamicPalette, def: Palette) void { + self.original = def; + + // Fast path, the palette is usually not changed. + if (self.mask.count() == 0) { + self.current = self.original; + return; + } + + // There are usually less set than unset, so iterate over the changed + // values and override them. + var current = def; + var it = self.mask.iterator(.{}); + while (it.next()) |idx| current[idx] = self.current[idx]; + self.current = current; + } +}; + +/// RGB value that can be changed and reset. This can also be totally unset +/// in every way, in which case the caller can determine their own ultimate +/// default. +pub const DynamicRGB = struct { + override: ?RGB, + default: ?RGB, + + pub const unset: DynamicRGB = .{ .override = null, .default = null }; + + pub fn init(def: RGB) DynamicRGB { + return .{ + .override = null, + .default = def, + }; + } + + pub fn get(self: *const DynamicRGB) ?RGB { + return self.override orelse self.default; + } + + pub fn set(self: *DynamicRGB, color: RGB) void { + self.override = color; + } + + pub fn reset(self: *DynamicRGB) void { + self.override = self.default; + } +}; + +/// Color names in the standard 8 or 16 color palette. +pub const Name = enum(u8) { + black = 0, + red = 1, + green = 2, + yellow = 3, + blue = 4, + magenta = 5, + cyan = 6, + white = 7, + + bright_black = 8, + bright_red = 9, + bright_green = 10, + bright_yellow = 11, + bright_blue = 12, + bright_magenta = 13, + bright_cyan = 14, + bright_white = 15, + + // Remainders are valid unnamed values in the 256 color palette. + _, + + pub const C = u8; + + pub fn cval(self: Name) C { + return @intFromEnum(self); + } + + /// Default colors for tagged values. + pub fn default(self: Name) error{NoDefaultValue}!RGB { + return switch (self) { + .black => RGB{ .r = 0x1D, .g = 0x1F, .b = 0x21 }, + .red => RGB{ .r = 0xCC, .g = 0x66, .b = 0x66 }, + .green => RGB{ .r = 0xB5, .g = 0xBD, .b = 0x68 }, + .yellow => RGB{ .r = 0xF0, .g = 0xC6, .b = 0x74 }, + .blue => RGB{ .r = 0x81, .g = 0xA2, .b = 0xBE }, + .magenta => RGB{ .r = 0xB2, .g = 0x94, .b = 0xBB }, + .cyan => RGB{ .r = 0x8A, .g = 0xBE, .b = 0xB7 }, + .white => RGB{ .r = 0xC5, .g = 0xC8, .b = 0xC6 }, + + .bright_black => RGB{ .r = 0x66, .g = 0x66, .b = 0x66 }, + .bright_red => RGB{ .r = 0xD5, .g = 0x4E, .b = 0x53 }, + .bright_green => RGB{ .r = 0xB9, .g = 0xCA, .b = 0x4A }, + .bright_yellow => RGB{ .r = 0xE7, .g = 0xC5, .b = 0x47 }, + .bright_blue => RGB{ .r = 0x7A, .g = 0xA6, .b = 0xDA }, + .bright_magenta => RGB{ .r = 0xC3, .g = 0x97, .b = 0xD8 }, + .bright_cyan => RGB{ .r = 0x70, .g = 0xC0, .b = 0xB1 }, + .bright_white => RGB{ .r = 0xEA, .g = 0xEA, .b = 0xEA }, + + else => error.NoDefaultValue, + }; + } +}; + +/// The "special colors" as denoted by xterm. These can be set via +/// OSC 5 or via OSC 4 by adding the palette length to it. +/// +/// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html +pub const Special = enum(u3) { + bold = 0, + underline = 1, + blink = 2, + reverse = 3, + italic = 4, + + pub fn osc4(self: Special) u16 { + // "The special colors can also be set by adding the maximum + // number of colors (e.g., 88 or 256) to these codes in an + // OSC 4 control" - xterm ctlseqs + const max = @typeInfo(Palette).array.len; + return @as(u16, @intCast(@intFromEnum(self))) + max; + } + + test "osc4" { + const testing = std.testing; + try testing.expectEqual(256, Special.bold.osc4()); + try testing.expectEqual(257, Special.underline.osc4()); + try testing.expectEqual(258, Special.blink.osc4()); + try testing.expectEqual(259, Special.reverse.osc4()); + try testing.expectEqual(260, Special.italic.osc4()); + } +}; + +test Special { + _ = Special; +} + +/// The "dynamic colors" as denoted by xterm. These can be set via +/// OSC 10 through 19. +pub const Dynamic = enum(u5) { + foreground = 10, + background = 11, + cursor = 12, + pointer_foreground = 13, + pointer_background = 14, + tektronix_foreground = 15, + tektronix_background = 16, + highlight_background = 17, + tektronix_cursor = 18, + highlight_foreground = 19, + + /// The next dynamic color sequentially. This is required because + /// specifying colors sequentially without their index will automatically + /// use the next dynamic color. + /// + /// "Each successive parameter changes the next color in the list. The + /// value of Ps tells the starting point in the list." + pub fn next(self: Dynamic) ?Dynamic { + return std.meta.intToEnum( + Dynamic, + @intFromEnum(self) + 1, + ) catch null; + } + + test "next" { + const testing = std.testing; + try testing.expectEqual(.background, Dynamic.foreground.next()); + try testing.expectEqual(.cursor, Dynamic.background.next()); + try testing.expectEqual(.pointer_foreground, Dynamic.cursor.next()); + try testing.expectEqual(.pointer_background, Dynamic.pointer_foreground.next()); + try testing.expectEqual(.tektronix_foreground, Dynamic.pointer_background.next()); + try testing.expectEqual(.tektronix_background, Dynamic.tektronix_foreground.next()); + try testing.expectEqual(.highlight_background, Dynamic.tektronix_background.next()); + try testing.expectEqual(.tektronix_cursor, Dynamic.highlight_background.next()); + try testing.expectEqual(.highlight_foreground, Dynamic.tektronix_cursor.next()); + try testing.expectEqual(null, Dynamic.highlight_foreground.next()); + } +}; + +test Dynamic { + _ = Dynamic; +} + +/// RGB +pub const RGB = packed struct(u24) { + r: u8 = 0, + g: u8 = 0, + b: u8 = 0, + + pub const C = extern struct { + r: u8, + g: u8, + b: u8, + }; + + pub fn fromC(c: C) RGB { + return .{ .r = c.r, .g = c.g, .b = c.b }; + } + + pub fn cval(self: RGB) C { + return .{ + .r = self.r, + .g = self.g, + .b = self.b, + }; + } + + pub fn eql(self: RGB, other: RGB) bool { + return self.r == other.r and self.g == other.g and self.b == other.b; + } + + /// Calculates the contrast ratio between two colors. The contrast + /// ration is a value between 1 and 21 where 1 is the lowest contrast + /// and 21 is the highest contrast. + /// + /// https://www.w3.org/TR/WCAG20/#contrast-ratiodef + pub fn contrast(self: RGB, other: RGB) f64 { + // pair[0] = lighter, pair[1] = darker + const pair: [2]f64 = pair: { + const self_lum = self.luminance(); + const other_lum = other.luminance(); + if (self_lum > other_lum) break :pair .{ self_lum, other_lum }; + break :pair .{ other_lum, self_lum }; + }; + + return (pair[0] + 0.05) / (pair[1] + 0.05); + } + + /// Calculates luminance based on the W3C formula. This returns a + /// normalized value between 0 and 1 where 0 is black and 1 is white. + /// + /// https://www.w3.org/TR/WCAG20/#relativeluminancedef + pub fn luminance(self: RGB) f64 { + const r_lum = componentLuminance(self.r); + const g_lum = componentLuminance(self.g); + const b_lum = componentLuminance(self.b); + return 0.2126 * r_lum + 0.7152 * g_lum + 0.0722 * b_lum; + } + + /// Calculates single-component luminance based on the W3C formula. + /// + /// Expects sRGB color space which at the time of writing we don't + /// generally use but it's a good enough approximation until we fix that. + /// https://www.w3.org/TR/WCAG20/#relativeluminancedef + fn componentLuminance(c: u8) f64 { + const c_f64: f64 = @floatFromInt(c); + const normalized: f64 = c_f64 / 255; + if (normalized <= 0.03928) return normalized / 12.92; + return std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); + } + + /// Calculates "perceived luminance" which is better for determining + /// light vs dark. + /// + /// Source: https://www.w3.org/TR/AERT/#color-contrast + pub fn perceivedLuminance(self: RGB) f64 { + const r_f64: f64 = @floatFromInt(self.r); + const g_f64: f64 = @floatFromInt(self.g); + const b_f64: f64 = @floatFromInt(self.b); + return 0.299 * (r_f64 / 255) + 0.587 * (g_f64 / 255) + 0.114 * (b_f64 / 255); + } + + comptime { + assert(@bitSizeOf(RGB) == 24); + assert(@sizeOf(RGB) == 4); + } + + /// Parse a color from a floating point intensity value. + /// + /// The value should be between 0.0 and 1.0, inclusive. + fn fromIntensity(value: []const u8) error{InvalidFormat}!u8 { + const i = std.fmt.parseFloat(f64, value) catch { + @branchHint(.cold); + return error.InvalidFormat; + }; + if (i < 0.0 or i > 1.0) { + @branchHint(.cold); + return error.InvalidFormat; + } + + return @intFromFloat(i * std.math.maxInt(u8)); + } + + /// Parse a color from a string of hexadecimal digits + /// + /// The string can contain 1, 2, 3, or 4 characters and represents the color + /// value scaled in 4, 8, 12, or 16 bits, respectively. + fn fromHex(value: []const u8) error{InvalidFormat}!u8 { + if (value.len == 0 or value.len > 4) { + @branchHint(.cold); + return error.InvalidFormat; + } + + const color = std.fmt.parseUnsigned(u16, value, 16) catch { + @branchHint(.cold); + return error.InvalidFormat; + }; + + const divisor: usize = switch (value.len) { + 1 => std.math.maxInt(u4), + 2 => std.math.maxInt(u8), + 3 => std.math.maxInt(u12), + 4 => std.math.maxInt(u16), + else => unreachable, + }; + + return @intCast(@as(usize, color) * std.math.maxInt(u8) / divisor); + } + + /// Parse a color specification. + /// + /// Any of the following forms are accepted: + /// + /// 1. rgb:// + /// + /// , , := h | hh | hhh | hhhh + /// + /// where `h` is a single hexadecimal digit. + /// + /// 2. rgbi:// + /// + /// where , , and are floating point values between + /// 0.0 and 1.0 (inclusive). + /// + /// 3. #rgb, #rrggbb, #rrrgggbbb #rrrrggggbbbb + /// + /// where `r`, `g`, and `b` are a single hexadecimal digit. + /// These specify a color with 4, 8, 12, and 16 bits of precision + /// per color channel. + pub fn parse(value: []const u8) error{InvalidFormat}!RGB { + if (value.len == 0) { + @branchHint(.cold); + return error.InvalidFormat; + } + + if (value[0] == '#') { + switch (value.len) { + 4 => return RGB{ + .r = try RGB.fromHex(value[1..2]), + .g = try RGB.fromHex(value[2..3]), + .b = try RGB.fromHex(value[3..4]), + }, + 7 => return RGB{ + .r = try RGB.fromHex(value[1..3]), + .g = try RGB.fromHex(value[3..5]), + .b = try RGB.fromHex(value[5..7]), + }, + 10 => return RGB{ + .r = try RGB.fromHex(value[1..4]), + .g = try RGB.fromHex(value[4..7]), + .b = try RGB.fromHex(value[7..10]), + }, + 13 => return RGB{ + .r = try RGB.fromHex(value[1..5]), + .g = try RGB.fromHex(value[5..9]), + .b = try RGB.fromHex(value[9..13]), + }, + + else => { + @branchHint(.cold); + return error.InvalidFormat; + }, + } + } + + // Check for X11 named colors. We allow whitespace around the edges + // of the color because Kitty allows whitespace. This is not part of + // any spec I could find. + if (x11_color.map.get(std.mem.trim(u8, value, " "))) |rgb| return rgb; + + if (value.len < "rgb:a/a/a".len or !std.mem.eql(u8, value[0..3], "rgb")) { + @branchHint(.cold); + return error.InvalidFormat; + } + + var i: usize = 3; + + const use_intensity = if (value[i] == 'i') blk: { + i += 1; + break :blk true; + } else false; + + if (value[i] != ':') { + @branchHint(.cold); + return error.InvalidFormat; + } + + i += 1; + + const r = r: { + const slice = if (std.mem.indexOfScalarPos(u8, value, i, '/')) |end| + value[i..end] + else { + @branchHint(.cold); + return error.InvalidFormat; + }; + + i += slice.len + 1; + + break :r if (use_intensity) + try RGB.fromIntensity(slice) + else + try RGB.fromHex(slice); + }; + + const g = g: { + const slice = if (std.mem.indexOfScalarPos(u8, value, i, '/')) |end| + value[i..end] + else { + @branchHint(.cold); + return error.InvalidFormat; + }; + + i += slice.len + 1; + + break :g if (use_intensity) + try RGB.fromIntensity(slice) + else + try RGB.fromHex(slice); + }; + + const b = if (use_intensity) + try RGB.fromIntensity(value[i..]) + else + try RGB.fromHex(value[i..]); + + return RGB{ + .r = r, + .g = g, + .b = b, + }; + } +}; + +/// LAB color space +const LAB = struct { + l: f32, + a: f32, + b: f32, + + /// RGB to LAB + pub fn fromRgb(rgb: RGB) LAB { + // Step 1: Normalize sRGB channels from [0, 255] to [0.0, 1.0]. + var r: f32 = @as(f32, @floatFromInt(rgb.r)) / 255.0; + var g: f32 = @as(f32, @floatFromInt(rgb.g)) / 255.0; + var b: f32 = @as(f32, @floatFromInt(rgb.b)) / 255.0; + + // Step 2: Apply the inverse sRGB companding (gamma correction) to + // convert from sRGB to linear RGB. The sRGB transfer function has + // two segments: a linear portion for small values and a power curve + // for the rest. + r = if (r > 0.04045) std.math.pow(f32, (r + 0.055) / 1.055, 2.4) else r / 12.92; + g = if (g > 0.04045) std.math.pow(f32, (g + 0.055) / 1.055, 2.4) else g / 12.92; + b = if (b > 0.04045) std.math.pow(f32, (b + 0.055) / 1.055, 2.4) else b / 12.92; + + // Step 3: Convert linear RGB to CIE XYZ using the sRGB to XYZ + // transformation matrix (D65 illuminant). The X and Z values are + // normalized by the D65 white point reference values (Xn=0.95047, + // Zn=1.08883; Yn=1.0 is implicit). + var x = (r * 0.4124564 + g * 0.3575761 + b * 0.1804375) / 0.95047; + var y = r * 0.2126729 + g * 0.7151522 + b * 0.0721750; + var z = (r * 0.0193339 + g * 0.1191920 + b * 0.9503041) / 1.08883; + + // Step 4: Apply the CIE f(t) nonlinear transform to each XYZ + // component. Above the threshold (epsilon ≈ 0.008856) the cube + // root is used; below it, a linear approximation avoids numerical + // instability near zero. + x = if (x > 0.008856) std.math.cbrt(x) else 7.787 * x + 16.0 / 116.0; + y = if (y > 0.008856) std.math.cbrt(y) else 7.787 * y + 16.0 / 116.0; + z = if (z > 0.008856) std.math.cbrt(z) else 7.787 * z + 16.0 / 116.0; + + // Step 5: Compute the final CIELAB values from the transformed XYZ. + // L* is lightness (0–100), a* is green–red, b* is blue–yellow. + return .{ .l = 116.0 * y - 16.0, .a = 500.0 * (x - y), .b = 200.0 * (y - z) }; + } + + /// LAB to RGB + pub fn toRgb(self: LAB) RGB { + // Step 1: Recover the intermediate f(Y), f(X), f(Z) values from + // L*a*b* by inverting the CIELAB formulas. + const y = (self.l + 16.0) / 116.0; + const x = self.a / 500.0 + y; + const z = y - self.b / 200.0; + + // Step 2: Apply the inverse CIE f(t) transform to get back to + // XYZ. Above epsilon (≈0.008856) the cube is used; below it the + // linear segment is inverted. Results are then scaled by the D65 + // white point reference values (Xn=0.95047, Zn=1.08883; Yn=1.0). + const x3 = x * x * x; + const y3 = y * y * y; + const z3 = z * z * z; + const xf = (if (x3 > 0.008856) x3 else (x - 16.0 / 116.0) / 7.787) * 0.95047; + const yf = if (y3 > 0.008856) y3 else (y - 16.0 / 116.0) / 7.787; + const zf = (if (z3 > 0.008856) z3 else (z - 16.0 / 116.0) / 7.787) * 1.08883; + + // Step 3: Convert CIE XYZ back to linear RGB using the XYZ to sRGB + // matrix (inverse of the sRGB to XYZ matrix, D65 illuminant). + var r = xf * 3.2404542 - yf * 1.5371385 - zf * 0.4985314; + var g = -xf * 0.9692660 + yf * 1.8760108 + zf * 0.0415560; + var b = xf * 0.0556434 - yf * 0.2040259 + zf * 1.0572252; + + // Step 4: Apply sRGB companding (gamma correction) to convert from + // linear RGB back to sRGB. This is the forward sRGB transfer + // function with the same two-segment split as the inverse. + r = if (r > 0.0031308) 1.055 * std.math.pow(f32, r, 1.0 / 2.4) - 0.055 else 12.92 * r; + g = if (g > 0.0031308) 1.055 * std.math.pow(f32, g, 1.0 / 2.4) - 0.055 else 12.92 * g; + b = if (b > 0.0031308) 1.055 * std.math.pow(f32, b, 1.0 / 2.4) - 0.055 else 12.92 * b; + + // Step 5: Clamp to [0.0, 1.0], scale to [0, 255], and round to + // the nearest integer to produce the final 8-bit sRGB values. + return .{ + .r = @intFromFloat(@min(@max(r, 0.0), 1.0) * 255.0 + 0.5), + .g = @intFromFloat(@min(@max(g, 0.0), 1.0) * 255.0 + 0.5), + .b = @intFromFloat(@min(@max(b, 0.0), 1.0) * 255.0 + 0.5), + }; + } + + /// Linearly interpolate between two LAB colors component-wise. + /// `t` is the interpolation factor in [0, 1]: t=0 returns `a`, + /// t=1 returns `b`, and values in between blend proportionally. + pub fn lerp(t: f32, a: LAB, b: LAB) LAB { + return .{ + .l = a.l + t * (b.l - a.l), + .a = a.a + t * (b.a - a.a), + .b = a.b + t * (b.b - a.b), + }; + } +}; + +test "palette: default" { + const testing = std.testing; + + // Safety check + var i: u8 = 0; + while (i < 16) : (i += 1) { + try testing.expectEqual(Name.default(@as(Name, @enumFromInt(i))), default[i]); + } +} + +test "RGB.parse" { + const testing = std.testing; + + try testing.expectEqual(RGB{ .r = 255, .g = 0, .b = 0 }, try RGB.parse("rgbi:1.0/0/0")); + try testing.expectEqual(RGB{ .r = 127, .g = 160, .b = 0 }, try RGB.parse("rgb:7f/a0a0/0")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, try RGB.parse("rgb:f/ff/fff")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, try RGB.parse("#ffffff")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, try RGB.parse("#fff")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, try RGB.parse("#fffffffff")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, try RGB.parse("#ffffffffffff")); + try testing.expectEqual(RGB{ .r = 255, .g = 0, .b = 16 }, try RGB.parse("#ff0010")); + + try testing.expectEqual(RGB{ .r = 0, .g = 0, .b = 0 }, try RGB.parse("black")); + try testing.expectEqual(RGB{ .r = 255, .g = 0, .b = 0 }, try RGB.parse("red")); + try testing.expectEqual(RGB{ .r = 0, .g = 255, .b = 0 }, try RGB.parse("green")); + try testing.expectEqual(RGB{ .r = 0, .g = 0, .b = 255 }, try RGB.parse("blue")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, try RGB.parse("white")); + + try testing.expectEqual(RGB{ .r = 124, .g = 252, .b = 0 }, try RGB.parse("LawnGreen")); + try testing.expectEqual(RGB{ .r = 0, .g = 250, .b = 154 }, try RGB.parse("medium spring green")); + try testing.expectEqual(RGB{ .r = 34, .g = 139, .b = 34 }, try RGB.parse(" Forest Green ")); + + // Invalid format + try testing.expectError(error.InvalidFormat, RGB.parse("rgb;")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgb:")); + try testing.expectError(error.InvalidFormat, RGB.parse(":a/a/a")); + try testing.expectError(error.InvalidFormat, RGB.parse("a/a/a")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgb:a/a/a/")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgb:00000///")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgb:000/")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgbi:a/a/a")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgb:0.5/0.0/1.0")); + try testing.expectError(error.InvalidFormat, RGB.parse("rgb:not/hex/zz")); + try testing.expectError(error.InvalidFormat, RGB.parse("#")); + try testing.expectError(error.InvalidFormat, RGB.parse("#ff")); + try testing.expectError(error.InvalidFormat, RGB.parse("#ffff")); + try testing.expectError(error.InvalidFormat, RGB.parse("#fffff")); + try testing.expectError(error.InvalidFormat, RGB.parse("#gggggg")); +} + +test "DynamicPalette: init" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + try testing.expectEqual(default, p.current); + try testing.expectEqual(default, p.original); + try testing.expectEqual(@as(usize, 0), p.mask.count()); +} + +test "DynamicPalette: set" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + const new_color = RGB{ .r = 255, .g = 0, .b = 0 }; + + p.set(0, new_color); + try testing.expectEqual(new_color, p.current[0]); + try testing.expect(p.mask.isSet(0)); + try testing.expectEqual(@as(usize, 1), p.mask.count()); + + try testing.expectEqual(default[0], p.original[0]); +} + +test "DynamicPalette: reset" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + const new_color = RGB{ .r = 255, .g = 0, .b = 0 }; + + p.set(0, new_color); + try testing.expect(p.mask.isSet(0)); + + p.reset(0); + try testing.expectEqual(default[0], p.current[0]); + try testing.expect(!p.mask.isSet(0)); + try testing.expectEqual(@as(usize, 0), p.mask.count()); +} + +test "DynamicPalette: resetAll" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + const new_color = RGB{ .r = 255, .g = 0, .b = 0 }; + + p.set(0, new_color); + p.set(5, new_color); + p.set(10, new_color); + try testing.expectEqual(@as(usize, 3), p.mask.count()); + + p.resetAll(); + try testing.expectEqual(default, p.current); + try testing.expectEqual(default, p.original); + try testing.expectEqual(@as(usize, 0), p.mask.count()); +} + +test "DynamicPalette: changeDefault with no changes" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + var new_palette = default; + new_palette[0] = RGB{ .r = 100, .g = 100, .b = 100 }; + + p.changeDefault(new_palette); + try testing.expectEqual(new_palette, p.original); + try testing.expectEqual(new_palette, p.current); + try testing.expectEqual(@as(usize, 0), p.mask.count()); +} + +test "DynamicPalette: changeDefault preserves changes" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + const custom_color = RGB{ .r = 255, .g = 0, .b = 0 }; + + p.set(5, custom_color); + try testing.expect(p.mask.isSet(5)); + + var new_palette = default; + new_palette[0] = RGB{ .r = 100, .g = 100, .b = 100 }; + new_palette[5] = RGB{ .r = 50, .g = 50, .b = 50 }; + + p.changeDefault(new_palette); + + try testing.expectEqual(new_palette, p.original); + try testing.expectEqual(new_palette[0], p.current[0]); + try testing.expectEqual(custom_color, p.current[5]); + try testing.expect(p.mask.isSet(5)); + try testing.expectEqual(@as(usize, 1), p.mask.count()); +} + +test "DynamicPalette: changeDefault with multiple changes" { + const testing = std.testing; + + var p: DynamicPalette = .init(default); + const red = RGB{ .r = 255, .g = 0, .b = 0 }; + const green = RGB{ .r = 0, .g = 255, .b = 0 }; + const blue = RGB{ .r = 0, .g = 0, .b = 255 }; + + p.set(1, red); + p.set(2, green); + p.set(3, blue); + + var new_palette = default; + new_palette[0] = RGB{ .r = 50, .g = 50, .b = 50 }; + new_palette[1] = RGB{ .r = 60, .g = 60, .b = 60 }; + + p.changeDefault(new_palette); + + try testing.expectEqual(new_palette[0], p.current[0]); + try testing.expectEqual(red, p.current[1]); + try testing.expectEqual(green, p.current[2]); + try testing.expectEqual(blue, p.current[3]); + try testing.expectEqual(@as(usize, 3), p.mask.count()); +} + +test "LAB.fromRgb" { + const testing = std.testing; + const epsilon = 0.5; + + // White (255, 255, 255) -> L*=100, a*=0, b*=0 + const white = LAB.fromRgb(.{ .r = 255, .g = 255, .b = 255 }); + try testing.expectApproxEqAbs(@as(f32, 100.0), white.l, epsilon); + try testing.expectApproxEqAbs(@as(f32, 0.0), white.a, epsilon); + try testing.expectApproxEqAbs(@as(f32, 0.0), white.b, epsilon); + + // Black (0, 0, 0) -> L*=0, a*=0, b*=0 + const black = LAB.fromRgb(.{ .r = 0, .g = 0, .b = 0 }); + try testing.expectApproxEqAbs(@as(f32, 0.0), black.l, epsilon); + try testing.expectApproxEqAbs(@as(f32, 0.0), black.a, epsilon); + try testing.expectApproxEqAbs(@as(f32, 0.0), black.b, epsilon); + + // Pure red (255, 0, 0) -> L*≈53.23, a*≈80.11, b*≈67.22 + const red = LAB.fromRgb(.{ .r = 255, .g = 0, .b = 0 }); + try testing.expectApproxEqAbs(@as(f32, 53.23), red.l, epsilon); + try testing.expectApproxEqAbs(@as(f32, 80.11), red.a, epsilon); + try testing.expectApproxEqAbs(@as(f32, 67.22), red.b, epsilon); + + // Pure green (0, 128, 0) -> L*≈46.23, a*≈-51.70, b*≈49.90 + const green = LAB.fromRgb(.{ .r = 0, .g = 128, .b = 0 }); + try testing.expectApproxEqAbs(@as(f32, 46.23), green.l, epsilon); + try testing.expectApproxEqAbs(@as(f32, -51.70), green.a, epsilon); + try testing.expectApproxEqAbs(@as(f32, 49.90), green.b, epsilon); + + // Pure blue (0, 0, 255) -> L*≈32.30, a*≈79.20, b*≈-107.86 + const blue = LAB.fromRgb(.{ .r = 0, .g = 0, .b = 255 }); + try testing.expectApproxEqAbs(@as(f32, 32.30), blue.l, epsilon); + try testing.expectApproxEqAbs(@as(f32, 79.20), blue.a, epsilon); + try testing.expectApproxEqAbs(@as(f32, -107.86), blue.b, epsilon); +} + +test "generate256Color: base16 preserved" { + const testing = std.testing; + + const bg = RGB{ .r = 0, .g = 0, .b = 0 }; + const fg = RGB{ .r = 255, .g = 255, .b = 255 }; + const palette = generate256Color(default, .initEmpty(), bg, fg, false); + + // The first 16 colors (base16) must remain unchanged. + for (0..16) |i| { + try testing.expectEqual(default[i], palette[i]); + } +} + +test "generate256Color: cube corners match base colors" { + const testing = std.testing; + + const bg = RGB{ .r = 0, .g = 0, .b = 0 }; + const fg = RGB{ .r = 255, .g = 255, .b = 255 }; + const palette = generate256Color(default, .initEmpty(), bg, fg, false); + + // Index 16 is cube (0,0,0) which should equal bg. + try testing.expectEqual(bg, palette[16]); + + // Index 231 is cube (5,5,5) which should equal fg. + try testing.expectEqual(fg, palette[231]); +} + +test "generate256Color: cube corners black/white with harmonious=false" { + const testing = std.testing; + + const black = RGB{ .r = 0, .g = 0, .b = 0 }; + const white = RGB{ .r = 255, .g = 255, .b = 255 }; + + // Dark theme: bg=black, fg=white. + const dark = generate256Color(default, .initEmpty(), black, white, false); + try testing.expectEqual(black, dark[16]); + try testing.expectEqual(white, dark[231]); + + // Light theme: bg=white, fg=black. The bg/red swap ensures + // the cube still runs from black (16) to white (231). + const light = generate256Color(default, .initEmpty(), white, black, false); + try testing.expectEqual(black, light[16]); + try testing.expectEqual(white, light[231]); +} + +test "generate256Color: light theme cube corners with harmonious=true" { + const testing = std.testing; + + const white = RGB{ .r = 255, .g = 255, .b = 255 }; + const black = RGB{ .r = 0, .g = 0, .b = 0 }; + + // harmonious=true skips the bg/fg swap, so the cube preserves the + // original orientation: (0,0,0)=bg=white, (5,5,5)=fg=black. + const palette = generate256Color(default, .initEmpty(), white, black, true); + try testing.expectEqual(white, palette[16]); + try testing.expectEqual(black, palette[231]); +} + +test "generate256Color: grayscale ramp monotonic luminance" { + const testing = std.testing; + + const bg = RGB{ .r = 0, .g = 0, .b = 0 }; + const fg = RGB{ .r = 255, .g = 255, .b = 255 }; + const palette = generate256Color(default, .initEmpty(), bg, fg, false); + + // The grayscale ramp (232–255) should have monotonically increasing + // luminance from near-black to near-white. + var prev_lum: f64 = 0.0; + for (232..256) |i| { + const lum = palette[i].luminance(); + try testing.expect(lum >= prev_lum); + prev_lum = lum; + } +} + +test "generate256Color: skip mask preserves original colors" { + const testing = std.testing; + + const bg = RGB{ .r = 0, .g = 0, .b = 0 }; + const fg = RGB{ .r = 255, .g = 255, .b = 255 }; + + // Mark a few indices as skipped; they should keep their base value. + var skip: PaletteMask = .initEmpty(); + skip.set(20); + skip.set(100); + skip.set(240); + + const palette = generate256Color(default, skip, bg, fg, false); + try testing.expectEqual(default[20], palette[20]); + try testing.expectEqual(default[100], palette[100]); + try testing.expectEqual(default[240], palette[240]); + + // A non-skipped index in the cube should differ from the default. + try testing.expect(!palette[21].eql(default[21])); +} + +test "generate256Color: dark theme harmonious has no effect" { + const testing = std.testing; + + // For a dark theme (fg lighter than bg), harmonious should not change + // the output because the inversion is only relevant for light themes. + const bg = RGB{ .r = 0, .g = 0, .b = 0 }; + const fg = RGB{ .r = 255, .g = 255, .b = 255 }; + const normal = generate256Color(default, .initEmpty(), bg, fg, false); + const harmonious = generate256Color(default, .initEmpty(), bg, fg, true); + + for (16..256) |i| { + try testing.expectEqual(normal[i], harmonious[i]); + } +} + +test "generate256Color: light theme harmonious skips inversion" { + const testing = std.testing; + + // For a light theme (fg darker than bg), harmonious=true skips the + // bg/red swap, producing different cube colors than harmonious=false. + const bg = RGB{ .r = 255, .g = 255, .b = 255 }; + const fg = RGB{ .r = 0, .g = 0, .b = 0 }; + const inverted = generate256Color(default, .initEmpty(), bg, fg, false); + const harmonious = generate256Color(default, .initEmpty(), bg, fg, true); + + // Cube origin (0,0,0) at index 16: without harmonious, bg and red are + // swapped so it becomes the red base; with harmonious it stays as bg. + try testing.expectEqual(bg, harmonious[16]); + try testing.expect(!inverted[16].eql(bg)); + + // At least some cube colors should differ between the two modes. + var differ: usize = 0; + for (16..232) |i| { + if (!inverted[i].eql(harmonious[i])) differ += 1; + } + try testing.expect(differ > 0); +} + +test "generate256Color: light theme harmonious grayscale ramp" { + const testing = std.testing; + + const bg = RGB{ .r = 255, .g = 255, .b = 255 }; + const fg = RGB{ .r = 0, .g = 0, .b = 0 }; + + // harmonious=false swaps bg/fg, so the ramp runs black→white (increasing). + { + const palette = generate256Color(default, .initEmpty(), bg, fg, false); + var prev_lum: f64 = 0.0; + for (232..256) |i| { + const lum = palette[i].luminance(); + try testing.expect(lum >= prev_lum); + prev_lum = lum; + } + } + + // harmonious=true keeps original order, so the ramp runs white→black (decreasing). + { + const palette = generate256Color(default, .initEmpty(), bg, fg, true); + var prev_lum: f64 = 1.0; + for (232..256) |i| { + const lum = palette[i].luminance(); + try testing.expect(lum <= prev_lum); + prev_lum = lum; + } + } +} + +test "LAB.toRgb" { + const testing = std.testing; + + // Round-trip: RGB -> LAB -> RGB should recover the original values. + const cases = [_]RGB{ + .{ .r = 255, .g = 255, .b = 255 }, + .{ .r = 0, .g = 0, .b = 0 }, + .{ .r = 255, .g = 0, .b = 0 }, + .{ .r = 0, .g = 128, .b = 0 }, + .{ .r = 0, .g = 0, .b = 255 }, + .{ .r = 128, .g = 128, .b = 128 }, + .{ .r = 64, .g = 224, .b = 208 }, + }; + + for (cases) |expected| { + const lab = LAB.fromRgb(expected); + const actual = lab.toRgb(); + try testing.expectEqual(expected.r, actual.r); + try testing.expectEqual(expected.g, actual.g); + try testing.expectEqual(expected.b, actual.b); + } +} diff --git a/vendor/libghostty-vt/src/terminal/csi.zig b/vendor/libghostty-vt/src/terminal/csi.zig new file mode 100644 index 00000000..2491a234 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/csi.zig @@ -0,0 +1,55 @@ +const lib = @import("lib.zig"); + +/// Modes for the ED CSI command. +pub const EraseDisplay = enum(u8) { + below = 0, + above = 1, + complete = 2, + scrollback = 3, + + /// This is an extension added by Kitty to move the viewport into the + /// scrollback and then erase the display. + scroll_complete = 22, +}; + +/// Modes for the EL CSI command. +pub const EraseLine = enum(u8) { + right = 0, + left = 1, + complete = 2, + right_unless_pending_wrap = 4, + + // Non-exhaustive so that @intToEnum never fails since the inputs are + // user-generated. + _, +}; + +/// Modes for the TBC (tab clear) command. +pub const TabClear = enum(u8) { + current = 0, + all = 3, + + // Non-exhaustive so that @intToEnum never fails since the inputs are + // user-generated. + _, +}; + +/// Style formats for terminal size reports. +pub const SizeReportStyle = lib.Enum( + lib.target, + &.{ + // XTWINOPS + "csi_14_t", + "csi_16_t", + "csi_18_t", + "csi_21_t", + }, +); + +/// XTWINOPS CSI 22/23 +pub const TitlePushPop = struct { + op: Op, + index: u16, + + pub const Op = enum { push, pop }; +}; diff --git a/vendor/libghostty-vt/src/terminal/cursor.zig b/vendor/libghostty-vt/src/terminal/cursor.zig new file mode 100644 index 00000000..136ee085 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/cursor.zig @@ -0,0 +1,15 @@ +/// The visual style of the cursor. Whether or not it blinks +/// is determined by mode 12 (modes.zig). This mode is synchronized +/// with CSI q, the same as xterm. +pub const Style = enum { + bar, // DECSCUSR 5, 6 + block, // DECSCUSR 1, 2 + underline, // DECSCUSR 3, 4 + + /// The cursor styles below aren't known by DESCUSR and are custom + /// implemented in Ghostty. They are reported as some standard style + /// if requested, though. + /// Hollow block cursor. This is a block cursor with the center empty. + /// Reported as DECSCUSR 1 or 2 (block). + block_hollow, +}; diff --git a/vendor/libghostty-vt/src/terminal/dcs.zig b/vendor/libghostty-vt/src/terminal/dcs.zig new file mode 100644 index 00000000..425325d4 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/dcs.zig @@ -0,0 +1,430 @@ +const std = @import("std"); +const build_options = @import("terminal_options"); +const assert = @import("../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const terminal = @import("main.zig"); +const DCS = terminal.DCS; + +const log = std.log.scoped(.terminal_dcs); + +/// DCS command handler. This should be hooked into a terminal.Stream handler. +/// The hook/put/unhook functions are meant to be called from the +/// terminal.stream dcsHook, dcsPut, and dcsUnhook functions, respectively. +pub const Handler = struct { + state: State = .{ .inactive = {} }, + + /// Maximum bytes any DCS command can take. This is to prevent + /// malicious input from causing us to allocate too much memory. + /// This is arbitrarily set to 1MB today, increase if needed. + max_bytes: usize = 1024 * 1024, + + pub fn deinit(self: *Handler) void { + self.discard(); + } + + pub fn hook(self: *Handler, alloc: Allocator, dcs: DCS) ?Command { + assert(self.state == .inactive); + + // Initialize our state to ignore in case of error + self.state = .ignore; + + // Try to parse the hook. + const hk_ = self.tryHook(alloc, dcs) catch |err| { + log.info("error initializing DCS hook, will ignore hook err={}", .{err}); + return null; + }; + const hk = hk_ orelse { + log.info("unknown DCS hook: {}", .{dcs}); + return null; + }; + + self.state = hk.state; + return hk.command; + } + + const Hook = struct { + state: State, + command: ?Command = null, + }; + + fn tryHook(self: Handler, alloc: Allocator, dcs: DCS) !?Hook { + return switch (dcs.intermediates.len) { + 0 => switch (dcs.final) { + // Tmux control mode + 'p' => tmux: { + if (comptime !build_options.tmux_control_mode) { + log.debug("tmux control mode not enabled in build, ignoring", .{}); + break :tmux null; + } + + // Tmux control mode must start with ESC P 1000 p + if (dcs.params.len != 1 or dcs.params[0] != 1000) break :tmux null; + + break :tmux .{ + .state = .{ + .tmux = .{ + .max_bytes = self.max_bytes, + .buffer = try .initCapacity( + alloc, + 128, // Arbitrary choice to limit initial reallocs + ), + }, + }, + .command = .{ .tmux = .enter }, + }; + }, + + else => null, + }, + + 1 => switch (dcs.intermediates[0]) { + '+' => switch (dcs.final) { + // XTGETTCAP + // https://github.com/mitchellh/ghostty/issues/517 + 'q' => .{ + .state = .{ + .xtgettcap = try .initCapacity( + alloc, + 128, // Arbitrary choice + ), + }, + }, + + else => null, + }, + + '$' => switch (dcs.final) { + // DECRQSS + 'q' => .{ .state = .{ + .decrqss = .{}, + } }, + + else => null, + }, + + else => null, + }, + + else => null, + }; + } + + /// Put a byte into the DCS handler. This will return a command + /// if a command needs to be executed. + pub fn put(self: *Handler, byte: u8) ?Command { + return self.tryPut(byte) catch |err| { + // On error we just discard our state and ignore the rest + log.info("error putting byte into DCS handler err={}", .{err}); + self.discard(); + self.state = .ignore; + return null; + }; + } + + fn tryPut(self: *Handler, byte: u8) !?Command { + switch (self.state) { + .inactive, + .ignore, + => {}, + + .tmux => |*tmux| if (comptime build_options.tmux_control_mode) { + return .{ + .tmux = (try tmux.put(byte)) orelse return null, + }; + } else unreachable, + + .xtgettcap => |*list| { + if (list.written().len >= self.max_bytes) { + return error.OutOfMemory; + } + + try list.writer.writeByte(byte); + }, + + .decrqss => |*buffer| { + if (buffer.len >= buffer.data.len) { + return error.OutOfMemory; + } + + buffer.data[buffer.len] = byte; + buffer.len += 1; + }, + } + + return null; + } + + pub fn unhook(self: *Handler) ?Command { + // Note: we do NOT call deinit here on purpose because some commands + // transfer memory ownership. If state needs cleanup, the switch + // prong below should handle it. + defer self.state = .inactive; + + return switch (self.state) { + .inactive, + .ignore, + => null, + + .tmux => if (comptime build_options.tmux_control_mode) tmux: { + self.state.deinit(); + break :tmux .{ .tmux = .exit }; + } else unreachable, + + .xtgettcap => |*list| xtgettcap: { + // Note: purposely do not deinit our state here because + // we copy it into the resulting command. + const items = list.written(); + for (items, 0..) |b, i| items[i] = std.ascii.toUpper(b); + break :xtgettcap .{ .xtgettcap = .{ .data = list.* } }; + }, + + .decrqss => |buffer| .{ .decrqss = switch (buffer.len) { + 0 => .none, + 1 => switch (buffer.data[0]) { + 'm' => .sgr, + 'r' => .decstbm, + 's' => .decslrm, + else => .none, + }, + 2 => switch (buffer.data[0]) { + ' ' => switch (buffer.data[1]) { + 'q' => .decscusr, + else => .none, + }, + else => .none, + }, + else => unreachable, + } }, + }; + } + + fn discard(self: *Handler) void { + self.state.deinit(); + self.state = .inactive; + } +}; + +pub const Command = union(enum) { + /// XTGETTCAP + xtgettcap: XTGETTCAP, + + /// DECRQSS + decrqss: DECRQSS, + + /// Tmux control mode + tmux: if (build_options.tmux_control_mode) + terminal.tmux.ControlNotification + else + void, + + pub fn deinit(self: *Command) void { + switch (self.*) { + .xtgettcap => |*v| v.data.deinit(), + .decrqss => {}, + .tmux => {}, + } + } + + pub const XTGETTCAP = struct { + data: std.Io.Writer.Allocating, + i: usize = 0, + + /// Returns the next terminfo key being requested and null + /// when there are no more keys. The returned value is NOT hex-decoded + /// because we expect to use a comptime lookup table. + pub fn next(self: *XTGETTCAP) ?[]const u8 { + const items = self.data.written(); + if (self.i >= items.len) return null; + var rem = items[self.i..]; + const idx = std.mem.indexOf(u8, rem, ";") orelse rem.len; + + // Note that if we're at the end, idx + 1 is len + 1 so we're over + // the end but that's okay because our check above is >= so we'll + // never read. + self.i += idx + 1; + + return rem[0..idx]; + } + }; + + /// Supported DECRQSS settings + pub const DECRQSS = enum { + none, + sgr, + decscusr, + decstbm, + decslrm, + }; +}; + +const State = union(enum) { + /// We're not in a DCS state at the moment. + inactive, + + /// We're hooked, but its an unknown DCS command or one that went + /// invalid due to some bad input, so we're ignoring the rest. + ignore, + + /// XTGETTCAP + xtgettcap: std.Io.Writer.Allocating, + + /// DECRQSS + decrqss: struct { + data: [2]u8 = undefined, + len: u2 = 0, + }, + + /// Tmux control mode: https://github.com/tmux/tmux/wiki/Control-Mode + tmux: if (build_options.tmux_control_mode) + terminal.tmux.ControlParser + else + void, + + pub fn deinit(self: *State) void { + switch (self.*) { + .inactive, + .ignore, + => {}, + + .xtgettcap => |*v| v.deinit(), + .decrqss => {}, + .tmux => |*v| if (comptime build_options.tmux_control_mode) { + v.deinit(); + } else unreachable, + } + } +}; + +test "unknown DCS command" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .final = 'A' }) == null); + try testing.expect(h.state == .ignore); + try testing.expect(h.unhook() == null); + try testing.expect(h.state == .inactive); +} + +test "XTGETTCAP command" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .intermediates = "+", .final = 'q' }) == null); + for ("536D756C78") |byte| _ = h.put(byte); + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .xtgettcap); + try testing.expectEqualStrings("536D756C78", cmd.xtgettcap.next().?); + try testing.expect(cmd.xtgettcap.next() == null); +} + +test "XTGETTCAP mixed case" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .intermediates = "+", .final = 'q' }) == null); + for ("536d756C78") |byte| _ = h.put(byte); + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .xtgettcap); + try testing.expectEqualStrings("536D756C78", cmd.xtgettcap.next().?); + try testing.expect(cmd.xtgettcap.next() == null); +} + +test "XTGETTCAP command multiple keys" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .intermediates = "+", .final = 'q' }) == null); + for ("536D756C78;536D756C78") |byte| _ = h.put(byte); + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .xtgettcap); + try testing.expectEqualStrings("536D756C78", cmd.xtgettcap.next().?); + try testing.expectEqualStrings("536D756C78", cmd.xtgettcap.next().?); + try testing.expect(cmd.xtgettcap.next() == null); +} + +test "XTGETTCAP command invalid data" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .intermediates = "+", .final = 'q' }) == null); + for ("who;536D756C78") |byte| _ = h.put(byte); + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .xtgettcap); + try testing.expectEqualStrings("WHO", cmd.xtgettcap.next().?); + try testing.expectEqualStrings("536D756C78", cmd.xtgettcap.next().?); + try testing.expect(cmd.xtgettcap.next() == null); +} + +test "DECRQSS command" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .intermediates = "$", .final = 'q' }) == null); + _ = h.put('m'); + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .decrqss); + try testing.expect(cmd.decrqss == .sgr); +} + +test "DECRQSS invalid command" { + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + try testing.expect(h.hook(alloc, .{ .intermediates = "$", .final = 'q' }) == null); + _ = h.put('z'); + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .decrqss); + try testing.expect(cmd.decrqss == .none); + + h.discard(); + + try testing.expect(h.hook(alloc, .{ .intermediates = "$", .final = 'q' }) == null); + _ = h.put('"'); + _ = h.put(' '); + _ = h.put('q'); + try testing.expect(h.unhook() == null); +} + +test "tmux enter and implicit exit" { + if (comptime !build_options.tmux_control_mode) return error.SkipZigTest; + + const testing = std.testing; + const alloc = testing.allocator; + + var h: Handler = .{}; + defer h.deinit(); + + { + var cmd = h.hook(alloc, .{ .params = &.{1000}, .final = 'p' }).?; + defer cmd.deinit(); + try testing.expect(cmd == .tmux); + try testing.expect(cmd.tmux == .enter); + } + + { + var cmd = h.unhook().?; + defer cmd.deinit(); + try testing.expect(cmd == .tmux); + try testing.expect(cmd.tmux == .exit); + } +} diff --git a/vendor/libghostty-vt/src/terminal/device_attributes.zig b/vendor/libghostty-vt/src/terminal/device_attributes.zig new file mode 100644 index 00000000..38d08117 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/device_attributes.zig @@ -0,0 +1,227 @@ +const std = @import("std"); +const testing = std.testing; +const lib = @import("lib.zig"); + +/// The device attribute request type (CSI c). +pub const Req = lib.Enum(lib.target, &.{ + "primary", // Blank + "secondary", // > + "tertiary", // = +}); + +/// Response data for all device attribute queries. +pub const Attributes = struct { + /// Reply to CSI c (DA1). + primary: Primary = .{}, + + /// Reply to CSI > c (DA2). + secondary: Secondary = .{}, + + /// Reply to CSI = c (DA3). + tertiary: Tertiary = .{}, + + /// Encode the response for the given request type into the writer. + pub fn encode( + self: Attributes, + req: Req, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + switch (req) { + .primary => try self.primary.encode(writer), + .secondary => try self.secondary.encode(writer), + .tertiary => try self.tertiary.encode(writer), + } + } +}; + +/// Primary device attributes (DA1). +/// +/// Response format: CSI ? Pp ; Ps... c +/// where Pp is the conformance level and Ps are feature flags. +pub const Primary = struct { + /// Conformance level sent as the first parameter. + conformance_level: ConformanceLevel = .vt220, + + /// Optional feature attributes. + features: []const Feature = &.{.ansi_color}, + + /// DA1 feature attribute codes. + pub const Feature = enum(u16) { + columns_132 = 1, + printer = 2, + regis = 3, + sixel = 4, + selective_erase = 6, + user_defined_keys = 8, + national_replacement = 9, + technical_characters = 15, + locator = 16, + terminal_state = 17, + windowing = 18, + horizontal_scrolling = 21, + ansi_color = 22, + rectangular_editing = 28, + ansi_text_locator = 29, + clipboard = 52, + _, + }; + + /// Encode the primary DA response into the writer. + pub fn encode(self: Primary, writer: *std.Io.Writer) std.Io.Writer.Error!void { + try writer.print("\x1b[?{}", .{@intFromEnum(self.conformance_level)}); + for (self.features) |feature| try writer.print(";{}", .{@intFromEnum(feature)}); + try writer.writeAll("c"); + } +}; + +/// Secondary device attributes (DA2). +/// +/// Response format: CSI > Pp ; Pv ; Pc c +pub const Secondary = struct { + /// Terminal type identifier (Pp parameter from secondary DA response). + device_type: DeviceType = .vt220, + + /// Firmware/patch version number. + firmware_version: u16 = 0, + + /// ROM cartridge registration number. Always 0 for emulators. + rom_cartridge: u16 = 0, + + /// Encode the secondary DA response into the writer. + pub fn encode(self: Secondary, writer: *std.Io.Writer) std.Io.Writer.Error!void { + try writer.print("\x1b[>{};{};{}c", .{ + @intFromEnum(self.device_type), + self.firmware_version, + self.rom_cartridge, + }); + } +}; + +/// Tertiary device attributes (DA3). +/// +/// Response format: DCS ! | D...D ST +/// where D...D is the unit ID as hex digits (DECRPTUI). +pub const Tertiary = struct { + /// Unit ID (DECRPTUI). Encoded as 8 uppercase hex digits. + /// Meaningless for emulators nowadays. The actual DEC manuals + /// appear to split this into two 16-bit fields but since there + /// is no practical usage I know if I'm simplifying this. + unit_id: u32 = 0, + + /// Encode the tertiary DA response into the writer. + pub fn encode( + self: Tertiary, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + try writer.print( + "\x1bP!|{X:0>8}\x1b\\", + .{self.unit_id}, + ); + } +}; + +/// Conformance level reported as the first parameter (Pp) in the +/// primary device attributes (DA1) response. +pub const ConformanceLevel = enum(u16) { + // VT100-series have per-model values. + vt100 = 1, + vt132 = 4, + vt102 = 6, + vt131 = 7, + vt125 = 12, + + // VT200+ use 60 + decTerminalID/100. + /// Level 2 conformance (VT200 series, e.g. VT220, VT240). + level_2 = 62, + /// Level 3 conformance (VT300 series, e.g. VT320, VT340). + level_3 = 63, + /// Level 4 conformance (VT400 series, e.g. VT420). + level_4 = 64, + /// Level 5 conformance (VT500 series, e.g. VT510, VT520, VT525). + level_5 = 65, + + _, + + pub const vt101 = ConformanceLevel.vt100; + pub const vt220 = ConformanceLevel.level_2; + pub const vt240 = ConformanceLevel.level_2; + pub const vt320 = ConformanceLevel.level_3; + pub const vt340 = ConformanceLevel.level_3; + pub const vt420 = ConformanceLevel.level_4; + pub const vt510 = ConformanceLevel.level_5; + pub const vt520 = ConformanceLevel.level_5; + pub const vt525 = ConformanceLevel.level_5; +}; + +/// Terminal type identifier reported as the Pp parameter in the +/// secondary device attributes (DA2) response. Values correspond +/// to the decTerminalID resource in xterm. +pub const DeviceType = enum(u16) { + vt100 = 0, + vt220 = 1, + vt240 = 2, + vt330 = 18, + vt340 = 19, + vt320 = 24, + vt382 = 32, + vt420 = 41, + vt510 = 61, + vt520 = 64, + vt525 = 65, + _, +}; + +test "primary default" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Primary{}).encode(&writer); + try testing.expectEqualStrings("\x1b[?62;22c", writer.buffered()); +} + +test "primary with clipboard" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Primary{ .features = &.{ .ansi_color, .clipboard } }).encode(&writer); + try testing.expectEqualStrings("\x1b[?62;22;52c", writer.buffered()); +} + +test "primary with multiple features" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Primary{ + .conformance_level = .vt420, + .features = &.{ .columns_132, .selective_erase, .ansi_color }, + }).encode(&writer); + try testing.expectEqualStrings("\x1b[?64;1;6;22c", writer.buffered()); +} + +test "primary no features" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Primary{ + .conformance_level = .vt100, + .features = &.{}, + }).encode(&writer); + try testing.expectEqualStrings("\x1b[?1c", writer.buffered()); +} + +test "secondary default" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Secondary{}).encode(&writer); + try testing.expectEqualStrings("\x1b[>1;0;0c", writer.buffered()); +} + +test "tertiary default" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Tertiary{}).encode(&writer); + try testing.expectEqualStrings("\x1bP!|00000000\x1b\\", writer.buffered()); +} + +test "tertiary custom unit id" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try (Tertiary{ .unit_id = 0xAABBCCDD }).encode(&writer); + try testing.expectEqualStrings("\x1bP!|AABBCCDD\x1b\\", writer.buffered()); +} diff --git a/vendor/libghostty-vt/src/terminal/device_status.zig b/vendor/libghostty-vt/src/terminal/device_status.zig new file mode 100644 index 00000000..42b4bf01 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/device_status.zig @@ -0,0 +1,74 @@ +const std = @import("std"); +const lib = @import("lib.zig"); + +/// The color scheme reported in response to a CSI ? 996 n query. +pub const ColorScheme = lib.Enum(lib.target, &.{ + "light", + "dark", +}); + +/// An enum(u16) of the available device status requests. +pub const Request = dsr_enum: { + const EnumField = std.builtin.Type.EnumField; + var fields: [entries.len]EnumField = undefined; + for (entries, 0..) |entry, i| { + fields[i] = .{ + .name = entry.name, + .value = @as(Tag.Backing, @bitCast(Tag{ + .value = entry.value, + .question = entry.question, + })), + }; + } + + break :dsr_enum @Type(.{ .@"enum" = .{ + .tag_type = Tag.Backing, + .fields = &fields, + .decls = &.{}, + .is_exhaustive = true, + } }); +}; + +/// The tag type for our enum is a u16 but we use a packed struct +/// in order to pack the question bit into the tag. The "u16" size is +/// chosen somewhat arbitrarily to match the largest expected size +/// we see as a multiple of 8 bits. +pub const Tag = packed struct(u16) { + pub const Backing = @typeInfo(@This()).@"struct".backing_integer.?; + value: u15, + question: bool = false, + + test "order" { + const t: Tag = .{ .value = 1 }; + const int: Backing = @bitCast(t); + try std.testing.expectEqual(@as(Backing, 1), int); + } +}; + +pub fn reqFromInt(v: u16, question: bool) ?Request { + inline for (entries) |entry| { + if (entry.value == v and entry.question == question) { + const tag: Tag = .{ .question = question, .value = entry.value }; + const int: Tag.Backing = @bitCast(tag); + return @enumFromInt(int); + } + } + + return null; +} + +/// A single entry of a possible device status request we support. The +/// "question" field determines if it is valid with or without the "?" +/// prefix. +const Entry = struct { + name: [:0]const u8, + value: comptime_int, + question: bool = false, // "?" request +}; + +/// The full list of device status request entries. +const entries: []const Entry = &.{ + .{ .name = "operating_status", .value = 5 }, + .{ .name = "cursor_position", .value = 6 }, + .{ .name = "color_scheme", .value = 996, .question = true }, +}; diff --git a/vendor/libghostty-vt/src/terminal/focus.zig b/vendor/libghostty-vt/src/terminal/focus.zig new file mode 100644 index 00000000..91c579e1 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/focus.zig @@ -0,0 +1,39 @@ +const std = @import("std"); +const lib = @import("lib.zig"); + +/// Maximum number of bytes that `encode` will write. Any users of this +/// should be resilient to this changing, so this is always a specific +/// value (e.g. we don't add unnecessary padding). +pub const max_encode_size = 3; + +/// A focus event that can be reported to the application running in the +/// terminal when focus reporting mode (mode 1004) is enabled. +pub const Event = lib.Enum(lib.target, &.{ + "gained", + "lost", +}); + +/// Encode a focus in/out report (CSI I / CSI O). +pub fn encode( + writer: *std.Io.Writer, + event: Event, +) std.Io.Writer.Error!void { + try writer.writeAll(switch (event) { + .gained => "\x1B[I", + .lost => "\x1B[O", + }); +} + +test "encode focus gained" { + var buf: [max_encode_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, .gained); + try std.testing.expectEqualStrings("\x1B[I", writer.buffered()); +} + +test "encode focus lost" { + var buf: [max_encode_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, .lost); + try std.testing.expectEqualStrings("\x1B[O", writer.buffered()); +} diff --git a/vendor/libghostty-vt/src/terminal/formatter.zig b/vendor/libghostty-vt/src/terminal/formatter.zig new file mode 100644 index 00000000..a375b4dd --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/formatter.zig @@ -0,0 +1,6279 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const lib = @import("lib.zig"); +const Allocator = std.mem.Allocator; +const color = @import("color.zig"); +const size = @import("size.zig"); +const charsets = @import("charsets.zig"); +const hyperlink = @import("hyperlink.zig"); +const kitty = @import("kitty.zig"); +const modespkg = @import("modes.zig"); +const Screen = @import("Screen.zig"); +const Terminal = @import("Terminal.zig"); +const Cell = @import("page.zig").Cell; +const Coordinate = @import("point.zig").Coordinate; +const Page = @import("page.zig").Page; +const PageList = @import("PageList.zig"); +const Pin = PageList.Pin; +const Row = @import("page.zig").Row; +const Selection = @import("Selection.zig"); +const Style = @import("style.zig").Style; + +/// Formats available. +pub const Format = lib.Enum(lib.target, &.{ + // Plain text. + "plain", + + // Include VT sequences to preserve colors, styles, URLs, etc. + // This is predominantly SGR sequences but may contain others as needed. + // + // Note that for reference colors, like palette indices, this will + // vary based on the formatter and you should see the docs. For example, + // PageFormatter with VT will emit SGR sequences with palette indices, + // not the color itself. + // + // For VT, newlines will be emitted as `\r\n` so that the cursor properly + // moves back to the beginning prior emitting follow-up lines. + "vt", + + // HTML output. + // + // This will emit inline styles for as much styling as possible, + // in the interest of simplicity and ease of editing. This isn't meant + // to build the most beautiful or efficient HTML, but rather to be + // stylistically correct. + // + // For colors, RGB values are emitted as inline CSS (#RRGGBB) while palette + // indices use CSS variables (var(--vt-palette-N)). The palette colors are + // emitted by TerminalFormatter.Extra.palette as a "); + }, + } + + // If we have a pin_map, add the bytes we wrote to map. + if (self.pin_map) |*m| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + var extra_formatter: TerminalFormatter = self; + extra_formatter.content = .none; + extra_formatter.pin_map = null; + extra_formatter.extra = .none; + extra_formatter.extra.palette = true; + try extra_formatter.format(&discarding.writer); + + // Map all those bytes to the same pin. Use the top left to ensure + // the node pointer is always properly initialized. + m.map.appendNTimes( + m.alloc, + self.terminal.screens.active.pages.getTopLeft(.screen), + std.math.cast(usize, discarding.count) orelse return error.WriteFailed, + ) catch return error.WriteFailed; + } + } + + // Emit terminal modes that differ from defaults. We probably have + // some modes we want to emit before and some after, but for now for + // simplicity we just emit them all before. If we make this more complex + // later we should add test cases for it. + if (self.opts.emit == .vt and self.extra.modes) { + inline for (@typeInfo(modespkg.Mode).@"enum".fields) |field| { + const mode: modespkg.Mode = @enumFromInt(field.value); + const current = self.terminal.modes.get(mode); + const default_val = @field(self.terminal.modes.default, field.name); + + if (current != default_val) { + const tag: modespkg.ModeTag = @bitCast(@intFromEnum(mode)); + const prefix = if (tag.ansi) "" else "?"; + const suffix = if (current) "h" else "l"; + try writer.print("\x1b[{s}{d}{s}", .{ prefix, tag.value, suffix }); + } + } + + // If we have a pin_map, add the bytes we wrote to map. + if (self.pin_map) |*m| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + var extra_formatter: TerminalFormatter = self; + extra_formatter.content = .none; + extra_formatter.pin_map = null; + extra_formatter.extra = .none; + extra_formatter.extra.modes = true; + try extra_formatter.format(&discarding.writer); + + // Map all those bytes to the same pin. Use the top left to ensure + // the node pointer is always properly initialized. + m.map.appendNTimes( + m.alloc, + self.terminal.screens.active.pages.getTopLeft(.screen), + std.math.cast(usize, discarding.count) orelse return error.WriteFailed, + ) catch return error.WriteFailed; + } + } + + var screen_formatter: ScreenFormatter = .init(self.terminal.screens.active, self.opts); + screen_formatter.content = self.content; + screen_formatter.extra = self.extra.screen; + screen_formatter.pin_map = self.pin_map; + try screen_formatter.format(writer); + + // Extra terminal state to emit after the screen contents so that + // it doesn't impact the emitted contents. + if (self.opts.emit == .vt) { + // Emit scrolling region using DECSTBM and DECSLRM + if (self.extra.scrolling_region) { + const region = &self.terminal.scrolling_region; + + // DECSTBM: top and bottom margins (1-indexed) + // Only emit if not the full screen + if (region.top != 0 or region.bottom != self.terminal.rows - 1) { + try writer.print("\x1b[{d};{d}r", .{ region.top + 1, region.bottom + 1 }); + } + + // DECSLRM: left and right margins (1-indexed) + // Only emit if not the full width + if (region.left != 0 or region.right != self.terminal.cols - 1) { + try writer.print("\x1b[{d};{d}s", .{ region.left + 1, region.right + 1 }); + } + } + + // Emit tabstop positions + if (self.extra.tabstops) { + // Clear all tabs (CSI 3 g) + try writer.print("\x1b[3g", .{}); + + // Set each configured tabstop by moving cursor and using HTS + for (0..self.terminal.cols) |col| { + if (self.terminal.tabstops.get(col)) { + // Move cursor to the column (1-indexed) + try writer.print("\x1b[{d}G", .{col + 1}); + // Set tab (HTS) + try writer.print("\x1bH", .{}); + } + } + } + + // Emit keyboard modes such as ModifyOtherKeys + if (self.extra.keyboard) { + // Only emit if modify_other_keys_2 is true + if (self.terminal.flags.modify_other_keys_2) { + try writer.print("\x1b[>4;2m", .{}); + } + } + + // Emit present working directory using OSC 7 + if (self.extra.pwd) { + const pwd = self.terminal.pwd.items; + if (pwd.len > 0) try writer.print("\x1b]7;{s}\x1b\\", .{pwd}); + } + + // If we have a pin_map, add the bytes we wrote to map. + if (self.pin_map) |*m| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + var extra_formatter: TerminalFormatter = self; + extra_formatter.content = .none; + extra_formatter.pin_map = null; + extra_formatter.extra = .none; + extra_formatter.extra.scrolling_region = self.extra.scrolling_region; + extra_formatter.extra.tabstops = self.extra.tabstops; + extra_formatter.extra.keyboard = self.extra.keyboard; + extra_formatter.extra.pwd = self.extra.pwd; + try extra_formatter.format(&discarding.writer); + + m.map.appendNTimes( + m.alloc, + if (m.map.items.len > 0) pin: { + const last = m.map.items[m.map.items.len - 1]; + break :pin .{ + .node = last.node, + .x = last.x, + .y = last.y, + }; + } else self.terminal.screens.active.pages.getTopLeft(.screen), + std.math.cast(usize, discarding.count) orelse return error.WriteFailed, + ) catch return error.WriteFailed; + } + } + } +}; + +/// Screen formatter formats a single terminal screen (e.g. primary vs alt). +pub const ScreenFormatter = struct { + /// The screen to format. + screen: *const Screen, + + /// The common options + opts: Options, + + /// The content to include. + content: Content, + + /// Extra stuff to emit, such as cursor, style, hyperlinks, etc. + /// This information is ONLY emitted when the format is "vt". + extra: Extra, + + /// If non-null, then `map` will contain the Pin of every byte + /// byte written to the writer offset by the byte index. It is the + /// caller's responsibility to free the map. + /// + /// Note that some emitted bytes may not correspond to any Pin, such as + /// the extra data around screen state. For these, we'll map it to the + /// most previous pin so there is some continuity but its an arbitrary + /// choice. + /// + /// Warning: there is a significant performance hit to track this + pin_map: ?PinMap, + + pub const Content = union(enum) { + /// Emit no content, only terminal state such as modes, palette, etc. + /// via extra. + none, + + /// Emit the content specified by the selection. Null for all. + /// The selection is inclusive on both ends. + selection: ?Selection, + }; + + pub const Extra = packed struct { + /// Emit cursor position using CUP (CSI H). + cursor: bool, + + /// Emit current SGR style state based on the cursor's active style_id. + /// This reconstructs the SGR attributes (bold, italic, colors, etc.) at + /// the cursor position. + style: bool, + + /// Emit current hyperlink state using OSC 8 sequences. + /// This sets the active hyperlink based on cursor.hyperlink_id. + hyperlink: bool, + + /// Emit character protection mode using DECSCA. + protection: bool, + + /// Emit Kitty keyboard protocol state using CSI > u and CSI = sequences. + kitty_keyboard: bool, + + /// Emit character set designations and invocations. + /// This includes G0-G3 designations (ESC ( ) * +) and GL/GR invocations. + charsets: bool, + + /// Emit nothing. + pub const none: Extra = .{ + .cursor = false, + .style = false, + .hyperlink = false, + .protection = false, + .kitty_keyboard = false, + .charsets = false, + }; + + /// Emit style-relevant information only. + pub const styles: Extra = .{ + .cursor = false, + .style = true, + .hyperlink = true, + .protection = false, + .kitty_keyboard = false, + .charsets = false, + }; + + /// Emit everything. This reconstructs the screen state as closely + /// as possible. + pub const all: Extra = .{ + .cursor = true, + .style = true, + .hyperlink = true, + .protection = true, + .kitty_keyboard = true, + .charsets = true, + }; + + fn isSet(self: Extra) bool { + const Int = @typeInfo(Extra).@"struct".backing_integer.?; + const v: Int = @bitCast(self); + return v != 0; + } + }; + + pub fn init( + screen: *const Screen, + opts: Options, + ) ScreenFormatter { + return .{ + .screen = screen, + .opts = opts, + .content = .{ .selection = null }, + .extra = .none, + .pin_map = null, + }; + } + + pub fn format( + self: ScreenFormatter, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + switch (self.content) { + .none => {}, + + .selection => |selection_| { + // Emit our pagelist contents according to our selection. + var list_formatter: PageListFormatter = .init(&self.screen.pages, self.opts); + list_formatter.pin_map = self.pin_map; + if (selection_) |sel| { + list_formatter.top_left = sel.topLeft(self.screen); + list_formatter.bottom_right = sel.bottomRight(self.screen); + list_formatter.rectangle = sel.rectangle; + } + try list_formatter.format(writer); + }, + } + + // Emit extra screen state after content if we care. The state has + // to be emitted after since some state such as cursor position and + // style are impacted by content rendering. + switch (self.opts.emit) { + .plain => return, + .vt => if (!self.extra.isSet()) return, + + // HTML doesn't preserve any screen state because it has + // nothing to do with rendering. + .html => return, + } + + // Emit current SGR style state + if (self.extra.style) { + const cursor = &self.screen.cursor; + try writer.print("{f}", .{cursor.style.formatterVt()}); + } + + // Emit current hyperlink state using OSC 8 + if (self.extra.hyperlink) { + const cursor = &self.screen.cursor; + if (cursor.hyperlink) |link| { + // Start hyperlink with uri (and explicit id if present) + switch (link.id) { + .explicit => |id| try writer.print( + "\x1b]8;id={s};{s}\x1b\\", + .{ id, link.uri }, + ), + .implicit => try writer.print( + "\x1b]8;;{s}\x1b\\", + .{link.uri}, + ), + } + } + } + + // Emit character protection mode using DECSCA + if (self.extra.protection) { + const cursor = &self.screen.cursor; + if (cursor.protected) { + // DEC protected mode + try writer.print("\x1b[1\"q", .{}); + } + } + + // Emit Kitty keyboard protocol state using CSI = u + if (self.extra.kitty_keyboard) { + const current_flags = self.screen.kitty_keyboard.current(); + if (current_flags.int() != kitty.KeyFlags.disabled.int()) { + const flags = current_flags.int(); + try writer.print("\x1b[={d};1u", .{flags}); + } + } + + // Emit character set designations and invocations + if (self.extra.charsets) { + const charset = &self.screen.charset; + + // Emit G0-G3 designations + for (std.enums.values(charsets.Slots)) |slot| { + const cs = charset.charsets.get(slot); + if (cs != .utf8) { // Only emit non-default charsets + const intermediate: u8 = switch (slot) { + .G0 => '(', + .G1 => ')', + .G2 => '*', + .G3 => '+', + }; + const final: u8 = switch (cs) { + .ascii => 'B', + .british => 'A', + .dec_special => '0', + else => continue, + }; + try writer.print("\x1b{c}{c}", .{ intermediate, final }); + } + } + + // Emit GL invocation if not G0 + if (charset.gl != .G0) { + const seq = switch (charset.gl) { + .G0 => unreachable, + .G1 => "\x0e", // SO - Shift Out + .G2 => "\x1bn", // LS2 + .G3 => "\x1bo", // LS3 + }; + try writer.print("{s}", .{seq}); + } + + // Emit GR invocation if not G2 + if (charset.gr != .G2) { + const seq = switch (charset.gr) { + .G0 => unreachable, // GR can't be G0 + .G1 => "\x1b~", // LS1R + .G2 => unreachable, + .G3 => "\x1b|", // LS3R + }; + try writer.print("{s}", .{seq}); + } + } + + // Emit cursor position using CUP (CSI H) + if (self.extra.cursor) { + const cursor = &self.screen.cursor; + // CUP is 1-indexed + try writer.print("\x1b[{d};{d}H", .{ cursor.y + 1, cursor.x + 1 }); + } + + // If we have a pin_map, we need to count how many bytes the extras + // will emit so we can map them all to the same pin. We do this by + // formatting to a discarding writer with content=none. + if (self.pin_map) |*m| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + var extra_formatter: ScreenFormatter = self; + extra_formatter.content = .none; + extra_formatter.pin_map = null; + try extra_formatter.format(&discarding.writer); + + // Map all those bytes to the same pin. Use the first page node + // to ensure the node pointer is always properly initialized. + m.map.appendNTimes( + m.alloc, + if (m.map.items.len > 0) pin: { + // There is a weird Zig miscompilation here on 0.15.2. + // If I return the m.map.items value directly then we + // get undefined memory (even though we're copying a + // Pin struct). If we duplicate here like this we do + // not. + const last = m.map.items[m.map.items.len - 1]; + break :pin .{ + .node = last.node, + .x = last.x, + .y = last.y, + }; + } else self.screen.pages.getTopLeft(.screen), + std.math.cast(usize, discarding.count) orelse return error.WriteFailed, + ) catch return error.WriteFailed; + } + } +}; + +/// PageList formatter formats multiple pages as represented by a PageList. +pub const PageListFormatter = struct { + /// The pagelist to format. + list: *const PageList, + + /// The common options + opts: Options, + + /// The bounds of the PageList to format. The top left and bottom right + /// MUST be ordered properly. + top_left: ?PageList.Pin, + bottom_right: ?PageList.Pin, + + /// If true, the boundaries define a rectangle selection where start_x + /// and end_x apply to every row, not just the first and last. + rectangle: bool, + + /// If non-null, then `map` will contain the Pin of every byte + /// byte written to the writer offset by the byte index. It is the + /// caller's responsibility to free the map. + /// + /// Warning: there is a significant performance hit to track this + pin_map: ?PinMap, + + pub fn init( + list: *const PageList, + opts: Options, + ) PageListFormatter { + return PageListFormatter{ + .list = list, + .opts = opts, + .top_left = null, + .bottom_right = null, + .rectangle = false, + .pin_map = null, + }; + } + + pub fn format( + self: PageListFormatter, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + const tl: PageList.Pin = self.top_left orelse self.list.getTopLeft(.screen); + const br: PageList.Pin = self.bottom_right orelse self.list.getBottomRight(.screen).?; + + // If we keep track of pins, we'll need this. + var point_map: std.ArrayList(Coordinate) = .empty; + defer if (self.pin_map) |*m| point_map.deinit(m.alloc); + + var page_state: ?PageFormatter.TrailingState = null; + var iter = tl.pageIterator(.right_down, br); + while (iter.next()) |chunk| { + assert(chunk.start < chunk.end); + assert(chunk.end > 0); + + var formatter: PageFormatter = .init(&chunk.node.data, self.opts); + formatter.start_y = chunk.start; + formatter.end_y = chunk.end - 1; + formatter.trailing_state = page_state; + formatter.rectangle = self.rectangle; + + // For rectangle selection, apply start_x and end_x to all chunks + if (self.rectangle) { + formatter.start_x = tl.x; + formatter.end_x = br.x; + } else { + // Otherwise only on the first/last, respectively. + if (chunk.node == tl.node) formatter.start_x = tl.x; + if (chunk.node == br.node) formatter.end_x = br.x; + } + + // If we're tracking pins, then we setup a point map for the + // page formatter (cause it can't track pins). And then we convert + // this to pins later. + if (self.pin_map) |*m| { + point_map.clearRetainingCapacity(); + formatter.point_map = .{ .alloc = m.alloc, .map = &point_map }; + } + + page_state = try formatter.formatWithState(writer); + + // If we're tracking pins then grab our points and write them + // to our pin map. + if (self.pin_map) |*m| { + for (point_map.items) |coord| { + m.map.append(m.alloc, .{ + .node = chunk.node, + .x = coord.x, + .y = @intCast(coord.y), + }) catch return error.WriteFailed; + } + } + } + } +}; + +/// Page formatter. +/// +/// For styled formatting such as VT, this will emit references for palette +/// colors. If you want to capture the palette as-is at the type of formatting, +/// you'll have to emit the sequences for setting up the palette prior to +/// this formatting. (TODO: A function to do this) +pub const PageFormatter = struct { + /// The page to format. + page: *const Page, + + /// The common options + opts: Options, + + /// Start and end points within the page to format. If end x is not given + /// then it will be the full width. If end y is not given then it will be + /// the full height. + /// + /// The start and end are both inclusive, so equal values will still + /// return a non-empty result (i.e. a single cell or row). + /// + /// The start x is considered the X in the first row and end X is + /// X in the final row. This isn't a rectangle selection by default. + /// + /// If start X falls on the second column of a wide character, then + /// the entire character will be included (as if you specified the + /// previous column). + start_x: size.CellCountInt, + start_y: size.CellCountInt, + end_x: ?size.CellCountInt, + end_y: ?size.CellCountInt, + + /// If true, the start x/y and end x/y define a rectangle selection. + /// In this case, the boundaries will apply to every row, not just + /// the first and last. + rectangle: bool, + + /// If non-null, then `map` will contain the x/y coordinate of every + /// byte written to the writer offset by the byte index. It is the + /// caller's responsibility to free the map. + /// + /// The x/y coordinate will be the coordinates within the page. + /// + /// Warning: there is a significant performance hit to track this + point_map: ?struct { + alloc: Allocator, + map: *std.ArrayList(Coordinate), + }, + + /// The previous trailing state from the prior page. If you're iterating + /// over multiple pages this helps ensure that unwrapping and other + /// accounting works properly. + trailing_state: ?TrailingState, + + /// Trailing state. This is used to ensure that rows wrapped across + /// multiple pages are unwrapped properly, as well as other accounting + /// we may do in the future. + pub const TrailingState = struct { + rows: usize = 0, + cells: usize = 0, + + pub const empty: TrailingState = .{ .rows = 0, .cells = 0 }; + }; + + /// Initializes a page formatter. Other options can be set directly on the + /// struct after initialization and before calling `format()`. + pub fn init(page: *const Page, opts: Options) PageFormatter { + return .{ + .page = page, + .opts = opts, + .start_x = 0, + .start_y = 0, + .end_x = null, + .end_y = null, + .rectangle = false, + .point_map = null, + .trailing_state = null, + }; + } + + pub fn format( + self: PageFormatter, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + _ = try self.formatWithState(writer); + } + + pub fn formatWithState( + self: PageFormatter, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!TrailingState { + var blank_rows: usize = 0; + var blank_cells: usize = 0; + + // Continue our prior trailing state if we have it, but only if we're + // starting from the beginning (start_y and start_x are both 0). + // If a non-zero start position is specified, ignore trailing state. + if (self.trailing_state) |state| { + if (self.start_y == 0 and self.start_x == 0) { + blank_rows = state.rows; + blank_cells = state.cells; + } + } + + // Setup our starting column and perform some validation for overflows. + // Note: start_x only applies to the first row, end_x only applies to the last row. + const start_x: size.CellCountInt = self.start_x; + if (start_x >= self.page.size.cols) return .{ .rows = blank_rows, .cells = blank_cells }; + const end_x_unclamped: size.CellCountInt = self.end_x orelse self.page.size.cols - 1; + var end_x = @min(end_x_unclamped, self.page.size.cols - 1); + + // Setup our starting row and perform some validation for overflows. + const start_y: size.CellCountInt = self.start_y; + if (start_y >= self.page.size.rows) return .{ .rows = blank_rows, .cells = blank_cells }; + const end_y_unclamped: size.CellCountInt = self.end_y orelse self.page.size.rows - 1; + if (start_y > end_y_unclamped) return .{ .rows = blank_rows, .cells = blank_cells }; + var end_y = @min(end_y_unclamped, self.page.size.rows - 1); + + // Edge case: if our end x/y falls on a spacer head AND we're unwrapping, + // then we move the x/y to the start of the next row (if available). + if (self.opts.unwrap and !self.rectangle) { + const final_row = self.page.getRow(end_y); + const cells = self.page.getCells(final_row); + switch (cells[end_x].wide) { + .spacer_head => { + // Move to next row if available + // + // TODO: if unavailable, we should add to our trailing state + // + // so the pagelist formatter can be aware and maybe add + // another page + if (end_y < self.page.size.rows - 1) { + end_y += 1; + end_x = 0; + } + }, + + else => {}, + } + } + + // If we only have a single row, validate that start_x <= end_x + if (start_y == end_y and start_x > end_x) { + return .{ .rows = blank_rows, .cells = blank_cells }; + } + + // Wrap HTML output in monospace font styling + switch (self.opts.emit) { + .plain => {}, + + .html => { + // Setup our div. We use a buffer here that should always + // fit the stuff we need, in order to make counting bytes easier. + var buf: [1024]u8 = undefined; + var stream = std.io.fixedBufferStream(&buf); + const buf_writer = stream.writer(); + + // Monospace and whitespace preserving + buf_writer.writeAll("
2}{x:0>2}{x:0>2};", + .{ bg.r, bg.g, bg.b }, + ) catch return error.WriteFailed; + if (self.opts.foreground) |fg| buf_writer.print( + "color: #{x:0>2}{x:0>2}{x:0>2};", + .{ fg.r, fg.g, fg.b }, + ) catch return error.WriteFailed; + + buf_writer.writeAll("\">") catch return error.WriteFailed; + + const header = stream.getWritten(); + try writer.writeAll(header); + if (self.point_map) |*map| map.map.appendNTimes( + map.alloc, + .{ .x = 0, .y = 0 }, + header.len, + ) catch return error.WriteFailed; + }, + + .vt => { + // OSC 10 sets foreground color, OSC 11 sets background color + var buf: [512]u8 = undefined; + var stream = std.io.fixedBufferStream(&buf); + const buf_writer = stream.writer(); + if (self.opts.foreground) |fg| { + buf_writer.print( + "\x1b]10;rgb:{x:0>2}/{x:0>2}/{x:0>2}\x1b\\", + .{ fg.r, fg.g, fg.b }, + ) catch return error.WriteFailed; + } + if (self.opts.background) |bg| { + buf_writer.print( + "\x1b]11;rgb:{x:0>2}/{x:0>2}/{x:0>2}\x1b\\", + .{ bg.r, bg.g, bg.b }, + ) catch return error.WriteFailed; + } + + const header = stream.getWritten(); + try writer.writeAll(header); + if (self.point_map) |*map| map.map.appendNTimes( + map.alloc, + .{ .x = 0, .y = 0 }, + header.len, + ) catch return error.WriteFailed; + }, + } + + // Our style for non-plain formats + var style: Style = .{}; + + // Track hyperlink state for HTML output. We need to close tags + // when the hyperlink changes or ends. + var current_hyperlink_id: ?hyperlink.Id = null; + + for (start_y..end_y + 1) |y_usize| { + const y: size.CellCountInt = @intCast(y_usize); + const row: *Row = self.page.getRow(y); + const cells: []const Cell = self.page.getCells(row); + + // Determine the x range for this row + // - First row: start_x to end of row (or end_x if single row) + // - Last row: start of row to end_x + // - Middle rows: full width + const cells_subset, const row_start_x = cells_subset: { + // The end is always straightforward + const row_end_x: size.CellCountInt = if (self.rectangle or y == end_y) + end_x + 1 + else + self.page.size.cols; + + // The first we have to check if our start X falls on the + // tail of a wide character. + const row_start_x: size.CellCountInt = if (start_x > 0 and + (self.rectangle or y == start_y)) + start_x: { + break :start_x switch (cells[start_x].wide) { + // Include the prior cell to get the full wide char + .spacer_tail => start_x - 1, + + // If we're a spacer head on our first row then we + // skip this whole row. + .spacer_head => continue, + + .narrow, .wide => start_x, + }; + } else 0; + + const subset = cells[row_start_x..row_end_x]; + break :cells_subset .{ subset, row_start_x }; + }; + + // If this row is blank, accumulate to avoid a bunch of extra + // work later. If it isn't blank, make sure we dump all our + // blanks. + if (!Cell.hasTextAny(cells_subset)) { + blank_rows += 1; + continue; + } + + if (blank_rows > 0) { + // Reset style before emitting newlines to prevent background + // colors from bleeding into the next line's leading cells. + if (!style.default()) { + try self.formatStyleClose(writer); + style = .{}; + } + + const sequence: []const u8 = switch (self.opts.emit) { + // Plaintext just uses standard newlines because newlines + // on their own usually move the cursor back in anywhere + // you type plaintext. + .plain => "\n", + + // VT uses \r\n because in a raw pty, \n alone doesn't + // guarantee moving the cursor back to column 0. \r + // makes it work for sure. + .vt => "\r\n", + + // HTML uses just \n because HTML rendering will move + // the cursor back. + .html => "\n", + }; + + for (0..blank_rows) |_| try writer.writeAll(sequence); + + // \r and \n map to the row that ends with this newline. + // If we're continuing (trailing state) then this will be + // in a prior page, so we just map to the first row of this + // page. + if (self.point_map) |*map| { + const start: Coordinate = if (map.map.items.len > 0) + map.map.items[map.map.items.len - 1] + else + .{ .x = 0, .y = 0 }; + + // The first one inherits the x value. + map.map.appendNTimes( + map.alloc, + .{ .x = start.x, .y = start.y }, + sequence.len, + ) catch return error.WriteFailed; + + // All others have x = 0 since they reference their prior + // blank line. + for (1..blank_rows) |y_offset_usize| { + const y_offset: size.CellCountInt = @intCast(y_offset_usize); + map.map.appendNTimes( + map.alloc, + .{ .x = 0, .y = start.y + y_offset }, + sequence.len, + ) catch return error.WriteFailed; + } + } + + blank_rows = 0; + } + + // If we're not wrapped, we always add a newline so after + // the row is printed we can add a newline. + if (!row.wrap or !self.opts.unwrap) blank_rows += 1; + + // If the row doesn't continue a wrap then we need to reset + // our blank cell count. + if (!row.wrap_continuation or !self.opts.unwrap) blank_cells = 0; + + // Go through each cell and print it + for (cells_subset, row_start_x..) |*cell, x_usize| { + const x: size.CellCountInt = @intCast(x_usize); + + // Skip spacers. These happen naturally when wide characters + // are printed again on the screen (for well-behaved terminals!) + switch (cell.wide) { + .narrow, .wide => {}, + .spacer_head, .spacer_tail => continue, + } + + // If we have a zero value, then we accumulate a counter. We + // only want to turn zero values into spaces if we have a non-zero + // char sometime later. + blank: { + // If we're emitting styled output (not plaintext) and + // the cell has some kind of styling or is not empty + // then this isn't blank. + if (formatStyled(self.opts.emit) and + (!cell.isEmpty() or cell.hasStyling())) break :blank; + + // Cells with no text are blank + if (!cell.hasText()) { + blank_cells += 1; + continue; + } + + // Trailing spaces are blank. We know it is trailing + // because if we get a non-empty cell later we'll + // fill the blanks. + if (cell.codepoint() == ' ' and self.opts.trim) { + blank_cells += 1; + continue; + } + } + + // This cell is not blank. If we have accumulated blank cells + // then we want to emit them now. + if (blank_cells > 0) { + try writer.splatByteAll(' ', blank_cells); + + if (self.point_map) |*map| { + // Map each blank cell to its coordinate. Blank cells can span + // multiple rows if they carry over from wrap continuation. + var remaining_blanks = blank_cells; + var blank_x = x; + var blank_y = y; + while (remaining_blanks > 0) : (remaining_blanks -= 1) { + if (blank_x > 0) { + // We have space in this row + blank_x -= 1; + } else if (blank_y > 0) { + // Wrap to previous row + blank_y -= 1; + blank_x = self.page.size.cols - 1; + } else { + // Can't go back further, just use (0, 0) + blank_x = 0; + blank_y = 0; + } + + map.map.append( + map.alloc, + .{ .x = blank_x, .y = blank_y }, + ) catch return error.WriteFailed; + } + } + + blank_cells = 0; + } + + style: { + // If we aren't emitting styled output then we don't + // have to worry about styles. + if (!formatStyled(self.opts.emit)) break :style; + + // Get our cell style. + const cell_style = self.cellStyle(cell); + + // If the style hasn't changed, don't bloat output. + if (cell_style.eql(style)) break :style; + + // If we had a previous style, we need to close it, + // because we've confirmed we have some new style + // (which is maybe default). + if (!style.default()) switch (self.opts.emit) { + .html => try self.formatStyleClose(writer), + + // For VT, we only close if we're switching to a default + // style because any non-default style will emit + // a \x1b[0m as the start of a VT coloring sequence. + .vt => if (cell_style.default()) try self.formatStyleClose(writer), + + // Unreachable because of the styled() check at the + // top of this block. + .plain => unreachable, + }; + + // At this point, we can copy our style over + style = cell_style; + + // If we're just the default style now, we're done. + if (cell_style.default()) break :style; + + // New style, emit it. + try self.formatStyleOpen( + writer, + &style, + ); + + // If we have a point map, we map the style to + // this cell. + if (self.point_map) |*map| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + try self.formatStyleOpen( + &discarding.writer, + &style, + ); + for (0..std.math.cast( + usize, + discarding.count, + ) orelse return error.WriteFailed) |_| map.map.append(map.alloc, .{ + .x = x, + .y = y, + }) catch return error.WriteFailed; + } + } + + // Hyperlink state + hyperlink: { + // We currently only emit hyperlinks for HTML. In the + // future we can support emitting OSC 8 hyperlinks for + // VT output as well. + if (self.opts.emit != .html) break :hyperlink; + + // Get the hyperlink ID. This ID is our internal ID, + // not necessarily the OSC8 ID. + const link_id_: ?u16 = if (cell.hyperlink) + self.page.lookupHyperlink(cell) + else + null; + + // If our hyperlink IDs match (even null) then we have + // identical hyperlink state and we do nothing. + if (current_hyperlink_id == link_id_) break :hyperlink; + + // If our prior hyperlink ID was non-null, we need to + // close it because the ID has changed. + if (current_hyperlink_id != null) { + try self.formatHyperlinkClose(writer); + current_hyperlink_id = null; + } + + // Set our current hyperlink ID + const link_id = link_id_ orelse break :hyperlink; + current_hyperlink_id = link_id; + + // Emit the opening hyperlink tag + const uri = uri: { + const link = self.page.hyperlink_set.get( + self.page.memory, + link_id, + ); + break :uri link.uri.offset.ptr(self.page.memory)[0..link.uri.len]; + }; + try self.formatHyperlinkOpen( + writer, + uri, + ); + + // If we have a point map, we map the hyperlink to + // this cell. + if (self.point_map) |*map| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + try self.formatHyperlinkOpen( + &discarding.writer, + uri, + ); + for (0..std.math.cast( + usize, + discarding.count, + ) orelse return error.WriteFailed) |_| map.map.append(map.alloc, .{ + .x = x, + .y = y, + }) catch return error.WriteFailed; + } + } + + switch (cell.content_tag) { + // We combine codepoint and graphemes because both have + // shared style handling. We use comptime to dup it. + inline .codepoint, .codepoint_grapheme => |tag| { + try self.writeCell(tag, writer, cell); + + // If we have a point map, all codepoints map to this + // cell. + if (self.point_map) |*map| { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + try self.writeCell(tag, &discarding.writer, cell); + for (0..std.math.cast( + usize, + discarding.count, + ) orelse return error.WriteFailed) |_| map.map.append(map.alloc, .{ + .x = x, + .y = y, + }) catch return error.WriteFailed; + } + }, + + // Cells with only background color (no text). Emit a space + // with the appropriate background color SGR sequence. + .bg_color_palette, .bg_color_rgb => { + try writer.writeByte(' '); + if (self.point_map) |*map| map.map.append( + map.alloc, + .{ .x = x, .y = y }, + ) catch return error.WriteFailed; + }, + } + } + } + + // If the style is non-default, we need to close our style tag. + if (!style.default()) try self.formatStyleClose(writer); + + // Close any open hyperlink for HTML output + if (current_hyperlink_id != null) try self.formatHyperlinkClose(writer); + + // Close the monospace wrapper for HTML output + if (self.opts.emit == .html) { + const closing = "
"; + try writer.writeAll(closing); + if (self.point_map) |*map| { + map.map.ensureUnusedCapacity( + map.alloc, + closing.len, + ) catch return error.WriteFailed; + map.map.appendNTimesAssumeCapacity( + map.map.items[map.map.items.len - 1], + closing.len, + ); + } + } + + return .{ .rows = blank_rows, .cells = blank_cells }; + } + + fn writeCell( + self: PageFormatter, + comptime tag: Cell.ContentTag, + writer: *std.Io.Writer, + cell: *const Cell, + ) !void { + // Blank cells get an empty space that isn't replaced by anything + // because it isn't really a space. We do this so that formatting + // is preserved if we're emitting styles. + if (!cell.hasText()) { + try writer.writeByte(' '); + return; + } + + try self.writeCodepointWithReplacement(writer, cell.content.codepoint); + if (comptime tag == .codepoint_grapheme) { + for (self.page.lookupGrapheme(cell).?) |cp| { + try self.writeCodepointWithReplacement(writer, cp); + } + } + } + + fn writeCodepointWithReplacement( + self: PageFormatter, + writer: *std.Io.Writer, + codepoint: u21, + ) !void { + // Search for our replacement + const r_: ?CodepointMap.Replacement = replacement: { + const map = self.opts.codepoint_map orelse break :replacement null; + const items = map.items(.range); + for (0..items.len) |forward_i| { + const i = items.len - forward_i - 1; + const range = items[i]; + if (range[0] <= codepoint and codepoint <= range[1]) { + const replacements = map.items(.replacement); + break :replacement replacements[i]; + } + } + + break :replacement null; + }; + + // If no replacement, write it directly. + const r = r_ orelse return try self.writeCodepoint( + writer, + codepoint, + ); + + switch (r) { + .codepoint => |v| try self.writeCodepoint( + writer, + v, + ), + + .string => |s| { + const view = std.unicode.Utf8View.init(s) catch unreachable; + var it = view.iterator(); + while (it.nextCodepoint()) |cp| try self.writeCodepoint( + writer, + cp, + ); + }, + } + } + + fn writeCodepoint( + self: PageFormatter, + writer: *std.Io.Writer, + codepoint: u21, + ) !void { + switch (self.opts.emit) { + .plain, .vt => try writer.print("{u}", .{codepoint}), + .html => { + switch (codepoint) { + '<' => try writer.writeAll("<"), + '>' => try writer.writeAll(">"), + '&' => try writer.writeAll("&"), + '"' => try writer.writeAll("""), + '\'' => try writer.writeAll("'"), + else => { + // For HTML, emit ASCII (< 0x80) directly, but encode + // all non-ASCII as numeric entities to avoid encoding + // detection issues (fixes #9426). We can't set the + // meta tag because we emit partial HTML so this ensures + // proper unicode handling. + if (codepoint < 0x80) { + try writer.print("{u}", .{codepoint}); + } else { + try writer.print("&#{d};", .{codepoint}); + } + }, + } + }, + } + } + + /// Returns the style for the given cell. If there is no styling this + /// will return the default style. + fn cellStyle( + self: *const PageFormatter, + cell: *const Cell, + ) Style { + return switch (cell.content_tag) { + inline .codepoint, .codepoint_grapheme => if (!cell.hasStyling()) + .{} + else + self.page.styles.get( + self.page.memory, + cell.style_id, + ).*, + + .bg_color_palette => .{ + .bg_color = .{ + .palette = cell.content.color_palette, + }, + }, + + .bg_color_rgb => .{ + .bg_color = .{ + .rgb = .{ + .r = cell.content.color_rgb.r, + .g = cell.content.color_rgb.g, + .b = cell.content.color_rgb.b, + }, + }, + }, + }; + } + + /// Write a string with HTML escaping. Used for escaping href attributes + /// and other HTML attribute values. + fn formatStyleOpen( + self: PageFormatter, + writer: *std.Io.Writer, + style: *const Style, + ) std.Io.Writer.Error!void { + switch (self.opts.emit) { + .plain => unreachable, + + .vt => { + var formatter = style.formatterVt(); + formatter.palette = self.opts.palette; + try writer.print("{f}", .{formatter}); + }, + + // We use `display: inline` so that the div doesn't impact + // layout since we're primarily using it as a CSS wrapper. + .html => { + var formatter = style.formatterHtml(); + formatter.palette = self.opts.palette; + try writer.print( + "
", + .{formatter}, + ); + }, + } + } + + fn formatStyleClose( + self: PageFormatter, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + const str: []const u8 = switch (self.opts.emit) { + .plain => return, + .vt => "\x1b[0m", + .html => "
", + }; + + try writer.writeAll(str); + if (self.point_map) |*m| { + assert(m.map.items.len > 0); + m.map.ensureUnusedCapacity( + m.alloc, + str.len, + ) catch return error.WriteFailed; + m.map.appendNTimesAssumeCapacity( + m.map.items[m.map.items.len - 1], + str.len, + ); + } + } + + fn formatHyperlinkOpen( + self: PageFormatter, + writer: *std.Io.Writer, + uri: []const u8, + ) std.Io.Writer.Error!void { + switch (self.opts.emit) { + .plain, .vt => unreachable, + + // layout since we're primarily using it as a CSS wrapper. + .html => { + try writer.writeAll(""); + }, + } + } + + fn formatHyperlinkClose( + self: PageFormatter, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + const str: []const u8 = switch (self.opts.emit) { + .html => "", + .plain, .vt => return, + }; + + try writer.writeAll(str); + if (self.point_map) |*m| { + assert(m.map.items.len > 0); + m.map.ensureUnusedCapacity( + m.alloc, + str.len, + ) catch return error.WriteFailed; + m.map.appendNTimesAssumeCapacity( + m.map.items[m.map.items.len - 1], + str.len, + ); + } + } +}; + +test "Page plain single line" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello, world"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + // Test our point map. + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello, world", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 12), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..output.len) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); +} + +test "Page plain single line soft-wrapped unwrapped" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 3, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello!"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ + .emit = .plain, + .unwrap = true, + }); + + // Test our point map. + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output + // Note: we don't test the trailing state, which may have bugs + // with unwrap... + _ = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello!", output); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + try testing.expectEqual( + Coordinate{ .x = 0, .y = 0 }, + point_map.items[0], + ); + try testing.expectEqual( + Coordinate{ .x = 1, .y = 0 }, + point_map.items[1], + ); + try testing.expectEqual( + Coordinate{ .x = 2, .y = 0 }, + point_map.items[2], + ); + try testing.expectEqual( + Coordinate{ .x = 0, .y = 1 }, + point_map.items[3], + ); + try testing.expectEqual( + Coordinate{ .x = 1, .y = 1 }, + point_map.items[4], + ); + try testing.expectEqual( + Coordinate{ .x = 2, .y = 1 }, + point_map.items[5], + ); +} + +test "Page plain single wide char" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("1A⚡"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + // Test our point map. + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Full string + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("1A⚡", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 4), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (2..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 2, .y = 0 }, + point_map.items[i], + ); + } + + // Wide only (from start) + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + + formatter.start_x = 2; + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("⚡", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 4), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 2, .y = 0 }, + point_map.items[i], + ); + } + + // Wide only (from tail) + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + + formatter.start_x = 3; + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("⚡", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 4), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 2, .y = 0 }, + point_map.items[i], + ); + } +} + +test "Page plain single wide char soft-wrapped unwrapped" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 3, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("1A⚡"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + formatter.opts.unwrap = true; + + // Test our point map. + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Full string + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("1A⚡", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 2), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (2..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 0, .y = 1 }, + point_map.items[i], + ); + } + + // Full string (ending on spacer head) + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + + formatter.end_x = 2; + formatter.end_y = 0; + defer { + formatter.end_x = null; + formatter.end_y = null; + } + + _ = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("1A⚡", output); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (2..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 0, .y = 1 }, + point_map.items[i], + ); + } + + // Wide only (from start) + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + + formatter.start_x = 2; + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("⚡", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 2), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 0, .y = 1 }, + point_map.items[i], + ); + } + + // Wide only (from tail) + { + builder.clearRetainingCapacity(); + point_map.clearRetainingCapacity(); + + formatter.start_y = 1; + formatter.start_x = 1; + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("⚡", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 2), state.cells); + + // Verify our point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..output.len) |i| try testing.expectEqual( + Coordinate{ .x = 0, .y = 1 }, + point_map.items[i], + ); + } +} + +test "Page plain multiline" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\nworld", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[5]); // \n + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[6 + i], + ); +} + +test "Page plain multiline rectangle" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + formatter.start_x = 1; + formatter.end_x = 3; + formatter.rectangle = true; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("ell\norl", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..3) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i + 1), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 3, .y = 0 }, point_map.items[3]); // \n + for (0..3) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i + 1), .y = 1 }, + point_map.items[4 + i], + ); +} + +test "Page plain multi blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\n\r\n\r\nworld"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\n\n\nworld", output); + try testing.expectEqual(@as(usize, page.size.rows - 3), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[5]); // \n after row 0 + try testing.expectEqual(Coordinate{ .x = 0, .y = 1 }, point_map.items[6]); // \n after blank row 1 + try testing.expectEqual(Coordinate{ .x = 0, .y = 2 }, point_map.items[7]); // \n after blank row 2 + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 3 }, + point_map.items[8 + i], + ); +} + +test "Page plain trailing blank lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld\r\n\r\n"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output. We expect there to be no trailing newlines because + // we can't differentiate trailing blank lines as being meaningful because + // the page formatter can't see the cursor position. + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\nworld", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[5]); // \n + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[6 + i], + ); +} + +test "Page plain trailing whitespace" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello \r\nworld "); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output. We expect there to be no trailing newlines because + // we can't differentiate trailing blank lines as being meaningful because + // the page formatter can't see the cursor position. + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\nworld", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[5]); // \n + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[6 + i], + ); +} + +test "Page plain trailing whitespace no trim" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello \r\nworld "); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ + .emit = .plain, + .trim = false, + }); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output. We expect there to be no trailing newlines because + // we can't differentiate trailing blank lines as being meaningful because + // the page formatter can't see the cursor position. + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello \nworld ", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 7), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..8) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 7, .y = 0 }, point_map.items[8]); // \n + for (0..7) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[9 + i], + ); +} + +test "Page plain with prior trailing state rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + formatter.trailing_state = .{ .rows = 2, .cells = 0 }; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\n\nhello", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[0]); // \n first blank row + try testing.expectEqual(Coordinate{ .x = 0, .y = 1 }, point_map.items[1]); // \n second blank row + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[2 + i], + ); +} + +test "Page plain with prior trailing state cells no wrapped line" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + formatter.trailing_state = .{ .rows = 0, .cells = 3 }; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Blank cells are reset when row is not a wrap continuation + try testing.expectEqualStrings("hello", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); +} + +test "Page plain with prior trailing state cells with wrap continuation" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("world"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + + // Surgically modify the first row to be a wrap continuation + const row = page.getRow(0); + row.wrap_continuation = true; + + var formatter: PageFormatter = .init(page, .{ .emit = .plain, .unwrap = true }); + formatter.trailing_state = .{ .rows = 0, .cells = 3 }; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Blank cells are preserved when row is a wrap continuation with unwrap enabled + try testing.expectEqualStrings(" world", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map - 3 spaces from prior trailing state + "world" + try testing.expectEqual(output.len, point_map.items.len); + // The 3 blank cells can't go back beyond (0,0) so they all map to (0,0) + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[0]); // space + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[1]); // space + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[2]); // space + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[3 + i], + ); +} + +test "Page plain soft-wrapped without unwrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world test"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Without unwrap, wrapped lines show as separate lines + try testing.expectEqualStrings("hello worl\nd test", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 6), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..10) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 9, .y = 0 }, point_map.items[10]); // \n + for (0..6) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[11 + i], + ); +} + +test "Page plain soft-wrapped with unwrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world test"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .plain, .unwrap = true }); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // With unwrap, wrapped lines are joined together + try testing.expectEqualStrings("hello world test", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 6), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..10) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + for (0..6) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[10 + i], + ); +} + +test "Page plain soft-wrapped 3 lines without unwrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world this is a test"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Without unwrap, wrapped lines show as separate lines + try testing.expectEqualStrings("hello worl\nd this is\na test", output); + try testing.expectEqual(@as(usize, page.size.rows - 2), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 6), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..10) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 9, .y = 0 }, point_map.items[10]); // \n + for (0..9) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[11 + i], + ); + try testing.expectEqual(Coordinate{ .x = 8, .y = 1 }, point_map.items[20]); // \n + for (0..6) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 2 }, + point_map.items[21 + i], + ); +} + +test "Page plain soft-wrapped 3 lines with unwrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world this is a test"); + + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .plain, .unwrap = true }); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // With unwrap, wrapped lines are joined together + try testing.expectEqualStrings("hello world this is a test", output); + try testing.expectEqual(@as(usize, page.size.rows - 2), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 6), state.cells); + + // Verify point map - unwrapped text spans 3 rows + try testing.expectEqual(output.len, point_map.items.len); + for (0..10) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + for (0..10) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[10 + i], + ); + for (0..6) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 2 }, + point_map.items[20 + i], + ); +} + +test "Page plain start_y subset" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld\r\ntest"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_y = 1; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("world\ntest", output); + try testing.expectEqual(@as(usize, page.size.rows - 2), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 4), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 1 }, point_map.items[5]); // \n + for (0..4) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 2 }, + point_map.items[6 + i], + ); +} + +test "Page plain end_y subset" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld\r\ntest"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.end_y = 1; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\nworld", output); + try testing.expectEqual(@as(usize, 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[5]); // \n + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[6 + i], + ); +} + +test "Page plain start_y and end_y range" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld\r\ntest\r\nfoo"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_y = 1; + formatter.end_y = 2; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("world\ntest", output); + try testing.expectEqual(@as(usize, 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 4), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 4, .y = 1 }, point_map.items[5]); // \n + for (0..4) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 2 }, + point_map.items[6 + i], + ); +} + +test "Page plain start_y out of bounds" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_y = 30; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("", output); + try testing.expectEqual(@as(usize, 0), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map is empty + try testing.expectEqual(@as(usize, 0), point_map.items.len); +} + +test "Page plain end_y greater than rows" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.end_y = 30; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Should clamp to page.size.rows and work normally + try testing.expectEqualStrings("hello", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); +} + +test "Page plain end_y less than start_y" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_y = 5; + formatter.end_y = 2; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("", output); + try testing.expectEqual(@as(usize, 0), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map is empty + try testing.expectEqual(@as(usize, 0), point_map.items.len); +} + +test "Page plain start_x on first row only" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_x = 6; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("world", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 11), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i + 6), .y = 0 }, + point_map.items[i], + ); +} + +test "Page plain end_x on last row only" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("first line\r\nsecond line\r\nthird line"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.end_y = 2; + formatter.end_x = 4; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("first line\nsecond line\nthird", output); + try testing.expectEqual(@as(usize, 1), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..10) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 9, .y = 0 }, point_map.items[10]); // \n + for (0..11) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[11 + i], + ); + try testing.expectEqual(Coordinate{ .x = 10, .y = 1 }, point_map.items[22]); // \n + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 2 }, + point_map.items[23 + i], + ); +} + +test "Page plain start_x and end_x multiline" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world\r\ntest case\r\nfoo bar"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_x = 6; + formatter.end_y = 2; + formatter.end_x = 2; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // First row: "world" (start_x=6 to end of row) + // Second row: "test case" (full row) + // Third row: "foo" (start to end_x=2, inclusive) + try testing.expectEqualStrings("world\ntest case\nfoo", output); + try testing.expectEqual(@as(usize, 1), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i + 6), .y = 0 }, + point_map.items[i], + ); + try testing.expectEqual(Coordinate{ .x = 10, .y = 0 }, point_map.items[5]); // \n + for (0..9) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[6 + i], + ); + try testing.expectEqual(Coordinate{ .x = 8, .y = 1 }, point_map.items[15]); // \n + for (0..3) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 2 }, + point_map.items[16 + i], + ); +} + +test "Page plain start_x out of bounds" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_x = 100; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("", output); + try testing.expectEqual(@as(usize, 0), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map is empty + try testing.expectEqual(@as(usize, 0), point_map.items.len); +} + +test "Page plain end_x greater than cols" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.end_x = 100; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); +} + +test "Page plain end_x less than start_x single row" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_x = 10; + formatter.end_y = 0; + formatter.end_x = 5; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("", output); + try testing.expectEqual(@as(usize, 0), state.rows); + try testing.expectEqual(@as(usize, 0), state.cells); + + // Verify point map is empty + try testing.expectEqual(@as(usize, 0), point_map.items.len); +} + +test "Page plain start_y non-zero ignores trailing state" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_y = 1; + formatter.trailing_state = .{ .rows = 5, .cells = 10 }; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Should NOT output the 5 newlines from trailing_state because start_y is non-zero + try testing.expectEqualStrings("world", output); + try testing.expectEqual(@as(usize, page.size.rows - 1), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 1 }, + point_map.items[i], + ); +} + +test "Page plain start_x non-zero ignores trailing state" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_x = 6; + formatter.trailing_state = .{ .rows = 2, .cells = 8 }; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // Should NOT output the 2 newlines or 8 spaces from trailing_state because start_x is non-zero + try testing.expectEqualStrings("world", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 11), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i + 6), .y = 0 }, + point_map.items[i], + ); +} + +test "Page plain start_y and start_x zero uses trailing state" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .plain); + formatter.start_y = 0; + formatter.start_x = 0; + formatter.trailing_state = .{ .rows = 2, .cells = 0 }; + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + // SHOULD output the 2 newlines from trailing_state because both start_y and start_x are 0 + try testing.expectEqualStrings("\n\nhello", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 5), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[0]); // \n first blank row + try testing.expectEqual(Coordinate{ .x = 0, .y = 1 }, point_map.items[1]); // \n second blank row + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[2 + i], + ); +} + +test "Page plain single line with styling" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello, \x1b[1mworld\x1b[0m"); + + // Verify we have only a single page + const pages = &t.screens.active.pages; + try testing.expect(pages.pages.first != null); + try testing.expect(pages.pages.first == pages.pages.last); + + // Create the formatter + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .plain); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + // Verify output + const state = try formatter.formatWithState(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello, world", output); + try testing.expectEqual(@as(usize, page.size.rows), state.rows); + try testing.expectEqual(@as(usize, page.size.cols - 12), state.cells); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..12) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); +} + +test "Page VT single line plain text" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello", output); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); +} + +test "Page VT single line with bold" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b[1mhello\x1b[0m"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\x1b[0m\x1b[1mhello\x1b[0m", output); + + // Verify point map - style sequences should point to first character they style + try testing.expectEqual(output.len, point_map.items.len); + // \x1b[0m = 4 bytes, \x1b[1m = 4 bytes, total 8 bytes of style sequences + // All style bytes should map to the first styled character at (0, 0) + for (0..8) |i| try testing.expectEqual( + Coordinate{ .x = 0, .y = 0 }, + point_map.items[i], + ); + // Then "hello" maps to its respective positions + for (0..5) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[8 + i], + ); +} + +test "Page VT multiple styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b[1mhello \x1b[3mworld\x1b[0m"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\x1b[0m\x1b[1mhello \x1b[0m\x1b[1m\x1b[3mworld\x1b[0m", output); + + // Verify point map matches output length + try testing.expectEqual(output.len, point_map.items.len); +} + +test "Page VT with foreground color" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b[31mred\x1b[0m"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\x1b[0m\x1b[38;5;1mred\x1b[0m", output); + + // Verify point map - style sequences should point to first character they style + try testing.expectEqual(output.len, point_map.items.len); + // \x1b[0m = 4 bytes, \x1b[38;5;1m = 9 bytes, total 13 bytes of style sequences + // All style bytes should map to the first styled character at (0, 0) + for (0..13) |i| try testing.expectEqual( + Coordinate{ .x = 0, .y = 0 }, + point_map.items[i], + ); + // Then "red" maps to its respective positions + for (0..3) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[13 + i], + ); +} + +test "Page VT with background and foreground colors" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .{ + .emit = .vt, + .background = .{ .r = 0x12, .g = 0x34, .b = 0x56 }, + .foreground = .{ .r = 0xab, .g = 0xcd, .b = 0xef }, + }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Should emit OSC 10 for foreground, OSC 11 for background, then the text + try testing.expectEqualStrings( + "\x1b]10;rgb:ab/cd/ef\x1b\\\x1b]11;rgb:12/34/56\x1b\\hello", + output, + ); +} + +test "Page VT multi-line with styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b[1mfirst\x1b[0m\r\n\x1b[3msecond\x1b[0m"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + // Note: style is reset before newline to prevent background colors from + // bleeding to the next line's leading cells. + try testing.expectEqualStrings("\x1b[0m\x1b[1mfirst\x1b[0m\r\n\x1b[0m\x1b[3msecond\x1b[0m", output); + + // Verify point map matches output length + try testing.expectEqual(output.len, point_map.items.len); +} + +test "Page VT duplicate style not emitted twice" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b[1mhel\x1b[1mlo\x1b[0m"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\x1b[0m\x1b[1mhello\x1b[0m", output); + + // Verify point map matches output length + try testing.expectEqual(output.len, point_map.items.len); +} + +test "PageList plain single line" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello, world"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(&t.screens.active.pages, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello, world", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| try testing.expectEqual( + Pin{ .node = node, .x = @intCast(i), .y = 0 }, + pin_map.items[i], + ); +} + +test "PageList plain spanning two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const pages = &t.screens.active.pages; + const first_page_rows = pages.pages.first.?.data.capacity.rows; + + // Fill the first page almost completely + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("page one"); + + // Verify we're still on one page + try testing.expect(pages.pages.first == pages.pages.last); + + // Add one more newline to push content to a second page + s.nextSlice("\r\n"); + try testing.expect(pages.pages.first != pages.pages.last); + + // Write content on the second page + s.nextSlice("page two"); + + // Format the entire PageList + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + try formatter.format(&builder.writer); + const full_output = builder.writer.buffered(); + const output = std.mem.trimStart(u8, full_output, "\n"); + try testing.expectEqualStrings("page one\npage two", output); + + // Verify pin map + try testing.expectEqual(full_output.len, pin_map.items.len); + const first_node = pages.pages.first.?; + const last_node = pages.pages.last.?; + const trimmed_count = full_output.len - output.len; + + // First part (trimmed blank lines) maps to first node + for (0..trimmed_count) |i| { + try testing.expectEqual(first_node, pin_map.items[i].node); + } + + // "page one" (8 chars) maps to first node + for (0..8) |i| { + const idx = trimmed_count + i; + try testing.expectEqual(first_node, pin_map.items[idx].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[idx].x); + } + + // \n - maps to last node as it represents the transition to new page + try testing.expectEqual(last_node, pin_map.items[trimmed_count + 8].node); + + // "page two" (8 chars) maps to last node + for (0..8) |i| { + const idx = trimmed_count + 9 + i; + try testing.expectEqual(last_node, pin_map.items[idx].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[idx].x); + } +} + +test "PageList soft-wrapped line spanning two pages without unwrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const pages = &t.screens.active.pages; + const first_page_rows = pages.pages.first.?.data.capacity.rows; + + // Fill the first page with soft-wrapped content + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("hello world test"); + + // Verify we're on two pages due to wrapping + try testing.expect(pages.pages.first != pages.pages.last); + + // Format without unwrap - should show line breaks + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + try formatter.format(&builder.writer); + const full_output = builder.writer.buffered(); + const output = std.mem.trimStart(u8, full_output, "\n"); + try testing.expectEqualStrings("hello worl\nd test", output); + + // Verify pin map + try testing.expectEqual(full_output.len, pin_map.items.len); + const first_node = pages.pages.first.?; + const last_node = pages.pages.last.?; + const trimmed_count = full_output.len - output.len; + + // First part (trimmed blank lines) maps to first node + for (0..trimmed_count) |i| { + try testing.expectEqual(first_node, pin_map.items[i].node); + } + + // First line maps to first node + for (0..10) |i| { + const idx = trimmed_count + i; + try testing.expectEqual(first_node, pin_map.items[idx].node); + } + + // \n - maps to last node as it represents the transition to new page + try testing.expectEqual(last_node, pin_map.items[trimmed_count + 10].node); + + // "d test" (6 chars) maps to last node + for (0..6) |i| { + const idx = trimmed_count + 11 + i; + try testing.expectEqual(last_node, pin_map.items[idx].node); + } +} + +test "PageList soft-wrapped line spanning two pages with unwrap" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const pages = &t.screens.active.pages; + const first_page_rows = pages.pages.first.?.data.capacity.rows; + + // Fill the first page with soft-wrapped content + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("hello world test"); + + // Verify we're on two pages due to wrapping + try testing.expect(pages.pages.first != pages.pages.last); + + // Format with unwrap - should join the wrapped lines + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .{ .emit = .plain, .unwrap = true }); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + try formatter.format(&builder.writer); + const full_output = builder.writer.buffered(); + const output = std.mem.trimStart(u8, full_output, "\r\n"); + try testing.expectEqualStrings("hello world test", output); + + // Verify pin map + try testing.expectEqual(full_output.len, pin_map.items.len); + const first_node = pages.pages.first.?; + const last_node = pages.pages.last.?; + const trimmed_count = full_output.len - output.len; + + // First part (trimmed blank lines) maps to first node + for (0..trimmed_count) |i| { + try testing.expectEqual(first_node, pin_map.items[i].node); + } + + // First line from first page + for (0..10) |i| { + const idx = trimmed_count + i; + try testing.expectEqual(first_node, pin_map.items[idx].node); + } + + // "d test" (6 chars) from last page + for (0..6) |i| { + const idx = trimmed_count + 10 + i; + try testing.expectEqual(last_node, pin_map.items[idx].node); + } +} + +test "PageList VT spanning two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const pages = &t.screens.active.pages; + const first_page_rows = pages.pages.first.?.data.capacity.rows; + + // Fill the first page almost completely + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("\x1b[1mpage one"); + + // Verify we're still on one page + try testing.expect(pages.pages.first == pages.pages.last); + + // Add one more newline to push content to a second page + s.nextSlice("\r\n"); + try testing.expect(pages.pages.first != pages.pages.last); + + // New content is still styled + s.nextSlice("page two"); + + // Format the entire PageList with VT + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .vt); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + try formatter.format(&builder.writer); + const full_output = builder.writer.buffered(); + const output = std.mem.trimStart(u8, full_output, "\r\n"); + try testing.expectEqualStrings("\x1b[0m\x1b[1mpage one\x1b[0m\r\n\x1b[0m\x1b[1mpage two\x1b[0m", output); + + // Verify pin map + try testing.expectEqual(full_output.len, pin_map.items.len); + const first_node = pages.pages.first.?; + const last_node = pages.pages.last.?; + + // Just verify we have entries for both pages in the pin map + var first_count: usize = 0; + var last_count: usize = 0; + for (pin_map.items) |pin| { + if (pin.node == first_node) first_count += 1; + if (pin.node == last_node) last_count += 1; + } + try testing.expect(first_count > 0); + try testing.expect(last_count > 0); +} + +test "PageList plain with x offset on single page" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world\r\ntest case\r\nfoo bar"); + + const pages = &t.screens.active.pages; + const node = pages.pages.first.?; + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.top_left = .{ .node = node, .y = 0, .x = 6 }; + formatter.bottom_right = .{ .node = node, .y = 2, .x = 2 }; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("world\ntest case\nfoo", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + for (pin_map.items) |pin| { + try testing.expectEqual(node, pin.node); + } + + // "world" starts at x=6, y=0 + for (0..5) |i| { + try testing.expectEqual(@as(size.CellCountInt, @intCast(6 + i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 0), pin_map.items[i].y); + } +} + +test "PageList plain with x offset spanning two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const pages = &t.screens.active.pages; + const first_page_rows = pages.pages.first.?.data.capacity.rows; + + // Fill first page almost completely + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("hello world"); + + // Verify we're still on one page + try testing.expect(pages.pages.first == pages.pages.last); + + // Push to second page + s.nextSlice("\r\n"); + try testing.expect(pages.pages.first != pages.pages.last); + + s.nextSlice("foo bar test"); + + const first_node = pages.pages.first.?; + const last_node = pages.pages.last.?; + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.top_left = .{ .node = first_node, .y = first_node.data.size.rows - 1, .x = 6 }; + formatter.bottom_right = .{ .node = last_node, .y = 1, .x = 2 }; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const full_output = builder.writer.buffered(); + const output = std.mem.trimStart(u8, full_output, "\n"); + try testing.expectEqualStrings("world\nfoo", output); + + // Verify pin map + try testing.expectEqual(full_output.len, pin_map.items.len); + const trimmed_count = full_output.len - output.len; + + // "world" (5 chars) from first page + for (0..5) |i| { + const idx = trimmed_count + i; + try testing.expectEqual(first_node, pin_map.items[idx].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(6 + i)), pin_map.items[idx].x); + } + + // \n - maps to last node as it represents the transition to new page + try testing.expectEqual(last_node, pin_map.items[trimmed_count + 5].node); + + // "foo" (3 chars) from last page + for (0..3) |i| { + const idx = trimmed_count + 6 + i; + try testing.expectEqual(last_node, pin_map.items[idx].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[idx].x); + } +} + +test "PageList plain with start_x only" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const node = pages.pages.first.?; + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.top_left = .{ .node = node, .y = 0, .x = 6 }; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("world", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + for (0..5) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(6 + i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 0), pin_map.items[i].y); + } +} + +test "PageList plain with end_x only" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world\r\ntest"); + + const pages = &t.screens.active.pages; + const node = pages.pages.first.?; + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.bottom_right = .{ .node = node, .y = 1, .x = 2 }; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello world\ntes", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + + // "hello world" (11 chars) on y=0 + for (0..11) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 0), pin_map.items[i].y); + } + + // \n + try testing.expectEqual(node, pin_map.items[11].node); + + // "tes" (3 chars) on y=1 + for (0..3) |i| { + try testing.expectEqual(node, pin_map.items[12 + i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[12 + i].x); + try testing.expectEqual(@as(size.CellCountInt, 1), pin_map.items[12 + i].y); + } +} + +test "PageList plain rectangle basic" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 30, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("Lorem ipsum dolor\r\n"); + s.nextSlice("sit amet, consectetur\r\n"); + s.nextSlice("adipiscing elit, sed do\r\n"); + s.nextSlice("eiusmod tempor incididunt\r\n"); + s.nextSlice("ut labore et dolore"); + + const pages = &t.screens.active.pages; + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.top_left = pages.pin(.{ .screen = .{ .x = 2, .y = 1 } }).?; + formatter.bottom_right = pages.pin(.{ .screen = .{ .x = 6, .y = 3 } }).?; + formatter.rectangle = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + const expected = + \\t ame + \\ipisc + \\usmod + ; + try testing.expectEqualStrings(expected, output); +} + +test "PageList plain rectangle with EOL" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 30, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("Lorem ipsum dolor\r\n"); + s.nextSlice("sit amet, consectetur\r\n"); + s.nextSlice("adipiscing elit, sed do\r\n"); + s.nextSlice("eiusmod tempor incididunt\r\n"); + s.nextSlice("ut labore et dolore"); + + const pages = &t.screens.active.pages; + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.top_left = pages.pin(.{ .screen = .{ .x = 12, .y = 0 } }).?; + formatter.bottom_right = pages.pin(.{ .screen = .{ .x = 26, .y = 4 } }).?; + formatter.rectangle = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + const expected = + \\dolor + \\nsectetur + \\lit, sed do + \\or incididunt + \\ dolore + ; + try testing.expectEqualStrings(expected, output); +} + +test "PageList plain rectangle more complex with breaks" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 30, + .rows = 8, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("Lorem ipsum dolor\r\n"); + s.nextSlice("sit amet, consectetur\r\n"); + s.nextSlice("adipiscing elit, sed do\r\n"); + s.nextSlice("eiusmod tempor incididunt\r\n"); + s.nextSlice("ut labore et dolore\r\n"); + s.nextSlice("\r\n"); + s.nextSlice("magna aliqua. Ut enim\r\n"); + s.nextSlice("ad minim veniam, quis"); + + const pages = &t.screens.active.pages; + + var formatter: PageListFormatter = .init(pages, .plain); + formatter.top_left = pages.pin(.{ .screen = .{ .x = 11, .y = 2 } }).?; + formatter.bottom_right = pages.pin(.{ .screen = .{ .x = 26, .y = 7 } }).?; + formatter.rectangle = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + const expected = + \\elit, sed do + \\por incididunt + \\t dolore + \\ + \\a. Ut enim + \\niam, quis + ; + try testing.expectEqualStrings(expected, output); +} + +test "TerminalFormatter plain no selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld"); + + const formatter: TerminalFormatter = .init(&t, .plain); + + try formatter.format(&builder.writer); + try testing.expectEqualStrings("hello\nworld", builder.writer.buffered()); +} + +test "TerminalFormatter vt with palette" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Modify some palette colors using VT sequences + s.nextSlice("\x1b]4;0;rgb:12/34/56\x1b\\"); + s.nextSlice("\x1b]4;1;rgb:ab/cd/ef\x1b\\"); + s.nextSlice("\x1b]4;255;rgb:ff/00/ff\x1b\\"); + s.nextSlice("test"); + + const formatter: TerminalFormatter = .init(&t, .vt); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify the palettes match + try testing.expectEqual(t.colors.palette.current[0], t2.colors.palette.current[0]); + try testing.expectEqual(t.colors.palette.current[1], t2.colors.palette.current[1]); + try testing.expectEqual(t.colors.palette.current[255], t2.colors.palette.current[255]); +} + +test "TerminalFormatter with selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("line1\r\nline2\r\nline3"); + + var formatter: TerminalFormatter = .init(&t, .plain); + formatter.content = .{ .selection = .init( + t.screens.active.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + t.screens.active.pages.pin(.{ .active = .{ .x = 4, .y = 1 } }).?, + false, + ) }; + + try formatter.format(&builder.writer); + try testing.expectEqualStrings("line2", builder.writer.buffered()); +} + +test "TerminalFormatter plain with pin_map" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello, world"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: TerminalFormatter = .init(&t, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello, world", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| try testing.expectEqual( + Pin{ .node = node, .x = @intCast(i), .y = 0 }, + pin_map.items[i], + ); +} + +test "TerminalFormatter plain multiline with pin_map" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: TerminalFormatter = .init(&t, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\nworld", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + // "hello" (5 chars) + for (0..5) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 0), pin_map.items[i].y); + } + // "\n" maps to end of first line + try testing.expectEqual(node, pin_map.items[5].node); + // "world" (5 chars) + for (0..5) |i| { + const idx = 6 + i; + try testing.expectEqual(node, pin_map.items[idx].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[idx].x); + try testing.expectEqual(@as(size.CellCountInt, 1), pin_map.items[idx].y); + } +} + +test "TerminalFormatter vt with palette and pin_map" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Modify some palette colors using VT sequences + s.nextSlice("\x1b]4;0;rgb:12/34/56\x1b\\"); + s.nextSlice("test"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: TerminalFormatter = .init(&t, .vt); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Verify pin map - palette bytes should be mapped to top left + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "TerminalFormatter with selection and pin_map" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("line1\r\nline2\r\nline3"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: TerminalFormatter = .init(&t, .plain); + formatter.content = .{ .selection = .init( + t.screens.active.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + t.screens.active.pages.pin(.{ .active = .{ .x = 4, .y = 1 } }).?, + false, + ) }; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("line2", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + // "line2" (5 chars) from row 1 + for (0..5) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 1), pin_map.items[i].y); + } +} + +test "Screen plain single line" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello, world"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello, world", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| try testing.expectEqual( + Pin{ .node = node, .x = @intCast(i), .y = 0 }, + pin_map.items[i], + ); +} + +test "Screen plain multiline" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello\r\nworld"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .plain); + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello\nworld", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + // "hello" (5 chars) + for (0..5) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 0), pin_map.items[i].y); + } + // "\n" maps to end of first line + try testing.expectEqual(node, pin_map.items[5].node); + // "world" (5 chars) + for (0..5) |i| { + const idx = 6 + i; + try testing.expectEqual(node, pin_map.items[idx].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[idx].x); + try testing.expectEqual(@as(size.CellCountInt, 1), pin_map.items[idx].y); + } +} + +test "Screen plain with selection" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("line1\r\nline2\r\nline3"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .plain); + formatter.content = .{ .selection = .init( + t.screens.active.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + t.screens.active.pages.pin(.{ .active = .{ .x = 4, .y = 1 } }).?, + false, + ) }; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("line2", output); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + // "line2" (5 chars) from row 1 + for (0..5) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + try testing.expectEqual(@as(size.CellCountInt, @intCast(i)), pin_map.items[i].x); + try testing.expectEqual(@as(size.CellCountInt, 1), pin_map.items[i].y); + } +} + +test "Screen vt with cursor position" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Position cursor at a specific location + s.nextSlice("hello\r\nworld"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .vt); + formatter.extra.cursor = true; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify cursor positions match + try testing.expectEqual(t.screens.active.cursor.x, t2.screens.active.cursor.x); + try testing.expectEqual(t.screens.active.cursor.y, t2.screens.active.cursor.y); + + // Verify pin map - the extras should be mapped to the last pin + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + const content_len = "hello\r\nworld".len; + // Content bytes map to their positions + for (0..content_len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } + // Extra bytes (cursor position) map to last content pin + for (content_len..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "Screen vt with style" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set some style attributes + s.nextSlice("\x1b[1;31mhello"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .vt); + formatter.extra.style = true; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify styles match + try testing.expect(t.screens.active.cursor.style.eql(t2.screens.active.cursor.style)); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "Screen vt with hyperlink" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set a hyperlink + s.nextSlice("\x1b]8;;http://example.com\x1b\\hello"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .vt); + formatter.extra.hyperlink = true; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify hyperlinks match + const has_link1 = t.screens.active.cursor.hyperlink != null; + const has_link2 = t2.screens.active.cursor.hyperlink != null; + try testing.expectEqual(has_link1, has_link2); + + if (has_link1) { + const link1 = t.screens.active.cursor.hyperlink.?; + const link2 = t2.screens.active.cursor.hyperlink.?; + try testing.expectEqualStrings(link1.uri, link2.uri); + } + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "Screen vt with protection" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Enable protection mode + s.nextSlice("\x1b[1\"qhello"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .vt); + formatter.extra.protection = true; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify protection state matches + try testing.expectEqual(t.screens.active.cursor.protected, t2.screens.active.cursor.protected); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "Screen vt with kitty keyboard" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set kitty keyboard flags (disambiguate + report_events = 3) + s.nextSlice("\x1b[=3;1uhello"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .vt); + formatter.extra.kitty_keyboard = true; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify kitty keyboard state matches + const flags1 = t.screens.active.kitty_keyboard.current().int(); + const flags2 = t2.screens.active.kitty_keyboard.current().int(); + try testing.expectEqual(flags1, flags2); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "Screen vt with charsets" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set G0 to DEC special and shift to G1 + s.nextSlice("\x1b(0\x0ehello"); + + var pin_map: std.ArrayList(Pin) = .empty; + defer pin_map.deinit(alloc); + + var formatter: ScreenFormatter = .init(t.screens.active, .vt); + formatter.extra.charsets = true; + formatter.pin_map = .{ .alloc = alloc, .map = &pin_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify charset state matches + try testing.expectEqual(t.screens.active.charset.gl, t2.screens.active.charset.gl); + try testing.expectEqual(t.screens.active.charset.gr, t2.screens.active.charset.gr); + try testing.expectEqual( + t.screens.active.charset.charsets.get(.G0), + t2.screens.active.charset.charsets.get(.G0), + ); + + // Verify pin map + try testing.expectEqual(output.len, pin_map.items.len); + const node = t.screens.active.pages.pages.first.?; + for (0..output.len) |i| { + try testing.expectEqual(node, pin_map.items[i].node); + } +} + +test "Terminal vt with scrolling region" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set scrolling region: top=5, bottom=20 + s.nextSlice("\x1b[6;21rhello"); + + var formatter: TerminalFormatter = .init(&t, .vt); + formatter.extra.scrolling_region = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify scrolling regions match + try testing.expectEqual(t.scrolling_region.top, t2.scrolling_region.top); + try testing.expectEqual(t.scrolling_region.bottom, t2.scrolling_region.bottom); + try testing.expectEqual(t.scrolling_region.left, t2.scrolling_region.left); + try testing.expectEqual(t.scrolling_region.right, t2.scrolling_region.right); +} + +test "Terminal vt with modes" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Enable some modes that differ from defaults + s.nextSlice("\x1b[?2004h"); // Bracketed paste + s.nextSlice("\x1b[?1000h"); // Mouse event normal + s.nextSlice("\x1b[?7l"); // Disable wraparound (default is true) + s.nextSlice("hello"); + + var formatter: TerminalFormatter = .init(&t, .vt); + formatter.extra.modes = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify modes match + try testing.expectEqual(t.modes.get(.bracketed_paste), t2.modes.get(.bracketed_paste)); + try testing.expectEqual(t.modes.get(.mouse_event_normal), t2.modes.get(.mouse_event_normal)); + try testing.expectEqual(t.modes.get(.wraparound), t2.modes.get(.wraparound)); +} + +test "Terminal vt with tabstops" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Clear all tabs and set custom tabstops + s.nextSlice("\x1b[3g"); // Clear all tabs + s.nextSlice("\x1b[5G\x1bH"); // Set tab at column 5 + s.nextSlice("\x1b[15G\x1bH"); // Set tab at column 15 + s.nextSlice("\x1b[30G\x1bH"); // Set tab at column 30 + s.nextSlice("hello"); + + var formatter: TerminalFormatter = .init(&t, .vt); + formatter.extra.tabstops = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify tabstops match (columns are 0-indexed in the API) + try testing.expectEqual(t.tabstops.get(4), t2.tabstops.get(4)); + try testing.expectEqual(t.tabstops.get(14), t2.tabstops.get(14)); + try testing.expectEqual(t.tabstops.get(29), t2.tabstops.get(29)); + try testing.expect(t2.tabstops.get(4)); // Column 5 (1-indexed) + try testing.expect(t2.tabstops.get(14)); // Column 15 (1-indexed) + try testing.expect(t2.tabstops.get(29)); // Column 30 (1-indexed) + try testing.expect(!t2.tabstops.get(8)); // Not a tab +} + +test "Terminal vt with keyboard modes" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set modify other keys mode 2 + s.nextSlice("\x1b[>4;2m"); + s.nextSlice("hello"); + + var formatter: TerminalFormatter = .init(&t, .vt); + formatter.extra.keyboard = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify keyboard mode matches + try testing.expectEqual(t.flags.modify_other_keys_2, t2.flags.modify_other_keys_2); + try testing.expect(t2.flags.modify_other_keys_2); +} + +test "Terminal vt with pwd" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set pwd using OSC 7 + s.nextSlice("\x1b]7;file://host/home/user\x1b\\hello"); + + var formatter: TerminalFormatter = .init(&t, .vt); + formatter.extra.pwd = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Create a second terminal and apply the output + var t2 = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t2.deinit(alloc); + + var s2 = t2.vtStream(); + defer s2.deinit(); + + s2.nextSlice(output); + + // Verify pwd matches + try testing.expectEqualStrings(t.pwd.items, t2.pwd.items); +} + +test "Page html with multiple styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set bold, then italic, then reset + s.nextSlice("\x1b[1mbold\x1b[3mitalic\x1b[0mnormal"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "
bold
" ++ + "
italic
" ++ + "normal" ++ + "
", + output, + ); +} + +test "Page html plain text" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello, world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Plain text without styles should be wrapped in monospace div + try testing.expectEqualStrings( + "
hello, world
", + output, + ); +} + +test "Page html with colors" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set red foreground, blue background + s.nextSlice("\x1b[31;44mcolored"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "
colored
" ++ + "
", + output, + ); +} + +test "TerminalFormatter html with palette" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Modify some palette colors + s.nextSlice("\x1b]4;0;rgb:12/34/56\x1b\\"); + s.nextSlice("\x1b]4;1;rgb:ab/cd/ef\x1b\\"); + s.nextSlice("\x1b]4;255;rgb:ff/00/ff\x1b\\"); + s.nextSlice("test"); + + var formatter: TerminalFormatter = .init(&t, .{ .emit = .html }); + formatter.extra.palette = true; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Verify palette CSS variables are emitted + try testing.expect(std.mem.indexOf(u8, output, "") != null); + try testing.expect(std.mem.indexOf(u8, output, "test") != null); +} + +test "Page html with background and foreground colors" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ + .emit = .html, + .background = .{ .r = 0x12, .g = 0x34, .b = 0x56 }, + .foreground = .{ .r = 0xab, .g = 0xcd, .b = 0xef }, + }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
hello
", + output, + ); +} + +test "Page html with escaping" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("&\"'text"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
<tag>&"'text
", + output, + ); + + // Verify point map length matches output + try testing.expectEqual(output.len, point_map.items.len); + + // Opening wrapper div + const wrapper_start = "
"; + const wrapper_start_len = wrapper_start.len; + for (0..wrapper_start_len) |i| try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[i]); + + // Verify each character maps correctly, accounting for escaping + const offset = wrapper_start_len; + // < (4 bytes: <) -> x=0 + for (0..4) |i| try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[offset + i]); + // t (1 byte) -> x=1 + try testing.expectEqual(Coordinate{ .x = 1, .y = 0 }, point_map.items[offset + 4]); + // a (1 byte) -> x=2 + try testing.expectEqual(Coordinate{ .x = 2, .y = 0 }, point_map.items[offset + 5]); + // g (1 byte) -> x=3 + try testing.expectEqual(Coordinate{ .x = 3, .y = 0 }, point_map.items[offset + 6]); + // > (4 bytes: >) -> x=4 + for (0..4) |i| try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[offset + 7 + i]); + // & (5 bytes: &) -> x=5 + for (0..5) |i| try testing.expectEqual(Coordinate{ .x = 5, .y = 0 }, point_map.items[offset + 11 + i]); + // " (6 bytes: ") -> x=6 + for (0..6) |i| try testing.expectEqual(Coordinate{ .x = 6, .y = 0 }, point_map.items[offset + 16 + i]); + // ' (5 bytes: ') -> x=7 + for (0..5) |i| try testing.expectEqual(Coordinate{ .x = 7, .y = 0 }, point_map.items[offset + 22 + i]); + // t (1 byte) -> x=8 + try testing.expectEqual(Coordinate{ .x = 8, .y = 0 }, point_map.items[offset + 27]); + // e (1 byte) -> x=9 + try testing.expectEqual(Coordinate{ .x = 9, .y = 0 }, point_map.items[offset + 28]); + // x (1 byte) -> x=10 + try testing.expectEqual(Coordinate{ .x = 10, .y = 0 }, point_map.items[offset + 29]); + // t (1 byte) -> x=11 + try testing.expectEqual(Coordinate{ .x = 11, .y = 0 }, point_map.items[offset + 30]); +} + +test "Page html with unicode as numeric entities" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Box drawing characters that caused issue #9426 + s.nextSlice("╰─ ❯"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Expected: box drawing chars as numeric entities + // ╰ = U+2570 = 9584, ─ = U+2500 = 9472, ❯ = U+276F = 10095 + try testing.expectEqualStrings( + "
╰─ ❯
", + output, + ); +} + +test "Page html ascii characters unchanged" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // ASCII should be emitted directly + try testing.expectEqualStrings( + "
hello world
", + output, + ); +} + +test "Page html mixed ascii and unicode" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("test ╰─❯ ok"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // Mix of ASCII and Unicode entities + try testing.expectEqualStrings( + "
test ╰─❯ ok
", + output, + ); +} + +test "Page VT with palette option emits RGB" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set a custom palette color and use it + s.nextSlice("\x1b]4;1;rgb:ab/cd/ef\x1b\\"); + s.nextSlice("\x1b[31mred"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Without palette option - should emit palette index + { + builder.clearRetainingCapacity(); + var formatter: PageFormatter = .init(page, .vt); + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\x1b[0m\x1b[38;5;1mred\x1b[0m", output); + } + + // With palette option - should emit RGB directly + { + builder.clearRetainingCapacity(); + var opts: Options = .vt; + opts.palette = &t.colors.palette.current; + var formatter: PageFormatter = .init(page, opts); + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("\x1b[0m\x1b[38;2;171;205;239mred\x1b[0m", output); + } +} + +test "Page html with palette option emits RGB" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set a custom palette color and use it + s.nextSlice("\x1b]4;1;rgb:ab/cd/ef\x1b\\"); + s.nextSlice("\x1b[31mred"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Without palette option - should emit CSS variable + { + builder.clearRetainingCapacity(); + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings( + "
" ++ + "
red
" ++ + "
", + output, + ); + } + + // With palette option - should emit RGB directly + { + builder.clearRetainingCapacity(); + var opts: Options = .{ .emit = .html }; + opts.palette = &t.colors.palette.current; + var formatter: PageFormatter = .init(page, opts); + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings( + "
" ++ + "
red
" ++ + "
", + output, + ); + } +} + +test "Page VT style reset properly closes styles" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Set bold, then reset with SGR 0 + s.nextSlice("\x1b[1mbold\x1b[0mnormal"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + builder.clearRetainingCapacity(); + var formatter: PageFormatter = .init(page, .vt); + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // The reset should properly close the bold style + try testing.expectEqualStrings("\x1b[0m\x1b[1mbold\x1b[0mnormal", output); +} + +test "Page codepoint_map single replacement" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace 'o' with 'x' + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ 'o', 'o' }, + .replacement = .{ .codepoint = 'x' }, + }); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hellx wxrld", output); + + // Verify point map - each output byte should map to original cell position + try testing.expectEqual(output.len, point_map.items.len); + // "hello world" -> "hellx wxrld" + // h e l l o w o r l d + // 0 1 2 3 4 5 6 7 8 9 10 + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[0]); // h + try testing.expectEqual(Coordinate{ .x = 1, .y = 0 }, point_map.items[1]); // e + try testing.expectEqual(Coordinate{ .x = 2, .y = 0 }, point_map.items[2]); // l + try testing.expectEqual(Coordinate{ .x = 3, .y = 0 }, point_map.items[3]); // l + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[4]); // x (was o) + try testing.expectEqual(Coordinate{ .x = 5, .y = 0 }, point_map.items[5]); // space + try testing.expectEqual(Coordinate{ .x = 6, .y = 0 }, point_map.items[6]); // w + try testing.expectEqual(Coordinate{ .x = 7, .y = 0 }, point_map.items[7]); // x (was o) + try testing.expectEqual(Coordinate{ .x = 8, .y = 0 }, point_map.items[8]); // r + try testing.expectEqual(Coordinate{ .x = 9, .y = 0 }, point_map.items[9]); // l + try testing.expectEqual(Coordinate{ .x = 10, .y = 0 }, point_map.items[10]); // d +} + +test "Page codepoint_map conflicting replacement prefers last" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace 'o' with 'x', then with 'y' - should prefer last + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ 'o', 'o' }, + .replacement = .{ .codepoint = 'x' }, + }); + try map.append(alloc, .{ + .range = .{ 'o', 'o' }, + .replacement = .{ .codepoint = 'y' }, + }); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("helly", output); +} + +test "Page codepoint_map replace with string" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace 'o' with a multi-byte string + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ 'o', 'o' }, + .replacement = .{ .string = "XYZ" }, + }); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hellXYZ", output); + + // Verify point map - string replacements should all map to the original cell + try testing.expectEqual(output.len, point_map.items.len); + // "hello" -> "hellXYZ" + // h e l l o + // 0 1 2 3 4 + try testing.expectEqual(Coordinate{ .x = 0, .y = 0 }, point_map.items[0]); // h + try testing.expectEqual(Coordinate{ .x = 1, .y = 0 }, point_map.items[1]); // e + try testing.expectEqual(Coordinate{ .x = 2, .y = 0 }, point_map.items[2]); // l + try testing.expectEqual(Coordinate{ .x = 3, .y = 0 }, point_map.items[3]); // l + // All bytes of the replacement string "XYZ" should point to position 4 (where 'o' was) + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[4]); // X + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[5]); // Y + try testing.expectEqual(Coordinate{ .x = 4, .y = 0 }, point_map.items[6]); // Z +} + +test "Page codepoint_map range replacement" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("abcdefg"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace 'b' through 'e' with 'X' + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ 'b', 'e' }, + .replacement = .{ .codepoint = 'X' }, + }); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("aXXXXfg", output); +} + +test "Page codepoint_map multiple ranges" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace 'a'-'m' with 'A' and 'n'-'z' with 'Z' + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ 'a', 'm' }, + .replacement = .{ .codepoint = 'A' }, + }); + try map.append(alloc, .{ + .range = .{ 'n', 'z' }, + .replacement = .{ .codepoint = 'Z' }, + }); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + // h e l l o w o r l d + // A A A A Z Z Z Z A A + try testing.expectEqualStrings("AAAAZ ZZZAA", output); +} + +test "Page codepoint_map unicode replacement" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello ⚡ world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace lightning bolt with fire emoji + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ '⚡', '⚡' }, + .replacement = .{ .string = "🔥" }, + }); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello 🔥 world", output); + + // Verify point map + try testing.expectEqual(output.len, point_map.items.len); + // "hello ⚡ world" + // h e l l o ⚡ w o r l d + // 0 1 2 3 4 5 6 8 9 10 11 12 + // Note: ⚡ is a wide character occupying cells 6-7 + for (0..6) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(i), .y = 0 }, + point_map.items[i], + ); + // 🔥 is 4 UTF-8 bytes, all should map to cell 6 (where ⚡ was) + const fire_start = 6; // "hello " is 6 bytes + for (0..4) |i| try testing.expectEqual( + Coordinate{ .x = 6, .y = 0 }, + point_map.items[fire_start + i], + ); + // " world" follows + const world_start = fire_start + 4; + for (0..6) |i| try testing.expectEqual( + Coordinate{ .x = @intCast(8 + i), .y = 0 }, + point_map.items[world_start + i], + ); +} + +test "Page codepoint_map with styled formats" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b[31mred text\x1b[0m"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Replace 'e' with 'X' in styled text + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + try map.append(alloc, .{ + .range = .{ 'e', 'e' }, + .replacement = .{ .codepoint = 'X' }, + }); + + var opts: Options = .vt; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + // Should preserve styles while replacing text + // "red text" becomes "rXd tXxt" + // VT format uses \x1b[38;5;1m for palette color 1 + try testing.expectEqualStrings("\x1b[0m\x1b[38;5;1mrXd tXxt\x1b[0m", output); +} + +test "Page codepoint_map empty map" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("hello world"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + // Empty map should not change anything + var map: std.MultiArrayList(CodepointMap) = .{}; + defer map.deinit(alloc); + + var opts: Options = .plain; + opts.codepoint_map = map; + var formatter: PageFormatter = .init(page, opts); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + try testing.expectEqualStrings("hello world", output); +} + +test "Page VT background color on trailing blank cells" { + // This test reproduces a bug where trailing cells with background color + // but no text are emitted as plain spaces without SGR sequences. + // This causes TUIs like htop to lose background colors on rehydration. + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 20, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Simulate a TUI row: "CPU:" with text, then trailing cells with red background + // to end of line (no text after the colored region). + // \x1b[41m sets red background, then EL fills rest of row with that bg. + s.nextSlice("CPU:\x1b[41m\x1b[K"); + // Reset colors and move to next line with different content + s.nextSlice("\x1b[0m\r\nline2"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + + var formatter: PageFormatter = .init(page, .vt); + formatter.opts.trim = false; // Don't trim so we can see the trailing behavior + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + // The output should preserve the red background SGR for trailing cells on line 1. + // Bug: the first row outputs "CPU:\r\n" only - losing the background color fill. + // The red background should appear BEFORE the newline, not after. + + // Find position of CRLF + const crlf_pos = std.mem.indexOf(u8, output, "\r\n") orelse { + // No CRLF found, fail the test + return error.TestUnexpectedResult; + }; + + // Check that red background (48;5;1) appears BEFORE the newline (on line 1) + const line1 = output[0..crlf_pos]; + const has_red_bg_line1 = std.mem.indexOf(u8, line1, "\x1b[41m") != null or + std.mem.indexOf(u8, line1, "\x1b[48;5;1m") != null; + + // This should be true but currently fails due to the bug + try testing.expect(has_red_bg_line1); +} + +test "Page HTML with hyperlinks" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Start a hyperlink, write some text, end it + s.nextSlice("\x1b]8;;https://example.com\x1b\\link text\x1b]8;;\x1b\\ normal"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "link text normal" ++ + "
", + output, + ); +} + +test "Page HTML with multiple hyperlinks" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Two different hyperlinks + s.nextSlice("\x1b]8;;https://first.com\x1b\\first\x1b]8;;\x1b\\ "); + s.nextSlice("\x1b]8;;https://second.com\x1b\\second\x1b]8;;\x1b\\"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "first" ++ + " " ++ + "second" ++ + "
", + output, + ); +} + +test "Page HTML with hyperlink escaping" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // URL with special characters that need escaping + s.nextSlice("\x1b]8;;https://example.com?a=1&b=2\x1b\\link\x1b]8;;\x1b\\"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "link" ++ + "
", + output, + ); +} + +test "Page HTML with styled hyperlink" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Bold hyperlink + s.nextSlice("\x1b]8;;https://example.com\x1b\\\x1b[1mbold link\x1b[0m\x1b]8;;\x1b\\"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "
" ++ + "bold link
" ++ + "
", + output, + ); +} + +test "Page HTML hyperlink closes style before anchor" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Styled hyperlink followed by plain text + s.nextSlice("\x1b]8;;https://example.com\x1b\\\x1b[1mbold\x1b[0m plain"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + try testing.expectEqualStrings( + "
" ++ + "
" ++ + "bold
plain" ++ + "
", + output, + ); +} + +test "Page HTML hyperlink point map maps closing to previous cell" { + const testing = std.testing; + const alloc = testing.allocator; + + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\ normal"); + + const pages = &t.screens.active.pages; + const page = &pages.pages.last.?.data; + var formatter: PageFormatter = .init(page, .{ .emit = .html }); + + var point_map: std.ArrayList(Coordinate) = .empty; + defer point_map.deinit(alloc); + formatter.point_map = .{ .alloc = alloc, .map = &point_map }; + + try formatter.format(&builder.writer); + const output = builder.writer.buffered(); + + const expected_output = + "
" ++ + "link normal" ++ + "
"; + try testing.expectEqualStrings(expected_output, output); + try testing.expectEqual(expected_output.len, point_map.items.len); + + // The closing tag bytes should all map to the last cell of the link + const closing_idx = comptime std.mem.indexOf(u8, expected_output, "").?; + const expected_coord = point_map.items[closing_idx - 1]; + for (closing_idx..closing_idx + "".len) |i| { + try testing.expectEqual(expected_coord, point_map.items[i]); + } +} diff --git a/vendor/libghostty-vt/src/terminal/hash_map.zig b/vendor/libghostty-vt/src/terminal/hash_map.zig new file mode 100644 index 00000000..5a38cc17 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/hash_map.zig @@ -0,0 +1,1540 @@ +//! This file contains a fork of the Zig stdlib HashMap implementation tuned +//! for use with our terminal page representation. +//! +//! The main goal we need to achieve that wasn't possible with the stdlib +//! HashMap is to utilize offsets rather than full pointers so that we can +//! copy around the entire backing memory and keep the hash map working. +//! +//! Additionally, for serialization/deserialization purposes, we need to be +//! able to create a HashMap instance and manually set the offsets up. The +//! stdlib HashMap does not export Metadata so this isn't possible. +//! +//! Also, I want to be able to understand possible capacity for a given K,V +//! type and fixed memory amount. The stdlib HashMap doesn't publish its +//! internal allocation size calculation. +//! +//! Finally, I removed many of the APIs that we'll never require for our +//! usage just so that this file is smaller, easier to understand, and has +//! less opportunity for bugs. +//! +//! Besides these shortcomings, the stdlib HashMap has some great qualities +//! that we want to keep, namely the fact that it is backed by a single large +//! allocation rather than pointers to separate allocations. This is important +//! because our terminal page representation is backed by a single large +//! allocation so we can give the HashMap a slice of memory to operate in. +//! +//! I haven't carefully benchmarked this implementation against other hash +//! map implementations. It's possible using some of the newer variants out +//! there would be better. However, I trust the built-in version is pretty good +//! and its more important to get the terminal page representation working +//! first then we can measure and improve this later if we find it to be a +//! bottleneck. + +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const autoHash = std.hash.autoHash; +const math = std.math; +const mem = std.mem; +const Allocator = mem.Allocator; +const Wyhash = std.hash.Wyhash; + +const Offset = @import("size.zig").Offset; +const OffsetBuf = @import("size.zig").OffsetBuf; +const getOffset = @import("size.zig").getOffset; + +pub fn AutoOffsetHashMap(comptime K: type, comptime V: type) type { + return OffsetHashMap(K, V, AutoContext(K)); +} + +fn AutoHashMapUnmanaged(comptime K: type, comptime V: type) type { + return HashMapUnmanaged(K, V, AutoContext(K)); +} + +fn AutoContext(comptime K: type) type { + return struct { + pub const hash = std.hash_map.getAutoHashFn(K, @This()); + pub const eql = std.hash_map.getAutoEqlFn(K, @This()); + }; +} + +/// A HashMap type that uses offsets rather than pointers, making it +/// possible to efficiently move around the backing memory without +/// invalidating the HashMap. +pub fn OffsetHashMap( + comptime K: type, + comptime V: type, + comptime Context: type, +) type { + return struct { + const Self = @This(); + + /// This is the pointer-based map that we're wrapping. + pub const Unmanaged = HashMapUnmanaged(K, V, Context); + pub const Layout = Unmanaged.Layout; + + /// This is the alignment that the base pointer must have. + pub const base_align = Unmanaged.base_align; + + metadata: Offset(Unmanaged.Metadata) = .{}, + + /// Returns the total size of the backing memory required for a + /// HashMap with the given capacity. The base ptr must also be + /// aligned to base_align. + pub fn layout(cap: Unmanaged.Size) Layout { + return Unmanaged.layoutForCapacity(cap); + } + + /// Initialize a new HashMap with the given capacity and backing + /// memory. The backing memory must be aligned to base_align. + pub fn init(buf: OffsetBuf, l: Layout) Self { + assert(base_align.check(@intFromPtr(buf.start()))); + + const m = Unmanaged.init(buf, l); + return .{ .metadata = getOffset( + Unmanaged.Metadata, + buf, + @ptrCast(m.metadata.?), + ) }; + } + + /// Returns the pointer-based map from a base pointer. + pub fn map(self: Self, base: anytype) Unmanaged { + return .{ .metadata = self.metadata.ptr(base) }; + } + }; +} + +/// Fork of stdlib.HashMap as of Zig 0.12 modified to use offsets for +/// the key/values pointer. The metadata is still a pointer to limit +/// the amount of arithmetic required to access it. See the file comment +/// for full details. +fn HashMapUnmanaged( + comptime K: type, + comptime V: type, + comptime Context: type, +) type { + return struct { + const Self = @This(); + + comptime { + assert(@alignOf(Metadata) == 1); + } + + const header_align = @alignOf(Header); + const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K); + const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V); + const base_align: mem.Alignment = .fromByteUnits(@max( + header_align, + key_align, + val_align, + )); + + // This is actually a midway pointer to the single buffer containing + // a `Header` field, the `Metadata`s and `Entry`s. + // At `-@sizeOf(Header)` is the Header field. + // At `sizeOf(Metadata) * capacity + offset`, which is pointed to by + // self.header().entries, is the array of entries. + // This means that the hashmap only holds one live allocation, to + // reduce memory fragmentation and struct size. + /// Pointer to the metadata. + metadata: ?[*]Metadata = null, + + // This is purely empirical and not a /very smart magic constant™/. + /// Capacity of the first grow when bootstrapping the hashmap. + const minimal_capacity = 8; + + // This hashmap is specially designed for sizes that fit in a u32. + pub const Size = u32; + + // u64 hashes guarantee us that the fingerprint bits will never be used + // to compute the index of a slot, maximizing the use of entropy. + pub const Hash = u64; + + pub const Entry = struct { + key_ptr: *K, + value_ptr: *V, + }; + + pub const KV = struct { + key: K, + value: V, + }; + + const Header = struct { + /// The keys/values offset are relative to the metadata + values: Offset(V), + keys: Offset(K), + capacity: Size, + size: Size, + }; + + /// Metadata for a slot. It can be in three states: empty, used or + /// tombstone. Tombstones indicate that an entry was previously used, + /// they are a simple way to handle removal. + /// To this state, we add 7 bits from the slot's key hash. These are + /// used as a fast way to disambiguate between entries without + /// having to use the equality function. If two fingerprints are + /// different, we know that we don't have to compare the keys at all. + /// The 7 bits are the highest ones from a 64 bit hash. This way, not + /// only we use the `log2(capacity)` lowest bits from the hash to determine + /// a slot index, but we use 7 more bits to quickly resolve collisions + /// when multiple elements with different hashes end up wanting to be in the same slot. + /// Not using the equality function means we don't have to read into + /// the entries array, likely avoiding a cache miss and a potentially + /// costly function call. + const Metadata = packed struct { + const FingerPrint = u7; + + const free: FingerPrint = 0; + const tombstone: FingerPrint = 1; + + fingerprint: FingerPrint = free, + used: u1 = 0, + + const slot_free = @as(u8, @bitCast(Metadata{ .fingerprint = free })); + const slot_tombstone = @as(u8, @bitCast(Metadata{ .fingerprint = tombstone })); + + pub fn isUsed(self: Metadata) bool { + return self.used == 1; + } + + pub fn isTombstone(self: Metadata) bool { + return @as(u8, @bitCast(self)) == slot_tombstone; + } + + pub fn isFree(self: Metadata) bool { + return @as(u8, @bitCast(self)) == slot_free; + } + + pub fn takeFingerprint(hash: Hash) FingerPrint { + const hash_bits = @typeInfo(Hash).int.bits; + const fp_bits = @typeInfo(FingerPrint).int.bits; + return @as(FingerPrint, @truncate(hash >> (hash_bits - fp_bits))); + } + + pub fn fill(self: *Metadata, fp: FingerPrint) void { + self.used = 1; + self.fingerprint = fp; + } + + pub fn remove(self: *Metadata) void { + self.used = 0; + self.fingerprint = tombstone; + } + }; + + comptime { + assert(@sizeOf(Metadata) == 1); + assert(@alignOf(Metadata) == 1); + } + + pub const Iterator = struct { + hm: *const Self, + index: Size = 0, + + pub fn next(it: *Iterator) ?Entry { + assert(it.index <= it.hm.capacity()); + if (it.hm.header().size == 0) return null; + + const cap = it.hm.capacity(); + const end = it.hm.metadata.? + cap; + var metadata = it.hm.metadata.? + it.index; + + while (metadata != end) : ({ + metadata += 1; + it.index += 1; + }) { + if (metadata[0].isUsed()) { + const key = &it.hm.keys()[it.index]; + const value = &it.hm.values()[it.index]; + it.index += 1; + return Entry{ .key_ptr = key, .value_ptr = value }; + } + } + + return null; + } + }; + + pub const KeyIterator = FieldIterator(K); + pub const ValueIterator = FieldIterator(V); + + fn FieldIterator(comptime T: type) type { + return struct { + len: usize, + metadata: [*]const Metadata, + items: [*]T, + + pub fn next(self: *@This()) ?*T { + while (self.len > 0) { + self.len -= 1; + const used = self.metadata[0].isUsed(); + const item = &self.items[0]; + self.metadata += 1; + self.items += 1; + if (used) { + return item; + } + } + return null; + } + }; + } + + pub const GetOrPutResult = struct { + key_ptr: *K, + value_ptr: *V, + found_existing: bool, + }; + + /// Initialize a hash map with a given capacity and a buffer. The + /// buffer must fit within the size defined by `layoutForCapacity`. + pub fn init(buf: OffsetBuf, layout: Layout) Self { + assert(base_align.check(@intFromPtr(buf.start()))); + + // Get all our main pointers + const metadata_buf = buf.rebase(@sizeOf(Header)); + const metadata_ptr: [*]Metadata = @ptrCast(metadata_buf.start()); + + // Build our map + var map: Self = .{ .metadata = metadata_ptr }; + const hdr = map.header(); + hdr.capacity = layout.capacity; + hdr.size = 0; + if (@sizeOf([*]K) != 0) hdr.keys = metadata_buf.member(K, layout.keys_start); + if (@sizeOf([*]V) != 0) hdr.values = metadata_buf.member(V, layout.vals_start); + map.initMetadatas(); + + return map; + } + + pub fn ensureTotalCapacity(self: *Self, new_size: Size) Allocator.Error!void { + if (new_size > self.header().size) { + try self.growIfNeeded(new_size - self.header().size); + } + } + + pub fn ensureUnusedCapacity(self: *Self, additional_size: Size) Allocator.Error!void { + return ensureTotalCapacity(self, self.count() + additional_size); + } + + pub fn clearRetainingCapacity(self: *Self) void { + if (self.metadata) |_| { + self.initMetadatas(); + self.header().size = 0; + } + } + + pub fn count(self: *const Self) Size { + return self.header().size; + } + + fn header(self: *const Self) *Header { + return @ptrCast(@as([*]Header, @ptrCast(@alignCast(self.metadata.?))) - 1); + } + + fn keys(self: *const Self) [*]K { + return self.header().keys.ptr(self.metadata.?); + } + + fn values(self: *const Self) [*]V { + return self.header().values.ptr(self.metadata.?); + } + + pub fn capacity(self: *const Self) Size { + if (self.metadata == null) return 0; + + return self.header().capacity; + } + + pub fn iterator(self: *const Self) Iterator { + return .{ .hm = self }; + } + + pub fn keyIterator(self: *const Self) KeyIterator { + if (self.metadata) |metadata| { + return .{ + .len = self.capacity(), + .metadata = metadata, + .items = self.keys(), + }; + } else { + return .{ + .len = 0, + .metadata = undefined, + .items = undefined, + }; + } + } + + pub fn valueIterator(self: *const Self) ValueIterator { + if (self.metadata) |metadata| { + return .{ + .len = self.capacity(), + .metadata = metadata, + .items = self.values(), + }; + } else { + return .{ + .len = 0, + .metadata = undefined, + .items = undefined, + }; + } + } + + /// Insert an entry in the map. Assumes it is not already present. + pub fn putNoClobber(self: *Self, key: K, value: V) Allocator.Error!void { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putNoClobberContext instead."); + return self.putNoClobberContext(key, value, undefined); + } + pub fn putNoClobberContext(self: *Self, key: K, value: V, ctx: Context) Allocator.Error!void { + assert(!self.containsContext(key, ctx)); + try self.growIfNeeded(1); + + self.putAssumeCapacityNoClobberContext(key, value, ctx); + } + + /// Asserts there is enough capacity to store the new key-value pair. + /// Clobbers any existing data. To detect if a put would clobber + /// existing data, see `getOrPutAssumeCapacity`. + pub fn putAssumeCapacity(self: *Self, key: K, value: V) void { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putAssumeCapacityContext instead."); + return self.putAssumeCapacityContext(key, value, undefined); + } + pub fn putAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) void { + const gop = self.getOrPutAssumeCapacityContext(key, ctx); + gop.value_ptr.* = value; + } + + /// Insert an entry in the map. Assumes it is not already present, + /// and that no allocation is needed. + pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putAssumeCapacityNoClobberContext instead."); + return self.putAssumeCapacityNoClobberContext(key, value, undefined); + } + pub fn putAssumeCapacityNoClobberContext(self: *Self, key: K, value: V, ctx: Context) void { + assert(!self.containsContext(key, ctx)); + + const hash = ctx.hash(key); + const mask = self.capacity() - 1; + var idx = @as(usize, @truncate(hash & mask)); + + var metadata = self.metadata.? + idx; + while (metadata[0].isUsed()) { + idx = (idx + 1) & mask; + metadata = self.metadata.? + idx; + } + + const fingerprint = Metadata.takeFingerprint(hash); + metadata[0].fill(fingerprint); + self.keys()[idx] = key; + self.values()[idx] = value; + self.header().size += 1; + } + + /// Inserts a new `Entry` into the hash map, returning the previous one, if any. + pub fn fetchPut(self: *Self, key: K, value: V) Allocator.Error!?KV { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchPutContext instead."); + return self.fetchPutContext(key, value, undefined); + } + pub fn fetchPutContext(self: *Self, key: K, value: V, ctx: Context) Allocator.Error!?KV { + const gop = try self.getOrPutContext(key, ctx); + var result: ?KV = null; + if (gop.found_existing) { + result = KV{ + .key = gop.key_ptr.*, + .value = gop.value_ptr.*, + }; + } + gop.value_ptr.* = value; + return result; + } + + /// Inserts a new `Entry` into the hash map, returning the previous one, if any. + /// If insertion happens, asserts there is enough capacity without allocating. + pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KV { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchPutAssumeCapacityContext instead."); + return self.fetchPutAssumeCapacityContext(key, value, undefined); + } + pub fn fetchPutAssumeCapacityContext(self: *Self, key: K, value: V, ctx: Context) ?KV { + const gop = self.getOrPutAssumeCapacityContext(key, ctx); + var result: ?KV = null; + if (gop.found_existing) { + result = KV{ + .key = gop.key_ptr.*, + .value = gop.value_ptr.*, + }; + } + gop.value_ptr.* = value; + return result; + } + + /// If there is an `Entry` with a matching key, it is deleted from + /// the hash map, and then returned from this function. + pub fn fetchRemove(self: *Self, key: K) ?KV { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call fetchRemoveContext instead."); + return self.fetchRemoveContext(key, undefined); + } + pub fn fetchRemoveContext(self: *Self, key: K, ctx: Context) ?KV { + return self.fetchRemoveAdapted(key, ctx); + } + pub fn fetchRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV { + if (self.getIndex(key, ctx)) |idx| { + const old_key = &self.keys()[idx]; + const old_val = &self.values()[idx]; + const result = KV{ + .key = old_key.*, + .value = old_val.*, + }; + self.metadata.?[idx].remove(); + old_key.* = undefined; + old_val.* = undefined; + self.header().size -= 1; + return result; + } + + return null; + } + + /// Find the index containing the data for the given key. + /// Whether this function returns null is almost always + /// branched on after this function returns, and this function + /// returns null/not null from separate code paths. We + /// want the optimizer to remove that branch and instead directly + /// fuse the basic blocks after the branch to the basic blocks + /// from this function. To encourage that, this function is + /// marked as inline. + inline fn getIndex(self: Self, key: anytype, ctx: anytype) ?usize { + if (self.header().size == 0) { + return null; + } + + // If you get a compile error on this line, it means that your generic hash + // function is invalid for these parameters. + const hash = ctx.hash(key); + if (@TypeOf(hash) != Hash) { + @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic hash function that returns the wrong type! " ++ @typeName(Hash) ++ " was expected, but found " ++ @typeName(@TypeOf(hash))); + } + const mask = self.capacity() - 1; + const fingerprint = Metadata.takeFingerprint(hash); + // Don't loop indefinitely when there are no empty slots. + var limit = self.capacity(); + var idx = @as(usize, @truncate(hash & mask)); + + var metadata = self.metadata.? + idx; + while (!metadata[0].isFree() and limit != 0) { + if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) { + const test_key = &self.keys()[idx]; + // If you get a compile error on this line, it means that your generic eql + // function is invalid for these parameters. + const eql = ctx.eql(key, test_key.*); + // verifyContext can't verify the return type of generic eql functions, + // so we need to double-check it here. + if (@TypeOf(eql) != bool) { + @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic eql function that returns the wrong type! bool was expected, but found " ++ @typeName(@TypeOf(eql))); + } + if (eql) { + return idx; + } + } + + limit -= 1; + idx = (idx + 1) & mask; + metadata = self.metadata.? + idx; + } + + return null; + } + + pub fn getEntry(self: Self, key: K) ?Entry { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getEntryContext instead."); + return self.getEntryContext(key, undefined); + } + pub fn getEntryContext(self: Self, key: K, ctx: Context) ?Entry { + return self.getEntryAdapted(key, ctx); + } + pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry { + if (self.getIndex(key, ctx)) |idx| { + return Entry{ + .key_ptr = &self.keys()[idx], + .value_ptr = &self.values()[idx], + }; + } + return null; + } + + /// Insert an entry if the associated key is not already present, otherwise update preexisting value. + pub fn put(self: *Self, key: K, value: V) Allocator.Error!void { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call putContext instead."); + return self.putContext(key, value, undefined); + } + pub fn putContext(self: *Self, key: K, value: V, ctx: Context) Allocator.Error!void { + const result = try self.getOrPutContext(key, ctx); + result.value_ptr.* = value; + } + + /// Get an optional pointer to the actual key associated with adapted key, if present. + pub fn getKeyPtr(self: Self, key: K) ?*K { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getKeyPtrContext instead."); + return self.getKeyPtrContext(key, undefined); + } + pub fn getKeyPtrContext(self: Self, key: K, ctx: Context) ?*K { + return self.getKeyPtrAdapted(key, ctx); + } + pub fn getKeyPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*K { + if (self.getIndex(key, ctx)) |idx| { + return &self.keys()[idx]; + } + return null; + } + + /// Get a copy of the actual key associated with adapted key, if present. + pub fn getKey(self: Self, key: K) ?K { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getKeyContext instead."); + return self.getKeyContext(key, undefined); + } + pub fn getKeyContext(self: Self, key: K, ctx: Context) ?K { + return self.getKeyAdapted(key, ctx); + } + pub fn getKeyAdapted(self: Self, key: anytype, ctx: anytype) ?K { + if (self.getIndex(key, ctx)) |idx| { + return self.keys()[idx]; + } + return null; + } + + /// Get an optional pointer to the value associated with key, if present. + pub fn getPtr(self: Self, key: K) ?*V { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getPtrContext instead."); + return self.getPtrContext(key, undefined); + } + pub fn getPtrContext(self: Self, key: K, ctx: Context) ?*V { + return self.getPtrAdapted(key, ctx); + } + pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V { + if (self.getIndex(key, ctx)) |idx| { + return &self.values()[idx]; + } + return null; + } + + /// Get a copy of the value associated with key, if present. + pub fn get(self: Self, key: K) ?V { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getContext instead."); + return self.getContext(key, undefined); + } + pub fn getContext(self: Self, key: K, ctx: Context) ?V { + return self.getAdapted(key, ctx); + } + pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V { + if (self.getIndex(key, ctx)) |idx| { + return self.values()[idx]; + } + return null; + } + + pub fn getOrPut(self: *Self, key: K) Allocator.Error!GetOrPutResult { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContext instead."); + return self.getOrPutContext(key, undefined); + } + pub fn getOrPutContext(self: *Self, key: K, ctx: Context) Allocator.Error!GetOrPutResult { + const gop = try self.getOrPutContextAdapted(key, ctx); + if (!gop.found_existing) { + gop.key_ptr.* = key; + } + return gop; + } + pub fn getOrPutAdapted(self: *Self, key: anytype, key_ctx: anytype) Allocator.Error!GetOrPutResult { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutContextAdapted instead."); + return self.getOrPutContextAdapted(key, key_ctx); + } + pub fn getOrPutContextAdapted(self: *Self, key: anytype, key_ctx: anytype) Allocator.Error!GetOrPutResult { + self.growIfNeeded(1) catch |err| { + // If allocation fails, try to do the lookup anyway. + // If we find an existing item, we can return it. + // Otherwise return the error, we could not add another. + const index = self.getIndex(key, key_ctx) orelse return err; + return GetOrPutResult{ + .key_ptr = &self.keys()[index], + .value_ptr = &self.values()[index], + .found_existing = true, + }; + }; + return self.getOrPutAssumeCapacityAdapted(key, key_ctx); + } + + pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutAssumeCapacityContext instead."); + return self.getOrPutAssumeCapacityContext(key, undefined); + } + pub fn getOrPutAssumeCapacityContext(self: *Self, key: K, ctx: Context) GetOrPutResult { + const result = self.getOrPutAssumeCapacityAdapted(key, ctx); + if (!result.found_existing) { + result.key_ptr.* = key; + } + return result; + } + pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult { + // If you get a compile error on this line, it means that your generic hash + // function is invalid for these parameters. + const hash = ctx.hash(key); + // verifyContext can't verify the return type of generic hash functions, + // so we need to double-check it here. + if (@TypeOf(hash) != Hash) { + @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic hash function that returns the wrong type! " ++ @typeName(Hash) ++ " was expected, but found " ++ @typeName(@TypeOf(hash))); + } + const mask = self.capacity() - 1; + const fingerprint = Metadata.takeFingerprint(hash); + var limit = self.capacity(); + var idx = @as(usize, @truncate(hash & mask)); + + var first_tombstone_idx: usize = self.capacity(); // invalid index + var metadata = self.metadata.? + idx; + while (!metadata[0].isFree() and limit != 0) { + if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) { + const test_key = &self.keys()[idx]; + // If you get a compile error on this line, it means that your generic eql + // function is invalid for these parameters. + const eql = ctx.eql(key, test_key.*); + // verifyContext can't verify the return type of generic eql functions, + // so we need to double-check it here. + if (@TypeOf(eql) != bool) { + @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic eql function that returns the wrong type! bool was expected, but found " ++ @typeName(@TypeOf(eql))); + } + if (eql) { + return GetOrPutResult{ + .key_ptr = test_key, + .value_ptr = &self.values()[idx], + .found_existing = true, + }; + } + } else if (first_tombstone_idx == self.capacity() and metadata[0].isTombstone()) { + first_tombstone_idx = idx; + } + + limit -= 1; + idx = (idx + 1) & mask; + metadata = self.metadata.? + idx; + } + + if (first_tombstone_idx < self.capacity()) { + // Cheap try to lower probing lengths after deletions. Recycle a tombstone. + idx = first_tombstone_idx; + metadata = self.metadata.? + idx; + } + + metadata[0].fill(fingerprint); + const new_key = &self.keys()[idx]; + const new_value = &self.values()[idx]; + new_key.* = undefined; + new_value.* = undefined; + self.header().size += 1; + + return GetOrPutResult{ + .key_ptr = new_key, + .value_ptr = new_value, + .found_existing = false, + }; + } + + pub fn getOrPutValue(self: *Self, key: K, value: V) Allocator.Error!Entry { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call getOrPutValueContext instead."); + return self.getOrPutValueContext(key, value, undefined); + } + pub fn getOrPutValueContext(self: *Self, key: K, value: V, ctx: Context) Allocator.Error!Entry { + const res = try self.getOrPutAdapted(key, ctx); + if (!res.found_existing) { + res.key_ptr.* = key; + res.value_ptr.* = value; + } + return Entry{ .key_ptr = res.key_ptr, .value_ptr = res.value_ptr }; + } + + /// Return true if there is a value associated with key in the map. + pub fn contains(self: *const Self, key: K) bool { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call containsContext instead."); + return self.containsContext(key, undefined); + } + pub fn containsContext(self: *const Self, key: K, ctx: Context) bool { + return self.containsAdapted(key, ctx); + } + pub fn containsAdapted(self: *const Self, key: anytype, ctx: anytype) bool { + return self.getIndex(key, ctx) != null; + } + + fn removeByIndex(self: *Self, idx: usize) void { + self.metadata.?[idx].remove(); + self.keys()[idx] = undefined; + self.values()[idx] = undefined; + self.header().size -= 1; + } + + /// If there is an `Entry` with a matching key, it is deleted from + /// the hash map, and this function returns true. Otherwise this + /// function returns false. + pub fn remove(self: *Self, key: K) bool { + if (@sizeOf(Context) != 0) + @compileError("Cannot infer context " ++ @typeName(Context) ++ ", call removeContext instead."); + return self.removeContext(key, undefined); + } + pub fn removeContext(self: *Self, key: K, ctx: Context) bool { + return self.removeAdapted(key, ctx); + } + pub fn removeAdapted(self: *Self, key: anytype, ctx: anytype) bool { + if (self.getIndex(key, ctx)) |idx| { + self.removeByIndex(idx); + return true; + } + + return false; + } + + /// Delete the entry with key pointed to by key_ptr from the hash map. + /// key_ptr is assumed to be a valid pointer to a key that is present + /// in the hash map. + pub fn removeByPtr(self: *Self, key_ptr: *K) void { + // TODO: replace with pointer subtraction once supported by zig + // if @sizeOf(K) == 0 then there is at most one item in the hash + // map, which is assumed to exist as key_ptr must be valid. This + // item must be at index 0. + const idx = if (@sizeOf(K) > 0) + (@intFromPtr(key_ptr) - @intFromPtr(self.keys())) / @sizeOf(K) + else + 0; + + self.removeByIndex(idx); + } + + fn initMetadatas(self: *Self) void { + @memset(@as([*]u8, @ptrCast(self.metadata.?))[0 .. @sizeOf(Metadata) * self.capacity()], 0); + } + + fn growIfNeeded(self: *Self, new_count: Size) Allocator.Error!void { + const available = self.capacity() - self.header().size; + if (new_count > available) return error.OutOfMemory; + } + + /// The memory layout for the underlying buffer for a given capacity. + const Layout = struct { + /// The total size of the buffer required. The buffer is expected + /// to be aligned to `base_align`. + total_size: usize, + + /// The offset to the start of the keys data. + keys_start: usize, + + /// The offset to the start of the values data. + vals_start: usize, + + /// The capacity that was used to calculate this layout. + capacity: Size, + }; + + /// Returns the memory layout for the buffer for a given capacity. + /// The actual size may be able to fit more than the given capacity + /// because capacity is rounded up to the next power of two. This is + /// a design requirement for this hash map implementation. + pub fn layoutForCapacity(new_capacity: Size) Layout { + assert(new_capacity == 0 or std.math.isPowerOfTwo(new_capacity)); + + // Cast to usize to prevent overflow in size calculations. + // See: https://github.com/ziglang/zig/pull/19048 + const cap: usize = new_capacity; + + // Pack our metadata, keys, and values. + const meta_start = @sizeOf(Header); + const meta_end = @sizeOf(Header) + cap * @sizeOf(Metadata); + const keys_start = std.mem.alignForward(usize, meta_end, key_align); + const keys_end = keys_start + cap * @sizeOf(K); + const vals_start = std.mem.alignForward(usize, keys_end, val_align); + const vals_end = vals_start + cap * @sizeOf(V); + + // Our total memory size required is the end of our values + // aligned to the base required alignment. + const total_size = std.mem.alignForward( + usize, + vals_end, + base_align.toByteUnits(), + ); + + // The offsets we actually store in the map are from the + // metadata pointer so that we can use self.metadata as + // the base. + const keys_offset = keys_start - meta_start; + const vals_offset = vals_start - meta_start; + + return .{ + .total_size = total_size, + .keys_start = keys_offset, + .vals_start = vals_offset, + .capacity = new_capacity, + }; + } + }; +} + +const testing = std.testing; +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; + +test "HashMap basic usage" { + const Map = AutoHashMapUnmanaged(u32, u32); + + const alloc = testing.allocator; + const cap = 16; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + + var map = Map.init(.init(buf), layout); + + const count = 5; + var i: u32 = 0; + var total: u32 = 0; + while (i < count) : (i += 1) { + try map.put(i, i); + total += i; + } + + var sum: u32 = 0; + var it = map.iterator(); + while (it.next()) |kv| { + sum += kv.key_ptr.*; + } + try expectEqual(total, sum); + + i = 0; + sum = 0; + while (i < count) : (i += 1) { + try expectEqual(i, map.get(i).?); + sum += map.get(i).?; + } + try expectEqual(total, sum); +} + +test "HashMap ensureTotalCapacity" { + const Map = AutoHashMapUnmanaged(i32, i32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + const initial_capacity = map.capacity(); + try testing.expect(initial_capacity >= 20); + var i: i32 = 0; + while (i < 20) : (i += 1) { + try testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null); + } + // shouldn't resize from putAssumeCapacity + try testing.expect(initial_capacity == map.capacity()); +} + +test "HashMap ensureUnusedCapacity with tombstones" { + const Map = AutoHashMapUnmanaged(i32, i32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: i32 = 0; + while (i < 100) : (i += 1) { + try map.ensureUnusedCapacity(1); + map.putAssumeCapacity(i, i); + _ = map.remove(i); + } +} + +test "HashMap clearRetainingCapacity" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 16; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + map.clearRetainingCapacity(); + + try map.put(1, 1); + try expectEqual(map.get(1).?, 1); + try expectEqual(map.count(), 1); + + map.clearRetainingCapacity(); + map.putAssumeCapacity(1, 1); + try expectEqual(map.get(1).?, 1); + try expectEqual(map.count(), 1); + + const actual_cap = map.capacity(); + try expect(actual_cap > 0); + + map.clearRetainingCapacity(); + map.clearRetainingCapacity(); + try expectEqual(map.count(), 0); + try expectEqual(map.capacity(), actual_cap); + try expect(!map.contains(1)); +} + +test "HashMap ensureTotalCapacity with existing elements" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = Map.minimal_capacity; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + try map.put(0, 0); + try expectEqual(map.count(), 1); + try expectEqual(map.capacity(), Map.minimal_capacity); + + try testing.expectError(error.OutOfMemory, map.ensureTotalCapacity(65)); + try expectEqual(map.count(), 1); + try expectEqual(map.capacity(), Map.minimal_capacity); +} + +test "HashMap remove" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: u32 = 0; + while (i < 16) : (i += 1) { + try map.put(i, i); + } + + i = 0; + while (i < 16) : (i += 1) { + if (i % 3 == 0) { + _ = map.remove(i); + } + } + try expectEqual(map.count(), 10); + var it = map.iterator(); + while (it.next()) |kv| { + try expectEqual(kv.key_ptr.*, kv.value_ptr.*); + try expect(kv.key_ptr.* % 3 != 0); + } + + i = 0; + while (i < 16) : (i += 1) { + if (i % 3 == 0) { + try expect(!map.contains(i)); + } else { + try expectEqual(map.get(i).?, i); + } + } +} + +test "HashMap reverse removes" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: u32 = 0; + while (i < 16) : (i += 1) { + try map.putNoClobber(i, i); + } + + i = 16; + while (i > 0) : (i -= 1) { + _ = map.remove(i - 1); + try expect(!map.contains(i - 1)); + var j: u32 = 0; + while (j < i - 1) : (j += 1) { + try expectEqual(map.get(j).?, j); + } + } + + try expectEqual(map.count(), 0); +} + +test "HashMap multiple removes on same metadata" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: u32 = 0; + while (i < 16) : (i += 1) { + try map.put(i, i); + } + + _ = map.remove(7); + _ = map.remove(15); + _ = map.remove(14); + _ = map.remove(13); + try expect(!map.contains(7)); + try expect(!map.contains(15)); + try expect(!map.contains(14)); + try expect(!map.contains(13)); + + i = 0; + while (i < 13) : (i += 1) { + if (i == 7) { + try expect(!map.contains(i)); + } else { + try expectEqual(map.get(i).?, i); + } + } + + try map.put(15, 15); + try map.put(13, 13); + try map.put(14, 14); + try map.put(7, 7); + i = 0; + while (i < 16) : (i += 1) { + try expectEqual(map.get(i).?, i); + } +} + +test "HashMap put and remove loop in random order" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 64; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var keys: std.ArrayList(u32) = .empty; + defer keys.deinit(alloc); + + const size = 32; + const iterations = 100; + + var i: u32 = 0; + while (i < size) : (i += 1) { + try keys.append(alloc, i); + } + var prng = std.Random.DefaultPrng.init(0); + const random = prng.random(); + + while (i < iterations) : (i += 1) { + random.shuffle(u32, keys.items); + + for (keys.items) |key| { + try map.put(key, key); + } + try expectEqual(map.count(), size); + + for (keys.items) |key| { + _ = map.remove(key); + } + try expectEqual(map.count(), 0); + } +} + +test "HashMap put" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: u32 = 0; + while (i < 16) : (i += 1) { + try map.put(i, i); + } + + i = 0; + while (i < 16) : (i += 1) { + try expectEqual(map.get(i).?, i); + } + + i = 0; + while (i < 16) : (i += 1) { + try map.put(i, i * 16 + 1); + } + + i = 0; + while (i < 16) : (i += 1) { + try expectEqual(map.get(i).?, i * 16 + 1); + } +} + +test "HashMap put full load" { + const Map = AutoHashMapUnmanaged(usize, usize); + const cap = 16; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + for (0..cap) |i| try map.put(i, i); + for (0..cap) |i| try expectEqual(map.get(i).?, i); + + try testing.expectError(error.OutOfMemory, map.put(cap, cap)); +} + +test "HashMap putAssumeCapacity" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: u32 = 0; + while (i < 20) : (i += 1) { + map.putAssumeCapacityNoClobber(i, i); + } + + i = 0; + var sum = i; + while (i < 20) : (i += 1) { + sum += map.getPtr(i).?.*; + } + try expectEqual(sum, 190); + + i = 0; + while (i < 20) : (i += 1) { + map.putAssumeCapacity(i, 1); + } + + i = 0; + sum = i; + while (i < 20) : (i += 1) { + sum += map.get(i).?; + } + try expectEqual(sum, 20); +} + +test "HashMap repeat putAssumeCapacity/remove" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + const limit = cap; + + var i: u32 = 0; + while (i < limit) : (i += 1) { + map.putAssumeCapacityNoClobber(i, i); + } + + // Repeatedly delete/insert an entry without resizing the map. + // Put to different keys so entries don't land in the just-freed slot. + i = 0; + while (i < 10 * limit) : (i += 1) { + try testing.expect(map.remove(i)); + if (i % 2 == 0) { + map.putAssumeCapacityNoClobber(limit + i, i); + } else { + map.putAssumeCapacity(limit + i, i); + } + } + + i = 9 * limit; + while (i < 10 * limit) : (i += 1) { + try expectEqual(map.get(limit + i), i); + } + try expectEqual(map.count(), limit); +} + +test "HashMap getOrPut" { + const Map = AutoHashMapUnmanaged(u32, u32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: u32 = 0; + while (i < 10) : (i += 1) { + try map.put(i * 2, 2); + } + + i = 0; + while (i < 20) : (i += 1) { + _ = try map.getOrPutValue(i, 1); + } + + i = 0; + var sum = i; + while (i < 20) : (i += 1) { + sum += map.get(i).?; + } + + try expectEqual(sum, 30); +} + +test "HashMap basic hash map usage" { + const Map = AutoHashMapUnmanaged(i32, i32); + const cap = 32; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + try testing.expect((try map.fetchPut(1, 11)) == null); + try testing.expect((try map.fetchPut(2, 22)) == null); + try testing.expect((try map.fetchPut(3, 33)) == null); + try testing.expect((try map.fetchPut(4, 44)) == null); + + try map.putNoClobber(5, 55); + try testing.expect((try map.fetchPut(5, 66)).?.value == 55); + try testing.expect((try map.fetchPut(5, 55)).?.value == 66); + + const gop1 = try map.getOrPut(5); + try testing.expect(gop1.found_existing == true); + try testing.expect(gop1.value_ptr.* == 55); + gop1.value_ptr.* = 77; + try testing.expect(map.getEntry(5).?.value_ptr.* == 77); + + const gop2 = try map.getOrPut(99); + try testing.expect(gop2.found_existing == false); + gop2.value_ptr.* = 42; + try testing.expect(map.getEntry(99).?.value_ptr.* == 42); + + const gop3 = try map.getOrPutValue(5, 5); + try testing.expect(gop3.value_ptr.* == 77); + + const gop4 = try map.getOrPutValue(100, 41); + try testing.expect(gop4.value_ptr.* == 41); + + try testing.expect(map.contains(2)); + try testing.expect(map.getEntry(2).?.value_ptr.* == 22); + try testing.expect(map.get(2).? == 22); + + const rmv1 = map.fetchRemove(2); + try testing.expect(rmv1.?.key == 2); + try testing.expect(rmv1.?.value == 22); + try testing.expect(map.fetchRemove(2) == null); + try testing.expect(map.remove(2) == false); + try testing.expect(map.getEntry(2) == null); + try testing.expect(map.get(2) == null); + + try testing.expect(map.remove(3) == true); +} + +test "HashMap ensureUnusedCapacity" { + const Map = AutoHashMapUnmanaged(u64, u64); + const cap = 64; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + try map.ensureUnusedCapacity(32); + try testing.expectError(error.OutOfMemory, map.ensureUnusedCapacity(cap + 1)); +} + +test "HashMap removeByPtr" { + const Map = AutoHashMapUnmanaged(i32, u64); + const cap = 64; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + var i: i32 = undefined; + i = 0; + while (i < 10) : (i += 1) { + try map.put(i, 0); + } + + try testing.expect(map.count() == 10); + + i = 0; + while (i < 10) : (i += 1) { + const key_ptr = map.getKeyPtr(i); + try testing.expect(key_ptr != null); + + if (key_ptr) |ptr| { + map.removeByPtr(ptr); + } + } + + try testing.expect(map.count() == 0); +} + +test "HashMap removeByPtr 0 sized key" { + const Map = AutoHashMapUnmanaged(i32, u64); + const cap = 64; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + try map.put(0, 0); + + try testing.expect(map.count() == 1); + + const key_ptr = map.getKeyPtr(0); + try testing.expect(key_ptr != null); + + if (key_ptr) |ptr| { + map.removeByPtr(ptr); + } + + try testing.expect(map.count() == 0); +} + +test "HashMap repeat fetchRemove" { + const Map = AutoHashMapUnmanaged(u64, void); + const cap = 64; + + const alloc = testing.allocator; + const layout = Map.layoutForCapacity(cap); + const buf = try alloc.alignedAlloc(u8, Map.base_align, layout.total_size); + defer alloc.free(buf); + var map = Map.init(.init(buf), layout); + + map.putAssumeCapacity(0, {}); + map.putAssumeCapacity(1, {}); + map.putAssumeCapacity(2, {}); + map.putAssumeCapacity(3, {}); + + // fetchRemove() should make slots available. + var i: usize = 0; + while (i < 10) : (i += 1) { + try testing.expect(map.fetchRemove(3) != null); + map.putAssumeCapacity(3, {}); + } + + try testing.expect(map.get(0) != null); + try testing.expect(map.get(1) != null); + try testing.expect(map.get(2) != null); + try testing.expect(map.get(3) != null); +} + +test "OffsetHashMap basic usage" { + const OffsetMap = AutoOffsetHashMap(u32, u32); + const cap = 16; + + const alloc = testing.allocator; + const layout = OffsetMap.layout(cap); + const buf = try alloc.alignedAlloc(u8, OffsetMap.base_align, layout.total_size); + defer alloc.free(buf); + var offset_map = OffsetMap.init(.init(buf), layout); + var map = offset_map.map(buf.ptr); + + const count = 5; + var i: u32 = 0; + var total: u32 = 0; + while (i < count) : (i += 1) { + try map.put(i, i); + total += i; + } + + var sum: u32 = 0; + var it = map.iterator(); + while (it.next()) |kv| { + sum += kv.key_ptr.*; + } + try expectEqual(total, sum); + + i = 0; + sum = 0; + while (i < count) : (i += 1) { + try expectEqual(i, map.get(i).?); + sum += map.get(i).?; + } + try expectEqual(total, sum); +} + +test "OffsetHashMap remake map" { + const OffsetMap = AutoOffsetHashMap(u32, u32); + const cap = 16; + + const alloc = testing.allocator; + const layout = OffsetMap.layout(cap); + const buf = try alloc.alignedAlloc(u8, OffsetMap.base_align, layout.total_size); + defer alloc.free(buf); + var offset_map = OffsetMap.init(.init(buf), layout); + + { + var map = offset_map.map(buf.ptr); + try map.put(5, 5); + } + + { + var map = offset_map.map(buf.ptr); + try expectEqual(5, map.get(5).?); + } +} + +test "layoutForCapacity no overflow for large capacity" { + // Test that layoutForCapacity correctly handles large capacities without overflow. + // Prior to the fix, new_capacity (u32) was multiplied before widening to usize, + // causing overflow when new_capacity * @sizeOf(K) exceeded 2^32. + // See: https://github.com/ghostty-org/ghostty/issues/9862 + const Map = AutoHashMapUnmanaged(u64, u64); + + // Use 2^30 capacity - this would overflow in u32 when multiplied by @sizeOf(u64)=8 + // 0x40000000 * 8 = 0x2_0000_0000 which wraps to 0 in u32 + const large_cap: Map.Size = 1 << 30; + const layout = Map.layoutForCapacity(large_cap); + + // With the fix, total_size should be at least cap * (sizeof(K) + sizeof(V)) + // = 2^30 * 16 = 2^34 bytes = 16 GiB + // Without the fix, this would wrap and produce a much smaller value. + const min_expected: usize = @as(usize, large_cap) * (@sizeOf(u64) + @sizeOf(u64)); + try expect(layout.total_size >= min_expected); + + // Also verify the individual offsets don't wrap + try expect(layout.keys_start > 0); + try expect(layout.vals_start > layout.keys_start); +} diff --git a/vendor/libghostty-vt/src/terminal/highlight.zig b/vendor/libghostty-vt/src/terminal/highlight.zig new file mode 100644 index 00000000..bc3a1758 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/highlight.zig @@ -0,0 +1,213 @@ +//! Highlights are any contiguous sequences of cells that should +//! be called out in some way, most commonly for text selection but +//! also search results or any other purpose. +//! +//! Within the terminal package, a highlight is a generic concept +//! that represents a range of cells. + +// NOTE: The plan is for highlights to ultimately replace Selection +// completely. Selection is deeply tied to various parts of the Ghostty +// internals so this may take some time. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const size = @import("size.zig"); +const PageList = @import("PageList.zig"); +const PageChunk = PageList.PageIterator.Chunk; +const Pin = PageList.Pin; +const Screen = @import("Screen.zig"); + +/// An untracked highlight is a highlight that stores its highlighted +/// area as a top-left and bottom-right screen pin. Since it is untracked, +/// the pins are only valid for the current terminal state and may not +/// be safe to use after any terminal modifications. +/// +/// For rectangle highlights/selections, the downstream consumer of this +/// code is expected to interpret the pins in whatever shape they want. +/// For example, a rectangular selection would interpret the pins as +/// setting the x bounds for each row between start.y and end.y. +/// +/// To simplify all operations, start MUST be before or equal to end. +pub const Untracked = struct { + start: Pin, + end: Pin, + + pub fn track( + self: *const Untracked, + screen: *Screen, + ) Allocator.Error!Tracked { + return try .init( + screen, + self.start, + self.end, + ); + } + + pub fn eql(self: Untracked, other: Untracked) bool { + return self.start.eql(other.start) and self.end.eql(other.end); + } +}; + +/// A tracked highlight is a highlight that stores its highlighted +/// area as tracked pins within a screen. +/// +/// A tracked highlight ensures that the pins remain valid even as +/// the terminal state changes. Because of this, tracked highlights +/// have more operations available to them. +/// +/// There is more overhead to creating and maintaining tracked highlights. +/// If you're manipulating highlights that are untracked and you're sure +/// that the terminal state won't change, you can use the `initAssume` +/// function. +pub const Tracked = struct { + start: *Pin, + end: *Pin, + + pub fn init( + screen: *Screen, + start: Pin, + end: Pin, + ) Allocator.Error!Tracked { + const start_tracked = try screen.pages.trackPin(start); + errdefer screen.pages.untrackPin(start_tracked); + const end_tracked = try screen.pages.trackPin(end); + errdefer screen.pages.untrackPin(end_tracked); + return .{ + .start = start_tracked, + .end = end_tracked, + }; + } + + /// Initializes a tracked highlight by assuming that the provided + /// pins are already tracked. This allows callers to perform tracked + /// operations without the overhead of tracking the pins, if the + /// caller can guarantee that the pins are already tracked or that + /// the terminal state will not change. + /// + /// Do not call deinit on highlights created with this function. + pub fn initAssume( + start: *Pin, + end: *Pin, + ) Tracked { + return .{ + .start = start, + .end = end, + }; + } + + pub fn deinit( + self: Tracked, + screen: *Screen, + ) void { + screen.pages.untrackPin(self.start); + screen.pages.untrackPin(self.end); + } +}; + +/// A flattened highlight is a highlight that stores its highlighted +/// area as a list of page chunks. This representation allows for +/// traversing the entire highlighted area without needing to read any +/// terminal state or dereference any page nodes (which may have been +/// pruned). +pub const Flattened = struct { + /// The page chunks that make up this highlight. This handles the + /// y bounds since chunks[0].start is the first highlighted row + /// and chunks[len - 1].end is the last highlighted row (exclsive). + chunks: std.MultiArrayList(Chunk), + + /// The x bounds of the highlight. `bot_x` may be less than `top_x` + /// for typical left-to-right highlights: can start the selection right + /// of the end on a higher row. + top_x: size.CellCountInt, + bot_x: size.CellCountInt, + + /// A flattened chunk is almost identical to a PageList.Chunk but + /// we also flatten the serial number. This lets the flattened + /// highlight more robust for comparisons and validity checks with + /// the PageList. + pub const Chunk = struct { + node: *PageList.List.Node, + serial: u64, + start: size.CellCountInt, + end: size.CellCountInt, + }; + + pub const empty: Flattened = .{ + .chunks = .empty, + .top_x = 0, + .bot_x = 0, + }; + + pub fn init( + alloc: Allocator, + start: Pin, + end: Pin, + ) Allocator.Error!Flattened { + var result: std.MultiArrayList(PageChunk) = .empty; + errdefer result.deinit(alloc); + var it = start.pageIterator(.right_down, end); + while (it.next()) |chunk| try result.append(alloc, .{ + .node = chunk.node, + .serial = chunk.node.serial, + .start = chunk.start, + .end = chunk.end, + }); + return .{ + .chunks = result, + .top_x = start.x, + .end_x = end.x, + }; + } + + pub fn deinit(self: *Flattened, alloc: Allocator) void { + self.chunks.deinit(alloc); + } + + pub fn clone(self: *const Flattened, alloc: Allocator) Allocator.Error!Flattened { + return .{ + .chunks = try self.chunks.clone(alloc), + .top_x = self.top_x, + .bot_x = self.bot_x, + }; + } + + pub fn startPin(self: Flattened) Pin { + const slice = self.chunks.slice(); + return .{ + .node = slice.items(.node)[0], + .x = self.top_x, + .y = slice.items(.start)[0], + }; + } + + pub fn endPin(self: Flattened) Pin { + const slice = self.chunks.slice(); + return .{ + .node = slice.items(.node)[slice.len - 1], + .x = self.bot_x, + .y = slice.items(.end)[slice.len - 1] - 1, + }; + } + + /// Convert to an Untracked highlight. + pub fn untracked(self: Flattened) Untracked { + // Note: we don't use startPin/endPin here because it is slightly + // faster to reuse the slices. + const slice = self.chunks.slice(); + const nodes = slice.items(.node); + const starts = slice.items(.start); + const ends = slice.items(.end); + return .{ + .start = .{ + .node = nodes[0], + .x = self.top_x, + .y = starts[0], + }, + .end = .{ + .node = nodes[nodes.len - 1], + .x = self.bot_x, + .y = ends[ends.len - 1] - 1, + }, + }; + } +}; diff --git a/vendor/libghostty-vt/src/terminal/hyperlink.zig b/vendor/libghostty-vt/src/terminal/hyperlink.zig new file mode 100644 index 00000000..94f86466 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/hyperlink.zig @@ -0,0 +1,240 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const hash_map = @import("hash_map.zig"); +const AutoOffsetHashMap = hash_map.AutoOffsetHashMap; +const pagepkg = @import("page.zig"); +const size = @import("size.zig"); +const Offset = size.Offset; +const Cell = pagepkg.Cell; +const Page = pagepkg.Page; +const RefCountedSet = @import("ref_counted_set.zig").RefCountedSet; +const Wyhash = std.hash.Wyhash; +const autoHash = std.hash.autoHash; +const autoHashStrat = std.hash.autoHashStrat; + +/// The unique identifier for a hyperlink. This is at most the number of cells +/// that can fit in a single terminal page, since each cell can only contain +/// at most one hyperlink. +pub const Id = size.HyperlinkCountInt; + +// The mapping of cell to hyperlink. We use an offset hash map to save space +// since its very unlikely a cell is a hyperlink, so its a waste to store +// the hyperlink ID in the cell itself. +pub const Map = AutoOffsetHashMap(Offset(Cell), Id); + +/// A fully decoded hyperlink that may or may not have its +/// memory within a page. The memory location of this is dependent +/// on the context so users should check with the source of the +/// hyperlink. +pub const Hyperlink = struct { + id: Hyperlink.Id, + uri: []const u8, + + /// See PageEntry.Id + pub const Id = union(enum) { + explicit: []const u8, + implicit: size.OffsetInt, + }; + + /// Deinit and deallocate all the pointers using the given + /// allocator. + /// + /// WARNING: This should only be called if the hyperlink was + /// heap-allocated. This DOES NOT need to be unconditionally + /// called. + pub fn deinit(self: *const Hyperlink, alloc: Allocator) void { + alloc.free(self.uri); + switch (self.id) { + .implicit => {}, + .explicit => |v| alloc.free(v), + } + } + + /// Duplicate a hyperlink by allocating all values with the + /// given allocator. The returned hyperlink should have deinit + /// called. + pub fn dupe( + self: *const Hyperlink, + alloc: Allocator, + ) Allocator.Error!Hyperlink { + const uri = try alloc.dupe(u8, self.uri); + errdefer alloc.free(uri); + + const id: Hyperlink.Id = switch (self.id) { + .implicit => self.id, + .explicit => |v| .{ .explicit = try alloc.dupe(u8, v) }, + }; + errdefer switch (id) { + .implicit => {}, + .explicit => |v| alloc.free(v), + }; + + return .{ .id = id, .uri = uri }; + } +}; + +/// A hyperlink that has been committed to page memory. This +/// is a "page entry" because while it represents a hyperlink, +/// some decoding (pointer chasing) is still necessary to get the +/// fully realized ID, URI, etc. +pub const PageEntry = struct { + id: PageEntry.Id, + uri: Offset(u8).Slice, + + pub const Id = union(enum) { + /// An explicitly provided ID via the OSC8 sequence. + explicit: Offset(u8).Slice, + + /// No ID was provided so we auto-generate the ID based on an + /// incrementing counter attached to the screen. + implicit: size.OffsetInt, + }; + + /// Duplicate this hyperlink from one page to another. + pub fn dupe( + self: *const PageEntry, + self_page: *const Page, + dst_page: *Page, + ) error{OutOfMemory}!PageEntry { + var copy = self.*; + + // If the pages are the same then we can return a shallow copy. + if (self_page == dst_page) return copy; + + // Copy the URI + { + const uri = self.uri.slice(self_page.memory); + const buf = try dst_page.string_alloc.alloc(u8, dst_page.memory, uri.len); + @memcpy(buf, uri); + copy.uri = .{ + .offset = size.getOffset(u8, dst_page.memory, &buf[0]), + .len = uri.len, + }; + } + errdefer dst_page.string_alloc.free( + dst_page.memory, + copy.uri.slice(dst_page.memory), + ); + + // Copy the ID + switch (copy.id) { + .implicit => {}, // Shallow is fine + .explicit => |slice| { + const id = slice.slice(self_page.memory); + const buf = try dst_page.string_alloc.alloc(u8, dst_page.memory, id.len); + @memcpy(buf, id); + copy.id = .{ .explicit = .{ + .offset = size.getOffset(u8, dst_page.memory, &buf[0]), + .len = id.len, + } }; + }, + } + errdefer switch (copy.id) { + .implicit => {}, + .explicit => |v| dst_page.string_alloc.free( + dst_page.memory, + v.slice(dst_page.memory), + ), + }; + + return copy; + } + + pub fn hash(self: *const PageEntry, base: anytype) u64 { + var hasher = Wyhash.init(0); + autoHash(&hasher, std.meta.activeTag(self.id)); + switch (self.id) { + .implicit => |v| autoHash(&hasher, v), + .explicit => |slice| autoHashStrat( + &hasher, + slice.slice(base), + .Deep, + ), + } + autoHashStrat( + &hasher, + self.uri.slice(base), + .Deep, + ); + return hasher.final(); + } + + pub fn eql( + self: *const PageEntry, + self_base: anytype, + other: *const PageEntry, + other_base: anytype, + ) bool { + if (std.meta.activeTag(self.id) != std.meta.activeTag(other.id)) return false; + switch (self.id) { + .implicit => if (self.id.implicit != other.id.implicit) return false, + .explicit => { + const self_ptr = self.id.explicit.offset.ptr(self_base); + const other_ptr = other.id.explicit.offset.ptr(other_base); + if (!std.mem.eql( + u8, + self_ptr[0..self.id.explicit.len], + other_ptr[0..other.id.explicit.len], + )) return false; + }, + } + + return std.mem.eql( + u8, + self.uri.slice(self_base), + other.uri.slice(other_base), + ); + } + + /// Free the memory for this entry from its page. + pub fn free( + self: *const PageEntry, + page: *Page, + ) void { + const alloc = &page.string_alloc; + switch (self.id) { + .implicit => {}, + .explicit => |v| alloc.free( + page.memory, + v.slice(page.memory), + ), + } + alloc.free( + page.memory, + self.uri.slice(page.memory), + ); + } +}; + +/// The set of hyperlinks. This is ref-counted so that a set of cells +/// can share the same hyperlink without duplicating the data. +pub const Set = RefCountedSet( + PageEntry, + Id, + size.CellCountInt, + struct { + /// The page which holds the strings for items in this set. + page: ?*Page = null, + + /// The page which holds the strings for items + /// looked up with, e.g., `add` or `lookup`, + /// if different from the destination page. + src_page: ?*const Page = null, + + pub fn hash(self: *const @This(), link: PageEntry) u64 { + return link.hash((self.src_page orelse self.page.?).memory); + } + + pub fn eql(self: *const @This(), a: PageEntry, b: PageEntry) bool { + return a.eql( + (self.src_page orelse self.page.?).memory, + &b, + self.page.?.memory, + ); + } + + pub fn deleted(self: *const @This(), link: PageEntry) void { + link.free(self.page.?); + } + }, +); diff --git a/vendor/libghostty-vt/src/terminal/kitty.zig b/vendor/libghostty-vt/src/terminal/kitty.zig new file mode 100644 index 00000000..0868a771 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty.zig @@ -0,0 +1,15 @@ +//! Types and functions related to Kitty protocols. + +const build_options = @import("terminal_options"); + +const key = @import("kitty/key.zig"); +pub const color = @import("kitty/color.zig"); +pub const graphics = if (build_options.kitty_graphics) @import("kitty/graphics.zig") else struct {}; + +pub const KeyFlags = key.Flags; +pub const KeyFlagStack = key.FlagStack; +pub const KeySetMode = key.SetMode; + +test { + @import("std").testing.refAllDecls(@This()); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/color.zig b/vendor/libghostty-vt/src/terminal/kitty/color.zig new file mode 100644 index 00000000..c1072c39 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/color.zig @@ -0,0 +1,77 @@ +const std = @import("std"); +const terminal = @import("../main.zig"); +const RGB = terminal.color.RGB; +const Terminator = terminal.osc.Terminator; + +pub const OSC = struct { + pub const Request = union(enum) { + query: Kind, + set: struct { key: Kind, color: RGB }, + reset: Kind, + }; + + /// list of requests + list: std.ArrayList(Request), + + /// We must reply with the same string terminator (ST) as used in the + /// request. + terminator: Terminator = .st, + + pub fn deinit(self: *OSC, alloc: std.mem.Allocator) void { + self.list.deinit(alloc); + } + + /// We don't currently support encoding this to C in any way. + pub const C = void; + + pub fn cval(_: OSC) C { + return {}; + } +}; + +pub const Special = enum { + foreground, + background, + selection_foreground, + selection_background, + cursor, + cursor_text, + visual_bell, + second_transparent_background, +}; + +pub const Kind = union(enum) { + pub const max: usize = std.math.maxInt(u8) + @typeInfo(Special).@"enum".fields.len; + + palette: u8, + special: Special, + + pub fn parse(key: []const u8) ?Kind { + if (std.meta.stringToEnum(Special, key)) |s| return .{ .special = s }; + return .{ .palette = std.fmt.parseUnsigned(u8, key, 10) catch return null }; + } + + pub fn format( + self: Kind, + writer: *std.Io.Writer, + ) !void { + switch (self) { + .palette => |p| try writer.print("{d}", .{p}), + .special => |s| try writer.print("{s}", .{@tagName(s)}), + } + } +}; + +test "OSC: kitty color protocol kind string" { + const testing = std.testing; + + var buf: [256]u8 = undefined; + { + const actual = try std.fmt.bufPrint(&buf, "{f}", .{Kind{ .special = .foreground }}); + try testing.expectEqualStrings("foreground", actual); + } + { + const actual = try std.fmt.bufPrint(&buf, "{f}", .{Kind{ .palette = 42 }}); + try testing.expectEqualStrings("42", actual); + } +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics.zig new file mode 100644 index 00000000..c710f81a --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics.zig @@ -0,0 +1,36 @@ +//! Kitty graphics protocol support. +//! +//! Documentation: +//! https://sw.kovidgoyal.net/kitty/graphics-protocol +//! +//! Unimplemented features that are still todo: +//! - shared memory transmit +//! - virtual placement w/ unicode +//! - animation +//! +//! Performance: +//! The performance of this particular subsystem of Ghostty is not great. +//! We can avoid a lot more allocations, we can replace some C code (which +//! implicitly allocates) with native Zig, we can improve the data structures +//! to avoid repeated lookups, etc. I tried to avoid pessimization but my +//! aim to ship a v1 of this implementation came at some cost. I learned a lot +//! though and I think we can go back through and fix this up. + +const render = @import("graphics_render.zig"); +const command = @import("graphics_command.zig"); +const exec = @import("graphics_exec.zig"); +const image = @import("graphics_image.zig"); +const storage = @import("graphics_storage.zig"); +pub const unicode = @import("graphics_unicode.zig"); +pub const Command = command.Command; +pub const CommandParser = command.Parser; +pub const Image = image.Image; +pub const ImageStorage = storage.ImageStorage; +pub const RenderPlacement = render.Placement; +pub const Response = command.Response; + +pub const execute = exec.execute; + +test { + @import("std").testing.refAllDecls(@This()); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig new file mode 100644 index 00000000..dfce56e3 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_command.zig @@ -0,0 +1,1325 @@ +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; +const simd = @import("../../simd/main.zig"); + +const log = std.log.scoped(.kitty_gfx); + +/// The key-value pairs for the control information for a command. The +/// keys are always single characters and the values are either single +/// characters or 32-bit unsigned integers. +/// +/// For the value of this: if the value is a single printable ASCII character +/// it is the ASCII code. Otherwise, it is parsed as a 32-bit unsigned integer. +const KV = std.AutoHashMapUnmanaged(u8, u32); + +/// Command parser parses the Kitty graphics protocol escape sequence. +pub const Parser = struct { + /// The memory used by the parser is stored in an arena because it is + /// all freed at the end of the command. + arena: ArenaAllocator, + + /// This is the list of KV pairs that we're building up. + kv: KV, + + /// This is used as a buffer to store the key/value of a KV pair. The value + /// of a KV pair is at most a 32-bit integer which at most is 10 characters + /// (4294967295), plus one character for the sign bit on signed ints. + kv_temp: [11]u8, + kv_temp_len: u4, + kv_current: u8, // Current kv key + + /// This is the list we use to collect the bytes from the data payload. + /// The Kitty Graphics protocol specification seems to imply that the + /// payload content of a single command should never exceed 4096 bytes, + /// but Kitty itself supports larger payloads, so we use an ArrayList + /// here instead of a fixed buffer so that we can too. + data: std.ArrayList(u8), + + /// Internal state for parsing. + state: State, + + const State = enum { + /// Parsing k/v pairs. The "ignore" variants are in that state + /// but ignore any data because we know they're invalid. + control_key, + control_key_ignore, + control_value, + control_value_ignore, + + /// Collecting the data payload blob. + data, + }; + + /// Initialize the parser. The allocator given will be used for both + /// temporary data and long-lived values such as the final image blob. + pub fn init(alloc: Allocator) Parser { + var arena = ArenaAllocator.init(alloc); + errdefer arena.deinit(); + var result: Parser = .{ + .arena = arena, + .data = .empty, + .kv = .{}, + .kv_temp_len = 0, + .kv_current = 0, + .state = .control_key, + + .kv_temp = undefined, + }; + if (std.valgrind.runningOnValgrind() > 0) { + // Initialize our undefined fields so Valgrind can catch it. + // https://github.com/ziglang/zig/issues/19148 + result.kv_temp = undefined; + } + return result; + } + + pub fn deinit(self: *Parser) void { + // We don't free the hash map because its in the arena + self.data.deinit(self.arena.child_allocator); + self.arena.deinit(); + } + + /// Parse a complete command string. + pub fn parseString(alloc: Allocator, data: []const u8) !Command { + var parser = init(alloc); + defer parser.deinit(); + for (data) |c| try parser.feed(c); + return try parser.complete(alloc); + } + + /// Feed a single byte to the parser. + /// + /// The first byte to start parsing should be the byte immediately following + /// the "G" in the APC sequence, i.e. "\x1b_G123" the first byte should + /// be "1". + pub fn feed(self: *Parser, c: u8) !void { + switch (self.state) { + .control_key => switch (c) { + // '=' means the key is complete and we're moving to the value. + '=' => if (self.kv_temp_len != 1) { + // All control keys are a single character right now so + // if we're not a single character just ignore follow-up + // data. + self.state = .control_value_ignore; + self.kv_temp_len = 0; + } else { + self.kv_current = self.kv_temp[0]; + self.kv_temp_len = 0; + self.state = .control_value; + }, + + // This can be encountered if we have a sequence with no + // control data, only payload data (i.e. "\x1b_G;"). + // + // Kitty treats this as valid so we do as well. + ';' => self.state = .data, + + else => try self.accumulateValue(c, .control_key_ignore), + }, + + .control_key_ignore => switch (c) { + '=' => self.state = .control_value_ignore, + else => {}, + }, + + .control_value => switch (c) { + ',' => try self.finishValue(.control_key), // move to next key + ';' => try self.finishValue(.data), // move to data + else => try self.accumulateValue(c, .control_value_ignore), + }, + + .control_value_ignore => switch (c) { + ',' => self.state = .control_key_ignore, + ';' => self.state = .data, + else => {}, + }, + + .data => try self.data.append(self.arena.child_allocator, c), + } + } + + /// Complete the parsing. This must be called after all the + /// bytes have been fed to the parser. + /// + /// The allocator given will be used for the long-lived data + /// of the final command. + pub fn complete(self: *Parser, alloc: Allocator) !Command { + switch (self.state) { + // We can't ever end in the control key state and be valid. + // This means the command looked something like "a=1,b" + .control_key, .control_key_ignore => return error.InvalidFormat, + + // Some commands (i.e. placements) end without extra data so + // we end in the value state. i.e. "a=1,b=2" + .control_value => try self.finishValue(.data), + .control_value_ignore => {}, + + // Most commands end in data, i.e. "a=1,b=2;1234" + .data => {}, + } + + // Determine our action, which is always a single character. + const action: u8 = action: { + const value = self.kv.get('a') orelse break :action 't'; + const c = std.math.cast(u8, value) orelse return error.InvalidFormat; + break :action c; + }; + const control: Command.Control = switch (action) { + 'q' => .{ .query = try .parse(self.kv) }, + 't' => .{ .transmit = try .parse(self.kv) }, + 'T' => .{ .transmit_and_display = .{ + .transmission = try .parse(self.kv), + .display = try .parse(self.kv), + } }, + 'p' => .{ .display = try .parse(self.kv) }, + 'd' => .{ .delete = try .parse(self.kv) }, + 'f' => .{ .transmit_animation_frame = try .parse(self.kv) }, + 'a' => .{ .control_animation = try .parse(self.kv) }, + 'c' => .{ .compose_animation = try .parse(self.kv) }, + else => return error.InvalidFormat, + }; + + // Determine our quiet value + const quiet: Command.Quiet = if (self.kv.get('q')) |v| quiet: { + break :quiet switch (v) { + 0 => .no, + 1 => .ok, + 2 => .failures, + else => return error.InvalidFormat, + }; + } else .no; + + return .{ + .control = control, + .quiet = quiet, + .data = try self.decodeData(alloc), + }; + } + + /// Decodes the payload data from base64 and returns it as a slice. + /// This function will destroy the contents of self.data, it should + /// only be used once we are done collecting payload bytes. + fn decodeData(self: *Parser, alloc: Allocator) ![]const u8 { + if (self.data.items.len == 0) { + return ""; + } + + const max_len = simd.base64.maxLen(self.data.items); + assert(max_len <= self.data.items.len); + + // This is kinda cursed, but we can decode the base64 on top of + // itself, since it's guaranteed that the encoded size is larger, + // and any bytes in areas that are written to will have already + // been used (assuming scalar decoding). + const decoded = simd.base64.decode( + self.data.items, + self.data.items[0..max_len], + ) catch |err| { + log.warn("failed to decode base64 payload data: {}", .{err}); + return error.InvalidData; + }; + assert(decoded.len <= max_len); + + // Remove the extra bytes. + self.data.items.len = decoded.len; + + return try self.data.toOwnedSlice(alloc); + } + + fn accumulateValue(self: *Parser, c: u8, overflow_state: State) !void { + const idx = self.kv_temp_len; + self.kv_temp_len += 1; + if (self.kv_temp_len > self.kv_temp.len) { + self.state = overflow_state; + self.kv_temp_len = 0; + return; + } + self.kv_temp[idx] = c; + } + + fn finishValue(self: *Parser, next_state: State) !void { + const alloc = self.arena.allocator(); + + // We can move states right away, we don't use it. + self.state = next_state; + + // Check for ASCII chars first + if (self.kv_temp_len == 1) { + const c = self.kv_temp[0]; + if (c < '0' or c > '9') { + try self.kv.put(alloc, self.kv_current, @intCast(c)); + self.kv_temp_len = 0; + return; + } + } + + // Handle integer fields, parsing signed fields accordingly. We still + // store the fields as u32 as they can be bitcast back later during + // building of the higher-level command tree. + const v: u32 = switch (self.kv_current) { + 'z', 'H', 'V' => @bitCast(try std.fmt.parseInt(i32, self.kv_temp[0..self.kv_temp_len], 10)), + else => try std.fmt.parseInt(u32, self.kv_temp[0..self.kv_temp_len], 10), + }; + try self.kv.put(alloc, self.kv_current, v); + + // Clear our temp buffer + self.kv_temp_len = 0; + } +}; + +/// Represents a possible response to a command. +pub const Response = struct { + id: u32 = 0, + image_number: u32 = 0, + placement_id: u32 = 0, + message: []const u8 = "OK", + + pub fn encode(self: Response, writer: *std.Io.Writer) !void { + // We only encode a result if we have either an id or an image number. + if (self.id == 0 and self.image_number == 0) return; + + // Used to cheaply keep track if we need to add a comma before + // the next key-value pair. + var prior: bool = false; + + try writer.writeAll("\x1b_G"); + if (self.id > 0) { + prior = true; + try writer.print("i={}", .{self.id}); + } + if (self.image_number > 0) { + if (prior) try writer.writeByte(',') else prior = true; + try writer.print("I={}", .{self.image_number}); + } + if (self.placement_id > 0) { + if (prior) try writer.writeByte(',') else prior = true; + try writer.print("p={}", .{self.placement_id}); + } + try writer.writeByte(';'); + try writer.writeAll(self.message); + try writer.writeAll("\x1b\\"); + } + + /// Returns true if this response is not an error. + pub fn ok(self: Response) bool { + return std.mem.eql(u8, self.message, "OK"); + } + + /// Empty response + pub fn empty(self: Response) bool { + return self.id == 0 and self.image_number == 0; + } +}; + +pub const Command = struct { + control: Control, + quiet: Quiet = .no, + data: []const u8 = "", + + pub const Action = enum { + query, // q + transmit, // t + transmit_and_display, // T + display, // p + delete, // d + transmit_animation_frame, // f + control_animation, // a + compose_animation, // c + }; + + pub const Quiet = enum { + no, // 0 + ok, // 1 + failures, // 2 + }; + + pub const Control = union(Action) { + query: Transmission, + transmit: Transmission, + transmit_and_display: struct { + transmission: Transmission, + display: Display, + }, + display: Display, + delete: Delete, + transmit_animation_frame: AnimationFrameLoading, + control_animation: AnimationControl, + compose_animation: AnimationFrameComposition, + }; + + /// Take ownership over the data in this command. If the returned value + /// has a length of zero, then the data was empty and need not be freed. + pub fn toOwnedData(self: *Command) []const u8 { + const result = self.data; + self.data = ""; + return result; + } + + /// Returns the transmission data if it has any. + pub fn transmission(self: Command) ?Transmission { + return switch (self.control) { + .query => |t| t, + .transmit => |t| t, + .transmit_and_display => |t| t.transmission, + else => null, + }; + } + + /// Returns the display data if it has any. + pub fn display(self: Command) ?Display { + return switch (self.control) { + .display => |d| d, + .transmit_and_display => |t| t.display, + else => null, + }; + } + + pub fn deinit(self: Command, alloc: Allocator) void { + if (self.data.len > 0) alloc.free(self.data); + } +}; + +pub const Transmission = struct { + format: Format = .rgba, // f + medium: Medium = .direct, // t + width: u32 = 0, // s + height: u32 = 0, // v + size: u32 = 0, // S + offset: u32 = 0, // O + image_id: u32 = 0, // i + image_number: u32 = 0, // I + placement_id: u32 = 0, // p + compression: Compression = .none, // o + more_chunks: bool = false, // m + + pub const Format = enum { + rgb, // 24 + rgba, // 32 + png, // 100 + + // The following are not supported directly via the protocol + // but they are formats that a png may decode to that we + // support. + gray_alpha, + gray, + + pub fn bpp(self: Format) u8 { + return switch (self) { + .gray => 1, + .gray_alpha => 2, + .rgb => 3, + .rgba => 4, + .png => unreachable, // Must be validated before + }; + } + }; + + pub const Medium = enum { + direct, // d + file, // f + temporary_file, // t + shared_memory, // s + }; + + pub const Compression = enum { + none, + zlib_deflate, // z + }; + + fn parse(kv: KV) !Transmission { + var result: Transmission = .{}; + if (kv.get('f')) |v| { + result.format = switch (v) { + 24 => .rgb, + 32 => .rgba, + 100 => .png, + else => return error.InvalidFormat, + }; + } + + if (kv.get('t')) |v| { + const c = std.math.cast(u8, v) orelse return error.InvalidFormat; + result.medium = switch (c) { + 'd' => .direct, + 'f' => .file, + 't' => .temporary_file, + 's' => .shared_memory, + else => return error.InvalidFormat, + }; + } + + if (kv.get('s')) |v| { + result.width = v; + } + + if (kv.get('v')) |v| { + result.height = v; + } + + if (kv.get('S')) |v| { + result.size = v; + } + + if (kv.get('O')) |v| { + result.offset = v; + } + + if (kv.get('i')) |v| { + result.image_id = v; + } + + if (kv.get('I')) |v| { + result.image_number = v; + } + + if (kv.get('p')) |v| { + result.placement_id = v; + } + + if (kv.get('o')) |v| { + const c = std.math.cast(u8, v) orelse return error.InvalidFormat; + result.compression = switch (c) { + 'z' => .zlib_deflate, + else => return error.InvalidFormat, + }; + } + + // If the transmission medium is a local-only medium, ignore the "m" + // key. The Kitty graphics protocol specification does not explicitly + // call out this behavior (although the "m" key is only mentioned in + // connection with remote clients) but that's how it's implemented in + // Kitty and at least one client (mpv) relies on this behavior when + // using the shared memory transmission medium. + // + // https://sw.kovidgoyal.net/kitty/graphics-protocol/#the-transmission-medium + // https://github.com/kovidgoyal/kitty/blob/ccc3bee9af794f332b4e9adcd714a649f639c397/kitty/graphics.c#L547-L592 + if (result.medium == .direct) { + if (kv.get('m')) |v| { + result.more_chunks = v > 0; + } + } + + return result; + } +}; + +pub const Display = struct { + image_id: u32 = 0, // i + image_number: u32 = 0, // I + placement_id: u32 = 0, // p + x: u32 = 0, // x + y: u32 = 0, // y + width: u32 = 0, // w + height: u32 = 0, // h + x_offset: u32 = 0, // X + y_offset: u32 = 0, // Y + columns: u32 = 0, // c + rows: u32 = 0, // r + cursor_movement: CursorMovement = .after, // C + virtual_placement: bool = false, // U + parent_id: u32 = 0, // P + parent_placement_id: u32 = 0, // Q + horizontal_offset: i32 = 0, // H + vertical_offset: i32 = 0, // V + z: i32 = 0, // z + + pub const CursorMovement = enum { + after, // 0 + none, // 1 + }; + + fn parse(kv: KV) !Display { + var result: Display = .{}; + + if (kv.get('i')) |v| { + result.image_id = v; + } + + if (kv.get('I')) |v| { + result.image_number = v; + } + + if (kv.get('p')) |v| { + result.placement_id = v; + } + + if (kv.get('x')) |v| { + result.x = v; + } + + if (kv.get('y')) |v| { + result.y = v; + } + + if (kv.get('w')) |v| { + result.width = v; + } + + if (kv.get('h')) |v| { + result.height = v; + } + + if (kv.get('X')) |v| { + result.x_offset = v; + } + + if (kv.get('Y')) |v| { + result.y_offset = v; + } + + if (kv.get('c')) |v| { + result.columns = v; + } + + if (kv.get('r')) |v| { + result.rows = v; + } + + if (kv.get('C')) |v| { + result.cursor_movement = switch (v) { + 0 => .after, + 1 => .none, + else => return error.InvalidFormat, + }; + } + + if (kv.get('U')) |v| { + result.virtual_placement = switch (v) { + 0 => false, + 1 => true, + else => return error.InvalidFormat, + }; + } + + if (kv.get('z')) |v| { + // We can bitcast here because of how we parse it earlier. + result.z = @bitCast(v); + } + + if (kv.get('P')) |v| { + result.parent_id = v; + } + + if (kv.get('Q')) |v| { + result.parent_placement_id = v; + } + + if (kv.get('H')) |v| { + // We can bitcast here because of how we parse it earlier. + result.horizontal_offset = @bitCast(v); + } + + if (kv.get('V')) |v| { + // We can bitcast here because of how we parse it earlier. + result.vertical_offset = @bitCast(v); + } + + return result; + } +}; + +pub const AnimationFrameLoading = struct { + x: u32 = 0, // x + y: u32 = 0, // y + create_frame: u32 = 0, // c + edit_frame: u32 = 0, // r + gap_ms: u32 = 0, // z + composition_mode: CompositionMode = .alpha_blend, // X + background: Background = .{}, // Y + + pub const Background = packed struct(u32) { + r: u8 = 0, + g: u8 = 0, + b: u8 = 0, + a: u8 = 0, + }; + + fn parse(kv: KV) !AnimationFrameLoading { + var result: AnimationFrameLoading = .{}; + + if (kv.get('x')) |v| { + result.x = v; + } + + if (kv.get('y')) |v| { + result.y = v; + } + + if (kv.get('c')) |v| { + result.create_frame = v; + } + + if (kv.get('r')) |v| { + result.edit_frame = v; + } + + if (kv.get('z')) |v| { + result.gap_ms = v; + } + + if (kv.get('X')) |v| { + result.composition_mode = switch (v) { + 0 => .alpha_blend, + 1 => .overwrite, + else => return error.InvalidFormat, + }; + } + + if (kv.get('Y')) |v| { + result.background = @bitCast(v); + } + + return result; + } +}; + +pub const AnimationFrameComposition = struct { + frame: u32 = 0, // c + edit_frame: u32 = 0, // r + x: u32 = 0, // x + y: u32 = 0, // y + width: u32 = 0, // w + height: u32 = 0, // h + left_edge: u32 = 0, // X + top_edge: u32 = 0, // Y + composition_mode: CompositionMode = .alpha_blend, // C + + fn parse(kv: KV) !AnimationFrameComposition { + var result: AnimationFrameComposition = .{}; + + if (kv.get('c')) |v| { + result.frame = v; + } + + if (kv.get('r')) |v| { + result.edit_frame = v; + } + + if (kv.get('x')) |v| { + result.x = v; + } + + if (kv.get('y')) |v| { + result.y = v; + } + + if (kv.get('w')) |v| { + result.width = v; + } + + if (kv.get('h')) |v| { + result.height = v; + } + + if (kv.get('X')) |v| { + result.left_edge = v; + } + + if (kv.get('Y')) |v| { + result.top_edge = v; + } + + if (kv.get('C')) |v| { + result.composition_mode = switch (v) { + 0 => .alpha_blend, + 1 => .overwrite, + else => return error.InvalidFormat, + }; + } + + return result; + } +}; + +pub const AnimationControl = struct { + action: AnimationAction = .invalid, // s + frame: u32 = 0, // r + gap_ms: u32 = 0, // z + current_frame: u32 = 0, // c + loops: u32 = 0, // v + + pub const AnimationAction = enum { + invalid, // 0 + stop, // 1 + run_wait, // 2 + run, // 3 + }; + + fn parse(kv: KV) !AnimationControl { + var result: AnimationControl = .{}; + + if (kv.get('s')) |v| { + result.action = switch (v) { + 0 => .invalid, + 1 => .stop, + 2 => .run_wait, + 3 => .run, + else => return error.InvalidFormat, + }; + } + + if (kv.get('r')) |v| { + result.frame = v; + } + + if (kv.get('z')) |v| { + result.gap_ms = v; + } + + if (kv.get('c')) |v| { + result.current_frame = v; + } + + if (kv.get('v')) |v| { + result.loops = v; + } + + return result; + } +}; + +pub const Delete = union(enum) { + // a/A + all: bool, + + // i/I + id: struct { + delete: bool = false, // uppercase + image_id: u32 = 0, // i + placement_id: u32 = 0, // p + }, + + // n/N + newest: struct { + delete: bool = false, // uppercase + image_number: u32 = 0, // I + placement_id: u32 = 0, // p + }, + + // c/C, + intersect_cursor: bool, + + // f/F + animation_frames: bool, + + // p/P + intersect_cell: struct { + delete: bool = false, // uppercase + x: u32 = 0, // x + y: u32 = 0, // y + }, + + // q/Q + intersect_cell_z: struct { + delete: bool = false, // uppercase + x: u32 = 0, // x + y: u32 = 0, // y + z: i32 = 0, // z + }, + + // r/R + range: struct { + delete: bool = false, // uppercase + first: u32 = 0, // x + last: u32 = 0, // y + }, + + // x/X + column: struct { + delete: bool = false, // uppercase + x: u32 = 0, // x + }, + + // y/Y + row: struct { + delete: bool = false, // uppercase + y: u32 = 0, // y + }, + + // z/Z + z: struct { + delete: bool = false, // uppercase + z: i32 = 0, // z + }, + + fn parse(kv: KV) !Delete { + const what: u8 = what: { + const value = kv.get('d') orelse break :what 'a'; + const c = std.math.cast(u8, value) orelse return error.InvalidFormat; + break :what c; + }; + + return switch (what) { + 'a', 'A' => .{ .all = what == 'A' }, + + 'i', 'I' => blk: { + var result: Delete = .{ .id = .{ .delete = what == 'I' } }; + if (kv.get('i')) |v| { + result.id.image_id = v; + } + if (kv.get('p')) |v| { + result.id.placement_id = v; + } + + break :blk result; + }, + + 'n', 'N' => blk: { + var result: Delete = .{ .newest = .{ .delete = what == 'N' } }; + if (kv.get('I')) |v| { + result.newest.image_number = v; + } + if (kv.get('p')) |v| { + result.newest.placement_id = v; + } + + break :blk result; + }, + + 'c', 'C' => .{ .intersect_cursor = what == 'C' }, + + 'f', 'F' => .{ .animation_frames = what == 'F' }, + + 'p', 'P' => blk: { + var result: Delete = .{ .intersect_cell = .{ .delete = what == 'P' } }; + if (kv.get('x')) |v| { + result.intersect_cell.x = v; + } + if (kv.get('y')) |v| { + result.intersect_cell.y = v; + } + + break :blk result; + }, + + 'q', 'Q' => blk: { + var result: Delete = .{ .intersect_cell_z = .{ .delete = what == 'Q' } }; + if (kv.get('x')) |v| { + result.intersect_cell_z.x = v; + } + if (kv.get('y')) |v| { + result.intersect_cell_z.y = v; + } + if (kv.get('z')) |v| { + // We can bitcast here because of how we parse it earlier. + result.intersect_cell_z.z = @bitCast(v); + } + + break :blk result; + }, + + 'r', 'R' => blk: { + const x = kv.get('x') orelse return error.InvalidFormat; + const y = kv.get('y') orelse return error.InvalidFormat; + if (x > y) return error.InvalidFormat; + break :blk .{ + .range = .{ + .delete = what == 'R', + .first = x, + .last = y, + }, + }; + }, + + 'x', 'X' => blk: { + var result: Delete = .{ .column = .{ .delete = what == 'X' } }; + if (kv.get('x')) |v| { + result.column.x = v; + } + + break :blk result; + }, + + 'y', 'Y' => blk: { + var result: Delete = .{ .row = .{ .delete = what == 'Y' } }; + if (kv.get('y')) |v| { + result.row.y = v; + } + + break :blk result; + }, + + 'z', 'Z' => blk: { + var result: Delete = .{ .z = .{ .delete = what == 'Z' } }; + if (kv.get('z')) |v| { + // We can bitcast here because of how we parse it earlier. + result.z.z = @bitCast(v); + } + + break :blk result; + }, + + else => return error.InvalidFormat, + }; + } +}; + +pub const CompositionMode = enum { + alpha_blend, // 0 + overwrite, // 1 +}; + +test "transmission command" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "f=24,s=10,v=20"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Format.rgb, v.format); + try testing.expectEqual(@as(u32, 10), v.width); + try testing.expectEqual(@as(u32, 20), v.height); +} + +test "transmission ignores 'm' if medium is not direct" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=t,t=t,m=1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Medium.temporary_file, v.medium); + try testing.expect(!v.more_chunks); +} + +test "transmission respects 'm' if medium is direct" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=t,t=d,m=1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Medium.direct, v.medium); + try testing.expect(v.more_chunks); +} + +test "query command" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "i=31,s=1,v=1,a=q,t=d,f=24;QUFBQQ"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .query); + const v = command.control.query; + try testing.expectEqual(Transmission.Medium.direct, v.medium); + try testing.expectEqual(@as(u32, 1), v.width); + try testing.expectEqual(@as(u32, 1), v.height); + try testing.expectEqual(@as(u32, 31), v.image_id); + try testing.expectEqualStrings("AAAA", command.data); +} + +test "display command" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=p,U=1,i=31,c=80,r=120"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + const v = command.control.display; + try testing.expectEqual(@as(u32, 80), v.columns); + try testing.expectEqual(@as(u32, 120), v.rows); + try testing.expectEqual(@as(u32, 31), v.image_id); +} + +test "delete command" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=d,d=p,x=3,y=4"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete; + try testing.expect(v == .intersect_cell); + const dv = v.intersect_cell; + try testing.expect(!dv.delete); + try testing.expectEqual(@as(u32, 3), dv.x); + try testing.expectEqual(@as(u32, 4), dv.y); +} + +test "no control data" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = ";QUFBQQ"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + try testing.expectEqualStrings("AAAA", command.data); +} + +test "ignore unknown keys (long)" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "f=24,s=10,v=20,hello=world"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Format.rgb, v.format); + try testing.expectEqual(@as(u32, 10), v.width); + try testing.expectEqual(@as(u32, 20), v.height); +} + +test "ignore very long values" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "f=24,s=10,v=2000000000000000000000000000000000000000"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .transmit); + const v = command.control.transmit; + try testing.expectEqual(Transmission.Format.rgb, v.format); + try testing.expectEqual(@as(u32, 10), v.width); + try testing.expectEqual(@as(u32, 0), v.height); +} + +test "ensure very large negative values don't get skipped" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=p,i=1,z=-2000000000"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + const v = command.control.display; + try testing.expectEqual(1, v.image_id); + try testing.expectEqual(-2000000000, v.z); +} + +test "ensure proper overflow error for u32" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=p,i=10000000000"; + for (input) |c| try p.feed(c); + try testing.expectError(error.Overflow, p.complete(alloc)); +} + +test "ensure proper overflow error for i32" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=p,i=1,z=-9999999999"; + for (input) |c| try p.feed(c); + try testing.expectError(error.Overflow, p.complete(alloc)); +} + +test "all i32 values" { + const testing = std.testing; + const alloc = testing.allocator; + + { + // 'z' (usually z-axis values) + var p = Parser.init(alloc); + defer p.deinit(); + const input = "a=p,i=1,z=-1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + const v = command.control.display; + try testing.expectEqual(1, v.image_id); + try testing.expectEqual(-1, v.z); + } + + { + // 'H' (relative placement, horizontal offset) + var p = Parser.init(alloc); + defer p.deinit(); + const input = "a=p,i=1,H=-1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + const v = command.control.display; + try testing.expectEqual(1, v.image_id); + try testing.expectEqual(-1, v.horizontal_offset); + } + + { + // 'V' (relative placement, vertical offset) + var p = Parser.init(alloc); + defer p.deinit(); + const input = "a=p,i=1,V=-1"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .display); + const v = command.control.display; + try testing.expectEqual(1, v.image_id); + try testing.expectEqual(-1, v.vertical_offset); + } +} + +test "response: encode nothing without ID or image number" { + const testing = std.testing; + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + + var r: Response = .{}; + try r.encode(&writer); + try testing.expectEqualStrings("", writer.buffered()); +} + +test "response: encode with only image id" { + const testing = std.testing; + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + + var r: Response = .{ .id = 4 }; + try r.encode(&writer); + try testing.expectEqualStrings("\x1b_Gi=4;OK\x1b\\", writer.buffered()); +} + +test "response: encode with only image number" { + const testing = std.testing; + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + + var r: Response = .{ .image_number = 4 }; + try r.encode(&writer); + try testing.expectEqualStrings("\x1b_GI=4;OK\x1b\\", writer.buffered()); +} + +test "response: encode with image ID and number" { + const testing = std.testing; + var buf: [1024]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + + var r: Response = .{ .id = 12, .image_number = 4 }; + try r.encode(&writer); + try testing.expectEqualStrings("\x1b_Gi=12,I=4;OK\x1b\\", writer.buffered()); +} + +test "delete range command 1" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=d,d=r,x=3,y=4"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete; + try testing.expect(v == .range); + const range = v.range; + try testing.expect(!range.delete); + try testing.expectEqual(@as(u32, 3), range.first); + try testing.expectEqual(@as(u32, 4), range.last); +} + +test "delete range command 2" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=d,d=R,x=5,y=11"; + for (input) |c| try p.feed(c); + const command = try p.complete(alloc); + defer command.deinit(alloc); + + try testing.expect(command.control == .delete); + const v = command.control.delete; + try testing.expect(v == .range); + const range = v.range; + try testing.expect(range.delete); + try testing.expectEqual(@as(u32, 5), range.first); + try testing.expectEqual(@as(u32, 11), range.last); +} + +test "delete range command 3" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=d,d=R,x=5,y=4"; + for (input) |c| try p.feed(c); + try testing.expectError(error.InvalidFormat, p.complete(alloc)); +} + +test "delete range command 4" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=d,d=R,x=5"; + for (input) |c| try p.feed(c); + try testing.expectError(error.InvalidFormat, p.complete(alloc)); +} + +test "delete range command 5" { + const testing = std.testing; + const alloc = testing.allocator; + var p = Parser.init(alloc); + defer p.deinit(); + + const input = "a=d,d=R,y=5"; + for (input) |c| try p.feed(c); + try testing.expectError(error.InvalidFormat, p.complete(alloc)); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig new file mode 100644 index 00000000..5b3ab915 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig @@ -0,0 +1,570 @@ +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; + +const Terminal = @import("../Terminal.zig"); +const command = @import("graphics_command.zig"); +const image = @import("graphics_image.zig"); +const Command = command.Command; +const Response = command.Response; +const LoadingImage = image.LoadingImage; +const Image = image.Image; +const ImageStorage = @import("graphics_storage.zig").ImageStorage; + +const log = std.log.scoped(.kitty_gfx); + +/// Execute a Kitty graphics command against the given terminal. This +/// will never fail, but the response may indicate an error and the +/// terminal state may not be updated to reflect the command. This will +/// never put the terminal in an unrecoverable state, however. +/// +/// The allocator must be the same allocator that was used to build +/// the command. +pub fn execute( + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) ?Response { + // If storage is disabled then we disable the full protocol. This means + // we don't even respond to queries so the terminal completely acts as + // if this feature is not supported. + if (!terminal.screens.active.kitty_images.enabled()) { + log.debug("kitty graphics requested but disabled", .{}); + return null; + } + + log.debug("executing kitty graphics command: quiet={} control={}", .{ + cmd.quiet, + cmd.control, + }); + + // The quiet settings used to control the response. We have to make this + // a var because in certain special cases (namely chunked transmissions) + // this can change. + var quiet = cmd.quiet; + + const resp_: ?Response = switch (cmd.control) { + .query => query(alloc, cmd), + .display => display(alloc, terminal, cmd), + .delete => delete(alloc, terminal, cmd), + + .transmit, .transmit_and_display => resp: { + // If we're transmitting, then our `q` setting value is complicated. + // The `q` setting inherits the value from the starting command + // unless `q` is set >= 1 on this command. If it is, then we save + // that as the new `q` setting. + const storage = &terminal.screens.active.kitty_images; + if (storage.loading) |loading| switch (cmd.quiet) { + // q=0 we use whatever the start command value is + .no => quiet = loading.quiet, + + // q>=1 we use the new value, but we should already be set to it + inline .ok, .failures => |tag| { + assert(quiet == tag); + loading.quiet = tag; + }, + }; + + break :resp transmit(alloc, terminal, cmd); + }, + + .transmit_animation_frame, + .control_animation, + .compose_animation, + => .{ .message = "ERROR: unimplemented action" }, + }; + + // Handle the quiet settings + if (resp_) |resp| { + if (!resp.ok()) { + log.warn("erroneous kitty graphics response: {s}", .{resp.message}); + } + + return switch (quiet) { + .no => if (resp.empty()) null else resp, + .ok => if (resp.ok()) null else resp, + .failures => null, + }; + } + + return null; +} +/// Execute a "query" command. +/// +/// This command is used to attempt to load an image and respond with +/// success/error but does not persist any of the command to the terminal +/// state. +fn query(alloc: Allocator, cmd: *const Command) Response { + const t = cmd.control.query; + + // Query requires image ID. We can't actually send a response without + // an image ID either but we return an error and this will be logged + // downstream. + if (t.image_id == 0) { + return .{ .message = "EINVAL: image ID required" }; + } + + // Build a partial response to start + var result: Response = .{ + .id = t.image_id, + .image_number = t.image_number, + .placement_id = t.placement_id, + }; + + // Attempt to load the image. If we cannot, then set an appropriate error. + var loading = LoadingImage.init(alloc, cmd) catch |err| { + encodeError(&result, err); + return result; + }; + loading.deinit(alloc); + + return result; +} + +/// Transmit image data. +/// +/// This loads the image, validates it, and puts it into the terminal +/// screen storage. It does not display the image. +fn transmit( + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) Response { + const t = cmd.transmission().?; + var result: Response = .{ + .id = t.image_id, + .image_number = t.image_number, + .placement_id = t.placement_id, + }; + if (t.image_id > 0 and t.image_number > 0) { + return .{ .message = "EINVAL: image ID and number are mutually exclusive" }; + } + + const load = loadAndAddImage(alloc, terminal, cmd) catch |err| { + encodeError(&result, err); + return result; + }; + errdefer load.image.deinit(alloc); + + // If we're also displaying, then do that now. This function does + // both transmit and transmit and display. The display might also be + // deferred if it is multi-chunk. + if (load.display) |d| { + assert(!load.more); + var d_copy = d; + d_copy.image_id = load.image.id; + result = display(alloc, terminal, &.{ + .control = .{ .display = d_copy }, + .quiet = cmd.quiet, + }); + } + + // If there are more chunks expected we do not respond. + if (load.more) return .{}; + + // If the loaded image was assigned its ID automatically, not based + // on a number or explicitly specified ID, then we don't respond. + if (load.image.implicit_id) return .{}; + + // After the image is added, set the ID in case it changed. + // The resulting image number and placement ID never change. + result.id = load.image.id; + + return result; +} + +/// Display a previously transmitted image. +fn display( + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) Response { + const d = cmd.display().?; + + // Display requires image ID or number. + if (d.image_id == 0 and d.image_number == 0) { + return .{ .message = "EINVAL: image ID or number required" }; + } + + // Build up our response + var result: Response = .{ + .id = d.image_id, + .image_number = d.image_number, + .placement_id = d.placement_id, + }; + + // Verify the requested image exists if we have an ID + const storage = &terminal.screens.active.kitty_images; + const img_: ?Image = if (d.image_id != 0) + storage.imageById(d.image_id) + else + storage.imageByNumber(d.image_number); + const img = img_ orelse { + result.message = "ENOENT: image not found"; + return result; + }; + + // Make sure our response has the image id in case we looked up by number + result.id = img.id; + + // Location where the placement will go. + const location: ImageStorage.Placement.Location = location: { + // Virtual placements are not tracked + if (d.virtual_placement) { + if (d.parent_id > 0) { + result.message = "EINVAL: virtual placement cannot refer to a parent"; + return result; + } + + break :location .{ .virtual = {} }; + } + + // Track a new pin for our cursor. The cursor is always tracked but we + // don't want this one to move with the cursor. + const pin = terminal.screens.active.pages.trackPin( + terminal.screens.active.cursor.page_pin.*, + ) catch |err| { + log.warn("failed to create pin for Kitty graphics err={}", .{err}); + result.message = "EINVAL: failed to prepare terminal state"; + return result; + }; + break :location .{ .pin = pin }; + }; + + // Add the placement + const p: ImageStorage.Placement = .{ + .location = location, + .x_offset = d.x_offset, + .y_offset = d.y_offset, + .source_x = d.x, + .source_y = d.y, + .source_width = d.width, + .source_height = d.height, + .columns = d.columns, + .rows = d.rows, + .z = d.z, + }; + storage.addPlacement( + alloc, + img.id, + result.placement_id, + p, + ) catch |err| { + p.deinit(terminal.screens.active); + encodeError(&result, err); + return result; + }; + + // Apply cursor movement setting. This only applies to pin placements. + switch (p.location) { + .virtual => {}, + .pin => |pin| switch (d.cursor_movement) { + .none => {}, + .after => { + // We use terminal.index to properly handle scroll regions. + const size = p.gridSize(img, terminal); + for (0..size.rows) |_| terminal.index() catch |err| { + log.warn("failed to move cursor: {}", .{err}); + break; + }; + + terminal.setCursorPos( + terminal.screens.active.cursor.y, + pin.x + size.cols + 1, + ); + }, + }, + } + + return result; +} + +/// Display a previously transmitted image. +fn delete( + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) Response { + const storage = &terminal.screens.active.kitty_images; + storage.delete(alloc, terminal, cmd.control.delete); + + // Delete never responds on success + return .{}; +} + +fn loadAndAddImage( + alloc: Allocator, + terminal: *Terminal, + cmd: *const Command, +) !struct { + image: Image, + more: bool = false, + display: ?command.Display = null, +} { + const t = cmd.transmission().?; + const storage = &terminal.screens.active.kitty_images; + + // Determine our image. This also handles chunking and early exit. + var loading: LoadingImage = if (storage.loading) |loading| loading: { + // Note: we do NOT want to call "cmd.toOwnedData" here because + // we're _copying_ the data. We want the command data to be freed. + try loading.addData(alloc, cmd.data); + + // If we have more then we're done + if (t.more_chunks) return .{ .image = loading.image, .more = true }; + + // We have no more chunks. We're going to be completing the + // image so we want to destroy the pointer to the loading + // image and copy it out. + defer { + alloc.destroy(loading); + storage.loading = null; + } + + break :loading loading.*; + } else try .init(alloc, cmd); + + // We only want to deinit on error. If we're chunking, then we don't + // want to deinit at all. If we're not chunking, then we'll deinit + // after we've copied the image out. + errdefer loading.deinit(alloc); + + // If the image has no ID, we assign one + if (loading.image.id == 0) { + loading.image.id = storage.next_image_id; + storage.next_image_id +%= 1; + + // If the image also has no number then its auto-ID is "implicit". + // See the doc comment on the Image.implicit_id field for more detail. + if (loading.image.number == 0) loading.image.implicit_id = true; + } + + // If this is chunked, this is the beginning of a new chunked transmission. + // (We checked for an in-progress chunk above.) + if (t.more_chunks) { + // We allocate the pointer on the heap because its rare and we + // don't want to always pay the memory cost to keep it around. + const loading_ptr = try alloc.create(LoadingImage); + errdefer alloc.destroy(loading_ptr); + loading_ptr.* = loading; + storage.loading = loading_ptr; + return .{ .image = loading.image, .more = true }; + } + + // Dump the image data before it is decompressed + // loading.debugDump() catch unreachable; + + // Validate and store our image + var img = try loading.complete(alloc); + errdefer img.deinit(alloc); + try storage.addImage(alloc, img); + + // Get our display settings + const display_ = loading.display; + + // Ensure we deinit the loading state because we're done. The image + // won't be deinit because of "complete" above. + loading.deinit(alloc); + + return .{ .image = img, .display = display_ }; +} + +const EncodeableError = Image.Error || Allocator.Error; + +/// Encode an error code into a message for a response. +fn encodeError(r: *Response, err: EncodeableError) void { + switch (err) { + error.OutOfMemory => r.message = "ENOMEM: out of memory", + error.InternalError => r.message = "EINVAL: internal error", + error.InvalidData => r.message = "EINVAL: invalid data", + error.DecompressionFailed => r.message = "EINVAL: decompression failed", + error.FilePathTooLong => r.message = "EINVAL: file path too long", + error.TemporaryFileNotInTempDir => r.message = "EINVAL: temporary file not in temp dir", + error.TemporaryFileNotNamedCorrectly => r.message = "EINVAL: temporary file not named correctly", + error.UnsupportedFormat => r.message = "EINVAL: unsupported format", + error.UnsupportedMedium => r.message = "EINVAL: unsupported medium", + error.UnsupportedDepth => r.message = "EINVAL: unsupported pixel depth", + error.DimensionsRequired => r.message = "EINVAL: dimensions required", + error.DimensionsTooLarge => r.message = "EINVAL: dimensions too large", + } +} + +test "kittygfx more chunks with q=1" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Initial chunk has q=1 + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,f=24,t=d,i=1,s=1,v=2,c=10,r=1,m=1,q=1;////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } + + // Subsequent chunk has no q but should respect initial + { + const cmd = try command.Parser.parseString( + alloc, + "m=0;////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } +} + +test "kittygfx more chunks with q=0" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Initial chunk has q=0 + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,t=d,s=1,v=2,c=10,r=1,m=1,i=1,q=0;////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } + + // Subsequent chunk has no q so should respond OK + { + const cmd = try command.Parser.parseString( + alloc, + "m=0;////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + } +} + +test "kittygfx more chunks with chunk increasing q" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + // Initial chunk has q=0 + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,t=d,s=1,v=2,c=10,r=1,m=1,i=1,q=0;////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } + + // Subsequent chunk sets q=1 so should not respond + { + const cmd = try command.Parser.parseString( + alloc, + "m=0,q=1;////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } +} + +test "kittygfx default format is rgba" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString( + alloc, + "a=t,t=d,i=1,s=1,v=2,c=10,r=1;///////////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd).?; + try testing.expect(resp.ok()); + + const storage = &t.screens.active.kitty_images; + const img = storage.imageById(1).?; + try testing.expectEqual(command.Transmission.Format.rgba, img.format); +} + +test "kittygfx test valid u32 (expect invalid image ID)" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString( + alloc, + "a=p,i=4294967295", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(resp.message, "ENOENT: image not found"); +} + +test "kittygfx test valid i32 (expect invalid image ID)" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + const cmd = try command.Parser.parseString( + alloc, + "a=p,i=1,z=-2147483648", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd).?; + try testing.expect(!resp.ok()); + try testing.expectEqual(resp.message, "ENOENT: image not found"); +} + +test "kittygfx no response with no image ID or number" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + { + const cmd = try command.Parser.parseString( + alloc, + "a=t,f=24,t=d,s=1,v=2,c=10,r=1,i=0,I=0;////////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } +} + +test "kittygfx no response with no image ID or number load and display" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + + { + const cmd = try command.Parser.parseString( + alloc, + "a=T,f=24,t=d,s=1,v=2,c=10,r=1,i=0,I=0;////////", + ); + defer cmd.deinit(alloc); + const resp = execute(alloc, &t, &cmd); + try testing.expect(resp == null); + } +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig new file mode 100644 index 00000000..d2877cfc --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_image.zig @@ -0,0 +1,835 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const assert = @import("../../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; +const posix = std.posix; + +const fastmem = @import("../../fastmem.zig"); +const command = @import("graphics_command.zig"); +const PageList = @import("../PageList.zig"); +const wuffs = @import("wuffs"); + +const temp_dir = struct { + const TempDir = @import("../../os/TempDir.zig"); + const allocTmpDir = @import("../../os/file.zig").allocTmpDir; + const freeTmpDir = @import("../../os/file.zig").freeTmpDir; +}; + +const log = std.log.scoped(.kitty_gfx); + +/// Maximum width or height of an image. Taken directly from Kitty. +const max_dimension = 10000; + +/// Maximum size in bytes, taken from Kitty. +const max_size = 400 * 1024 * 1024; // 400MB + +/// An image that is still being loaded. The image should be initialized +/// using init on the first chunk and then addData for each subsequent +/// chunk. Once all chunks have been added, complete should be called +/// to finalize the image. +pub const LoadingImage = struct { + /// The in-progress image. The first chunk must have all the metadata + /// so this comes from that initially. + image: Image, + + /// The data that is being built up. + data: std.ArrayListUnmanaged(u8) = .{}, + + /// This is non-null when a transmit and display command is given + /// so that we display the image after it is fully loaded. + display: ?command.Display = null, + + /// Quiet is the quiet settings for the initial load command. This is + /// used if q isn't set on subsequent chunks. + quiet: command.Command.Quiet, + + /// Initialize a chunked immage from the first image transmission. + /// If this is a multi-chunk image, this should only be the FIRST + /// chunk. + pub fn init(alloc: Allocator, cmd: *const command.Command) !LoadingImage { + // Build our initial image from the properties sent via the control. + // These can be overwritten by the data loading process. For example, + // PNG loading sets the width/height from the data. + const t = cmd.transmission().?; + var result: LoadingImage = .{ + .image = .{ + .id = t.image_id, + .number = t.image_number, + .width = t.width, + .height = t.height, + .compression = t.compression, + .format = t.format, + }, + + .display = cmd.display(), + .quiet = cmd.quiet, + }; + + // Special case for the direct medium, we just add the chunk directly. + if (t.medium == .direct) { + try result.addData(alloc, cmd.data); + return result; + } + + // Otherwise, the payload data is guaranteed to be a path. + + if (comptime builtin.os.tag != .windows) { + if (std.mem.indexOfScalar(u8, cmd.data, 0) != null) { + // posix.realpath *asserts* that the path does not have + // internal nulls instead of erroring. + log.warn("failed to get absolute path: BadPathName", .{}); + return error.InvalidData; + } + } + + var abs_buf: [std.fs.max_path_bytes]u8 = undefined; + const path = switch (t.medium) { + .direct => unreachable, // handled above + .file, .temporary_file => posix.realpath(cmd.data, &abs_buf) catch |err| { + log.warn("failed to get absolute path: {}", .{err}); + return error.InvalidData; + }, + .shared_memory => cmd.data, + }; + + // Depending on the medium, load the data from the path. + switch (t.medium) { + .direct => unreachable, // handled above + .file => try result.readFile(.file, alloc, t, path), + .temporary_file => try result.readFile(.temporary_file, alloc, t, path), + .shared_memory => try result.readSharedMemory(alloc, t, path), + } + + return result; + } + + /// Reads the data from a shared memory segment. + fn readSharedMemory( + self: *LoadingImage, + alloc: Allocator, + t: command.Transmission, + path: []const u8, + ) !void { + // windows is currently unsupported, does it support shm? + if (comptime builtin.target.os.tag == .windows) { + return error.UnsupportedMedium; + } + + // libc is required for shm_open + if (comptime !builtin.link_libc) { + return error.UnsupportedMedium; + } + + // Since we're only supporting posix then max_path_bytes should + // be enough to stack allocate the path. + var buf: [std.fs.max_path_bytes]u8 = undefined; + const pathz = std.fmt.bufPrintZ(&buf, "{s}", .{path}) catch return error.InvalidData; + + const fd = std.c.shm_open(pathz, @as(c_int, @bitCast(std.c.O{ .ACCMODE = .RDONLY })), 0); + switch (std.posix.errno(fd)) { + .SUCCESS => {}, + else => |err| { + log.warn("unable to open shared memory {s}: {}", .{ path, err }); + return error.InvalidData; + }, + } + defer _ = std.c.close(fd); + defer _ = std.c.shm_unlink(pathz); + + // The size from stat on may be larger than our expected size because + // shared memory has to be a multiple of the page size. + const stat_size: usize = stat: { + const stat = std.posix.fstat(fd) catch |err| { + log.warn("unable to fstat shared memory {s}: {}", .{ path, err }); + return error.InvalidData; + }; + if (stat.size <= 0) return error.InvalidData; + break :stat @intCast(stat.size); + }; + + const expected_size: usize = switch (self.image.format) { + // Png we decode the full data size because later decoding will + // get the proper dimensions and assert validity. + .png => stat_size, + + // For these formats we have a size we must have. + .gray, .gray_alpha, .rgb, .rgba => |f| size: { + const bpp = f.bpp(); + break :size self.image.width * self.image.height * bpp; + }, + }; + + // Our stat size must be at least the expected size otherwise + // the shared memory data is invalid. + if (stat_size < expected_size) { + log.warn( + "shared memory size too small expected={} actual={}", + .{ expected_size, stat_size }, + ); + return error.InvalidData; + } + + const map = std.posix.mmap( + null, + stat_size, // mmap always uses the stat size + std.c.PROT.READ, + std.c.MAP{ .TYPE = .SHARED }, + fd, + 0, + ) catch |err| { + log.warn("unable to mmap shared memory {s}: {}", .{ path, err }); + return error.InvalidData; + }; + defer std.posix.munmap(map); + + // Our end size always uses the expected size so we cut off the + // padding for mmap alignment. + const start: usize = @intCast(t.offset); + const end: usize = if (t.size > 0) @min( + @as(usize, @intCast(t.offset)) + @as(usize, @intCast(t.size)), + expected_size, + ) else expected_size; + + assert(self.data.items.len == 0); + try self.data.appendSlice(alloc, map[start..end]); + } + + /// Reads the data from a temporary file and returns it. This allocates + /// and does not free any of the data, so the caller must free it. + /// + /// This will also delete the temporary file if it is in a safe location. + fn readFile( + self: *LoadingImage, + comptime medium: command.Transmission.Medium, + alloc: Allocator, + t: command.Transmission, + path: []const u8, + ) !void { + switch (medium) { + .file, .temporary_file => {}, + else => @compileError("readFile only supports file and temporary_file"), + } + + // Verify file seems "safe". This is logic copied directly from Kitty, + // mostly. This is really rough but it will catch obvious bad actors. + if (std.mem.startsWith(u8, path, "/proc/") or + std.mem.startsWith(u8, path, "/sys/") or + (std.mem.startsWith(u8, path, "/dev/") and + !std.mem.startsWith(u8, path, "/dev/shm/"))) + { + return error.InvalidData; + } + + // Temporary file logic + if (medium == .temporary_file) { + if (!isPathInTempDir(path)) return error.TemporaryFileNotInTempDir; + if (std.mem.indexOf(u8, path, "tty-graphics-protocol") == null) { + return error.TemporaryFileNotNamedCorrectly; + } + } + defer if (medium == .temporary_file) { + posix.unlink(path) catch |err| { + log.warn("failed to delete temporary file: {}", .{err}); + }; + }; + + var file = std.fs.cwd().openFile(path, .{}) catch |err| { + log.warn("failed to open temporary file: {}", .{err}); + return error.InvalidData; + }; + defer file.close(); + + // File must be a regular file + if (file.stat()) |stat| { + if (stat.kind != .file) { + log.warn("file is not a regular file kind={}", .{stat.kind}); + return error.InvalidData; + } + } else |err| { + log.warn("failed to stat file: {}", .{err}); + return error.InvalidData; + } + + if (t.offset > 0) { + file.seekTo(@intCast(t.offset)) catch |err| { + log.warn("failed to seek to offset {}: {}", .{ t.offset, err }); + return error.InvalidData; + }; + } + + var buf: [4096]u8 = undefined; + var buf_reader = file.reader(&buf); + const reader = &buf_reader.interface; + + // Read the file + var managed: std.ArrayList(u8) = .empty; + errdefer managed.deinit(alloc); + const size: usize = if (t.size > 0) @min(t.size, max_size) else max_size; + reader.appendRemaining(alloc, &managed, .limited(size)) catch { + log.warn("failed to read temporary file: {?}", .{buf_reader.err}); + return error.InvalidData; + }; + + // Set our data + assert(self.data.items.len == 0); + self.data = .{ .items = managed.items, .capacity = managed.capacity }; + } + + /// Returns true if path appears to be in a temporary directory. + /// Copies logic from Kitty. + fn isPathInTempDir(path: []const u8) bool { + if (std.mem.startsWith(u8, path, "/tmp")) return true; + if (std.mem.startsWith(u8, path, "/dev/shm")) return true; + if (temp_dir.allocTmpDir(std.heap.page_allocator)) |dir| { + defer temp_dir.freeTmpDir(std.heap.page_allocator, dir); + if (std.mem.startsWith(u8, path, dir)) return true; + + // The temporary dir is sometimes a symlink. On macOS for + // example /tmp is /private/var/... + var buf: [std.fs.max_path_bytes]u8 = undefined; + if (posix.realpath(dir, &buf)) |real_dir| { + if (std.mem.startsWith(u8, path, real_dir)) return true; + } else |_| {} + } + + return false; + } + + pub fn deinit(self: *LoadingImage, alloc: Allocator) void { + self.image.deinit(alloc); + self.data.deinit(alloc); + } + + pub fn destroy(self: *LoadingImage, alloc: Allocator) void { + self.deinit(alloc); + alloc.destroy(self); + } + + /// Adds a chunk of data to the image. Use this if the image + /// is coming in chunks (the "m" parameter in the protocol). + pub fn addData(self: *LoadingImage, alloc: Allocator, data: []const u8) !void { + // If no data, skip + if (data.len == 0) return; + + // If our data would get too big, return an error + if (self.data.items.len + data.len > max_size) { + log.warn("image data too large max_size={}", .{max_size}); + return error.InvalidData; + } + + // Ensure we have enough room to add the data + // to the end of the ArrayList before doing so. + try self.data.ensureUnusedCapacity(alloc, data.len); + + const start_i = self.data.items.len; + self.data.items.len = start_i + data.len; + fastmem.copy(u8, self.data.items[start_i..], data); + } + + /// Complete the chunked image, returning a completed image. + pub fn complete(self: *LoadingImage, alloc: Allocator) !Image { + const img = &self.image; + + // Decompress the data if it is compressed. + try self.decompress(alloc); + + // Decode the png if we have to + if (img.format == .png) try self.decodePng(alloc); + + // Validate our dimensions. + if (img.width == 0 or img.height == 0) return error.DimensionsRequired; + if (img.width > max_dimension or img.height > max_dimension) return error.DimensionsTooLarge; + + // Data length must be what we expect + const bpp = img.format.bpp(); + const expected_len = img.width * img.height * bpp; + const actual_len = self.data.items.len; + if (actual_len != expected_len) { + std.log.warn( + "unexpected length image id={} width={} height={} bpp={} expected_len={} actual_len={}", + .{ img.id, img.width, img.height, bpp, expected_len, actual_len }, + ); + return error.InvalidData; + } + + // Set our time + self.image.transmit_time = std.time.Instant.now() catch |err| { + log.warn("failed to get time: {}", .{err}); + return error.InternalError; + }; + + // Everything looks good, copy the image data over. + var result = self.image; + result.data = try self.data.toOwnedSlice(alloc); + errdefer result.deinit(alloc); + self.image = .{}; + return result; + } + + /// Debug function to write the data to a file. This is useful for + /// capturing some test data for unit tests. + pub fn debugDump(self: LoadingImage) !void { + if (comptime builtin.mode != .Debug) @compileError("debugDump in non-debug"); + + var buf: [1024]u8 = undefined; + const filename = try std.fmt.bufPrint( + &buf, + "image-{s}-{s}-{d}x{d}-{}.data", + .{ + @tagName(self.image.format), + @tagName(self.image.compression), + self.image.width, + self.image.height, + self.image.id, + }, + ); + const cwd = std.fs.cwd(); + const f = try cwd.createFile(filename, .{}); + defer f.close(); + + const writer = f.writer(); + try writer.writeAll(self.data.items); + } + + /// Decompress the data in-place. + fn decompress(self: *LoadingImage, alloc: Allocator) !void { + return switch (self.image.compression) { + .none => {}, + .zlib_deflate => self.decompressZlib(alloc), + }; + } + + fn decompressZlib(self: *LoadingImage, alloc: Allocator) !void { + // Open our zlib stream + var buf: [std.compress.flate.max_window_len]u8 = undefined; + var reader: std.Io.Reader = .fixed(self.data.items); + var stream: std.compress.flate.Decompress = .init(&reader, .zlib, &buf); + + // Write it to an array list + var list: std.ArrayList(u8) = .empty; + errdefer list.deinit(alloc); + stream.reader.appendRemaining(alloc, &list, .limited(max_size)) catch { + log.warn("failed to read decompressed data: {?}", .{stream.err}); + return error.DecompressionFailed; + }; + + // Empty our current data list, take ownership over managed array list + self.data.deinit(alloc); + self.data = .{ .items = list.items, .capacity = list.capacity }; + + // Make sure we note that our image is no longer compressed + self.image.compression = .none; + } + + /// Decode the data as PNG. This will also updated the image dimensions. + fn decodePng(self: *LoadingImage, alloc: Allocator) !void { + assert(self.image.format == .png); + + const result = wuffs.png.decode( + alloc, + self.data.items, + ) catch |err| switch (err) { + error.WuffsError => return error.InvalidData, + error.OutOfMemory => return error.OutOfMemory, + error.Overflow => return error.InvalidData, + }; + defer alloc.free(result.data); + + if (result.data.len > max_size) { + log.warn("png image too large size={} max_size={}", .{ result.data.len, max_size }); + return error.InvalidData; + } + + // Replace our data + self.data.deinit(alloc); + self.data = .{}; + try self.data.ensureUnusedCapacity(alloc, result.data.len); + try self.data.appendSlice(alloc, result.data[0..result.data.len]); + + // Store updated image dimensions + self.image.width = result.width; + self.image.height = result.height; + self.image.format = .rgba; + } +}; + +/// Image represents a single fully loaded image. +pub const Image = struct { + id: u32 = 0, + number: u32 = 0, + width: u32 = 0, + height: u32 = 0, + format: command.Transmission.Format = .rgb, + compression: command.Transmission.Compression = .none, + data: []const u8 = "", + transmit_time: std.time.Instant = undefined, + + /// Set this to true if this image was loaded by a command that + /// doesn't specify an ID or number, since such commands should + /// not be responded to, even though we do currently give them + /// IDs in the public range (which is bad!). + implicit_id: bool = false, + + pub const Error = error{ + InternalError, + InvalidData, + DecompressionFailed, + DimensionsRequired, + DimensionsTooLarge, + FilePathTooLong, + TemporaryFileNotInTempDir, + TemporaryFileNotNamedCorrectly, + UnsupportedFormat, + UnsupportedMedium, + UnsupportedDepth, + }; + + pub fn deinit(self: *Image, alloc: Allocator) void { + if (self.data.len > 0) alloc.free(self.data); + } + + /// Mostly for logging + pub fn withoutData(self: *const Image) Image { + var copy = self.*; + copy.data = ""; + return copy; + } +}; + +/// The rect taken up by some image placement, in grid cells. This will +/// be rounded up to the nearest grid cell since we can't place images +/// in partial grid cells. +pub const Rect = struct { + top_left: PageList.Pin, + bottom_right: PageList.Pin, +}; + +// This specifically tests we ALLOW invalid RGB data because Kitty +// documents that this should work. +test "image load with invalid RGB data" { + const testing = std.testing; + const alloc = testing.allocator; + + // _Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\ + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .width = 1, + .height = 1, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, "AAAA"), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); +} + +test "image load with image too wide" { + const testing = std.testing; + const alloc = testing.allocator; + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .width = max_dimension + 1, + .height = 1, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, "AAAA"), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + try testing.expectError(error.DimensionsTooLarge, loading.complete(alloc)); +} + +test "image load with image too tall" { + const testing = std.testing; + const alloc = testing.allocator; + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .height = max_dimension + 1, + .width = 1, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, "AAAA"), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + try testing.expectError(error.DimensionsTooLarge, loading.complete(alloc)); +} + +test "image load: rgb, zlib compressed, direct" { + const testing = std.testing; + const alloc = testing.allocator; + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .direct, + .compression = .zlib_deflate, + .height = 96, + .width = 128, + .image_id = 31, + } }, + .data = try alloc.dupe( + u8, + @embedFile("testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data"), + ), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + + // should be decompressed + try testing.expect(img.compression == .none); +} + +test "image load: rgb, not compressed, direct" { + const testing = std.testing; + const alloc = testing.allocator; + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .direct, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe( + u8, + @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"), + ), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + + // should be decompressed + try testing.expect(img.compression == .none); +} + +test "image load: rgb, zlib compressed, direct, chunked" { + const testing = std.testing; + const alloc = testing.allocator; + + const data = @embedFile("testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data"); + + // Setup our initial chunk + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .direct, + .compression = .zlib_deflate, + .height = 96, + .width = 128, + .image_id = 31, + .more_chunks = true, + } }, + .data = try alloc.dupe(u8, data[0..1024]), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + + // Read our remaining chunks + var fbs = std.io.fixedBufferStream(data[1024..]); + var buf: [1024]u8 = undefined; + while (fbs.reader().readAll(&buf)) |size| { + try loading.addData(alloc, buf[0..size]); + if (size < buf.len) break; + } else |err| return err; + + // Complete + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); +} + +test "image load: rgb, zlib compressed, direct, chunked with zero initial chunk" { + const testing = std.testing; + const alloc = testing.allocator; + + const data = @embedFile("testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data"); + + // Setup our initial chunk + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .direct, + .compression = .zlib_deflate, + .height = 96, + .width = 128, + .image_id = 31, + .more_chunks = true, + } }, + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + + // Read our remaining chunks + var fbs = std.io.fixedBufferStream(data); + var buf: [1024]u8 = undefined; + while (fbs.reader().readAll(&buf)) |size| { + try loading.addData(alloc, buf[0..size]); + if (size < buf.len) break; + } else |err| return err; + + // Complete + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); +} + +test "image load: temporary file without correct path" { + const testing = std.testing; + const alloc = testing.allocator; + + var tmp_dir = try temp_dir.TempDir.init(); + defer tmp_dir.deinit(); + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(.{ + .sub_path = "image.data", + .data = data, + }); + + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try tmp_dir.dir.realpath("image.data", &buf); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .temporary_file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + try testing.expectError(error.TemporaryFileNotNamedCorrectly, LoadingImage.init(alloc, &cmd)); + + // Temporary file should still be there + try tmp_dir.dir.access(path, .{}); +} + +test "image load: rgb, not compressed, temporary file" { + const testing = std.testing; + const alloc = testing.allocator; + + var tmp_dir = try temp_dir.TempDir.init(); + defer tmp_dir.deinit(); + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(.{ + .sub_path = "tty-graphics-protocol-image.data", + .data = data, + }); + + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try tmp_dir.dir.realpath("tty-graphics-protocol-image.data", &buf); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .temporary_file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); + + // Temporary file should be gone + try testing.expectError(error.FileNotFound, tmp_dir.dir.access(path, .{})); +} + +test "image load: rgb, not compressed, regular file" { + const testing = std.testing; + const alloc = testing.allocator; + + var tmp_dir = try temp_dir.TempDir.init(); + defer tmp_dir.deinit(); + const data = @embedFile("testdata/image-rgb-none-20x15-2147483647-raw.data"); + try tmp_dir.dir.writeFile(.{ + .sub_path = "image.data", + .data = data, + }); + + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try tmp_dir.dir.realpath("image.data", &buf); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .rgb, + .medium = .file, + .compression = .none, + .width = 20, + .height = 15, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); + try tmp_dir.dir.access(path, .{}); +} + +test "image load: png, not compressed, regular file" { + const testing = std.testing; + const alloc = testing.allocator; + + var tmp_dir = try temp_dir.TempDir.init(); + defer tmp_dir.deinit(); + const data = @embedFile("testdata/image-png-none-50x76-2147483647-raw.data"); + try tmp_dir.dir.writeFile(.{ + .sub_path = "tty-graphics-protocol-image.data", + .data = data, + }); + + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try tmp_dir.dir.realpath("tty-graphics-protocol-image.data", &buf); + + var cmd: command.Command = .{ + .control = .{ .transmit = .{ + .format = .png, + .medium = .file, + .compression = .none, + .width = 0, + .height = 0, + .image_id = 31, + } }, + .data = try alloc.dupe(u8, path), + }; + defer cmd.deinit(alloc); + var loading = try LoadingImage.init(alloc, &cmd); + defer loading.deinit(alloc); + var img = try loading.complete(alloc); + defer img.deinit(alloc); + try testing.expect(img.compression == .none); + try testing.expect(img.format == .rgba); + try tmp_dir.dir.access(path, .{}); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_render.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_render.zig new file mode 100644 index 00000000..946b537a --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_render.zig @@ -0,0 +1,27 @@ +const std = @import("std"); +const testing = std.testing; +const terminal = @import("../main.zig"); + +/// A render placement is a way to position a Kitty graphics image onto +/// the screen. It is broken down into the fields that make it easier to +/// position the image using a renderer. +pub const Placement = struct { + /// The top-left corner of the image in grid coordinates. + top_left: terminal.Pin, + + /// The offset in pixels from the top-left corner of the grid cell. + offset_x: u32 = 0, + offset_y: u32 = 0, + + /// The source rectangle of the image to render. This doesn't have to + /// match the size the destination size and the renderer is expected + /// to scale the image to fit the destination size. + source_x: u32 = 0, + source_y: u32 = 0, + source_width: u32 = 0, + source_height: u32 = 0, + + /// The final width/height of the image in pixels. + dest_width: u32 = 0, + dest_height: u32 = 0, +}; diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig new file mode 100644 index 00000000..8ff68e3f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_storage.zig @@ -0,0 +1,1359 @@ +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; + +const terminal = @import("../main.zig"); +const point = @import("../point.zig"); +const size = @import("../size.zig"); +const command = @import("graphics_command.zig"); +const PageList = @import("../PageList.zig"); +const Screen = @import("../Screen.zig"); +const LoadingImage = @import("graphics_image.zig").LoadingImage; +const Image = @import("graphics_image.zig").Image; +const Rect = @import("graphics_image.zig").Rect; +const Command = command.Command; + +const log = std.log.scoped(.kitty_gfx); + +/// An image storage is associated with a terminal screen (i.e. main +/// screen, alt screen) and contains all the transmitted images and +/// placements. +pub const ImageStorage = struct { + const ImageMap = std.AutoHashMapUnmanaged(u32, Image); + const PlacementMap = std.AutoHashMapUnmanaged(PlacementKey, Placement); + + /// Dirty is set to true if placements or images change. This is + /// purely informational for the renderer and doesn't affect the + /// correctness of the program. The renderer must set this to false + /// if it cares about this value. + dirty: bool = false, + + /// This is the next automatically assigned image ID. We start mid-way + /// through the u32 range to avoid collisions with buggy programs. + /// TODO: This isn't good enough, it's perfectly legal for programs + /// to use IDs in the latter half of the range and collisions + /// are not gracefully handled. + next_image_id: u32 = 2147483647, + + /// This is the next automatically assigned placement ID. This is never + /// user-facing so we can start at 0. This is 32-bits because we use + /// the same space for external placement IDs. We can start at zero + /// because any number is valid. + next_internal_placement_id: u32 = 0, + + /// The set of images that are currently known. + images: ImageMap = .{}, + + /// The set of placements for loaded images. + placements: PlacementMap = .{}, + + /// Non-null if there is an in-progress loading image. + loading: ?*LoadingImage = null, + + /// The total bytes of image data that have been loaded and the limit. + /// If the limit is reached, the oldest images will be evicted to make + /// space. Unused images take priority. + total_bytes: usize = 0, + total_limit: usize = 320 * 1000 * 1000, // 320MB + + pub fn deinit( + self: *ImageStorage, + alloc: Allocator, + s: *terminal.Screen, + ) void { + if (self.loading) |loading| loading.destroy(alloc); + + var it = self.images.iterator(); + while (it.next()) |kv| kv.value_ptr.deinit(alloc); + self.images.deinit(alloc); + + self.clearPlacements(s); + self.placements.deinit(alloc); + } + + /// Kitty image protocol is enabled if we have a non-zero limit. + pub fn enabled(self: *const ImageStorage) bool { + return self.total_limit != 0; + } + + /// Sets the limit in bytes for the total amount of image data that + /// can be loaded. If this limit is lower, this will do an eviction + /// if necessary. If the value is zero, then Kitty image protocol will + /// be disabled. + pub fn setLimit( + self: *ImageStorage, + alloc: Allocator, + s: *terminal.Screen, + limit: usize, + ) !void { + // Special case disabling by quickly deleting all + if (limit == 0) { + self.deinit(alloc, s); + self.* = .{}; + } + + // If we re lowering our limit, check if we need to evict. + if (limit < self.total_bytes) { + const req_bytes = self.total_bytes - limit; + log.info("evicting images to lower limit, evicting={}", .{req_bytes}); + if (!try self.evictImage(alloc, req_bytes)) { + log.warn("failed to evict enough images for required bytes", .{}); + } + } + + self.total_limit = limit; + } + + /// Add an already-loaded image to the storage. This will automatically + /// free any existing image with the same ID. + pub fn addImage(self: *ImageStorage, alloc: Allocator, img: Image) Allocator.Error!void { + // If the image itself is over the limit, then error immediately + if (img.data.len > self.total_limit) return error.OutOfMemory; + + // If this would put us over the limit, then evict. + const total_bytes = self.total_bytes + img.data.len; + if (total_bytes > self.total_limit) { + const req_bytes = total_bytes - self.total_limit; + log.info("evicting images to make space for {} bytes", .{req_bytes}); + if (!try self.evictImage(alloc, req_bytes)) { + log.warn("failed to evict enough images for required bytes", .{}); + return error.OutOfMemory; + } + } + + // Do the gop op first so if it fails we don't get a partial state + const gop = try self.images.getOrPut(alloc, img.id); + + log.debug("addImage image={}", .{img: { + var copy = img; + copy.data = ""; + break :img copy; + }}); + + // Write our new image + if (gop.found_existing) { + self.total_bytes -= gop.value_ptr.data.len; + gop.value_ptr.deinit(alloc); + } + + gop.value_ptr.* = img; + self.total_bytes += img.data.len; + + self.dirty = true; + } + + /// Add a placement for a given image. The caller must verify in advance + /// the image exists to prevent memory corruption. + pub fn addPlacement( + self: *ImageStorage, + alloc: Allocator, + image_id: u32, + placement_id: u32, + p: Placement, + ) !void { + assert(self.images.get(image_id) != null); + log.debug("placement image_id={} placement_id={} placement={}\n", .{ + image_id, + placement_id, + p, + }); + + // The important piece here is that the placement ID needs to + // be marked internal if it is zero. This allows multiple placements + // to be added for the same image. If it is non-zero, then it is + // an external placement ID and we can only have one placement + // per (image id, placement id) pair. + const key: PlacementKey = .{ + .image_id = image_id, + .placement_id = if (placement_id == 0) .{ + .tag = .internal, + .id = id: { + defer self.next_internal_placement_id +%= 1; + break :id self.next_internal_placement_id; + }, + } else .{ + .tag = .external, + .id = placement_id, + }, + }; + + const gop = try self.placements.getOrPut(alloc, key); + gop.value_ptr.* = p; + + self.dirty = true; + } + + fn clearPlacements(self: *ImageStorage, s: *terminal.Screen) void { + var it = self.placements.iterator(); + while (it.next()) |entry| entry.value_ptr.deinit(s); + self.placements.clearRetainingCapacity(); + } + + /// Get an image by its ID. If the image doesn't exist, null is returned. + pub fn imageById(self: *const ImageStorage, image_id: u32) ?Image { + return self.images.get(image_id); + } + + /// Get an image by its number. If the image doesn't exist, return null. + pub fn imageByNumber(self: *const ImageStorage, image_number: u32) ?Image { + var newest: ?Image = null; + + var it = self.images.iterator(); + while (it.next()) |kv| { + if (kv.value_ptr.number == image_number) { + if (newest == null or + kv.value_ptr.transmit_time.order(newest.?.transmit_time) == .gt) + { + newest = kv.value_ptr.*; + } + } + } + + return newest; + } + + /// Delete placements, images. + pub fn delete( + self: *ImageStorage, + alloc: Allocator, + t: *terminal.Terminal, + cmd: command.Delete, + ) void { + switch (cmd) { + .all => |delete_images| { + var it = self.placements.iterator(); + while (it.next()) |entry| { + // Skip virtual placements + switch (entry.value_ptr.location) { + .pin => {}, + .virtual => continue, + } + + // Deinit the placement and remove it + const image_id = entry.key_ptr.image_id; + entry.value_ptr.deinit(t.screens.active); + self.placements.removeByPtr(entry.key_ptr); + if (delete_images) self.deleteIfUnused(alloc, image_id); + } + + if (delete_images) { + var image_it = self.images.iterator(); + while (image_it.next()) |kv| self.deleteIfUnused(alloc, kv.key_ptr.*); + } + + self.dirty = true; + }, + + .id => |v| self.deleteById( + alloc, + t.screens.active, + v.image_id, + v.placement_id, + v.delete, + ), + + .newest => |v| newest: { + const img = self.imageByNumber(v.image_number) orelse break :newest; + self.deleteById( + alloc, + t.screens.active, + img.id, + v.placement_id, + v.delete, + ); + }, + + .intersect_cursor => |delete_images| { + self.deleteIntersecting( + alloc, + t, + .{ .active = .{ + .x = t.screens.active.cursor.x, + .y = t.screens.active.cursor.y, + } }, + delete_images, + {}, + null, + ); + }, + + .intersect_cell => |v| intersect_cell: { + if (v.x <= 0 or v.y <= 0) { + log.warn("delete intersect cell coords must be at least 1", .{}); + break :intersect_cell; + } + + self.deleteIntersecting( + alloc, + t, + .{ .active = .{ + .x = std.math.cast(size.CellCountInt, v.x - 1) orelse break :intersect_cell, + .y = std.math.cast(size.CellCountInt, v.y - 1) orelse break :intersect_cell, + } }, + v.delete, + {}, + null, + ); + }, + + .intersect_cell_z => |v| intersect_cell_z: { + if (v.x <= 0 or v.y <= 0) { + log.warn("delete intersect cell coords must be at least 1", .{}); + break :intersect_cell_z; + } + + self.deleteIntersecting( + alloc, + t, + .{ .active = .{ + .x = std.math.cast(size.CellCountInt, v.x - 1) orelse break :intersect_cell_z, + .y = std.math.cast(size.CellCountInt, v.y - 1) orelse break :intersect_cell_z, + } }, + v.delete, + v.z, + struct { + fn filter(ctx: i32, p: Placement) bool { + return p.z == ctx; + } + }.filter, + ); + }, + + .column => |v| column: { + if (v.x <= 0) { + log.warn("delete column must be greater than zero", .{}); + break :column; + } + + const x = v.x - 1; + var it = self.placements.iterator(); + while (it.next()) |entry| { + const img = self.imageById(entry.key_ptr.image_id) orelse continue; + const rect = entry.value_ptr.rect(img, t) orelse continue; + if (rect.top_left.x <= x and rect.bottom_right.x >= x) { + entry.value_ptr.deinit(t.screens.active); + self.placements.removeByPtr(entry.key_ptr); + if (v.delete) self.deleteIfUnused(alloc, img.id); + } + } + + // Mark dirty to force redraw + self.dirty = true; + }, + + .row => |v| row: { + if (v.y <= 0) { + log.warn("delete row must be greater than zero", .{}); + break :row; + } + + // v.y is in active coords so we want to convert it to a pin + // so we can compare by page offsets. + const target_pin = t.screens.active.pages.pin(.{ .active = .{ + .y = std.math.cast(size.CellCountInt, v.y - 1) orelse break :row, + } }) orelse break :row; + + var it = self.placements.iterator(); + while (it.next()) |entry| { + const img = self.imageById(entry.key_ptr.image_id) orelse continue; + const rect = entry.value_ptr.rect(img, t) orelse continue; + + // We need to copy our pin to ensure we are at least at + // the top-left x. + var target_pin_copy = target_pin; + target_pin_copy.x = rect.top_left.x; + if (target_pin_copy.isBetween(rect.top_left, rect.bottom_right)) { + entry.value_ptr.deinit(t.screens.active); + self.placements.removeByPtr(entry.key_ptr); + if (v.delete) self.deleteIfUnused(alloc, img.id); + } + } + + // Mark dirty to force redraw + self.dirty = true; + }, + + .z => |v| { + var it = self.placements.iterator(); + while (it.next()) |entry| { + switch (entry.value_ptr.location) { + .pin => {}, + + // Virtual placeholders cannot delete by z according + // to the spec. + .virtual => continue, + } + + if (entry.value_ptr.z == v.z) { + const image_id = entry.key_ptr.image_id; + entry.value_ptr.deinit(t.screens.active); + self.placements.removeByPtr(entry.key_ptr); + if (v.delete) self.deleteIfUnused(alloc, image_id); + } + } + + // Mark dirty to force redraw + self.dirty = true; + }, + + .range => |v| range: { + if (v.first <= 0 or v.last <= 0) { + log.warn("delete range values must be greater than zero", .{}); + break :range; + } + if (v.first > v.last) { + log.warn("delete range 'x' ({}) must be less than or equal to 'y' ({})", .{ v.first, v.last }); + break :range; + } + + var it = self.placements.iterator(); + while (it.next()) |entry| { + if (entry.key_ptr.image_id >= v.first or entry.key_ptr.image_id <= v.last) { + const image_id = entry.key_ptr.image_id; + entry.value_ptr.deinit(t.screens.active); + self.placements.removeByPtr(entry.key_ptr); + if (v.delete) self.deleteIfUnused(alloc, image_id); + } + } + + // Mark dirty to force redraw + self.dirty = true; + }, + + // We don't support animation frames yet so they are successfully + // deleted! + .animation_frames => {}, + } + } + + fn deleteById( + self: *ImageStorage, + alloc: Allocator, + s: *terminal.Screen, + image_id: u32, + placement_id: u32, + delete_unused: bool, + ) void { + // If no placement, we delete all placements with the ID + if (placement_id == 0) { + var it = self.placements.iterator(); + while (it.next()) |entry| { + if (entry.key_ptr.image_id == image_id) { + entry.value_ptr.deinit(s); + self.placements.removeByPtr(entry.key_ptr); + } + } + } else { + if (self.placements.getEntry(.{ + .image_id = image_id, + .placement_id = .{ .tag = .external, .id = placement_id }, + })) |entry| { + entry.value_ptr.deinit(s); + self.placements.removeByPtr(entry.key_ptr); + } + } + + // If this is specified, then we also delete the image + // if it is no longer in use. + if (delete_unused) self.deleteIfUnused(alloc, image_id); + + // Mark dirty to force redraw + self.dirty = true; + } + + /// Delete an image if it is unused. + fn deleteIfUnused(self: *ImageStorage, alloc: Allocator, image_id: u32) void { + var it = self.placements.iterator(); + while (it.next()) |kv| { + if (kv.key_ptr.image_id == image_id) { + return; + } + } + + // If we get here, we can delete the image. + if (self.images.getEntry(image_id)) |entry| { + self.total_bytes -= entry.value_ptr.data.len; + entry.value_ptr.deinit(alloc); + self.images.removeByPtr(entry.key_ptr); + } + } + + /// Deletes all placements intersecting a screen point. + fn deleteIntersecting( + self: *ImageStorage, + alloc: Allocator, + t: *terminal.Terminal, + p: point.Point, + delete_unused: bool, + filter_ctx: anytype, + comptime filter: ?fn (@TypeOf(filter_ctx), Placement) bool, + ) void { + // Convert our target point to a pin for comparison. + const target_pin = t.screens.active.pages.pin(p) orelse return; + + var it = self.placements.iterator(); + while (it.next()) |entry| { + const img = self.imageById(entry.key_ptr.image_id) orelse continue; + const rect = entry.value_ptr.rect(img, t) orelse continue; + if (target_pin.isBetween(rect.top_left, rect.bottom_right)) { + if (filter) |f| if (!f(filter_ctx, entry.value_ptr.*)) continue; + entry.value_ptr.deinit(t.screens.active); + self.placements.removeByPtr(entry.key_ptr); + if (delete_unused) self.deleteIfUnused(alloc, img.id); + } + } + + // Mark dirty to force redraw + self.dirty = true; + } + + /// Evict image to make space. This will evict the oldest image, + /// prioritizing unused images first, as recommended by the published + /// Kitty spec. + /// + /// This will evict as many images as necessary to make space for + /// req bytes. + fn evictImage(self: *ImageStorage, alloc: Allocator, req: usize) !bool { + assert(req <= self.total_limit); + + // Ironically we allocate to evict. We should probably redesign the + // data structures to avoid this but for now allocating a little + // bit is fine compared to the megabytes we're looking to save. + const Candidate = struct { + id: u32, + time: std.time.Instant, + used: bool, + }; + + var candidates: std.ArrayList(Candidate) = .empty; + defer candidates.deinit(alloc); + + var it = self.images.iterator(); + while (it.next()) |kv| { + const img = kv.value_ptr; + + // This is a huge waste. See comment above about redesigning + // our data structures to avoid this. Eviction should be very + // rare though and we never have that many images/placements + // so hopefully this will last a long time. + const used = used: { + var p_it = self.placements.iterator(); + while (p_it.next()) |p_kv| { + if (p_kv.key_ptr.image_id == img.id) { + break :used true; + } + } + + break :used false; + }; + + try candidates.append(alloc, .{ + .id = img.id, + .time = img.transmit_time, + .used = used, + }); + } + + // Sort + std.mem.sortUnstable( + Candidate, + candidates.items, + {}, + struct { + fn lessThan( + ctx: void, + lhs: Candidate, + rhs: Candidate, + ) bool { + _ = ctx; + + // If they're usage matches, then its based on time. + if (lhs.used == rhs.used) return switch (lhs.time.order(rhs.time)) { + .lt => true, + .gt => false, + .eq => lhs.id < rhs.id, + }; + + // If not used, then its a better candidate + return !lhs.used; + } + }.lessThan, + ); + + // They're in order of best to evict. + var evicted: usize = 0; + for (candidates.items) |c| { + // Delete all the placements for this image and the image. + var p_it = self.placements.iterator(); + while (p_it.next()) |entry| { + if (entry.key_ptr.image_id == c.id) { + self.placements.removeByPtr(entry.key_ptr); + } + } + + if (self.images.getEntry(c.id)) |entry| { + log.info("evicting image id={} bytes={}", .{ c.id, entry.value_ptr.data.len }); + + evicted += entry.value_ptr.data.len; + self.total_bytes -= entry.value_ptr.data.len; + + entry.value_ptr.deinit(alloc); + self.images.removeByPtr(entry.key_ptr); + + if (evicted > req) return true; + } + } + + return false; + } + + /// Every placement is uniquely identified by the image ID and the + /// placement ID. If an image ID isn't specified it is assumed to be 0. + /// Likewise, if a placement ID isn't specified it is assumed to be 0. + pub const PlacementKey = struct { + image_id: u32, + placement_id: packed struct { + tag: enum(u1) { internal, external }, + id: u32, + }, + }; + + pub const Placement = struct { + /// The location where this placement should be drawn. + location: Location, + + /// Offset of the x/y from the top-left of the cell. + x_offset: u32 = 0, + y_offset: u32 = 0, + + /// Source rectangle for the image to pull from + source_x: u32 = 0, + source_y: u32 = 0, + source_width: u32 = 0, + source_height: u32 = 0, + + /// The columns/rows this image occupies. + columns: u32 = 0, + rows: u32 = 0, + + /// The z-index for this placement. + z: i32 = 0, + + pub const Location = union(enum) { + /// Exactly placed on a screen pin. + pin: *PageList.Pin, + + /// Virtual placement (U=1) for unicode placeholders. + virtual: void, + }; + + pub fn deinit( + self: *const Placement, + s: *terminal.Screen, + ) void { + switch (self.location) { + .pin => |p| s.pages.untrackPin(p), + .virtual => {}, + } + } + + /// Calculates the size of this placement's image in pixels, + /// taking in to account the specified rows and columns. + pub fn calculatedSize( + self: Placement, + image: Image, + t: *const terminal.Terminal, + ) struct { + width: u32, + height: u32, + } { + // Height / width of the image in px. + const width = if (self.source_width > 0) self.source_width else image.width; + const height = if (self.source_height > 0) self.source_height else image.height; + + // If we don't have any specified cols or rows then the placement + // should be the native size of the image, and doesn't need to be + // re-scaled. + if (self.columns == 0 and self.rows == 0) return .{ + .width = width, + .height = height, + }; + + // We calculate the size of a cell so that we can multiply + // it by the specified cols/rows to get the correct px size. + // + // We assume that the width is divided evenly by the column + // count and the height by the row count, because it should be. + const cell_width: u32 = t.width_px / t.cols; + const cell_height: u32 = t.height_px / t.rows; + + const width_f64: f64 = @floatFromInt(width); + const height_f64: f64 = @floatFromInt(height); + + // If we have a specified cols AND rows then we calculate + // the width and height from them directly, we don't need + // to adjust for aspect ratio. + if (self.columns > 0 and self.rows > 0) { + const calc_width = cell_width * self.columns; + const calc_height = cell_height * self.rows; + + return .{ + .width = calc_width, + .height = calc_height, + }; + } + + // Either the columns or the rows were specified, but not both, + // so we need to calculate the other one based on the aspect ratio. + + // If only the columns were specified, we determine + // the height of the image based on the aspect ratio. + if (self.columns > 0) { + const aspect = height_f64 / width_f64; + const calc_width: u32 = cell_width * self.columns; + const calc_height: u32 = @intFromFloat(@round( + @as(f64, @floatFromInt(calc_width)) * aspect, + )); + + return .{ + .width = calc_width, + .height = calc_height, + }; + } + + // Otherwise, only the rows were specified, so we + // determine the width based on the aspect ratio. + { + const aspect = width_f64 / height_f64; + const calc_height: u32 = cell_height * self.rows; + const calc_width: u32 = @intFromFloat(@round( + @as(f64, @floatFromInt(calc_height)) * aspect, + )); + + return .{ + .width = calc_width, + .height = calc_height, + }; + } + } + + /// Returns the size in grid cells that this placement takes up. + pub fn gridSize( + self: Placement, + image: Image, + t: *const terminal.Terminal, + ) struct { + cols: u32, + rows: u32, + } { + // If we have a specified columns and rows then this is trivial. + if (self.columns > 0 and self.rows > 0) return .{ + .cols = self.columns, + .rows = self.rows, + }; + + // Otherwise we calculate the pixel size, divide by + // cell size, and round up to the nearest integer. + const calc_size = self.calculatedSize(image, t); + return .{ + .cols = std.math.divCeil( + u32, + calc_size.width + self.x_offset, + t.width_px / t.cols, + ) catch 0, + .rows = std.math.divCeil( + u32, + calc_size.height + self.y_offset, + t.height_px / t.rows, + ) catch 0, + }; + // NOTE: Above `divCeil`s can only fail if the cell size is 0, + // in such a case it seems safe to return 0 for this. + } + + /// Returns a selection of the entire rectangle this placement + /// occupies within the screen. This can return null if the placement + /// doesn't have an associated rect (i.e. a virtual placement). + pub fn rect( + self: Placement, + image: Image, + t: *const terminal.Terminal, + ) ?Rect { + const grid_size = self.gridSize(image, t); + const pin = switch (self.location) { + .pin => |p| p, + .virtual => return null, + }; + + var br = switch (pin.downOverflow(grid_size.rows - 1)) { + .offset => |v| v, + .overflow => |v| v.end, + }; + br.x = @min( + // We need to sub one here because the x value is + // one width already. So if the image is width "1" + // then we add zero to X because X itself is width 1. + pin.x + (grid_size.cols - 1), + t.cols - 1, + ); + + return .{ + .top_left = pin.*, + .bottom_right = br, + }; + } + }; +}; + +// Our pin for the placement +fn trackPin( + t: *terminal.Terminal, + pt: point.Coordinate, +) !*PageList.Pin { + return try t.screens.active.pages.trackPin(t.screens.active.pages.pin(.{ + .active = pt, + }).?); +} + +test "storage: add placement with zero placement id" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(alloc, 1, 0, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + try s.addPlacement(alloc, 1, 0, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + + try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expectEqual(@as(usize, 2), s.images.count()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .internal, .id = 0 }, + }) != null); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .internal, .id = 1 }, + }) != null); +} + +test "storage: delete all placements and images" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .all = true }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete all placements and images preserves limit" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + s.total_limit = 5000; + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .all = true }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 0), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(@as(usize, 5000), s.total_limit); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete all placements" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .all = false }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete all placements by image id" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .id = .{ .image_id = 2 } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete all placements by image id and unused images" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .id = .{ .delete = true, .image_id = 2 } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete placement by specific id" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .id = .{ + .delete = true, + .image_id = 1, + .placement_id = 2, + } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(tracked + 2, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete intersecting cursor" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + + t.screens.active.cursorAbsolute(12, 12); + + s.dirty = false; + s.delete(alloc, &t, .{ .intersect_cursor = false }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }) != null); +} + +test "storage: delete intersecting cursor plus unused" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + + t.screens.active.cursorAbsolute(12, 12); + + s.dirty = false; + s.delete(alloc, &t, .{ .intersect_cursor = true }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 2 }, + }) != null); +} + +test "storage: delete intersecting cursor hits multiple" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + + t.screens.active.cursorAbsolute(26, 26); + + s.dirty = false; + s.delete(alloc, &t, .{ .intersect_cursor = true }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete by column" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .column = .{ + .delete = false, + .x = 60, + } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); +} + +test "storage: delete by column 1x1" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 3, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 2, .y = 0 }) } }); + + s.delete(alloc, &t, .{ .column = .{ + .delete = false, + .x = 2, + } }); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expectEqual(@as(usize, 1), s.images.count()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 3 }, + }) != null); +} + +test "storage: delete by row" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 50, .height = 50 }); + try s.addImage(alloc, .{ .id = 2, .width = 25, .height = 25 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 0, .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 25, .y = 25 }) } }); + + s.dirty = false; + s.delete(alloc, &t, .{ .row = .{ + .delete = false, + .y = 60, + } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.placements.count()); + try testing.expectEqual(@as(usize, 2), s.images.count()); + try testing.expectEqual(tracked + 1, t.screens.active.pages.countTrackedPins()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); +} + +test "storage: delete by row 1x1" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 100, .cols = 100 }); + defer t.deinit(alloc); + t.width_px = 100; + t.height_px = 100; + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1, .width = 1, .height = 1 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 0 }) } }); + try s.addPlacement(alloc, 1, 2, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 1 }) } }); + try s.addPlacement(alloc, 1, 3, .{ .location = .{ .pin = try trackPin(&t, .{ .y = 2 }) } }); + + s.delete(alloc, &t, .{ .row = .{ + .delete = false, + .y = 2, + } }); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + try testing.expectEqual(@as(usize, 1), s.images.count()); + + // verify the placement is what we expect + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 1 }, + }) != null); + try testing.expect(s.placements.get(.{ + .image_id = 1, + .placement_id = .{ .tag = .external, .id = 3 }, + }) != null); +} + +test "storage: delete images by range 1" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + s.dirty = false; + s.delete(alloc, &t, .{ .range = .{ .delete = false, .first = 1, .last = 2 } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete images by range 2" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + s.dirty = false; + s.delete(alloc, &t, .{ .range = .{ .delete = true, .first = 1, .last = 2 } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete images by range 3" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + s.dirty = false; + s.delete(alloc, &t, .{ .range = .{ .delete = false, .first = 1, .last = 1 } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: delete images by range 4" { + const testing = std.testing; + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 3, .cols = 3 }); + defer t.deinit(alloc); + const tracked = t.screens.active.pages.countTrackedPins(); + + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + try s.addImage(alloc, .{ .id = 1 }); + try s.addImage(alloc, .{ .id = 2 }); + try s.addImage(alloc, .{ .id = 3 }); + try s.addPlacement(alloc, 1, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try s.addPlacement(alloc, 2, 1, .{ .location = .{ .pin = try trackPin(&t, .{ .x = 1, .y = 1 }) } }); + try testing.expectEqual(@as(usize, 3), s.images.count()); + try testing.expectEqual(@as(usize, 2), s.placements.count()); + + s.dirty = false; + s.delete(alloc, &t, .{ .range = .{ .delete = true, .first = 1, .last = 1 } }); + try testing.expect(s.dirty); + try testing.expectEqual(@as(usize, 1), s.images.count()); + try testing.expectEqual(@as(usize, 0), s.placements.count()); + try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins()); +} + +test "storage: aspect ratio calculation when only columns or rows specified" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + defer t.deinit(alloc); + t.width_px = 1000; // 10 px per col + t.height_px = 2000; // 20 px per row + + // Case 1: Only columns specified + { + const image = Image{ .id = 1, .width = 16, .height = 9 }; + var placement = ImageStorage.Placement{ + .location = .{ .virtual = {} }, + .columns = 10, + .rows = 0, + }; + + // Image is 16x9, set to a width of 10 columns, at 10px per column + // that's 100px width. 100px * (9 / 16) = 56.25, which should round + // to a height of 56px. + + const calc_size = placement.calculatedSize(image, &t); + try testing.expectEqual(@as(u32, 100), calc_size.width); + try testing.expectEqual(@as(u32, 56), calc_size.height); + } + + // Case 2: Only rows specified + { + const image = Image{ .id = 2, .width = 16, .height = 9 }; + var placement = ImageStorage.Placement{ + .location = .{ .virtual = {} }, + .columns = 0, + .rows = 5, + }; + + // Image is 16x9, set to a height of 5 rows, at 20px per row that's + // 100px height. 100px * (16 / 9) = 177.77..., which should round to + // a width of 178px. + + const calc_size = placement.calculatedSize(image, &t); + try testing.expectEqual(@as(u32, 178), calc_size.width); + try testing.expectEqual(@as(u32, 100), calc_size.height); + } +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig b/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig new file mode 100644 index 00000000..a223797b --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/graphics_unicode.zig @@ -0,0 +1,1347 @@ +//! This file contains various logic and data for working with the +//! Kitty graphics protocol unicode placeholder, virtual placement feature. + +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const testing = std.testing; +const terminal = @import("../main.zig"); +const kitty_gfx = terminal.kitty.graphics; +const Image = kitty_gfx.Image; +const ImageStorage = kitty_gfx.ImageStorage; +const RenderPlacement = kitty_gfx.RenderPlacement; + +const log = std.log.scoped(.kitty_gfx); + +/// Codepoint for the unicode placeholder character. +pub const placeholder: u21 = 0x10EEEE; + +/// Returns an iterator that iterates over all of the virtual placements +/// in the given pin. If `limit` is provided, the iterator will stop +/// when it reaches that pin (inclusive). If `limit` is not provided, +/// the iterator will continue until the end of the page list. +pub fn placementIterator( + pin: terminal.Pin, + limit: ?terminal.Pin, +) PlacementIterator { + var row_it = pin.rowIterator(.right_down, limit); + const row = row_it.next(); + return .{ .row_it = row_it, .row = row }; +} + +/// Iterator over unicode virtual placements. +pub const PlacementIterator = struct { + row_it: terminal.PageList.RowIterator, + row: ?terminal.Pin, + + pub fn next(self: *PlacementIterator) ?Placement { + while (self.row) |*row| { + // This row flag is set on rows that have the virtual placeholder + if (!row.rowAndCell().row.kitty_virtual_placeholder) { + self.row = self.row_it.next(); + continue; + } + + // Our current run. A run is always only a single row. This + // assumption is built-in to our logic so if we want to change + // this later we have to redo the logic; tests should cover; + var run: ?IncompletePlacement = null; + + // Iterate over our remaining cells and find one with a placeholder. + const cells = row.cells(.right); + for (cells, row.x..) |*cell, x| { + // "row" now points to the top-left pin of the placement. + // We need this temporary state to build our incomplete + // placement. + assert(@intFromPtr(row) == @intFromPtr(&self.row)); + row.x = @intCast(x); + + // If this cell doesn't have the placeholder, then we + // complete the run if we have it otherwise we just move + // on and keep searching. + if (cell.codepoint() != placeholder) { + if (run) |prev| return prev.complete(); + continue; + } + + // If we don't have a previous run, then we save this + // incomplete one, start a run, and move on. + const curr = IncompletePlacement.init(row, cell); + if (run) |*prev| { + // If we can't append, then we complete the previous + // run and return it. + if (!prev.append(&curr)) { + // Note: self.row is already updated due to the + // row pointer above. It points back at this same + // cell so we can continue the new placements from + // here. + return prev.complete(); + } + + // append is mutating so if we reached this point + // then prev has been updated. + } else { + // For appending, we need to set our initial values. + var prev = curr; + if (prev.row == null) prev.row = 0; + if (prev.col == null) prev.col = 0; + run = prev; + } + } + + // We move to the next row no matter what + self.row = self.row_it.next(); + + // If we have a run, we complete it here. + if (run) |prev| return prev.complete(); + } + + return null; + } +}; + +/// A virtual placement in the terminal. This can represent more than +/// one cell if the cells combine to be a run. +pub const Placement = struct { + /// The top-left pin of the placement. This can be used to get the + /// screen x/y. + pin: terminal.Pin, + + /// The image ID and placement ID for this virtual placement. The + /// image ID is encoded in the fg color (plus optional a 8-bit high + /// value in the 3rd diacritic). The placement ID is encoded in the + /// underline color (optionally). + image_id: u32, + placement_id: u32, + + /// Starting row/col index for the image itself. This is the "fragment" + /// of the image we want to show in this placement. This is 0-indexed. + col: u32, + row: u32, + + /// The width/height in cells of this placement. + width: u32, + height: u32, + + pub const Error = error{ + PlacementGridOutOfBounds, + PlacementMissingPlacement, + }; + + /// Take this virtual placement and convert it to a render placement. + pub fn renderPlacement( + self: *const Placement, + storage: *const ImageStorage, + img: *const Image, + cell_width: u32, + cell_height: u32, + ) Error!RenderPlacement { + // In this function, there is a variable naming convention to try + // to make it slightly less confusing. The prefix will tell you what + // coordinate/size space a variable lives in: + // - img_* is for the original image + // - p_* is for the final placement + // - vp_* is for the virtual placement + + // Determine the grid size that this virtual placement fits into. + const p_grid = try self.grid(storage, img, cell_width, cell_height); + + // From here on out we switch to floating point math. These are + // constants that we'll reference repeatedly. + const img_width_f64: f64 = @floatFromInt(img.width); + const img_height_f64: f64 = @floatFromInt(img.height); + + // Next we have to fit the source image into the grid size while preserving + // aspect ratio. We will center the image horizontally/vertically if + // necessary. + const p_scale: struct { + /// The offsets are pixels from the top-left of the placement-sized + /// image in order to center the image as necessary. + x_offset: f64 = 0, + y_offset: f64 = 0, + + /// The multipliers to apply to the width/height of the original + /// image size in order to reach the placement size. + x_scale: f64 = 0, + y_scale: f64 = 0, + } = scale: { + const p_rows_px: f64 = @floatFromInt(p_grid.rows * cell_height); + const p_cols_px: f64 = @floatFromInt(p_grid.columns * cell_width); + if (img_width_f64 * p_rows_px > img_height_f64 * p_cols_px) { + // Image is wider than the grid, fit width and center height + const x_scale = p_cols_px / @max(img_width_f64, 1); + const y_scale = x_scale; + const y_offset = (p_rows_px - img_height_f64 * y_scale) / 2; + break :scale .{ + .x_scale = x_scale, + .y_scale = y_scale, + .y_offset = y_offset, + }; + } else { + // Image is taller than the grid, fit height and center width + const y_scale = p_rows_px / @max(img_height_f64, 1); + const x_scale = y_scale; + const x_offset = (p_cols_px - img_width_f64 * x_scale) / 2; + break :scale .{ + .x_scale = x_scale, + .y_scale = y_scale, + .x_offset = x_offset, + }; + } + }; + + // Scale our original image according to the aspect ratio + // and padding calculated for p_scale. + const img_scaled: struct { + x_offset: f64, + y_offset: f64, + width: f64, + height: f64, + } = scale: { + const x_offset: f64 = p_scale.x_offset / p_scale.x_scale; + const y_offset: f64 = p_scale.y_offset / p_scale.y_scale; + const width: f64 = img_width_f64 + (x_offset * 2); + const height: f64 = img_height_f64 + (y_offset * 2); + break :scale .{ + .x_offset = x_offset, + .y_offset = y_offset, + .width = width, + .height = height, + }; + }; + + // Calculate the source rectangle for the scaled image. These + // coordinates are in the scaled image space. + var img_scale_source: struct { + x: f64, + y: f64, + width: f64, + height: f64, + } = source: { + // Float-converted values we already have + const vp_width: f64 = @floatFromInt(self.width); + const vp_height: f64 = @floatFromInt(self.height); + const vp_col: f64 = @floatFromInt(self.col); + const vp_row: f64 = @floatFromInt(self.row); + const p_grid_cols: f64 = @floatFromInt(p_grid.columns); + const p_grid_rows: f64 = @floatFromInt(p_grid.rows); + + // Calculate the scaled source rectangle for the image, undoing + // the aspect ratio scaling as necessary. + const width: f64 = img_scaled.width * (vp_width / p_grid_cols); + const height: f64 = img_scaled.height * (vp_height / p_grid_rows); + const x: f64 = img_scaled.width * (vp_col / p_grid_cols); + const y: f64 = img_scaled.height * (vp_row / p_grid_rows); + + break :source .{ + .width = width, + .height = height, + .x = x, + .y = y, + }; + }; + + // The destination rectangle. The x/y is specified by offsets from + // the top-left since that's how our RenderPlacement works. + const p_dest: struct { + x_offset: f64, + y_offset: f64, + width: f64, + height: f64, + } = dest: { + var x_offset: f64 = 0; + var y_offset: f64 = 0; + var width: f64 = @floatFromInt(self.width * cell_width); + var height: f64 = @floatFromInt(self.height * cell_height); + + if (img_scale_source.y < img_scaled.y_offset) { + // If our source rect y is within the offset area, we need to + // adjust our source rect and destination since the source texture + // doesn't actually have the offset area blank. + const offset: f64 = img_scaled.y_offset - img_scale_source.y; + img_scale_source.height -= offset; + y_offset = offset; + height -= offset * p_scale.y_scale; + img_scale_source.y = 0; + + // If our height is greater than our original height, + // bring it back down. This addresses the case where the top + // and bottom offsets are both used. + if (img_scale_source.height > img_height_f64) { + img_scale_source.height = img_height_f64; + height = img_height_f64 * p_scale.y_scale; + } + } else if (img_scale_source.y + img_scale_source.height > + img_scaled.height - img_scaled.y_offset) + { + // if our y is in our bottom offset area, we need to shorten the + // source to fit in the cell. + img_scale_source.y -= img_scaled.y_offset; + img_scale_source.height = img_scaled.height - img_scaled.y_offset - img_scale_source.y; + img_scale_source.height -= img_scaled.y_offset; + height = img_scale_source.height * p_scale.y_scale; + } else { + img_scale_source.y -= img_scaled.y_offset; + } + + if (img_scale_source.x < img_scaled.x_offset) { + // If our source rect x is within the offset area, we need to + // adjust our source rect and destination since the source texture + // doesn't actually have the offset area blank. + const offset: f64 = img_scaled.x_offset - img_scale_source.x; + img_scale_source.width -= offset; + x_offset = offset; + width -= offset * p_scale.x_scale; + img_scale_source.x = 0; + + // If our width is greater than our original width, + // bring it back down. This addresses the case where the left + // and right offsets are both used. + if (img_scale_source.width > img_width_f64) { + img_scale_source.width = img_width_f64; + width = img_width_f64 * p_scale.x_scale; + } + } else if (img_scale_source.x + img_scale_source.width > + img_scaled.width - img_scaled.x_offset) + { + // if our x is in our right offset area, we need to shorten the + // source to fit in the cell. + img_scale_source.x -= img_scaled.x_offset; + img_scale_source.width = img_scaled.width - img_scaled.x_offset - img_scale_source.x; + img_scale_source.width -= img_scaled.x_offset; + width = img_scale_source.width * p_scale.x_scale; + } else { + img_scale_source.x -= img_scaled.x_offset; + } + + // If our modified source width/height is less than zero then + // we render nothing because it means we're rendering outside + // of the visible image. + if (img_scale_source.width <= 0 or img_scale_source.height <= 0) { + return .{ .top_left = self.pin }; + } + + break :dest .{ + .x_offset = x_offset * p_scale.x_scale, + .y_offset = y_offset * p_scale.y_scale, + .width = width, + .height = height, + }; + }; + // log.warn("img_width={} img_height={}\np_grid={}\np_scale={}\nimg_scaled={}\nimg_scale_source={}\np_dest={}\n", .{ + // img_width_f64, + // img_height_f64, + // p_grid, + // p_scale, + // img_scaled, + // img_scale_source, + // p_dest, + // }); + + return .{ + .top_left = self.pin, + .offset_x = @intFromFloat(@round(p_dest.x_offset)), + .offset_y = @intFromFloat(@round(p_dest.y_offset)), + .source_x = @intFromFloat(@round(img_scale_source.x)), + .source_y = @intFromFloat(@round(img_scale_source.y)), + .source_width = @intFromFloat(@round(img_scale_source.width)), + .source_height = @intFromFloat(@round(img_scale_source.height)), + .dest_width = @intFromFloat(@round(p_dest.width)), + .dest_height = @intFromFloat(@round(p_dest.height)), + }; + } + + // Calculate the grid size for the placement. For virtual placements, + // we use the requested row/cols. If either isn't specified, we choose + // the best size based on the image size to fit the entire image in its + // original size. + // + // This part of the code does NOT do preserve any aspect ratios. Its + // dumbly fitting the image into the grid size -- possibly user specified. + fn grid( + self: *const Placement, + storage: *const ImageStorage, + image: *const Image, + cell_width: u32, + cell_height: u32, + ) !struct { + rows: u32, + columns: u32, + } { + // Get the placement. If an ID is specified we look for the exact one. + // If no ID, then we find the first virtual placement for this image. + const placement = if (self.placement_id > 0) storage.placements.get(.{ + .image_id = self.image_id, + .placement_id = .{ .tag = .external, .id = self.placement_id }, + }) orelse { + return Error.PlacementMissingPlacement; + } else placement: { + var it = storage.placements.iterator(); + while (it.next()) |entry| { + if (entry.key_ptr.image_id == self.image_id and + entry.value_ptr.location == .virtual) + { + break :placement entry.value_ptr.*; + } + } + + return Error.PlacementMissingPlacement; + }; + + // Use requested rows/columns if specified + // For unspecified rows/columns, calculate based on the image size. + var rows = placement.rows; + var columns = placement.columns; + if (rows == 0) rows = (image.height + cell_height - 1) / cell_height; + if (columns == 0) columns = (image.width + cell_width - 1) / cell_width; + return .{ + .rows = std.math.cast(terminal.size.CellCountInt, rows) orelse + return Error.PlacementGridOutOfBounds, + .columns = std.math.cast(terminal.size.CellCountInt, columns) orelse + return Error.PlacementGridOutOfBounds, + }; + } +}; + +/// IncompletePlacement is the placement information present in a single +/// cell. It is "incomplete" because the specification allows for missing +/// diacritics and so on that continue from previous valid placements. +const IncompletePlacement = struct { + /// The pin of the cell that created this incomplete placement. + pin: terminal.Pin, + + /// Lower 24 bits of the image ID. This is specified in the fg color + /// and is always required. + image_id_low: u24, + + /// Higher 8 bits of the image ID specified using the 3rd diacritic. + /// This is optional. + image_id_high: ?u8 = null, + + /// Placement ID is optionally specified in the underline color. + placement_id: ?u24 = null, + + /// The row/col index for the image. These are 0-indexed. These + /// are specified using diacritics. The row is first and the col + /// is second. Both are optional. If not specified, they can continue + /// a previous placement under certain conditions. + row: ?u32 = null, + col: ?u32 = null, + + /// The run width so far in cells. + width: u32 = 1, + + /// Parse the incomplete placement information from a row and cell. + /// + /// The cell could be derived from the row but in our usage we already + /// have the cell and we don't want to waste cycles recomputing it. + pub fn init( + row: *const terminal.Pin, + cell: *const terminal.Cell, + ) IncompletePlacement { + assert(cell.codepoint() == placeholder); + const style = row.style(cell); + + var result: IncompletePlacement = .{ + .pin = row.*, + .image_id_low = colorToId(style.fg_color), + .placement_id = placement_id: { + const id = colorToId(style.underline_color); + break :placement_id if (id != 0) id else null; + }, + }; + + // Try to decode all our diacritics. Any invalid diacritics are + // treated as if they don't exist. This isn't explicitly specified + // at the time of writing this but it appears to be how Kitty behaves. + const cps: []const u21 = row.grapheme(cell) orelse &.{}; + if (cps.len > 0) { + result.row = getIndex(cps[0]) orelse value: { + log.warn("virtual placement with invalid row diacritic cp={X}", .{cps[0]}); + break :value null; + }; + + if (cps.len > 1) { + result.col = getIndex(cps[1]) orelse value: { + log.warn("virtual placement with invalid col diacritic cp={X}", .{cps[1]}); + break :value null; + }; + + if (cps.len > 2) { + const high_ = getIndex(cps[2]) orelse value: { + log.warn("virtual placement with invalid high diacritic cp={X}", .{cps[2]}); + break :value null; + }; + + if (high_) |high| { + result.image_id_high = std.math.cast( + u8, + high, + ) orelse value: { + log.warn("virtual placement with invalid high diacritic cp={X} value={}", .{ + cps[2], + high, + }); + break :value null; + }; + } + + // Any additional diacritics are ignored. + } + } + } + + return result; + } + + /// Append this incomplete placement to an existing placement to + /// create a run. This returns true if the placements are compatible + /// and were combined. If this returns false, the other placement is + /// unchanged. + pub fn append(self: *IncompletePlacement, other: *const IncompletePlacement) bool { + if (!self.canAppend(other)) return false; + self.width += 1; + return true; + } + + fn canAppend(self: *const IncompletePlacement, other: *const IncompletePlacement) bool { + // Converted from Kitty's logic, don't @ me. + return self.image_id_low == other.image_id_low and + self.placement_id == other.placement_id and + (other.row == null or other.row == self.row) and + (other.col == null or other.col == self.col.? + self.width) and + (other.image_id_high == null or other.image_id_high == self.image_id_high); + } + + /// Complete the incomplete placement to create a full placement. + /// This creates a new placement that isn't continuous with any previous + /// placements. + /// + /// The pin is the pin of the cell that created this incomplete placement. + pub fn complete(self: *const IncompletePlacement) Placement { + return .{ + .pin = self.pin, + .image_id = image_id: { + const low: u32 = @intCast(self.image_id_low); + const high: u32 = @intCast(self.image_id_high orelse 0); + break :image_id low | (high << 24); + }, + + .placement_id = self.placement_id orelse 0, + .col = self.col orelse 0, + .row = self.row orelse 0, + .width = self.width, + .height = 1, + }; + } + + /// Convert a style color to a Kitty image protocol ID. This works by + /// taking the 24 most significant bits of the color, which lets it work + /// for both palette and rgb-based colors. + fn colorToId(c: terminal.Style.Color) u24 { + return switch (c) { + .none => 0, + .palette => |v| @intCast(v), + .rgb => |rgb| rgb: { + const r: u24 = @intCast(rgb.r); + const g: u24 = @intCast(rgb.g); + const b: u24 = @intCast(rgb.b); + break :rgb (r << 16) | (g << 8) | b; + }, + }; + } +}; + +/// Get the row/col index for a diacritic codepoint. These are 0-indexed. +fn getIndex(cp: u21) ?u32 { + const idx = std.sort.binarySearch(u21, diacritics, cp, (struct { + fn compare(context: u21, item: u21) std.math.Order { + return std.math.order(context, item); + } + }).compare) orelse return null; + return @intCast(idx); +} + +/// These are the diacritics used with the Kitty graphics protocol +/// Unicode placement feature to specify the row/column for placement. +/// The index into the array determines the value. +/// +/// This is derived from: +/// https://sw.kovidgoyal.net/kitty/_downloads/f0a0de9ec8d9ff4456206db8e0814937/rowcolumn-diacritics.txt +const diacritics: []const u21 = &.{ + 0x0305, + 0x030D, + 0x030E, + 0x0310, + 0x0312, + 0x033D, + 0x033E, + 0x033F, + 0x0346, + 0x034A, + 0x034B, + 0x034C, + 0x0350, + 0x0351, + 0x0352, + 0x0357, + 0x035B, + 0x0363, + 0x0364, + 0x0365, + 0x0366, + 0x0367, + 0x0368, + 0x0369, + 0x036A, + 0x036B, + 0x036C, + 0x036D, + 0x036E, + 0x036F, + 0x0483, + 0x0484, + 0x0485, + 0x0486, + 0x0487, + 0x0592, + 0x0593, + 0x0594, + 0x0595, + 0x0597, + 0x0598, + 0x0599, + 0x059C, + 0x059D, + 0x059E, + 0x059F, + 0x05A0, + 0x05A1, + 0x05A8, + 0x05A9, + 0x05AB, + 0x05AC, + 0x05AF, + 0x05C4, + 0x0610, + 0x0611, + 0x0612, + 0x0613, + 0x0614, + 0x0615, + 0x0616, + 0x0617, + 0x0657, + 0x0658, + 0x0659, + 0x065A, + 0x065B, + 0x065D, + 0x065E, + 0x06D6, + 0x06D7, + 0x06D8, + 0x06D9, + 0x06DA, + 0x06DB, + 0x06DC, + 0x06DF, + 0x06E0, + 0x06E1, + 0x06E2, + 0x06E4, + 0x06E7, + 0x06E8, + 0x06EB, + 0x06EC, + 0x0730, + 0x0732, + 0x0733, + 0x0735, + 0x0736, + 0x073A, + 0x073D, + 0x073F, + 0x0740, + 0x0741, + 0x0743, + 0x0745, + 0x0747, + 0x0749, + 0x074A, + 0x07EB, + 0x07EC, + 0x07ED, + 0x07EE, + 0x07EF, + 0x07F0, + 0x07F1, + 0x07F3, + 0x0816, + 0x0817, + 0x0818, + 0x0819, + 0x081B, + 0x081C, + 0x081D, + 0x081E, + 0x081F, + 0x0820, + 0x0821, + 0x0822, + 0x0823, + 0x0825, + 0x0826, + 0x0827, + 0x0829, + 0x082A, + 0x082B, + 0x082C, + 0x082D, + 0x0951, + 0x0953, + 0x0954, + 0x0F82, + 0x0F83, + 0x0F86, + 0x0F87, + 0x135D, + 0x135E, + 0x135F, + 0x17DD, + 0x193A, + 0x1A17, + 0x1A75, + 0x1A76, + 0x1A77, + 0x1A78, + 0x1A79, + 0x1A7A, + 0x1A7B, + 0x1A7C, + 0x1B6B, + 0x1B6D, + 0x1B6E, + 0x1B6F, + 0x1B70, + 0x1B71, + 0x1B72, + 0x1B73, + 0x1CD0, + 0x1CD1, + 0x1CD2, + 0x1CDA, + 0x1CDB, + 0x1CE0, + 0x1DC0, + 0x1DC1, + 0x1DC3, + 0x1DC4, + 0x1DC5, + 0x1DC6, + 0x1DC7, + 0x1DC8, + 0x1DC9, + 0x1DCB, + 0x1DCC, + 0x1DD1, + 0x1DD2, + 0x1DD3, + 0x1DD4, + 0x1DD5, + 0x1DD6, + 0x1DD7, + 0x1DD8, + 0x1DD9, + 0x1DDA, + 0x1DDB, + 0x1DDC, + 0x1DDD, + 0x1DDE, + 0x1DDF, + 0x1DE0, + 0x1DE1, + 0x1DE2, + 0x1DE3, + 0x1DE4, + 0x1DE5, + 0x1DE6, + 0x1DFE, + 0x20D0, + 0x20D1, + 0x20D4, + 0x20D5, + 0x20D6, + 0x20D7, + 0x20DB, + 0x20DC, + 0x20E1, + 0x20E7, + 0x20E9, + 0x20F0, + 0x2CEF, + 0x2CF0, + 0x2CF1, + 0x2DE0, + 0x2DE1, + 0x2DE2, + 0x2DE3, + 0x2DE4, + 0x2DE5, + 0x2DE6, + 0x2DE7, + 0x2DE8, + 0x2DE9, + 0x2DEA, + 0x2DEB, + 0x2DEC, + 0x2DED, + 0x2DEE, + 0x2DEF, + 0x2DF0, + 0x2DF1, + 0x2DF2, + 0x2DF3, + 0x2DF4, + 0x2DF5, + 0x2DF6, + 0x2DF7, + 0x2DF8, + 0x2DF9, + 0x2DFA, + 0x2DFB, + 0x2DFC, + 0x2DFD, + 0x2DFE, + 0x2DFF, + 0xA66F, + 0xA67C, + 0xA67D, + 0xA6F0, + 0xA6F1, + 0xA8E0, + 0xA8E1, + 0xA8E2, + 0xA8E3, + 0xA8E4, + 0xA8E5, + 0xA8E6, + 0xA8E7, + 0xA8E8, + 0xA8E9, + 0xA8EA, + 0xA8EB, + 0xA8EC, + 0xA8ED, + 0xA8EE, + 0xA8EF, + 0xA8F0, + 0xA8F1, + 0xAAB0, + 0xAAB2, + 0xAAB3, + 0xAAB7, + 0xAAB8, + 0xAABE, + 0xAABF, + 0xAAC1, + 0xFE20, + 0xFE21, + 0xFE22, + 0xFE23, + 0xFE24, + 0xFE25, + 0xFE26, + 0x10A0F, + 0x10A38, + 0x1D185, + 0x1D186, + 0x1D187, + 0x1D188, + 0x1D189, + 0x1D1AA, + 0x1D1AB, + 0x1D1AC, + 0x1D1AD, + 0x1D242, + 0x1D243, + 0x1D244, +}; + +test "unicode diacritic sorted" { + // diacritics must be sorted since we use a binary search. + try testing.expect(std.sort.isSorted(u21, diacritics, {}, (struct { + fn lessThan(context: void, lhs: u21, rhs: u21) bool { + _ = context; + return lhs < rhs; + } + }).lessThan)); +} + +test "unicode diacritic" { + // Some spot checks based on Kitty behavior + try testing.expectEqual(30, getIndex(0x483).?); + try testing.expectEqual(294, getIndex(0x1d242).?); +} + +test "unicode placement: none" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Single cell + try t.printString("hello\nworld\n1\n2"); + + // No placements + const pin = t.screens.active.pages.getTopLeft(.viewport); + var it = placementIterator(pin, null); + try testing.expect(it.next() == null); +} + +test "unicode placement: single row/col" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Single cell + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: continuation break" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Two runs because it jumps cols + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + try t.printString("\u{10EEEE}\u{0305}\u{030E}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + try testing.expectEqual(1, p.width); + } + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(2, p.col); + try testing.expectEqual(1, p.width); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: continuation with diacritics set" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Three cells. They'll continue even though they're explicit + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + try t.printString("\u{10EEEE}\u{0305}\u{030D}"); + try t.printString("\u{10EEEE}\u{0305}\u{030E}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + try testing.expectEqual(3, p.width); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: continuation with no col" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Three cells. They'll continue even though they're explicit + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + try t.printString("\u{10EEEE}\u{0305}"); + try t.printString("\u{10EEEE}\u{0305}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + try testing.expectEqual(3, p.width); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: continuation with no diacritics" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Three cells. They'll continue even though they're explicit + try t.printString("\u{10EEEE}"); + try t.printString("\u{10EEEE}"); + try t.printString("\u{10EEEE}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + try testing.expectEqual(3, p.width); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: run ending" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Three cells. They'll continue even though they're explicit + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + try t.printString("\u{10EEEE}\u{0305}\u{030D}"); + try t.printString("ABC"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + try testing.expectEqual(2, p.width); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: run starting in the middle" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 10 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Three cells. They'll continue even though they're explicit + try t.printString("ABC"); + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + try t.printString("\u{10EEEE}\u{0305}\u{030D}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(0, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + try testing.expectEqual(2, p.width); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: specifying image id as palette" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Single cell + try t.setAttribute(.{ .@"256_fg" = 42 }); + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(42, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: specifying image id with high bits" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Single cell + try t.setAttribute(.{ .@"256_fg" = 42 }); + try t.printString("\u{10EEEE}\u{0305}\u{0305}\u{030E}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(33554474, p.image_id); + try testing.expectEqual(0, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + } + try testing.expect(it.next() == null); +} + +test "unicode placement: specifying placement id as palette" { + const alloc = testing.allocator; + var t = try terminal.Terminal.init(alloc, .{ .rows = 5, .cols = 5 }); + defer t.deinit(alloc); + t.modes.set(.grapheme_cluster, true); + + // Single cell + try t.setAttribute(.{ .@"256_fg" = 42 }); + try t.setAttribute(.{ .@"256_underline_color" = 21 }); + try t.printString("\u{10EEEE}\u{0305}\u{0305}"); + + // Get our top left pin + const pin = t.screens.active.pages.getTopLeft(.viewport); + + // Should have exactly one placement + var it = placementIterator(pin, null); + { + const p = it.next().?; + try testing.expectEqual(42, p.image_id); + try testing.expectEqual(21, p.placement_id); + try testing.expectEqual(0, p.row); + try testing.expectEqual(0, p.col); + } + try testing.expect(it.next() == null); +} + +// Fish: +// printf "\033_Gf=100,i=1,t=f,q=2;$(printf dog.png | base64)\033\\" +// printf "\e[38;5;1m\U10EEEE\U0305\U0305\U10EEEE\U0305\U030D\U10EEEE\U0305\U030E\U10EEEE\U0305\U0310\e[39m\n" +// printf "\e[38;5;1m\U10EEEE\U030D\U0305\U10EEEE\U030D\U030D\U10EEEE\U030D\U030E\U10EEEE\U030D\U0310\e[39m\n" +// printf "\033_Ga=p,i=1,U=1,q=2,c=4,r=2\033\\" +test "unicode render placement: dog 4x2" { + const alloc = testing.allocator; + const cell_width = 36; + const cell_height = 80; + + var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + defer t.deinit(alloc); + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + const image: Image = .{ .id = 1, .width = 500, .height = 306 }; + try s.addImage(alloc, image); + try s.addPlacement(alloc, 1, 0, .{ + .location = .{ .virtual = {} }, + .columns = 4, + .rows = 2, + }); + + // Row 1 + { + const p: Placement = .{ + .pin = t.screens.active.cursor.page_pin.*, + .image_id = 1, + .placement_id = 0, + .col = 0, + .row = 0, + .width = 4, + .height = 1, + }; + const rp = try p.renderPlacement(&s, &image, cell_width, cell_height); + try testing.expectEqual(0, rp.offset_x); + try testing.expectEqual(36, rp.offset_y); + try testing.expectEqual(0, rp.source_x); + try testing.expectEqual(0, rp.source_y); + try testing.expectEqual(500, rp.source_width); + try testing.expectEqual(153, rp.source_height); + try testing.expectEqual(144, rp.dest_width); + try testing.expectEqual(44, rp.dest_height); + } + // Row 2 + { + const p: Placement = .{ + .pin = t.screens.active.cursor.page_pin.*, + .image_id = 1, + .placement_id = 0, + .col = 0, + .row = 1, + .width = 4, + .height = 1, + }; + const rp = try p.renderPlacement(&s, &image, cell_width, cell_height); + try testing.expectEqual(0, rp.offset_x); + try testing.expectEqual(0, rp.offset_y); + try testing.expectEqual(0, rp.source_x); + try testing.expectEqual(153, rp.source_y); + try testing.expectEqual(500, rp.source_width); + try testing.expectEqual(153, rp.source_height); + try testing.expectEqual(144, rp.dest_width); + try testing.expectEqual(44, rp.dest_height); + } +} + +// Fish: +// printf "\033_Gf=100,i=1,t=f,q=2;$(printf dog.png | base64)\033\\" +// printf "\e[38;5;1m\U10EEEE\U0305\U0305\U10EEEE\U0305\U030D\U10EEEE\U0305\U030E\U10EEEE\U0305\U0310\e[39m\n" +// printf "\e[38;5;1m\U10EEEE\U030D\U0305\U10EEEE\U030D\U030D\U10EEEE\U030D\U030E\U10EEEE\U030D\U0310\e[39m\n" +// printf "\033_Ga=p,i=1,U=1,q=2,c=2,r=2\033\\" +test "unicode render placement: dog 2x2 with blank cells" { + const alloc = testing.allocator; + const cell_width = 36; + const cell_height = 80; + + var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + defer t.deinit(alloc); + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + const image: Image = .{ .id = 1, .width = 500, .height = 306 }; + try s.addImage(alloc, image); + try s.addPlacement(alloc, 1, 0, .{ + .location = .{ .virtual = {} }, + .columns = 2, + .rows = 2, + }); + + // Row 1 + { + const p: Placement = .{ + .pin = t.screens.active.cursor.page_pin.*, + .image_id = 1, + .placement_id = 0, + .col = 0, + .row = 0, + .width = 4, + .height = 1, + }; + const rp = try p.renderPlacement(&s, &image, cell_width, cell_height); + try testing.expectEqual(0, rp.offset_x); + try testing.expectEqual(58, rp.offset_y); + try testing.expectEqual(0, rp.source_x); + try testing.expectEqual(0, rp.source_y); + try testing.expectEqual(500, rp.source_width); + try testing.expectEqual(153, rp.source_height); + try testing.expectEqual(72, rp.dest_width); + try testing.expectEqual(22, rp.dest_height); + } + // Row 2 + { + const p: Placement = .{ + .pin = t.screens.active.cursor.page_pin.*, + .image_id = 1, + .placement_id = 0, + .col = 0, + .row = 1, + .width = 4, + .height = 1, + }; + const rp = try p.renderPlacement(&s, &image, cell_width, cell_height); + try testing.expectEqual(0, rp.offset_x); + try testing.expectEqual(0, rp.offset_y); + try testing.expectEqual(0, rp.source_x); + try testing.expectEqual(153, rp.source_y); + try testing.expectEqual(500, rp.source_width); + try testing.expectEqual(153, rp.source_height); + try testing.expectEqual(72, rp.dest_width); + try testing.expectEqual(22, rp.dest_height); + } +} + +// Fish: +// printf "\033_Gf=100,i=1,t=f,q=2;$(printf dog.png | base64)\033\\" +// printf "\e[38;5;1m\U10EEEE\U0305\U0305\U10EEEE\U0305\U030D\U10EEEE\U0305\U030E\U10EEEE\U0305\U0310\e[39m\n" +// printf "\033_Ga=p,i=1,U=1,q=2,c=1,r=1\033\\" +test "unicode render placement: dog 1x1" { + const alloc = testing.allocator; + const cell_width = 36; + const cell_height = 80; + + var t = try terminal.Terminal.init(alloc, .{ .cols = 100, .rows = 100 }); + defer t.deinit(alloc); + var s: ImageStorage = .{}; + defer s.deinit(alloc, t.screens.active); + + const image: Image = .{ .id = 1, .width = 500, .height = 306 }; + try s.addImage(alloc, image); + try s.addPlacement(alloc, 1, 0, .{ + .location = .{ .virtual = {} }, + .columns = 1, + .rows = 1, + }); + + // Row 1 + { + const p: Placement = .{ + .pin = t.screens.active.cursor.page_pin.*, + .image_id = 1, + .placement_id = 0, + .col = 0, + .row = 0, + .width = 4, + .height = 1, + }; + const rp = try p.renderPlacement(&s, &image, cell_width, cell_height); + try testing.expectEqual(0, rp.offset_x); + try testing.expectEqual(29, rp.offset_y); + try testing.expectEqual(0, rp.source_x); + try testing.expectEqual(0, rp.source_y); + try testing.expectEqual(500, rp.source_width); + try testing.expectEqual(306, rp.source_height); + try testing.expectEqual(36, rp.dest_width); + try testing.expectEqual(22, rp.dest_height); + } +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/key.zig b/vendor/libghostty-vt/src/terminal/kitty/key.zig new file mode 100644 index 00000000..8594c4c3 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/kitty/key.zig @@ -0,0 +1,169 @@ +//! Kitty keyboard protocol support. + +const std = @import("std"); + +/// Stack for the key flags. This implements the push/pop behavior +/// of the CSI > u and CSI < u sequences. We implement the stack as +/// fixed size to avoid heap allocation. +pub const FlagStack = struct { + const len = 8; + + flags: [len]Flags = @splat(.disabled), + idx: u3 = 0, + + /// Return the current stack value + pub fn current(self: FlagStack) Flags { + return self.flags[self.idx]; + } + + /// Perform the "set" operation as described in the spec for + /// the CSI = u sequence. + pub fn set( + self: *FlagStack, + mode: SetMode, + v: Flags, + ) void { + switch (mode) { + .set => self.flags[self.idx] = v, + .@"or" => self.flags[self.idx] = @bitCast( + self.flags[self.idx].int() | v.int(), + ), + .not => self.flags[self.idx] = @bitCast( + self.flags[self.idx].int() & ~v.int(), + ), + } + } + + /// Push a new set of flags onto the stack. If the stack is full + /// then the oldest entry is evicted. + pub fn push(self: *FlagStack, flags: Flags) void { + // Overflow and wrap around if we're full, which evicts + // the oldest entry. + self.idx +%= 1; + self.flags[self.idx] = flags; + } + + /// Pop `n` entries from the stack. This will just wrap around + /// if `n` is greater than the amount in the stack. + pub fn pop(self: *FlagStack, n: usize) void { + // If n is more than our length then we just reset the stack. + // This also avoids a DoS vector where a malicious client + // could send a huge number of pop commands to waste cpu. + if (n >= self.flags.len) { + self.idx = 0; + self.flags = @splat(.disabled); + return; + } + + for (0..n) |_| { + self.flags[self.idx] = .disabled; + self.idx -%= 1; + } + } + + // Make sure we the overflow works as expected + test { + const testing = std.testing; + var stack: FlagStack = .{}; + stack.idx = stack.flags.len - 1; + stack.idx +%= 1; + try testing.expect(stack.idx == 0); + + stack.idx = 0; + stack.idx -%= 1; + try testing.expect(stack.idx == stack.flags.len - 1); + } +}; + +/// The possible flags for the Kitty keyboard protocol. +pub const Flags = packed struct(u5) { + disambiguate: bool = false, + report_events: bool = false, + report_alternates: bool = false, + report_all: bool = false, + report_associated: bool = false, + + /// Kitty keyboard protocol disabled (all flags off). + pub const disabled: Flags = .{ + .disambiguate = false, + .report_events = false, + .report_alternates = false, + .report_all = false, + .report_associated = false, + }; + + /// Sets all modes on. + pub const @"true": Flags = .{ + .disambiguate = true, + .report_events = true, + .report_alternates = true, + .report_all = true, + .report_associated = true, + }; + + pub fn int(self: Flags) u5 { + return @bitCast(self); + } + + // Its easy to get packed struct ordering wrong so this test checks. + test { + const testing = std.testing; + + try testing.expectEqual( + @as(u5, 0b1), + (Flags{ .disambiguate = true }).int(), + ); + try testing.expectEqual( + @as(u5, 0b10), + (Flags{ .report_events = true }).int(), + ); + } +}; + +/// The possible modes for setting the key flags. +pub const SetMode = enum { set, @"or", not }; + +test "FlagStack: push pop" { + const testing = std.testing; + var stack: FlagStack = .{}; + stack.push(.{ .disambiguate = true }); + try testing.expectEqual( + Flags{ .disambiguate = true }, + stack.current(), + ); + + stack.pop(1); + try testing.expectEqual(Flags{}, stack.current()); +} + +test "FlagStack: pop big number" { + const testing = std.testing; + var stack: FlagStack = .{}; + stack.pop(100); + try testing.expectEqual(Flags{}, stack.current()); +} + +test "FlagStack: set" { + const testing = std.testing; + var stack: FlagStack = .{}; + stack.set(.set, .{ .disambiguate = true }); + try testing.expectEqual( + Flags{ .disambiguate = true }, + stack.current(), + ); + + stack.set(.@"or", .{ .report_events = true }); + try testing.expectEqual( + Flags{ + .disambiguate = true, + .report_events = true, + }, + stack.current(), + ); + + stack.set(.not, .{ .report_events = true }); + try testing.expectEqual( + Flags{ .disambiguate = true }, + stack.current(), + ); +} diff --git a/vendor/libghostty-vt/src/terminal/kitty/testdata/dog.png b/vendor/libghostty-vt/src/terminal/kitty/testdata/dog.png new file mode 100644 index 00000000..a5749c23 Binary files /dev/null and b/vendor/libghostty-vt/src/terminal/kitty/testdata/dog.png differ diff --git a/vendor/libghostty-vt/src/terminal/kitty/testdata/image-png-none-50x76-2147483647-raw.data b/vendor/libghostty-vt/src/terminal/kitty/testdata/image-png-none-50x76-2147483647-raw.data new file mode 100644 index 00000000..032cb07c Binary files /dev/null and b/vendor/libghostty-vt/src/terminal/kitty/testdata/image-png-none-50x76-2147483647-raw.data differ diff --git a/vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-none-20x15-2147483647-raw.data b/vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-none-20x15-2147483647-raw.data new file mode 100644 index 00000000..2c070cb2 Binary files /dev/null and b/vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-none-20x15-2147483647-raw.data differ diff --git a/vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data b/vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data new file mode 100644 index 00000000..ea816083 Binary files /dev/null and b/vendor/libghostty-vt/src/terminal/kitty/testdata/image-rgb-zlib_deflate-128x96-2147483647-raw.data differ diff --git a/vendor/libghostty-vt/src/terminal/lib.zig b/vendor/libghostty-vt/src/terminal/lib.zig new file mode 100644 index 00000000..3cd657b4 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/lib.zig @@ -0,0 +1,22 @@ +const std = @import("std"); +const build_options = @import("terminal_options"); +const lib = @import("../lib/main.zig"); + +/// The target for the terminal lib in particular. +pub const target: lib.Target = if (build_options.c_abi) .c else .zig; + +/// The calling convention to use for C APIs. +/// +/// This is always .c for now. I want to make this "Zig" when we're not +/// building the C ABI but there are bigger issues we need to resolve to +/// make that possible (change it and see for yourself). +pub const calling_conv: std.builtin.CallingConvention = .c; + +/// Forwarded decls from lib that are used. +pub const alloc = lib.allocator; +pub const Enum = lib.Enum; +pub const TaggedUnion = lib.TaggedUnion; +pub const Struct = lib.Struct; +pub const String = lib.String; +pub const checkGhosttyHEnum = lib.checkGhosttyHEnum; +pub const structSizedFieldFits = lib.structSizedFieldFits; diff --git a/vendor/libghostty-vt/src/terminal/main.zig b/vendor/libghostty-vt/src/terminal/main.zig new file mode 100644 index 00000000..9f5b65e3 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/main.zig @@ -0,0 +1,87 @@ +const charsets = @import("charsets.zig"); +const stream = @import("stream.zig"); +const ansi = @import("ansi.zig"); +const csi = @import("csi.zig"); +const render = @import("render.zig"); +const stream_terminal = @import("stream_terminal.zig"); +const style = @import("style.zig"); +pub const apc = @import("apc.zig"); +pub const dcs = @import("dcs.zig"); +pub const osc = @import("osc.zig"); +pub const point = @import("point.zig"); +pub const color = @import("color.zig"); +pub const device_attributes = @import("device_attributes.zig"); +pub const device_status = @import("device_status.zig"); +pub const focus = @import("focus.zig"); +pub const formatter = @import("formatter.zig"); +pub const highlight = @import("highlight.zig"); +pub const kitty = @import("kitty.zig"); +pub const modes = @import("modes.zig"); +pub const page = @import("page.zig"); +pub const parse_table = @import("parse_table.zig"); +pub const search = @import("search.zig"); +pub const sgr = @import("sgr.zig"); +pub const size = @import("size.zig"); +pub const size_report = @import("size_report.zig"); +pub const tmux = if (options.tmux_control_mode) @import("tmux.zig") else struct {}; +pub const x11_color = @import("x11_color.zig"); + +pub const Charset = charsets.Charset; +pub const CharsetSlot = charsets.Slots; +pub const CharsetActiveSlot = charsets.ActiveSlot; +pub const charsetTable = charsets.table; +pub const Cell = page.Cell; +pub const Coordinate = point.Coordinate; +pub const CSI = Parser.Action.CSI; +pub const DCS = Parser.Action.DCS; +pub const mouse = @import("mouse.zig"); +pub const MouseEvent = mouse.Event; +pub const MouseFormat = mouse.Format; +pub const MouseShape = mouse.Shape; +pub const Page = page.Page; +pub const PageList = @import("PageList.zig"); +pub const Parser = @import("Parser.zig"); +pub const Pin = PageList.Pin; +pub const Point = point.Point; +pub const RenderState = render.RenderState; +pub const Screen = @import("Screen.zig"); +pub const ScreenSet = @import("ScreenSet.zig"); +pub const Scrollbar = PageList.Scrollbar; +pub const Selection = @import("Selection.zig"); +pub const SizeReportStyle = csi.SizeReportStyle; +pub const StringMap = @import("StringMap.zig"); +pub const Style = style.Style; +pub const Terminal = @import("Terminal.zig"); +pub const TerminalStream = stream_terminal.Stream; +pub const Stream = stream.Stream; +pub const StreamAction = stream.Action; +pub const Cursor = Screen.Cursor; +pub const CursorStyle = Screen.CursorStyle; +pub const CursorStyleReq = ansi.CursorStyle; +pub const DeviceAttributeReq = device_attributes.Req; +pub const Mode = modes.Mode; +pub const ModePacked = modes.ModePacked; +pub const ModifyKeyFormat = ansi.ModifyKeyFormat; +pub const ProtectedMode = ansi.ProtectedMode; +pub const StatusLineType = ansi.StatusLineType; +pub const StatusDisplay = ansi.StatusDisplay; +pub const EraseDisplay = csi.EraseDisplay; +pub const EraseLine = csi.EraseLine; +pub const TabClear = csi.TabClear; +pub const Attribute = sgr.Attribute; + +pub const Options = @import("build_options.zig").Options; +pub const options = @import("terminal_options"); + +/// This is set to true when we're building the C library. +pub const c_api = if (options.c_abi) @import("c/main.zig") else void; + +test { + @import("std").testing.refAllDecls(@This()); + + // Internals + _ = @import("bitmap_allocator.zig"); + _ = @import("hash_map.zig"); + _ = @import("ref_counted_set.zig"); + _ = @import("size.zig"); +} diff --git a/vendor/libghostty-vt/src/terminal/modes.zig b/vendor/libghostty-vt/src/terminal/modes.zig new file mode 100644 index 00000000..0d8cde5b --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/modes.zig @@ -0,0 +1,381 @@ +//! This file contains all the terminal modes that we support +//! and various support types for them: an enum of supported modes, +//! a packed struct to store mode values, a more generalized state +//! struct to store values plus handle save/restore, and much more. +//! +//! There is pretty heavy comptime usage and type generation here. +//! I don't love to have this sort of complexity but its a good way +//! to ensure all our various types and logic remain in sync. + +const std = @import("std"); +const testing = std.testing; + +/// A struct that maintains the state of all the settable modes. +pub const ModeState = struct { + /// The values of the current modes. + values: ModePacked = .{}, + + /// The saved values. We only allow saving each mode once. + /// This is in line with other terminals that implement XTSAVE + /// and XTRESTORE. We can improve this in the future if it becomes + /// a real-world issue but we need to be aware of a DoS vector. + saved: ModePacked = .{}, + + /// The default values for the modes. This is used to reset + /// the modes to their default values during reset. + default: ModePacked = .{}, + + /// Reset the modes to their default values. This also clears the + /// saved state. + pub fn reset(self: *ModeState) void { + self.values = self.default; + self.saved = .{}; + } + + /// Set a mode to a value. + pub fn set(self: *ModeState, mode: Mode, value: bool) void { + switch (mode) { + inline else => |mode_comptime| { + const entry = comptime entryForMode(mode_comptime); + @field(self.values, entry.name) = value; + }, + } + } + + /// Get the value of a mode. + pub fn get(self: *const ModeState, mode: Mode) bool { + switch (mode) { + inline else => |mode_comptime| { + const entry = comptime entryForMode(mode_comptime); + return @field(self.values, entry.name); + }, + } + } + + /// Save the state of the given mode. This can then be restored + /// with restore. This will only be accurate if the previous + /// mode was saved exactly once and not restored. Otherwise this + /// will just keep restoring the last stored value in memory. + pub fn save(self: *ModeState, mode: Mode) void { + switch (mode) { + inline else => |mode_comptime| { + const entry = comptime entryForMode(mode_comptime); + @field(self.saved, entry.name) = @field(self.values, entry.name); + }, + } + } + + /// See save. This will return the restored value. + pub fn restore(self: *ModeState, mode: Mode) bool { + switch (mode) { + inline else => |mode_comptime| { + const entry = comptime entryForMode(mode_comptime); + @field(self.values, entry.name) = @field(self.saved, entry.name); + return @field(self.values, entry.name); + }, + } + } + + /// Return a DECRPM report for the given mode tag. If the tag does + /// not correspond to a known mode, the report state is .not_recognized. + pub fn getReport(self: *const ModeState, tag: ModeTag) Report { + const mode = modeFromInt(tag.value, tag.ansi) orelse return .{ + .tag = tag, + .state = .not_recognized, + }; + return .{ + .tag = tag, + .state = if (self.get(mode)) .set else .reset, + }; + } + + test { + // We have this here so that we explicitly fail when we change the + // size of modes. The size of modes is NOT particularly important, + // we just want to be mentally aware when it happens. + try std.testing.expectEqual(8, @sizeOf(ModePacked)); + } +}; + +/// A packed struct of all the settable modes. This shouldn't +/// be used directly but rather through the ModeState struct. +pub const ModePacked = packed_struct: { + const StructField = std.builtin.Type.StructField; + var fields: [entries.len]StructField = undefined; + for (entries, 0..) |entry, i| { + fields[i] = .{ + .name = entry.name, + .type = bool, + .default_value_ptr = &entry.default, + .is_comptime = false, + .alignment = 0, + }; + } + + break :packed_struct @Type(.{ .@"struct" = .{ + .layout = .@"packed", + .fields = &fields, + .decls = &.{}, + .is_tuple = false, + } }); +}; + +/// An enum(u16) of the available modes. See entries for available values. +pub const Mode = mode_enum: { + const EnumField = std.builtin.Type.EnumField; + var fields: [entries.len]EnumField = undefined; + for (entries, 0..) |entry, i| { + fields[i] = .{ + .name = entry.name, + .value = @as(ModeTag.Backing, @bitCast(ModeTag{ + .value = entry.value, + .ansi = entry.ansi, + })), + }; + } + + break :mode_enum @Type(.{ .@"enum" = .{ + .tag_type = ModeTag.Backing, + .fields = &fields, + .decls = &.{}, + .is_exhaustive = true, + } }); +}; + +/// The tag type for our enum is a u16 but we use a packed struct +/// in order to pack the ansi bit into the tag. +pub const ModeTag = packed struct(u16) { + pub const Backing = @typeInfo(@This()).@"struct".backing_integer.?; + value: u15, + ansi: bool = false, + + pub fn fromMode(mode: Mode) ModeTag { + return @bitCast(@intFromEnum(mode)); + } + + test "order" { + const t: ModeTag = .{ .value = 1 }; + const int: Backing = @bitCast(t); + try std.testing.expectEqual(@as(Backing, 1), int); + } +}; + +pub fn modeFromInt(v: u16, ansi: bool) ?Mode { + inline for (entries) |entry| { + if (comptime !entry.disabled) { + if (entry.value == v and entry.ansi == ansi) { + const tag: ModeTag = .{ .ansi = ansi, .value = entry.value }; + const int: ModeTag.Backing = @bitCast(tag); + return @enumFromInt(int); + } + } + } + + return null; +} + +/// A DECRPM mode report response. +pub const Report = struct { + tag: ModeTag, + state: State, + + pub const max_size = max_size: { + // Construct the largest possible report in terms of values. + const report: Report = .{ + .tag = .{ + .value = std.math.maxInt(u15), + .ansi = false, + }, + .state = .permanently_reset, + }; + + var discarding: std.Io.Writer.Discarding = .init(&.{}); + report.encode(&discarding.writer) catch unreachable; + break :max_size discarding.count; + }; + + /// The state of a mode as reported in a DECRPM response. + pub const State = enum(u8) { + not_recognized = 0, + set = 1, + reset = 2, + permanently_set = 3, + permanently_reset = 4, + }; + + /// Encode the DECRPM report sequence. + pub fn encode( + self: Report, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + try writer.print("\x1B[{s}{};{}$y", .{ + if (self.tag.ansi) "" else "?", + self.tag.value, + @intFromEnum(self.state), + }); + } +}; + +fn entryForMode(comptime mode: Mode) ModeEntry { + @setEvalBranchQuota(10_000); + const name = @tagName(mode); + for (entries) |entry| { + if (std.mem.eql(u8, entry.name, name)) return entry; + } + + unreachable; +} + +/// A single entry of a possible mode we support. This is used to +/// dynamically define the enum and other tables. +const ModeEntry = struct { + name: [:0]const u8, + value: comptime_int, + default: bool = false, + + /// True if this is an ANSI mode, false if its a DEC mode (?-prefixed). + ansi: bool = false, + + /// If true, this mode is disabled and Ghostty will not allow it to be + /// set or queried. The mode enum still has it, allowing Ghostty developers + /// to develop a mode without exposing it to real users. + disabled: bool = false, +}; + +/// The full list of available entries. For documentation see how +/// they're used within Ghostty or google their values. It is not +/// valuable to redocument them all here. +/// +/// NOTE: When adding a new mode entry, also add a corresponding +/// GHOSTTY_MODE_* macro in include/ghostty/vt/modes.h. +const entries: []const ModeEntry = &.{ + // ANSI + .{ .name = "disable_keyboard", .value = 2, .ansi = true }, // KAM + .{ .name = "insert", .value = 4, .ansi = true }, + .{ .name = "send_receive_mode", .value = 12, .ansi = true, .default = true }, // SRM + .{ .name = "linefeed", .value = 20, .ansi = true }, + + // DEC + .{ .name = "cursor_keys", .value = 1 }, // DECCKM + .{ .name = "132_column", .value = 3 }, + .{ .name = "slow_scroll", .value = 4 }, + .{ .name = "reverse_colors", .value = 5 }, + .{ .name = "origin", .value = 6 }, + .{ .name = "wraparound", .value = 7, .default = true }, + .{ .name = "autorepeat", .value = 8 }, + .{ .name = "mouse_event_x10", .value = 9 }, + .{ .name = "cursor_blinking", .value = 12 }, + .{ .name = "cursor_visible", .value = 25, .default = true }, + .{ .name = "enable_mode_3", .value = 40 }, + .{ .name = "reverse_wrap", .value = 45 }, + .{ .name = "alt_screen_legacy", .value = 47 }, + .{ .name = "keypad_keys", .value = 66 }, + .{ .name = "enable_left_and_right_margin", .value = 69 }, + .{ .name = "mouse_event_normal", .value = 1000 }, + .{ .name = "mouse_event_button", .value = 1002 }, + .{ .name = "mouse_event_any", .value = 1003 }, + .{ .name = "focus_event", .value = 1004 }, + .{ .name = "mouse_format_utf8", .value = 1005 }, + .{ .name = "mouse_format_sgr", .value = 1006 }, + .{ .name = "mouse_alternate_scroll", .value = 1007, .default = true }, + .{ .name = "mouse_format_urxvt", .value = 1015 }, + .{ .name = "mouse_format_sgr_pixels", .value = 1016 }, + .{ .name = "ignore_keypad_with_numlock", .value = 1035, .default = true }, + .{ .name = "alt_esc_prefix", .value = 1036, .default = true }, + .{ .name = "alt_sends_escape", .value = 1039 }, + .{ .name = "reverse_wrap_extended", .value = 1045 }, + .{ .name = "alt_screen", .value = 1047 }, + .{ .name = "save_cursor", .value = 1048 }, + .{ .name = "alt_screen_save_cursor_clear_enter", .value = 1049 }, + .{ .name = "bracketed_paste", .value = 2004 }, + .{ .name = "synchronized_output", .value = 2026 }, + .{ .name = "grapheme_cluster", .value = 2027 }, + .{ .name = "report_color_scheme", .value = 2031 }, + .{ .name = "in_band_size_reports", .value = 2048 }, +}; + +test { + _ = Mode; + _ = ModePacked; +} + +test modeFromInt { + try testing.expect(modeFromInt(4, true).? == .insert); + try testing.expect(modeFromInt(9, true) == null); + try testing.expect(modeFromInt(9, false).? == .mouse_event_x10); + try testing.expect(modeFromInt(14, true) == null); +} + +test ModeState { + var state: ModeState = .{}; + + // Normal set/get + try testing.expect(!state.get(.cursor_keys)); + state.set(.cursor_keys, true); + try testing.expect(state.get(.cursor_keys)); + + // Save/restore + state.save(.cursor_keys); + state.set(.cursor_keys, false); + try testing.expect(!state.get(.cursor_keys)); + try testing.expect(state.restore(.cursor_keys)); + try testing.expect(state.get(.cursor_keys)); +} + +test "getReport known DEC mode" { + var state: ModeState = .{}; + const report = state.getReport(.{ .value = 1 }); + try testing.expectEqual(Report.State.reset, report.state); + try testing.expectEqual(false, report.tag.ansi); + try testing.expectEqual(@as(u15, 1), report.tag.value); + + state.set(.cursor_keys, true); + const report2 = state.getReport(.{ .value = 1 }); + try testing.expectEqual(Report.State.set, report2.state); +} + +test "getReport known ANSI mode" { + var state: ModeState = .{}; + state.set(.insert, true); + const report = state.getReport(.{ .value = 4, .ansi = true }); + try testing.expectEqual(Report.State.set, report.state); + try testing.expectEqual(true, report.tag.ansi); +} + +test "getReport unknown mode" { + const state: ModeState = .{}; + const report = state.getReport(.{ .value = 9999 }); + try testing.expectEqual(Report.State.not_recognized, report.state); +} + +test "Report.encode DEC mode set" { + var buf: [Report.max_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + const report: Report = .{ .tag = .{ .value = 1, .ansi = false }, .state = .set }; + try report.encode(&writer); + try testing.expectEqualStrings("\x1B[?1;1$y", writer.buffered()); +} + +test "Report.encode DEC mode reset" { + var buf: [Report.max_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + const report: Report = .{ .tag = .{ .value = 1, .ansi = false }, .state = .reset }; + try report.encode(&writer); + try testing.expectEqualStrings("\x1B[?1;2$y", writer.buffered()); +} + +test "Report.encode ANSI mode" { + var buf: [Report.max_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + const report: Report = .{ .tag = .{ .value = 4, .ansi = true }, .state = .set }; + try report.encode(&writer); + try testing.expectEqualStrings("\x1B[4;1$y", writer.buffered()); +} + +test "Report.encode not recognized" { + var buf: [Report.max_size]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + const report: Report = .{ .tag = .{ .value = 9999, .ansi = false }, .state = .not_recognized }; + try report.encode(&writer); + try testing.expectEqualStrings("\x1B[?9999;0$y", writer.buffered()); +} diff --git a/vendor/libghostty-vt/src/terminal/mouse.zig b/vendor/libghostty-vt/src/terminal/mouse.zig new file mode 100644 index 00000000..2861ad1e --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/mouse.zig @@ -0,0 +1,168 @@ +const std = @import("std"); +const build_options = @import("terminal_options"); +const lib = @import("lib.zig"); + +/// The event types that can be reported for mouse-related activities. +/// These are all mutually exclusive (hence in a single enum). +pub const Event = lib.Enum(lib.target, &.{ + "none", + "x10", // 9 + "normal", // 1000 + "button", // 1002 + "any", // 1003 +}); + +/// Returns true if this event sends motion events. +pub fn eventSendsMotion(event: Event) bool { + return event == .button or event == .any; +} + +/// The format of mouse events when enabled. +/// These are all mutually exclusive (hence in a single enum). +pub const Format = lib.Enum(lib.target, &.{ + "x10", + "utf8", // 1005 + "sgr", // 1006 + "urxvt", // 1015 + "sgr_pixels", // 1016 +}); + +/// The possible cursor shapes. Not all app runtimes support these shapes. +/// The shapes are always based on the W3C supported cursor styles so we +/// can have a cross platform list. +// +// Must be kept in sync with ghostty_cursor_shape_e +pub const Shape = enum(c_int) { + default, + context_menu, + help, + pointer, + progress, + wait, + cell, + crosshair, + text, + vertical_text, + alias, + copy, + move, + no_drop, + not_allowed, + grab, + grabbing, + all_scroll, + col_resize, + row_resize, + n_resize, + e_resize, + s_resize, + w_resize, + ne_resize, + nw_resize, + se_resize, + sw_resize, + ew_resize, + ns_resize, + nesw_resize, + nwse_resize, + zoom_in, + zoom_out, + + /// Build cursor shape from string or null if its unknown. + pub fn fromString(v: []const u8) ?Shape { + return string_map.get(v); + } + + /// Make this a valid gobject if we're in a GTK environment. + pub const getGObjectType = gtk: { + switch (build_options.artifact) { + .ghostty => {}, + .lib => break :gtk void, + } + + break :gtk switch (@import("../build_config.zig").app_runtime) { + .gtk => @import("gobject").ext.defineEnum( + Shape, + .{ .name = "GhosttyMouseShape" }, + ), + + .none => void, + }; + }; + + test "ghostty.h MouseShape" { + if (comptime build_options.artifact == .lib) return error.SkipZigTest; + try lib.checkGhosttyHEnum(Shape, "GHOSTTY_MOUSE_SHAPE_"); + } +}; + +const string_map = std.StaticStringMap(Shape).initComptime(.{ + // W3C + .{ "default", .default }, + .{ "context-menu", .context_menu }, + .{ "help", .help }, + .{ "pointer", .pointer }, + .{ "progress", .progress }, + .{ "wait", .wait }, + .{ "cell", .cell }, + .{ "crosshair", .crosshair }, + .{ "text", .text }, + .{ "vertical-text", .vertical_text }, + .{ "alias", .alias }, + .{ "copy", .copy }, + .{ "move", .move }, + .{ "no-drop", .no_drop }, + .{ "not-allowed", .not_allowed }, + .{ "grab", .grab }, + .{ "grabbing", .grabbing }, + .{ "all-scroll", .all_scroll }, + .{ "col-resize", .col_resize }, + .{ "row-resize", .row_resize }, + .{ "n-resize", .n_resize }, + .{ "e-resize", .e_resize }, + .{ "s-resize", .s_resize }, + .{ "w-resize", .w_resize }, + .{ "ne-resize", .ne_resize }, + .{ "nw-resize", .nw_resize }, + .{ "se-resize", .se_resize }, + .{ "sw-resize", .sw_resize }, + .{ "ew-resize", .ew_resize }, + .{ "ns-resize", .ns_resize }, + .{ "nesw-resize", .nesw_resize }, + .{ "nwse-resize", .nwse_resize }, + .{ "zoom-in", .zoom_in }, + .{ "zoom-out", .zoom_out }, + + // xterm/foot + .{ "left_ptr", .default }, + .{ "question_arrow", .help }, + .{ "hand", .pointer }, + .{ "left_ptr_watch", .progress }, + .{ "watch", .wait }, + .{ "cross", .crosshair }, + .{ "xterm", .text }, + .{ "dnd-link", .alias }, + .{ "dnd-copy", .copy }, + .{ "dnd-move", .move }, + .{ "dnd-no-drop", .no_drop }, + .{ "crossed_circle", .not_allowed }, + .{ "hand1", .grab }, + .{ "right_side", .e_resize }, + .{ "top_side", .n_resize }, + .{ "top_right_corner", .ne_resize }, + .{ "top_left_corner", .nw_resize }, + .{ "bottom_side", .s_resize }, + .{ "bottom_right_corner", .se_resize }, + .{ "bottom_left_corner", .sw_resize }, + .{ "left_side", .w_resize }, + .{ "fleur", .all_scroll }, +}); + +test "cursor shape from string" { + const testing = std.testing; + try testing.expectEqual(Shape.default, Shape.fromString("default").?); +} + +test { + _ = std.testing.refAllDeclsRecursive(@This()); +} diff --git a/vendor/libghostty-vt/src/terminal/osc.zig b/vendor/libghostty-vt/src/terminal/osc.zig new file mode 100644 index 00000000..36cfd7f8 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc.zig @@ -0,0 +1,826 @@ +//! OSC (Operating System Command) related functions and types. +//! +//! OSC is another set of control sequences for terminal programs that start with +//! "ESC ]". Unlike CSI or standard ESC sequences, they may contain strings +//! and other irregular formatting so a dedicated parser is created to handle it. +const osc = @This(); + +const std = @import("std"); +const builtin = @import("builtin"); +const build_options = @import("terminal_options"); +const mem = std.mem; +const assert = @import("../quirks.zig").inlineAssert; +const Allocator = mem.Allocator; +const lib = @import("lib.zig"); +const LibEnum = lib.Enum; +const kitty_color = @import("kitty/color.zig"); +const parsers = @import("osc/parsers.zig"); +const encoding = @import("osc/encoding.zig"); + +pub const color = parsers.color; +pub const semantic_prompt = parsers.semantic_prompt; + +const log = std.log.scoped(.osc); + +pub const Command = union(Key) { + /// This generally shouldn't ever be set except as an initial zero value. + /// Ignore it. + invalid, + + /// Set the window title of the terminal + /// + /// If title mode 0 is set text is expect to be hex encoded (i.e. utf-8 + /// with each code unit further encoded with two hex digits). + /// + /// If title mode 2 is set or the terminal is setup for unconditional + /// utf-8 titles text is interpreted as utf-8. Else text is interpreted + /// as latin1. + change_window_title: [:0]const u8, + + /// Set the icon of the terminal window. The name of the icon is not + /// well defined, so this is currently ignored by Ghostty at the time + /// of writing this. We just parse it so that we don't get parse errors + /// in the log. + change_window_icon: [:0]const u8, + + /// Semantic prompt command: https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md + semantic_prompt: SemanticPrompt, + + /// Set or get clipboard contents. If data is null, then the current + /// clipboard contents are sent to the pty. If data is set, this + /// contents is set on the clipboard. + clipboard_contents: struct { + kind: u8, + data: [:0]const u8, + }, + + /// OSC 7. Reports the current working directory of the shell. This is + /// a moderately flawed escape sequence but one that many major terminals + /// support so we also support it. To understand the flaws, read through + /// this terminal-wg issue: https://gitlab.freedesktop.org/terminal-wg/specifications/-/issues/20 + report_pwd: struct { + /// The reported pwd value. This is not checked for validity. It should + /// be a file URL but it is up to the caller to utilize this value. + value: [:0]const u8, + }, + + /// OSC 22. Set the mouse shape. There doesn't seem to be a standard + /// naming scheme for cursors but it looks like terminals such as Foot + /// are moving towards using the W3C CSS cursor names. For OSC parsing, + /// we just parse whatever string is given. + mouse_shape: struct { + value: [:0]const u8, + }, + + /// OSC color operations to set, reset, or report color settings. Some OSCs + /// allow multiple operations to be specified in a single OSC so we need a + /// list-like datastructure to manage them. We use std.SegmentedList because + /// it minimizes the number of allocations and copies because a large + /// majority of the time there will be only one operation per OSC. + /// + /// Currently, these OSCs are handled by `color_operation`: + /// + /// 4, 5, 10-19, 104, 105, 110-119 + color_operation: struct { + op: color.Operation, + requests: color.List = .{}, + terminator: Terminator = .st, + }, + + /// Kitty color protocol, OSC 21 + /// https://sw.kovidgoyal.net/kitty/color-stack/#id1 + kitty_color_protocol: kitty_color.OSC, + + /// Show a desktop notification (OSC 9 or OSC 777) + show_desktop_notification: struct { + title: [:0]const u8, + body: [:0]const u8, + }, + + /// Start a hyperlink (OSC 8) + hyperlink_start: struct { + id: ?[:0]const u8 = null, + uri: [:0]const u8, + }, + + /// End a hyperlink (OSC 8) + hyperlink_end: void, + + /// ConEmu sleep (OSC 9;1) + conemu_sleep: struct { + duration_ms: u16, + }, + + /// ConEmu show GUI message box (OSC 9;2) + conemu_show_message_box: [:0]const u8, + + /// ConEmu change tab title (OSC 9;3) + conemu_change_tab_title: union(enum) { + reset, + value: [:0]const u8, + }, + + /// ConEmu progress report (OSC 9;4) + conemu_progress_report: ProgressReport, + + /// ConEmu wait input (OSC 9;5) + conemu_wait_input, + + /// ConEmu GUI macro (OSC 9;6) + conemu_guimacro: [:0]const u8, + + /// ConEmu run process (OSC 9;7) + conemu_run_process: [:0]const u8, + + /// ConEmu output environment variable (OSC 9;8) + conemu_output_environment_variable: [:0]const u8, + + /// ConEmu XTerm keyboard and output emulation (OSC 9;10) + /// https://conemu.github.io/en/TerminalModes.html + conemu_xterm_emulation: struct { + /// null => do not change + /// false => turn off + /// true => turn on + keyboard: ?bool, + /// null => do not change + /// false => turn off + /// true => turn on + output: ?bool, + }, + + /// ConEmu comment (OSC 9;11) + conemu_comment: [:0]const u8, + + /// Kitty text sizing protocol (OSC 66) + kitty_text_sizing: parsers.kitty_text_sizing.OSC, + + kitty_clipboard_protocol: KittyClipboardProtocol, + + /// OSC 3008. Hierarchical context signalling (UAPI spec). + /// https://uapi-group.org/specifications/specs/osc_context/ + context_signal: parsers.context_signal.Command, + + pub const SemanticPrompt = parsers.semantic_prompt.Command; + + pub const KittyClipboardProtocol = parsers.kitty_clipboard_protocol.OSC; + + pub const Key = LibEnum( + lib.target, + // NOTE: Order matters, see LibEnum documentation. + &.{ + "invalid", + "change_window_title", + "change_window_icon", + "semantic_prompt", + "clipboard_contents", + "report_pwd", + "mouse_shape", + "color_operation", + "kitty_color_protocol", + "show_desktop_notification", + "hyperlink_start", + "hyperlink_end", + "conemu_sleep", + "conemu_show_message_box", + "conemu_change_tab_title", + "conemu_progress_report", + "conemu_wait_input", + "conemu_guimacro", + "conemu_run_process", + "conemu_output_environment_variable", + "conemu_xterm_emulation", + "conemu_comment", + "kitty_text_sizing", + "kitty_clipboard_protocol", + "context_signal", + }, + ); + + pub const ProgressReport = struct { + pub const State = enum(c_int) { + remove, + set, + @"error", + indeterminate, + pause, + + test "ghostty.h Command.ProgressReport.State" { + if (comptime build_options.artifact == .lib) return error.SkipZigTest; + try lib.checkGhosttyHEnum(State, "GHOSTTY_PROGRESS_STATE_"); + } + }; + + state: State, + progress: ?u8 = null, + + // sync with ghostty_action_progress_report_s + pub const C = extern struct { + state: c_int, + progress: i8, + }; + + pub fn cval(self: ProgressReport) C { + return .{ + .state = @intFromEnum(self.state), + .progress = if (self.progress) |progress| @intCast(std.math.clamp( + progress, + 0, + 100, + )) else -1, + }; + } + }; + + comptime { + assert(@sizeOf(Command) == switch (@sizeOf(usize)) { + 4 => 44, + 8 => 64, + else => unreachable, + }); + } +}; + +/// The terminator used to end an OSC command. For OSC commands that demand +/// a response, we try to match the terminator used in the request since that +/// is most likely to be accepted by the calling program. +pub const Terminator = enum { + /// The preferred string terminator is ESC followed by \ + st, + + /// Some applications and terminals use BELL (0x07) as the string terminator. + bel, + + pub const C = LibEnum(.c, &.{ "st", "bel" }); + + /// Initialize the terminator based on the last byte seen. If the + /// last byte is a BEL then we use BEL, otherwise we just assume ST. + pub fn init(ch: ?u8) Terminator { + return switch (ch orelse return .st) { + 0x07 => .bel, + else => .st, + }; + } + + /// The terminator as a string. This is static memory so it doesn't + /// need to be freed. + pub fn string(self: Terminator) []const u8 { + return switch (self) { + .st => "\x1b\\", + .bel => "\x07", + }; + } + + pub fn cval(self: Terminator) C { + return switch (self) { + .st => .st, + .bel => .bel, + }; + } + + pub fn format( + self: Terminator, + comptime _: []const u8, + _: std.fmt.FormatOptions, + writer: *std.Io.Writer, + ) !void { + try writer.writeAll(self.string()); + } +}; + +pub const Parser = struct { + /// Maximum size of a "normal" OSC. + pub const MAX_BUF = 2048; + + /// Optional allocator used to accept data longer than MAX_BUF. + /// This only applies to some commands (e.g. OSC 52) that can + /// reasonably exceed MAX_BUF. + alloc: ?Allocator, + + /// Current state of the parser. + state: State, + + /// Buffer for temporary storage of OSC data + buffer: [MAX_BUF]u8, + + /// Capture state. If this is set then we're actively capturing the + /// bytes coming into the parser. + capture: ?Capture, + + /// The command that is the result of parsing. + command: Command, + + pub const State = enum { + start, + invalid, + + // OSC command prefixes. Not all of these are valid OSCs, but may be + // needed to "bridge" to a valid OSC (e.g. to support OSC 777 we need to + // have a state "77" even though there is no OSC 77). + @"0", + @"1", + @"2", + @"3", + @"4", + @"5", + @"6", + @"7", + @"8", + @"9", + @"30", + @"300", + @"3008", + @"10", + @"11", + @"12", + @"13", + @"14", + @"15", + @"16", + @"17", + @"18", + @"19", + @"21", + @"22", + @"52", + @"55", + @"66", + @"77", + @"104", + @"110", + @"111", + @"112", + @"113", + @"114", + @"115", + @"116", + @"117", + @"118", + @"119", + @"133", + @"552", + @"777", + @"1337", + @"5522", + }; + + pub fn init(alloc: ?Allocator) Parser { + var result: Parser = .{ + .alloc = alloc, + .state = .start, + .capture = null, + .command = .invalid, + + // Keeping all our undefined values together so we can + // visually easily duplicate them in the Valgrind check below. + .buffer = undefined, + }; + if (std.valgrind.runningOnValgrind() > 0) { + // Initialize our undefined fields so Valgrind can catch it. + // https://github.com/ziglang/zig/issues/19148 + result.buffer = undefined; + } + + return result; + } + + /// This must be called to clean up any allocated memory. + pub fn deinit(self: *Parser) void { + self.reset(); + } + + /// Reset the parser state. + pub fn reset(self: *Parser) void { + // If we're capturing, then stop it. + if (self.capture) |*cap| cap.deinit(); + + // Handle any cleanup that individual OSCs require. + switch (self.command) { + .kitty_color_protocol => |*v| kitty_color_protocol: { + v.deinit(self.alloc orelse break :kitty_color_protocol); + }, + .change_window_icon, + .change_window_title, + .clipboard_contents, + .color_operation, + .conemu_change_tab_title, + .conemu_comment, + .conemu_guimacro, + .conemu_output_environment_variable, + .conemu_progress_report, + .conemu_run_process, + .conemu_show_message_box, + .conemu_sleep, + .conemu_wait_input, + .conemu_xterm_emulation, + .hyperlink_end, + .hyperlink_start, + .invalid, + .mouse_shape, + .report_pwd, + .semantic_prompt, + .show_desktop_notification, + .kitty_text_sizing, + .kitty_clipboard_protocol, + .context_signal, + => {}, + } + + self.state = .start; + self.capture = null; + self.command = .invalid; + + if (std.valgrind.runningOnValgrind() > 0) { + // Initialize our undefined fields so Valgrind can catch it. + // https://github.com/ziglang/zig/issues/19148 + self.buffer = undefined; + } + } + + /// Make sure that we have an allocator. If we don't, set the state to + /// invalid so that any additional OSC data is discarded. + inline fn ensureAllocator(self: *Parser) bool { + if (self.alloc != null) return true; + log.warn("An allocator is required to process OSC {t} but none was provided.", .{self.state}); + self.state = .invalid; + return false; + } + + const Capture = struct { + writer: *std.Io.Writer, + backing: Backing, + + const Backing = union(enum) { + fixed: std.Io.Writer, + allocating: std.Io.Writer.Allocating, + }; + + const Mode = enum { + fixed, + allocating, + }; + + pub inline fn fixed(new: *?Capture, buf: []u8) void { + new.* = .{ + .backing = .{ .fixed = .fixed(buf) }, + .writer = &new.*.?.backing.fixed, + }; + } + + pub inline fn allocating( + new: *?Capture, + alloc: Allocator, + ) error{OutOfMemory}!void { + new.* = .{ + .backing = .{ .allocating = try std.Io.Writer.Allocating.initCapacity( + alloc, + 2048, + ) }, + .writer = &new.*.?.backing.allocating.writer, + }; + } + + pub fn deinit(self: *Capture) void { + switch (self.backing) { + .fixed => {}, + .allocating => |*w| w.deinit(), + } + } + + /// Return the captured trailing data. This is the data from the + /// point that trailing data capture was requested. + pub inline fn trailing(self: *Capture) []u8 { + return self.writer.buffered(); + } + }; + + /// Begin capturing trailing data. All inputs to next from this point + /// forward will be captured into the `self.capture.writer` buffer + /// which may be backed by either a fixed size or allocating buffer + /// depending on mode. + /// + /// Get the trailing data using `capture.trailing()`. Do not access + /// the writer directly. + inline fn captureTrailing( + self: *Parser, + comptime mode: Capture.Mode, + ) void { + assert(self.capture == null); + switch (mode) { + .fixed => Capture.fixed( + &self.capture, + &self.buffer, + ), + + .allocating => { + const alloc = self.alloc orelse { + // We don't have an allocator - fall back to a fixed buffer and hope + // that it's big enough. + self.captureTrailing(.fixed); + return; + }; + + Capture.allocating( + &self.capture, + alloc, + ) catch { + // The allocator failed for some reason, fall back to a fixed buffer + // and hope that it's big enough. + self.captureTrailing(.fixed); + return; + }; + }, + } + } + + /// Consume the next character c and advance the parser state. + pub fn next(self: *Parser, c: u8) void { + // If the state becomes invalid for any reason, just discard + // any further input. + if (self.state == .invalid) return; + + // If a writer has been initialized, we just accumulate the rest of the + // OSC sequence in the writer's buffer and skip the state machine. + if (self.capture) |*cap| { + cap.writer.writeByte(c) catch |err| switch (err) { + // We have overflowed our buffer or had some other error, set the + // state to invalid so that we discard any further input. + error.WriteFailed => self.state = .invalid, + }; + return; + } + + switch (self.state) { + // handled above, so should never be here + .invalid => unreachable, + + .start => switch (c) { + '0' => self.state = .@"0", + '1' => self.state = .@"1", + '2' => self.state = .@"2", + '3' => self.state = .@"3", + '4' => self.state = .@"4", + '5' => self.state = .@"5", + '6' => self.state = .@"6", + '7' => self.state = .@"7", + '8' => self.state = .@"8", + '9' => self.state = .@"9", + else => self.state = .invalid, + }, + + .@"3" => switch (c) { + '0' => self.state = .@"30", + else => self.state = .invalid, + }, + + .@"30" => switch (c) { + '0' => self.state = .@"300", + else => self.state = .invalid, + }, + + .@"300" => switch (c) { + '8' => self.state = .@"3008", + else => self.state = .invalid, + }, + + .@"3008" => switch (c) { + ';' => self.captureTrailing(.fixed), + else => self.state = .invalid, + }, + + .@"1" => switch (c) { + ';' => self.captureTrailing(.fixed), + '0' => self.state = .@"10", + '1' => self.state = .@"11", + '2' => self.state = .@"12", + '3' => self.state = .@"13", + '4' => self.state = .@"14", + '5' => self.state = .@"15", + '6' => self.state = .@"16", + '7' => self.state = .@"17", + '8' => self.state = .@"18", + '9' => self.state = .@"19", + else => self.state = .invalid, + }, + + .@"10" => switch (c) { + ';' => if (self.ensureAllocator()) self.captureTrailing(.fixed), + '4' => self.state = .@"104", + else => self.state = .invalid, + }, + + .@"104" => switch (c) { + ';' => if (self.ensureAllocator()) self.captureTrailing(.fixed), + else => self.state = .invalid, + }, + + .@"11" => switch (c) { + ';' => if (self.ensureAllocator()) self.captureTrailing(.fixed), + '0' => self.state = .@"110", + '1' => self.state = .@"111", + '2' => self.state = .@"112", + '3' => self.state = .@"113", + '4' => self.state = .@"114", + '5' => self.state = .@"115", + '6' => self.state = .@"116", + '7' => self.state = .@"117", + '8' => self.state = .@"118", + '9' => self.state = .@"119", + else => self.state = .invalid, + }, + + .@"4", + .@"12", + .@"14", + .@"15", + .@"16", + .@"17", + .@"18", + .@"19", + .@"21", + .@"110", + .@"111", + .@"112", + .@"113", + .@"114", + .@"115", + .@"116", + .@"117", + .@"118", + .@"119", + => switch (c) { + ';' => if (self.ensureAllocator()) self.captureTrailing(.fixed), + else => self.state = .invalid, + }, + + .@"13" => switch (c) { + ';' => if (self.ensureAllocator()) self.captureTrailing(.fixed), + '3' => self.state = .@"133", + else => self.state = .invalid, + }, + + .@"2" => switch (c) { + ';' => self.captureTrailing(.fixed), + '1' => self.state = .@"21", + '2' => self.state = .@"22", + else => self.state = .invalid, + }, + + .@"5" => switch (c) { + ';' => if (self.ensureAllocator()) self.captureTrailing(.fixed), + '2' => self.state = .@"52", + '5' => self.state = .@"55", + else => self.state = .invalid, + }, + + .@"6" => switch (c) { + '6' => self.state = .@"66", + else => self.state = .invalid, + }, + + .@"52", + .@"66", + => switch (c) { + ';' => self.captureTrailing(.allocating), + else => self.state = .invalid, + }, + + .@"55" => switch (c) { + '2' => self.state = .@"552", + else => self.state = .invalid, + }, + + .@"7" => switch (c) { + ';' => self.captureTrailing(.fixed), + '7' => self.state = .@"77", + else => self.state = .invalid, + }, + + .@"77" => switch (c) { + '7' => self.state = .@"777", + else => self.state = .invalid, + }, + + .@"133", + => switch (c) { + ';' => self.captureTrailing(.fixed), + '7' => self.state = .@"1337", + else => self.state = .invalid, + }, + + .@"552" => switch (c) { + '2' => self.state = .@"5522", + else => self.state = .invalid, + }, + + .@"1337", + => switch (c) { + ';' => self.captureTrailing(.fixed), + else => self.state = .invalid, + }, + + .@"5522", + => switch (c) { + ';' => self.captureTrailing(.allocating), + else => self.state = .invalid, + }, + + .@"0", + .@"22", + .@"777", + .@"8", + .@"9", + => switch (c) { + ';' => self.captureTrailing(.fixed), + else => self.state = .invalid, + }, + } + } + + /// End the sequence and return the command, if any. If the return value + /// is null, then no valid command was found. The optional terminator_ch + /// is the final character in the OSC sequence. This is used to determine + /// the response terminator. + /// + /// The returned pointer is only valid until the next call to the parser. + /// Callers should copy out any data they wish to retain across calls. + pub fn end(self: *Parser, terminator_ch: ?u8) ?*Command { + return switch (self.state) { + .start => null, + + .invalid => null, + + .@"0", + .@"2", + => parsers.change_window_title.parse(self, terminator_ch), + + .@"1" => parsers.change_window_icon.parse(self, terminator_ch), + + .@"4", + .@"5", + .@"10", + .@"11", + .@"12", + .@"13", + .@"14", + .@"15", + .@"16", + .@"17", + .@"18", + .@"19", + .@"104", + .@"110", + .@"111", + .@"112", + .@"113", + .@"114", + .@"115", + .@"116", + .@"117", + .@"118", + .@"119", + => parsers.color.parse(self, terminator_ch), + + .@"7" => parsers.report_pwd.parse(self, terminator_ch), + + .@"8" => parsers.hyperlink.parse(self, terminator_ch), + + .@"9" => parsers.osc9.parse(self, terminator_ch), + + .@"21" => parsers.kitty_color.parse(self, terminator_ch), + + .@"22" => parsers.mouse_shape.parse(self, terminator_ch), + + .@"52" => parsers.clipboard_operation.parse(self, terminator_ch), + + .@"55" => null, + + .@"3", + .@"30", + .@"300", + => null, + + .@"3008" => parsers.context_signal.parse(self, terminator_ch), + + .@"6" => null, + + .@"66" => parsers.kitty_text_sizing.parse(self, terminator_ch), + + .@"77" => null, + + .@"133" => parsers.semantic_prompt.parse(self, terminator_ch), + + .@"552" => null, + + .@"777" => parsers.rxvt_extension.parse(self, terminator_ch), + + .@"1337" => parsers.iterm2.parse(self, terminator_ch), + + .@"5522" => parsers.kitty_clipboard_protocol.parse(self, terminator_ch), + }; + } +}; + +test { + _ = parsers; + _ = encoding; +} diff --git a/vendor/libghostty-vt/src/terminal/osc/encoding.zig b/vendor/libghostty-vt/src/terminal/osc/encoding.zig new file mode 100644 index 00000000..7491d10c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/encoding.zig @@ -0,0 +1,38 @@ +//! Specialized encodings used in some OSC protocols. +const std = @import("std"); + +/// Kitty defines "Escape code safe UTF-8" as valid UTF-8 with the +/// additional requirement of not containing any C0 escape codes +/// (0x00-0x1f), DEL (0x7f) and C1 escape codes (0x80-0x9f). +/// +/// Used by OSC 66 (text sizing) and OSC 99 (Kitty notifications). +/// +/// See: https://sw.kovidgoyal.net/kitty/desktop-notifications/#safe-utf8 +pub fn isSafeUtf8(s: []const u8) bool { + const utf8 = std.unicode.Utf8View.init(s) catch { + @branchHint(.cold); + return false; + }; + + var it = utf8.iterator(); + while (it.nextCodepoint()) |cp| switch (cp) { + 0x00...0x1f, 0x7f, 0x80...0x9f => { + @branchHint(.cold); + return false; + }, + else => {}, + }; + + return true; +} + +test isSafeUtf8 { + const testing = std.testing; + + try testing.expect(isSafeUtf8("Hello world!")); + try testing.expect(isSafeUtf8("安全的ユニコード☀️")); + try testing.expect(!isSafeUtf8("No linebreaks\nallowed")); + try testing.expect(!isSafeUtf8("\x07no bells")); + try testing.expect(!isSafeUtf8("\x1b]9;no OSCs\x1b\\\x1b[m")); + try testing.expect(!isSafeUtf8("\x9f8-bit escapes are clever, but no")); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers.zig b/vendor/libghostty-vt/src/terminal/osc/parsers.zig new file mode 100644 index 00000000..a56b38e8 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers.zig @@ -0,0 +1,21 @@ +const std = @import("std"); + +pub const change_window_icon = @import("parsers/change_window_icon.zig"); +pub const context_signal = @import("parsers/context_signal.zig"); +pub const change_window_title = @import("parsers/change_window_title.zig"); +pub const clipboard_operation = @import("parsers/clipboard_operation.zig"); +pub const color = @import("parsers/color.zig"); +pub const hyperlink = @import("parsers/hyperlink.zig"); +pub const iterm2 = @import("parsers/iterm2.zig"); +pub const kitty_clipboard_protocol = @import("parsers/kitty_clipboard_protocol.zig"); +pub const kitty_color = @import("parsers/kitty_color.zig"); +pub const kitty_text_sizing = @import("parsers/kitty_text_sizing.zig"); +pub const mouse_shape = @import("parsers/mouse_shape.zig"); +pub const osc9 = @import("parsers/osc9.zig"); +pub const report_pwd = @import("parsers/report_pwd.zig"); +pub const rxvt_extension = @import("parsers/rxvt_extension.zig"); +pub const semantic_prompt = @import("parsers/semantic_prompt.zig"); + +test { + std.testing.refAllDecls(@This()); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/change_window_icon.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/change_window_icon.zig new file mode 100644 index 00000000..eeae6a71 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/change_window_icon.zig @@ -0,0 +1,33 @@ +const std = @import("std"); +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +/// Parse OSC 1 +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + parser.command = .{ + .change_window_icon = data[0 .. data.len - 1 :0], + }; + return &parser.command; +} + +test "OSC 1: change_window_icon" { + const testing = std.testing; + + var p: Parser = .init(null); + p.next('1'); + p.next(';'); + p.next('a'); + p.next('b'); + const cmd = p.end(null).?.*; + try testing.expect(cmd == .change_window_icon); + try testing.expectEqualStrings("ab", cmd.change_window_icon); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/change_window_title.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/change_window_title.zig new file mode 100644 index 00000000..5bd84dc3 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/change_window_title.zig @@ -0,0 +1,119 @@ +const std = @import("std"); + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +/// Parse OSC 0 and OSC 2 +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + parser.command = .{ + .change_window_title = data[0 .. data.len - 1 :0], + }; + return &parser.command; +} + +test "OSC 0: change_window_title" { + const testing = std.testing; + + var p: Parser = .init(null); + p.next('0'); + p.next(';'); + p.next('a'); + p.next('b'); + const cmd = p.end(null).?.*; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings("ab", cmd.change_window_title); +} + +test "OSC 0: longer than buffer" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "0;" ++ "a" ** (Parser.MAX_BUF + 2); + for (input) |ch| p.next(ch); + + try testing.expect(p.end(null) == null); +} + +test "OSC 0: one shorter than buffer length" { + const testing = std.testing; + + var p: Parser = .init(null); + + const prefix = "0;"; + const title = "a" ** (Parser.MAX_BUF - 1); + const input = prefix ++ title; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings(title, cmd.change_window_title); +} + +test "OSC 0: exactly at buffer length" { + const testing = std.testing; + + var p: Parser = .init(null); + + const prefix = "0;"; + const title = "a" ** Parser.MAX_BUF; + const input = prefix ++ title; + for (input) |ch| p.next(ch); + + // This should be null because we always reserve space for a null terminator. + try testing.expect(p.end(null) == null); +} +test "OSC 2: change_window_title with 2" { + const testing = std.testing; + + var p: Parser = .init(null); + p.next('2'); + p.next(';'); + p.next('a'); + p.next('b'); + const cmd = p.end(null).?.*; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings("ab", cmd.change_window_title); +} + +test "OSC 2: change_window_title with utf8" { + const testing = std.testing; + + var p: Parser = .init(null); + p.next('2'); + p.next(';'); + // '—' EM DASH U+2014 (E2 80 94) + p.next(0xE2); + p.next(0x80); + p.next(0x94); + + p.next(' '); + // '‐' HYPHEN U+2010 (E2 80 90) + // Intententionally chosen to conflict with the 0x90 C1 control + p.next(0xE2); + p.next(0x80); + p.next(0x90); + const cmd = p.end(null).?.*; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings("— ‐", cmd.change_window_title); +} + +test "OSC 2: change_window_title empty" { + const testing = std.testing; + + var p: Parser = .init(null); + p.next('2'); + p.next(';'); + const cmd = p.end(null).?.*; + try testing.expect(cmd == .change_window_title); + try testing.expectEqualStrings("", cmd.change_window_title); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/clipboard_operation.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/clipboard_operation.zig new file mode 100644 index 00000000..8d149f97 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/clipboard_operation.zig @@ -0,0 +1,106 @@ +const std = @import("std"); + +const assert = @import("../../../quirks.zig").inlineAssert; + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +/// Parse OSC 52 +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + assert(parser.state == .@"52"); + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + if (data.len == 1) { + parser.state = .invalid; + return null; + } + if (data[0] == ';') { + parser.command = .{ + .clipboard_contents = .{ + .kind = 'c', + .data = data[1 .. data.len - 1 :0], + }, + }; + } else { + if (data.len < 2) { + parser.state = .invalid; + return null; + } + if (data[1] != ';') { + parser.state = .invalid; + return null; + } + parser.command = .{ + .clipboard_contents = .{ + .kind = data[0], + .data = data[2 .. data.len - 1 :0], + }, + }; + } + return &parser.command; +} + +test "OSC 52: get/set clipboard" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "52;s;?"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .clipboard_contents); + try testing.expect(cmd.clipboard_contents.kind == 's'); + try testing.expectEqualStrings("?", cmd.clipboard_contents.data); +} + +test "OSC 52: get/set clipboard (optional parameter)" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "52;;?"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .clipboard_contents); + try testing.expect(cmd.clipboard_contents.kind == 'c'); + try testing.expectEqualStrings("?", cmd.clipboard_contents.data); +} + +test "OSC 52: get/set clipboard with allocator" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "52;s;?"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .clipboard_contents); + try testing.expect(cmd.clipboard_contents.kind == 's'); + try testing.expectEqualStrings("?", cmd.clipboard_contents.data); +} + +test "OSC 52: clear clipboard" { + const testing = std.testing; + + var p: Parser = .init(null); + defer p.deinit(); + + const input = "52;;"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .clipboard_contents); + try testing.expect(cmd.clipboard_contents.kind == 'c'); + try testing.expectEqualStrings("", cmd.clipboard_contents.data); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/color.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/color.zig new file mode 100644 index 00000000..547c98ea --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/color.zig @@ -0,0 +1,780 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; + +const DynamicColor = @import("../../color.zig").Dynamic; +const SpecialColor = @import("../../color.zig").Special; +const RGB = @import("../../color.zig").RGB; +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +const log = std.log.scoped(.osc_color); + +const ParseError = Allocator.Error || error{ + MissingOperation, +}; + +/// The possible operations we support for colors. +pub const Operation = enum { + osc_4, + osc_5, + osc_10, + osc_11, + osc_12, + osc_13, + osc_14, + osc_15, + osc_16, + osc_17, + osc_18, + osc_19, + osc_104, + osc_105, + osc_110, + osc_111, + osc_112, + osc_113, + osc_114, + osc_115, + osc_116, + osc_117, + osc_118, + osc_119, +}; + +/// Parse OSCs 4, 5, 10-19, 104, 110-119 +pub fn parse(parser: *Parser, terminator_ch: ?u8) ?*Command { + const alloc = parser.alloc orelse { + parser.state = .invalid; + return null; + }; + // If we've collected any extra data parse that, otherwise use an empty + // string. + const data = data: { + const cap = if (parser.capture) |*c| c else break :data ""; + break :data cap.trailing(); + }; + // Check and make sure that we're parsing the correct OSCs + const op: Operation = switch (parser.state) { + .@"4" => .osc_4, + .@"5" => .osc_5, + .@"10" => .osc_10, + .@"11" => .osc_11, + .@"12" => .osc_12, + .@"13" => .osc_13, + .@"14" => .osc_14, + .@"15" => .osc_15, + .@"16" => .osc_16, + .@"17" => .osc_17, + .@"18" => .osc_18, + .@"19" => .osc_19, + .@"104" => .osc_104, + .@"110" => .osc_110, + .@"111" => .osc_111, + .@"112" => .osc_112, + .@"113" => .osc_113, + .@"114" => .osc_114, + .@"115" => .osc_115, + .@"116" => .osc_116, + .@"117" => .osc_117, + .@"118" => .osc_118, + .@"119" => .osc_119, + else => { + parser.state = .invalid; + return null; + }, + }; + parser.command = .{ + .color_operation = .{ + .op = op, + .requests = parseColor(alloc, op, data) catch |err| list: { + log.info( + "failed to parse OSC {t} color request err={} data={s}", + .{ parser.state, err, data }, + ); + break :list .{}; + }, + .terminator = .init(terminator_ch), + }, + }; + return &parser.command; +} + +test "OSC 4: empty param" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "4;;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b'); + try testing.expect(cmd == null); +} + +/// Parse any color operation string. This should NOT include the operation +/// itself, but only the body of the operation. e.g. for "4;a;b;c" the body +/// should be "a;b;c" and the operation should be set accordingly. +/// +/// Color parsing is fairly complicated so we pull this out to a specialized +/// function rather than go through our OSC parsing state machine. This is +/// much slower and requires more memory (since we need to buffer the full +/// request) but grants us an easier to understand and testable implementation. +/// +/// If color changing ends up being a bottleneck we can optimize this later. +fn parseColor( + alloc: Allocator, + op: Operation, + buf: []const u8, +) ParseError!List { + var it = std.mem.tokenizeScalar(u8, buf, ';'); + return switch (op) { + .osc_4 => try parseGetSetAnsiColor(alloc, .osc_4, &it), + .osc_5 => try parseGetSetAnsiColor(alloc, .osc_5, &it), + .osc_104 => try parseResetAnsiColor(alloc, .osc_104, &it), + .osc_105 => try parseResetAnsiColor(alloc, .osc_105, &it), + .osc_10 => try parseGetSetDynamicColor(alloc, .foreground, &it), + .osc_11 => try parseGetSetDynamicColor(alloc, .background, &it), + .osc_12 => try parseGetSetDynamicColor(alloc, .cursor, &it), + .osc_13 => try parseGetSetDynamicColor(alloc, .pointer_foreground, &it), + .osc_14 => try parseGetSetDynamicColor(alloc, .pointer_background, &it), + .osc_15 => try parseGetSetDynamicColor(alloc, .tektronix_foreground, &it), + .osc_16 => try parseGetSetDynamicColor(alloc, .tektronix_background, &it), + .osc_17 => try parseGetSetDynamicColor(alloc, .highlight_background, &it), + .osc_18 => try parseGetSetDynamicColor(alloc, .tektronix_cursor, &it), + .osc_19 => try parseGetSetDynamicColor(alloc, .highlight_foreground, &it), + .osc_110 => try parseResetDynamicColor(alloc, .foreground, &it), + .osc_111 => try parseResetDynamicColor(alloc, .background, &it), + .osc_112 => try parseResetDynamicColor(alloc, .cursor, &it), + .osc_113 => try parseResetDynamicColor(alloc, .pointer_foreground, &it), + .osc_114 => try parseResetDynamicColor(alloc, .pointer_background, &it), + .osc_115 => try parseResetDynamicColor(alloc, .tektronix_foreground, &it), + .osc_116 => try parseResetDynamicColor(alloc, .tektronix_background, &it), + .osc_117 => try parseResetDynamicColor(alloc, .highlight_background, &it), + .osc_118 => try parseResetDynamicColor(alloc, .tektronix_cursor, &it), + .osc_119 => try parseResetDynamicColor(alloc, .highlight_foreground, &it), + }; +} + +/// OSC 4/5 +fn parseGetSetAnsiColor( + alloc: Allocator, + comptime op: Operation, + it: *std.mem.TokenIterator(u8, .scalar), +) Allocator.Error!List { + // Note: in ANY error scenario below we return the accumulated results. + // This matches the xterm behavior (see misc.c ChangeAnsiColorRequest) + + var result: List = .{}; + errdefer result.deinit(alloc); + while (true) { + // We expect a `c; spec` pair. If either doesn't exist then + // we return the results up to this point. + const color_str = it.next() orelse return result; + const spec_str = it.next() orelse return result; + + // Color must be numeric. u9 because that'll fit our palette + special + const color: u9 = std.fmt.parseInt( + u9, + color_str, + 10, + ) catch return result; + + // Parse the color. + const target: Target = switch (op) { + // OSC5 maps directly to the Special enum. + .osc_5 => .{ .special = std.meta.intToEnum( + SpecialColor, + std.math.cast(u3, color) orelse return result, + ) catch return result }, + + // OSC4 maps 0-255 to palette, 256-259 to special offset + // by the palette count. + .osc_4 => if (std.math.cast(u8, color)) |idx| .{ + .palette = idx, + } else .{ .special = std.meta.intToEnum( + SpecialColor, + std.math.cast(u3, color - 256) orelse return result, + ) catch return result }, + + else => comptime unreachable, + }; + + // "?" always results in a query. + if (std.mem.eql(u8, spec_str, "?")) { + const req = try result.addOne(alloc); + req.* = .{ .query = target }; + continue; + } + + const rgb = RGB.parse(spec_str) catch return result; + const req = try result.addOne(alloc); + req.* = .{ .set = .{ + .target = target, + .color = rgb, + } }; + } +} + +/// OSC 104/105: Reset ANSI Colors +fn parseResetAnsiColor( + alloc: Allocator, + comptime op: Operation, + it: *std.mem.TokenIterator(u8, .scalar), +) Allocator.Error!List { + // Note: xterm stops parsing the reset list on any error, but we're + // more flexible and try the next value. This matches the behavior of + // Kitty and I don't see a downside to being more flexible here. Hopefully + // no one depends on the exact behavior of xterm. + + var result: List = .{}; + errdefer result.deinit(alloc); + while (true) { + const color_str = it.next() orelse { + // If no parameters are given, we reset the full table. + if (result.count() == 0) { + const req = try result.addOne(alloc); + req.* = switch (op) { + .osc_104 => .reset_palette, + .osc_105 => .reset_special, + else => comptime unreachable, + }; + } + return result; + }; + + // Empty color strings are ignored, not treated as an error. + if (color_str.len == 0) continue; + + // Color must be numeric. u9 because that'll fit our palette + special + const color: u9 = std.fmt.parseInt( + u9, + color_str, + 10, + ) catch continue; + + // Parse the color. + const target: Target = switch (op) { + // OSC105 maps directly to the Special enum. + .osc_105 => .{ .special = std.meta.intToEnum( + SpecialColor, + std.math.cast(u3, color) orelse continue, + ) catch continue }, + + // OSC104 maps 0-255 to palette, 256-259 to special offset + // by the palette count. + .osc_104 => if (std.math.cast(u8, color)) |idx| .{ + .palette = idx, + } else .{ .special = std.meta.intToEnum( + SpecialColor, + std.math.cast(u3, color - 256) orelse continue, + ) catch continue }, + + else => comptime unreachable, + }; + + const req = try result.addOne(alloc); + req.* = .{ .reset = target }; + } +} + +/// OSC 10-19: Get/Set Dynamic Colors +fn parseGetSetDynamicColor( + alloc: Allocator, + start: DynamicColor, + it: *std.mem.TokenIterator(u8, .scalar), +) Allocator.Error!List { + // Note: in ANY error scenario below we return the accumulated results. + // This matches the xterm behavior (see misc.c ChangeColorsRequest) + + var result: List = .{}; + var color: DynamicColor = start; + while (true) { + const spec_str = it.next() orelse return result; + + if (std.mem.eql(u8, spec_str, "?")) { + const req = try result.addOne(alloc); + req.* = .{ .query = .{ .dynamic = color } }; + } else { + const rgb = RGB.parse(spec_str) catch return result; + const req = try result.addOne(alloc); + req.* = .{ .set = .{ + .target = .{ .dynamic = color }, + .color = rgb, + } }; + } + + // Each successive value uses the next color so long as it exists. + color = color.next() orelse return result; + } +} + +/// OSC 110-119: Reset Dynamic Colors +fn parseResetDynamicColor( + alloc: Allocator, + color: DynamicColor, + it: *std.mem.TokenIterator(u8, .scalar), +) Allocator.Error!List { + var result: List = .{}; + errdefer result.deinit(alloc); + if (it.next() != null) return result; + const req = try result.addOne(alloc); + req.* = .{ .reset = .{ .dynamic = color } }; + return result; +} + +/// A segmented list is used to avoid copying when many operations +/// are given in a single OSC. In most cases, OSC 4/104/etc. send +/// very few so the prealloc is optimized for that. +/// +/// The exact prealloc value is chosen arbitrarily assuming most +/// color ops have very few. If we can get empirical data on more +/// typical values we can switch to that. +pub const List = std.SegmentedList( + Request, + 2, +); + +/// A single operation related to the terminal color palette. +pub const Request = union(enum) { + set: ColoredTarget, + query: Target, + reset: Target, + reset_palette, + reset_special, +}; + +pub const Target = union(enum) { + palette: u8, + special: SpecialColor, + dynamic: DynamicColor, +}; + +pub const ColoredTarget = struct { + target: Target, + color: RGB, +}; + +test "OSC 4:" { + const testing = std.testing; + const alloc = testing.allocator; + + // Test every palette index + for (0..std.math.maxInt(u8)) |idx| { + // Simple color set + // printf '\e]4;0;red\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d};red", + .{idx}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_4, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = @intCast(idx) }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + } + + // Simple color query + // printf '\e]4;0;?\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d};?", + .{idx}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_4, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .query = .{ .palette = @intCast(idx) } }, + list.at(0).*, + ); + } + + // Trailing invalid data produces results up to that point + // printf '\e]4;0;red;\e\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d};red;", + .{idx}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_4, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = @intCast(idx) }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + } + + // Whitespace doesn't produce a working value in xterm but we + // allow it because Kitty does and it seems harmless. + // + // printf '\e]4;0;red \e\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d};red ", + .{idx}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_4, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = @intCast(idx) }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + } + } + + // Test every special color + for (0..@typeInfo(SpecialColor).@"enum".fields.len) |i| { + const special = try std.meta.intToEnum(SpecialColor, i); + + // Simple color set + // printf '\e]4;256;red\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d};red", + .{256 + i}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_4, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .special = special }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + } + } +} + +test "OSC 5:" { + const testing = std.testing; + const alloc = testing.allocator; + + // Test every special color + for (0..@typeInfo(SpecialColor).@"enum".fields.len) |i| { + const special = try std.meta.intToEnum(SpecialColor, i); + + // Simple color set + // printf '\e]4;256;red\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d};red", + .{i}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_5, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .special = special }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + } + } +} + +test "OSC 4: multiple requests" { + const testing = std.testing; + const alloc = testing.allocator; + + // printf '\e]4;0;red;1;blue\e\\' + { + var list = try parseColor( + alloc, + .osc_4, + "0;red;1;blue", + ); + defer list.deinit(alloc); + try testing.expectEqual(2, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = 0 }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = 1 }, + .color = RGB{ .r = 0, .g = 0, .b = 255 }, + } }, + list.at(1).*, + ); + } + + // Multiple requests with same index overwrite each other + // printf '\e]4;0;red;0;blue\e\\' + { + var list = try parseColor( + alloc, + .osc_4, + "0;red;0;blue", + ); + defer list.deinit(alloc); + try testing.expectEqual(2, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = 0 }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .palette = 0 }, + .color = RGB{ .r = 0, .g = 0, .b = 255 }, + } }, + list.at(1).*, + ); + } +} + +test "OSC 104:" { + const testing = std.testing; + const alloc = testing.allocator; + + // Test every palette index + for (0..std.math.maxInt(u8)) |idx| { + // Simple color set + // printf '\e]104;0\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d}", + .{idx}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_104, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset = .{ .palette = @intCast(idx) } }, + list.at(0).*, + ); + } + } + + // Test every special color + for (0..@typeInfo(SpecialColor).@"enum".fields.len) |i| { + const special = try std.meta.intToEnum(SpecialColor, i); + + // Simple color set + // printf '\e]104;256\\' + { + const body = try std.fmt.allocPrint( + alloc, + "{d}", + .{256 + i}, + ); + defer alloc.free(body); + + var list = try parseColor(alloc, .osc_104, body); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset = .{ .special = special } }, + list.at(0).*, + ); + } + } +} + +test "OSC 104: empty index" { + const testing = std.testing; + const alloc = testing.allocator; + + var list = try parseColor(alloc, .osc_104, "0;;1"); + defer list.deinit(alloc); + try testing.expectEqual(2, list.count()); + try testing.expectEqual( + Request{ .reset = .{ .palette = 0 } }, + list.at(0).*, + ); + try testing.expectEqual( + Request{ .reset = .{ .palette = 1 } }, + list.at(1).*, + ); +} + +test "OSC 104: invalid index" { + const testing = std.testing; + const alloc = testing.allocator; + + var list = try parseColor(alloc, .osc_104, "ffff;1"); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset = .{ .palette = 1 } }, + list.at(0).*, + ); +} + +test "OSC 104: reset all" { + const testing = std.testing; + const alloc = testing.allocator; + + var list = try parseColor(alloc, .osc_104, ""); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset_palette = {} }, + list.at(0).*, + ); +} + +test "OSC 105: reset all" { + const testing = std.testing; + const alloc = testing.allocator; + + var list = try parseColor(alloc, .osc_105, ""); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset_special = {} }, + list.at(0).*, + ); +} + +// OSC 10-19: Get/Set Dynamic Colors +test "OSC 10: OSC 11: OSC 12: OSC: 13: OSC 14: OSC 15: OSC: 16: OSC 17: OSC 18: OSC 19: dynamic" { + const testing = std.testing; + const alloc = testing.allocator; + + inline for (@typeInfo(DynamicColor).@"enum".fields) |field| { + const color = @field(DynamicColor, field.name); + const op = @field(Operation, std.fmt.comptimePrint( + "osc_{d}", + .{field.value}, + )); + + // Example script: + // printf '\e]10;red\e\\' + { + var list = try parseColor(alloc, op, "red"); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .dynamic = color }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + } + } +} + +test "OSC 10: OSC 11: OSC 12: OSC: 13: OSC 14: OSC 15: OSC: 16: OSC 17: OSC 18: OSC 19: dynamic multiple" { + const testing = std.testing; + const alloc = testing.allocator; + + // Example script: + // printf '\e]11;red;blue\e\\' + { + var list = try parseColor( + alloc, + .osc_11, + "red;blue", + ); + defer list.deinit(alloc); + try testing.expectEqual(2, list.count()); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .dynamic = .background }, + .color = RGB{ .r = 255, .g = 0, .b = 0 }, + } }, + list.at(0).*, + ); + try testing.expectEqual( + Request{ .set = .{ + .target = .{ .dynamic = .cursor }, + .color = RGB{ .r = 0, .g = 0, .b = 255 }, + } }, + list.at(1).*, + ); + } +} + +// OSC 110-119: Reset Dynamic Colors +test "OSC 110: OSC 111: OSC 112: OSC: 113: OSC 114: OSC 115: OSC: 116: OSC 117: OSC 118: OSC 119: reset dynamic" { + const testing = std.testing; + const alloc = testing.allocator; + + inline for (@typeInfo(DynamicColor).@"enum".fields) |field| { + const color = @field(DynamicColor, field.name); + const op = @field(Operation, std.fmt.comptimePrint( + "osc_1{d}", + .{field.value}, + )); + + // Example script: + // printf '\e]110\e\\' + { + var list = try parseColor(alloc, op, ""); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset = .{ .dynamic = color } }, + list.at(0).*, + ); + } + + // xterm allows a trailing semicolon. script to verify: + // + // printf '\e]110;\e\\' + { + var list = try parseColor(alloc, op, ";"); + defer list.deinit(alloc); + try testing.expectEqual(1, list.count()); + try testing.expectEqual( + Request{ .reset = .{ .dynamic = color } }, + list.at(0).*, + ); + } + + // xterm does NOT allow any whitespace + // + // printf '\e]110 \e\\' + { + var list = try parseColor(alloc, op, " "); + defer list.deinit(alloc); + try testing.expectEqual(0, list.count()); + } + } +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/context_signal.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/context_signal.zig new file mode 100644 index 00000000..e7eb9348 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/context_signal.zig @@ -0,0 +1,541 @@ +//! OSC 3008: Hierarchical Context Signalling (UAPI spec) +//! Specification: https://uapi-group.org/specifications/specs/osc_context/ +//! +//! OSC 3008 allows programs to signal context changes to the terminal emulator. +//! Each context has an identifier and metadata fields. Contexts are hierarchical +//! and form a stack. + +const std = @import("std"); +const Parser = @import("../../osc.zig").Parser; +const OSCCommand = @import("../../osc.zig").Command; + +const log = std.log.scoped(.osc_context_signal); + +/// Maximum length of a context identifier (per spec). +const max_context_id_len = 64; + +/// A single OSC 3008 context signal command. +pub const Command = struct { + pub const C = void; + + action: Action, + /// The context identifier. Must be 1-64 characters in the 32..126 byte range. + id: []const u8, + /// Raw unparsed metadata fields after the context ID. + /// Fields are semicolon-separated key=value pairs. + /// Parsed lazily via `readOption`. + metadata: []const u8, + + pub const Action = enum { + /// OSC 3008;start= — initiates, updates, or returns to a context. + start, + /// OSC 3008;end= — terminates a context. + end, + }; + + /// Read a metadata field value from the raw fields string. + /// Returns null if the field is not present or malformed. + pub fn readOption( + self: Command, + comptime option: Field, + ) option.Type() { + return option.read(self.metadata); + } +}; + +/// Context types defined by the specification. +pub const ContextType = enum { + boot, + container, + vm, + elevate, + chpriv, + subcontext, + remote, + shell, + command, + app, + service, + session, + + pub fn parse(value: []const u8) ?ContextType { + return std.meta.stringToEnum(ContextType, value); + } +}; + +/// Exit status for the `exit` end-sequence field. +pub const ExitStatus = enum { + success, + failure, + crash, + interrupt, + + pub fn parse(value: []const u8) ?ExitStatus { + return std.meta.stringToEnum(ExitStatus, value); + } +}; + +/// Metadata fields that can appear in OSC 3008 sequences. +/// Fields are read lazily from the raw string using the `read` method. +pub const Field = enum { + // Start sequence fields + type, + user, + hostname, + machineid, + bootid, + pid, + pidfdid, + comm, + cwd, + cmdline, + vm, + container, + targetuser, + targethost, + sessionid, + + // End sequence fields + exit, + status, + signal, + + pub fn Type(comptime self: Field) type { + return switch (self) { + .type => ?ContextType, + .exit => ?ExitStatus, + .pid, .pidfdid => ?u64, + .status => ?u64, + // All other fields are string values + .user, + .hostname, + .machineid, + .bootid, + .comm, + .cwd, + .cmdline, + .vm, + .container, + .targetuser, + .targethost, + .sessionid, + .signal, + => ?[]const u8, + }; + } + + fn key(comptime self: Field) []const u8 { + return @tagName(self); + } + + /// Read the field value from the raw fields string. + /// + /// The raw fields string contains semicolon-separated key=value pairs + /// e.g. "type=container;user=lennart;hostname=zeta". + /// + /// Unknown or malformed fields are ignored per the specification. + pub fn read( + comptime self: Field, + raw: []const u8, + ) self.Type() { + var it = std.mem.splitScalar(u8, raw, ';'); + while (it.next()) |full| { + // Parse key=value + const value = value: { + if (std.mem.indexOfScalar( + u8, + full, + '=', + )) |eql_idx| { + if (std.mem.eql( + u8, + full[0..eql_idx], + self.key(), + )) { + break :value full[eql_idx + 1 ..]; + } + } + + continue; + }; + + return switch (self) { + .type => .parse(value), + .exit => .parse(value), + .pid, .pidfdid, .status => value: { + for (value) |c| { + if (c < '0' or c > '9') break :value null; + } + break :value std.fmt.parseInt( + u64, + value, + 10, + ) catch null; + }, + // String fields + .user, + .hostname, + .machineid, + .bootid, + .comm, + .cwd, + .cmdline, + .vm, + .container, + .targetuser, + .targethost, + .sessionid, + .signal, + => if (value.len > 0) value else null, + }; + } + + // Not found + return null; + } +}; + +/// Parse OSC 3008: hierarchical context signalling. +/// +/// Expected data format (after "3008;" prefix has been consumed by the state machine): +/// start=[;=]* +/// end=[;=]* +pub fn parse(parser: *Parser, _: ?u8) ?*OSCCommand { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + if (data.len == 0) { + parser.state = .invalid; + return null; + } + + // Determine the action (start= or end=) + const action: Command.Action = action: { + if (std.mem.startsWith(u8, data, "start=")) break :action .start; + if (std.mem.startsWith(u8, data, "end=")) break :action .end; + + log.warn("OSC 3008: expected 'start=' or 'end=' prefix, got: {s}", .{ + data[0..@min(data.len, 10)], + }); + parser.state = .invalid; + return null; + }; + + // Skip past the "start=" or "end=" prefix + const prefix_len: usize = switch (action) { + .start => "start=".len, + .end => "end=".len, + }; + const rest = data[prefix_len..]; + + if (rest.len == 0) { + log.warn("OSC 3008: missing context ID", .{}); + parser.state = .invalid; + return null; + } + + // Extract the context ID (up to the first semicolon or end of data) + const id_end = std.mem.indexOfScalar(u8, rest, ';') orelse rest.len; + const id = rest[0..id_end]; + + // Validate context ID length (1-64 chars per spec) + if (id.len == 0 or id.len > max_context_id_len) { + log.warn("OSC 3008: context ID length {d} out of range (1-{d})", .{ + id.len, + max_context_id_len, + }); + parser.state = .invalid; + return null; + } + + // Validate context ID characters (32..126 byte range per spec) + for (id) |c| { + if (c < 0x20 or c > 0x7e) { + log.warn("OSC 3008: invalid character 0x{x:0>2} in context ID", .{c}); + parser.state = .invalid; + return null; + } + } + + // Extract raw metadata fields (everything after the ID) + const metadata = if (id_end < rest.len) rest[id_end + 1 ..] else ""; + + parser.command = .{ + .context_signal = .{ + .action = action, + .id = id, + .metadata = metadata, + }, + }; + + return &parser.command; +} + +// ============================================================================ +// Tests +// ============================================================================ + +test "OSC 3008: basic start command" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=abc123"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .start); + try testing.expectEqualStrings("abc123", cmd.context_signal.id); + try testing.expectEqualStrings("", cmd.context_signal.metadata); +} + +test "OSC 3008: basic end command" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;end=abc123"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .end); + try testing.expectEqualStrings("abc123", cmd.context_signal.id); + try testing.expectEqualStrings("", cmd.context_signal.metadata); +} + +test "OSC 3008: start with metadata fields" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=bed86fab93af4328bbed0a1224af6d40;type=container;user=lennart;hostname=zeta"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .start); + try testing.expectEqualStrings("bed86fab93af4328bbed0a1224af6d40", cmd.context_signal.id); + + // Read individual fields + try testing.expect(cmd.context_signal.readOption(.type).? == .container); + try testing.expectEqualStrings("lennart", cmd.context_signal.readOption(.user).?); + try testing.expectEqualStrings("zeta", cmd.context_signal.readOption(.hostname).?); +} + +test "OSC 3008: start with all common fields" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=myctx;type=shell;user=root;hostname=myhost;machineid=3deb5353d3ba43d08201c136a47ead7b;bootid=d4a3d0fdf2e24fdea6d971ce73f4fbf2;pid=1062862;pidfdid=1063162;comm=bash"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.readOption(.type).? == .shell); + try testing.expectEqualStrings("root", cmd.context_signal.readOption(.user).?); + try testing.expectEqualStrings("myhost", cmd.context_signal.readOption(.hostname).?); + try testing.expectEqualStrings("3deb5353d3ba43d08201c136a47ead7b", cmd.context_signal.readOption(.machineid).?); + try testing.expectEqualStrings("d4a3d0fdf2e24fdea6d971ce73f4fbf2", cmd.context_signal.readOption(.bootid).?); + try testing.expectEqual(@as(u64, 1062862), cmd.context_signal.readOption(.pid).?); + try testing.expectEqual(@as(u64, 1063162), cmd.context_signal.readOption(.pidfdid).?); + try testing.expectEqualStrings("bash", cmd.context_signal.readOption(.comm).?); +} + +test "OSC 3008: end with exit metadata" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;end=myctx;exit=success;status=0"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .end); + try testing.expectEqualStrings("myctx", cmd.context_signal.id); + try testing.expect(cmd.context_signal.readOption(.exit).? == .success); + try testing.expectEqual(@as(u64, 0), cmd.context_signal.readOption(.status).?); +} + +test "OSC 3008: end with failure exit" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;end=myctx;exit=failure;status=1;signal=SIGKILL"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.readOption(.exit).? == .failure); + try testing.expectEqual(@as(u64, 1), cmd.context_signal.readOption(.status).?); + try testing.expectEqualStrings("SIGKILL", cmd.context_signal.readOption(.signal).?); +} + +test "OSC 3008: unknown fields are ignored" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=myctx;type=shell;unknownfield=value;user=root"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.readOption(.type).? == .shell); + try testing.expectEqualStrings("root", cmd.context_signal.readOption(.user).?); +} + +test "OSC 3008: missing field returns null" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=myctx;user=lennart"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.readOption(.type) == null); + try testing.expect(cmd.context_signal.readOption(.hostname) == null); + try testing.expect(cmd.context_signal.readOption(.pid) == null); +} + +test "OSC 3008: invalid prefix" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;bogus=abc123"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 3008: empty data" { + const testing = std.testing; + + // Can't really produce empty data after "3008;" because the state machine + // won't write a writer for that case, but we test the edge case where + // only "start=" is present with no ID. + var p: Parser = .init(null); + const input = "3008;start="; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 3008: max length context ID" { + const testing = std.testing; + + var p: Parser = .init(null); + const id = "a" ** 64; + const input = "3008;start=" ++ id; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expectEqualStrings(id, cmd.context_signal.id); +} + +test "OSC 3008: over-length context ID" { + const testing = std.testing; + + var p: Parser = .init(null); + const id = "a" ** 65; + const input = "3008;start=" ++ id; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 3008: context type enum coverage" { + const testing = std.testing; + + const types = [_]struct { str: []const u8, expected: ContextType }{ + .{ .str = "boot", .expected = .boot }, + .{ .str = "container", .expected = .container }, + .{ .str = "vm", .expected = .vm }, + .{ .str = "elevate", .expected = .elevate }, + .{ .str = "chpriv", .expected = .chpriv }, + .{ .str = "subcontext", .expected = .subcontext }, + .{ .str = "remote", .expected = .remote }, + .{ .str = "shell", .expected = .shell }, + .{ .str = "command", .expected = .command }, + .{ .str = "app", .expected = .app }, + .{ .str = "service", .expected = .service }, + .{ .str = "session", .expected = .session }, + }; + + for (types) |t| { + try testing.expectEqual(t.expected, ContextType.parse(t.str).?); + } + + try testing.expect(ContextType.parse("invalid") == null); +} + +test "OSC 3008: exit status enum coverage" { + const testing = std.testing; + + try testing.expect(ExitStatus.parse("success").? == .success); + try testing.expect(ExitStatus.parse("failure").? == .failure); + try testing.expect(ExitStatus.parse("crash").? == .crash); + try testing.expect(ExitStatus.parse("interrupt").? == .interrupt); + try testing.expect(ExitStatus.parse("invalid") == null); +} + +test "OSC 3008: spec example - container start" { + const testing = std.testing; + + // From the spec: a new container "foobar" invoked by user "lennart" on host "zeta" + var p: Parser = .init(null); + const input = "3008;start=bed86fab93af4328bbed0a1224af6d40;type=container;user=lennart;hostname=zeta;machineid=3deb5353d3ba43d08201c136a47ead7b;bootid=d4a3d0fdf2e24fdea6d971ce73f4fbf2;pid=1062862;pidfdid=1063162;comm=systemd-nspawn;container=foobar"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .start); + try testing.expectEqualStrings("bed86fab93af4328bbed0a1224af6d40", cmd.context_signal.id); + try testing.expect(cmd.context_signal.readOption(.type).? == .container); + try testing.expectEqualStrings("lennart", cmd.context_signal.readOption(.user).?); + try testing.expectEqualStrings("zeta", cmd.context_signal.readOption(.hostname).?); + try testing.expectEqualStrings("systemd-nspawn", cmd.context_signal.readOption(.comm).?); + try testing.expectEqualStrings("foobar", cmd.context_signal.readOption(.container).?); + try testing.expectEqual(@as(u64, 1062862), cmd.context_signal.readOption(.pid).?); +} + +test "OSC 3008: spec example - context end" { + const testing = std.testing; + + // From the spec: context end + var p: Parser = .init(null); + const input = "3008;end=bed86fab93af4328bbed0a1224af6d40"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .end); + try testing.expectEqualStrings("bed86fab93af4328bbed0a1224af6d40", cmd.context_signal.id); +} + +test "OSC 3008: cwd and cmdline fields" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=myctx;type=command;cwd=/home/user;cmdline=ls -la"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expectEqualStrings("/home/user", cmd.context_signal.readOption(.cwd).?); + try testing.expectEqualStrings("ls -la", cmd.context_signal.readOption(.cmdline).?); +} + +test "OSC 3008: start command with no fields" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "3008;start=simpleid"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .context_signal); + try testing.expect(cmd.context_signal.action == .start); + try testing.expectEqualStrings("simpleid", cmd.context_signal.id); + try testing.expect(cmd.context_signal.readOption(.type) == null); + try testing.expect(cmd.context_signal.readOption(.user) == null); + try testing.expect(cmd.context_signal.readOption(.exit) == null); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/hyperlink.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/hyperlink.zig new file mode 100644 index 00000000..d8e84b63 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/hyperlink.zig @@ -0,0 +1,164 @@ +const std = @import("std"); + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +const log = std.log.scoped(.osc_hyperlink); + +/// Parse OSC 8 hyperlinks +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + const s = std.mem.indexOfScalar(u8, data, ';') orelse { + parser.state = .invalid; + return null; + }; + + parser.command = .{ + .hyperlink_start = .{ + .uri = data[s + 1 .. data.len - 1 :0], + }, + }; + + data[s] = 0; + const kvs = data[0 .. s + 1]; + std.mem.replaceScalar(u8, kvs, ':', 0); + var kv_start: usize = 0; + while (kv_start < kvs.len) { + const kv_end = std.mem.indexOfScalarPos(u8, kvs, kv_start + 1, 0) orelse break; + const kv = data[kv_start .. kv_end + 1]; + const v = std.mem.indexOfScalar(u8, kv, '=') orelse break; + const key = kv[0..v]; + const value = kv[v + 1 .. kv.len - 1 :0]; + if (std.mem.eql(u8, key, "id")) { + if (value.len > 0) parser.command.hyperlink_start.id = value; + } else { + log.warn("unknown hyperlink option: '{s}'", .{key}); + } + kv_start = kv_end + 1; + } + + if (parser.command.hyperlink_start.uri.len == 0) { + if (parser.command.hyperlink_start.id != null) { + parser.state = .invalid; + return null; + } + parser.command = .hyperlink_end; + } + + return &parser.command; +} + +test "OSC 8: hyperlink" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;;http://example.com"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_start); + try testing.expectEqualStrings(cmd.hyperlink_start.uri, "http://example.com"); +} + +test "OSC 8: hyperlink with id set" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;id=foo;http://example.com"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_start); + try testing.expectEqualStrings(cmd.hyperlink_start.id.?, "foo"); + try testing.expectEqualStrings(cmd.hyperlink_start.uri, "http://example.com"); +} + +test "OSC 8: hyperlink with empty id" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;id=;http://example.com"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_start); + try testing.expectEqual(null, cmd.hyperlink_start.id); + try testing.expectEqualStrings(cmd.hyperlink_start.uri, "http://example.com"); +} + +test "OSC 8: hyperlink with incomplete key" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;id;http://example.com"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_start); + try testing.expectEqual(null, cmd.hyperlink_start.id); + try testing.expectEqualStrings(cmd.hyperlink_start.uri, "http://example.com"); +} + +test "OSC 8: hyperlink with empty key" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;=value;http://example.com"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_start); + try testing.expectEqual(null, cmd.hyperlink_start.id); + try testing.expectEqualStrings(cmd.hyperlink_start.uri, "http://example.com"); +} + +test "OSC 8: hyperlink with empty key and id" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;=value:id=foo;http://example.com"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_start); + try testing.expectEqualStrings(cmd.hyperlink_start.id.?, "foo"); + try testing.expectEqualStrings(cmd.hyperlink_start.uri, "http://example.com"); +} + +test "OSC 8: hyperlink with empty uri" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;id=foo;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b'); + try testing.expect(cmd == null); +} + +test "OSC 8: hyperlink end" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "8;;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .hyperlink_end); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/iterm2.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/iterm2.zig new file mode 100644 index 00000000..b05dd1b2 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/iterm2.zig @@ -0,0 +1,435 @@ +const std = @import("std"); + +const assert = @import("../../../quirks.zig").inlineAssert; +const simd = @import("../../../simd/main.zig"); + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +const log = std.log.scoped(.osc_iterm2); + +const Key = enum { + AddAnnotation, + AddHiddenAnnotation, + Block, + Button, + ClearCapturedOutput, + ClearScrollback, + Copy, + CopyToClipboard, + CurrentDir, + CursorShape, + Custom, + Disinter, + EndCopy, + File, + FileEnd, + FilePart, + HighlightCursorLine, + MultipartFile, + OpenURL, + PopKeyLabels, + PushKeyLabels, + RemoteHost, + ReportCellSize, + ReportVariable, + RequestAttention, + RequestUpload, + SetBackgroundImageFile, + SetBadgeFormat, + SetColors, + SetKeyLabel, + SetMark, + SetProfile, + SetUserVar, + ShellIntegrationVersion, + StealFocus, + UnicodeVersion, +}; + +// Instead of using `std.meta.stringToEnum` we set up a StaticStringMap so +// that we can get ASCII case-insensitive lookups. +const Map = std.StaticStringMapWithEql(Key, std.ascii.eqlIgnoreCase); +const map: Map = .initComptime( + map: { + const fields = @typeInfo(Key).@"enum".fields; + var tmp: [fields.len]struct { [:0]const u8, Key } = undefined; + for (fields, 0..) |field, i| { + tmp[i] = .{ field.name, @enumFromInt(field.value) }; + } + break :map tmp; + }, +); + +/// Parse OSC 1337 +/// https://iterm2.com/documentation-escape-codes.html +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + assert(parser.state == .@"1337"); + + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + + const key_str: [:0]u8, const value_: ?[:0]u8 = kv: { + const index = std.mem.indexOfScalar(u8, data, '=') orelse { + break :kv .{ data[0 .. data.len - 1 :0], null }; + }; + data[index] = 0; + break :kv .{ data[0..index :0], data[index + 1 .. data.len - 1 :0] }; + }; + + const key = map.get(key_str) orelse { + parser.command = .invalid; + return null; + }; + + switch (key) { + .Copy => { + var value = value_ orelse { + parser.command = .invalid; + return null; + }; + + // Sending a blank entry to clear the clipboard is an OSC 52-ism, + // make sure that is invalid here. + if (value.len == 0) { + parser.command = .invalid; + return null; + } + + // base64 value must be prefixed by a colon + if (value[0] != ':') { + parser.command = .invalid; + return null; + } + + value = value[1..value.len :0]; + + // Sending a blank entry to clear the clipboard is an OSC 52-ism, + // make sure that is invalid here. + if (value.len == 0) { + parser.command = .invalid; + return null; + } + + // Sending a '?' to query the clipboard is an OSC 52-ism, make sure + // that is invalid here. + if (value.len == 1 and value[0] == '?') { + parser.command = .invalid; + return null; + } + + // It would be better to check for valid base64 data here, but that + // would mean parsing the base64 data twice in the "normal" case. + + parser.command = .{ + .clipboard_contents = .{ + .kind = 'c', + .data = value, + }, + }; + return &parser.command; + }, + + .CurrentDir => { + const value = value_ orelse { + parser.command = .invalid; + return null; + }; + if (value.len == 0) { + parser.command = .invalid; + return null; + } + parser.command = .{ + .report_pwd = .{ + .value = value, + }, + }; + return &parser.command; + }, + + .AddAnnotation, + .AddHiddenAnnotation, + .Block, + .Button, + .ClearCapturedOutput, + .ClearScrollback, + .CopyToClipboard, + .CursorShape, + .Custom, + .Disinter, + .EndCopy, + .File, + .FileEnd, + .FilePart, + .HighlightCursorLine, + .MultipartFile, + .OpenURL, + .PopKeyLabels, + .PushKeyLabels, + .RemoteHost, + .ReportCellSize, + .ReportVariable, + .RequestAttention, + .RequestUpload, + .SetBackgroundImageFile, + .SetBadgeFormat, + .SetColors, + .SetKeyLabel, + .SetMark, + .SetProfile, + .SetUserVar, + .ShellIntegrationVersion, + .StealFocus, + .UnicodeVersion, + => { + log.debug("unimplemented OSC 1337: {t}", .{key}); + parser.command = .invalid; + return null; + }, + } + return &parser.command; +} + +test "OSC: 1337: test valid unimplemented key with no value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;SetBadgeFormat"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test valid unimplemented key with empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;SetBadgeFormat="; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test valid unimplemented key with non-empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;SetBadgeFormat=abc123"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test valid key with lower case and with no value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;setbadgeformat"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test valid key with lower case and with empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;setbadgeformat="; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test valid key with lower case and with non-empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;setbadgeformat=abc123"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test invalid key with no value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;BobrKurwa"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test invalid key with empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;BobrKurwa="; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test invalid key with non-empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;BobrKurwa=abc123"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with no value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;Copy"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;Copy="; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with only prefix colon" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;Copy=:"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with question mark" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;Copy=:?"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with non-empty value that is invalid base64" { + // For performance reasons, we don't check for valid base64 data + // right now. + return error.SkipZigTest; + + // const testing = std.testing; + + // var p: Parser = .init(testing.allocator); + // defer p.deinit(); + + // const input = "1337;Copy=:abc123"; + // for (input) |ch| p.next(ch); + + // try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with non-empty value that is valid base64 but not prefixed with a colon" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;Copy=YWJjMTIz"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test Copy with non-empty value that is valid base64" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;Copy=:YWJjMTIz"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .clipboard_contents); + try testing.expectEqual('c', cmd.clipboard_contents.kind); + try testing.expectEqualStrings("YWJjMTIz", cmd.clipboard_contents.data); +} + +test "OSC: 1337: test CurrentDir with no value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;CurrentDir"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test CurrentDir with empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;CurrentDir="; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC: 1337: test CurrentDir with non-empty value" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "1337;CurrentDir=abc123"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .report_pwd); + try testing.expectEqualStrings("abc123", cmd.report_pwd.value); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_clipboard_protocol.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_clipboard_protocol.zig new file mode 100644 index 00000000..5bd0e254 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_clipboard_protocol.zig @@ -0,0 +1,702 @@ +//! Kitty's clipboard protocol (OSC 5522) +//! Specification: https://sw.kovidgoyal.net/kitty/clipboard/ +//! https://rockorager.dev/misc/bracketed-paste-mime/ + +const std = @import("std"); +const build_options = @import("terminal_options"); + +const assert = @import("../../../quirks.zig").inlineAssert; + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; +const Terminator = @import("../../osc.zig").Terminator; +const encoding = @import("../encoding.zig"); + +const log = std.log.scoped(.kitty_clipboard_protocol); + +pub const OSC = struct { + /// The raw metadata that was received. It can be parsed by using the `readOption` method. + metadata: []const u8, + /// The raw payload. It may be Base64 encoded, check the `e` option. + payload: ?[]const u8, + /// The terminator that was used in case we need to send a response. + terminator: Terminator, + + /// Decode an option from the metadata. + pub fn readOption(self: OSC, comptime key: Option) ?key.Type() { + return key.read(self.metadata); + } +}; + +pub const Location = enum { + primary, + + pub fn init(str: []const u8) ?Location { + return std.meta.stringToEnum(Location, str); + } +}; + +pub const Operation = enum { + read, + walias, + wdata, + write, + + pub fn init(str: []const u8) ?Operation { + return std.meta.stringToEnum(Operation, str); + } +}; + +pub const Status = enum { + DATA, + DONE, + EBUSY, + EINVAL, + EIO, + ENOSYS, + EPERM, + OK, + + pub fn init(str: []const u8) ?Status { + return std.meta.stringToEnum(Status, str); + } +}; + +pub const Option = enum { + id, + loc, + mime, + name, + password, + pw, + status, + type, + + pub fn Type(comptime key: Option) type { + return switch (key) { + .id => []const u8, + .loc => Location, + .mime => []const u8, + .name => []const u8, + .password => []const u8, + .pw => []const u8, + .status => Status, + .type => Operation, + }; + } + + /// Read the option value from the raw metadata string. + pub fn read( + comptime key: Option, + metadata: []const u8, + ) ?key.Type() { + const value: []const u8 = value: { + var pos: usize = 0; + while (pos < metadata.len) { + // skip any whitespace + while (pos < metadata.len and std.ascii.isWhitespace(metadata[pos])) pos += 1; + // bail if we are out of metadata + if (pos >= metadata.len) return null; + if (!std.mem.startsWith(u8, metadata[pos..], @tagName(key))) { + // this isn't the key we are looking for, skip to the next option, or bail if + // there is no next option + pos = std.mem.indexOfScalarPos(u8, metadata, pos, ':') orelse return null; + pos += 1; + continue; + } + // skip past the key + pos += @tagName(key).len; + // skip any whitespace + while (pos < metadata.len and std.ascii.isWhitespace(metadata[pos])) pos += 1; + // bail if we are out of metadata + if (pos >= metadata.len) return null; + // a valid option has an '=' + if (metadata[pos] != '=') return null; + // the end of the value is bounded by a ':' or the end of the metadata + const end = std.mem.indexOfScalarPos(u8, metadata, pos, ':') orelse metadata.len; + const start = pos + 1; + // strip any leading or trailing whitespace + break :value std.mem.trim(u8, metadata[start..end], &std.ascii.whitespace); + } + // the key was not found + return null; + }; + + // return the parsed value + return switch (key) { + .id => parseIdentifier(value), + .loc => .init(value), + .mime => value, + .name => value, + .password => value, + .pw => value, + .status => .init(value), + .type => .init(value), + }; + } +}; + +/// Characters that are valid in identifiers. +const valid_identifier_characters: []const u8 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_+."; + +fn isValidIdentifier(str: []const u8) bool { + if (str.len == 0) return false; + return std.mem.indexOfNone(u8, str, valid_identifier_characters) == null; +} + +fn parseIdentifier(str: []const u8) ?[]const u8 { + if (isValidIdentifier(str)) return str; + return null; +} + +pub fn parse(parser: *Parser, terminator_ch: ?u8) ?*Command { + assert(parser.state == .@"5522"); + + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + + const data = cap.trailing(); + + const metadata: []const u8, const payload: ?[]const u8 = result: { + const start = std.mem.indexOfScalar(u8, data, ';') orelse break :result .{ data, null }; + break :result .{ data[0..start], data[start + 1 .. data.len] }; + }; + + parser.command = .{ + .kitty_clipboard_protocol = .{ + .metadata = metadata, + .payload = payload, + .terminator = .init(terminator_ch), + }, + }; + + return &parser.command; +} + +test "OSC: 5522: empty metadata and missing payload" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("", cmd.kitty_clipboard_protocol.metadata); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.type) == null); +} + +test "OSC: 5522: empty metadata and empty payload" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("", cmd.kitty_clipboard_protocol.metadata); + try testing.expectEqualStrings("", cmd.kitty_clipboard_protocol.payload.?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.type) == null); +} + +test "OSC: 5522: non-empty metadata and payload" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read;dGV4dC9wbGFpbg=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("type=read", cmd.kitty_clipboard_protocol.metadata); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.payload.?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type)); +} + +test "OSC: 5522: empty id" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;id="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); +} + +test "OSC: 5522: valid id" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;id=5c076ad9-d36f-4705-847b-d4dbf356cc0d"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("5c076ad9-d36f-4705-847b-d4dbf356cc0d", cmd.kitty_clipboard_protocol.readOption(.id).?); +} + +test "OSC: 5522: invalid id" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;id=*42*"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); +} + +test "OSC: 5522: invalid status" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;status=BOBR"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); +} + +test "OSC: 5522: valid status" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;status=DONE"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqual(.DONE, cmd.kitty_clipboard_protocol.readOption(.status).?); +} + +test "OSC: 5522: invalid location" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;loc=bobr"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); +} + +test "OSC: 5522: valid location" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;loc=primary"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqual(.primary, cmd.kitty_clipboard_protocol.readOption(.loc).?); +} + +test "OSC: 5522: password 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;pw=R2hvc3R0eQ==:name=Qk9CUiBLVVJXQQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("R2hvc3R0eQ==", cmd.kitty_clipboard_protocol.readOption(.pw).?); + try testing.expectEqualStrings("Qk9CUiBLVVJXQQ==", cmd.kitty_clipboard_protocol.readOption(.name).?); +} + +test "OSC: 5522: password 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;password=R2hvc3R0eQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("R2hvc3R0eQ==", cmd.kitty_clipboard_protocol.readOption(.password).?); +} + +test "OSC: 5522: example 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=OK"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.OK, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:mime=dGV4dC9wbGFpbg==;R2hvc3R0eQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("R2hvc3R0eQ==", cmd.kitty_clipboard_protocol.payload.?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.readOption(.mime).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 3" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=OK"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.OK, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 4" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=write"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.write, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 5" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=wdata:mime=dGV4dC9wbGFpbg==;R2hvc3R0eQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("R2hvc3R0eQ==", cmd.kitty_clipboard_protocol.payload.?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.readOption(.mime).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.wdata, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 6" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=wdata"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.wdata, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 7" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=write:status=DONE"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.DONE, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.write, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 8" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=write:status=EPERM"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.EPERM, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.write, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 9" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=walias:mime=dGV4dC9wbGFpbg==;dGV4dC9odG1sIGFwcGxpY2F0aW9uL2pzb24="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("dGV4dC9odG1sIGFwcGxpY2F0aW9uL2pzb24=", cmd.kitty_clipboard_protocol.payload.?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.readOption(.mime).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.walias, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 10" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=OK:password=Qk9CUiBLVVJXQQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expectEqualStrings("Qk9CUiBLVVJXQQ==", cmd.kitty_clipboard_protocol.readOption(.password).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.OK, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 11" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=DATA:mime=dGV4dC9wbGFpbg=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.readOption(.mime).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.DATA, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 12" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:mime=dGV4dC9wbGFpbg==:password=Qk9CUiBLVVJXQQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.readOption(.mime).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expectEqualStrings("Qk9CUiBLVVJXQQ==", cmd.kitty_clipboard_protocol.readOption(.password).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.status) == null); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 13" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=OK"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.OK, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 14" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=DATA:mime=dGV4dC9wbGFpbg==;Qk9CUiBLVVJXQQ=="; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expectEqualStrings("Qk9CUiBLVVJXQQ==", cmd.kitty_clipboard_protocol.payload.?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expectEqualStrings("dGV4dC9wbGFpbg==", cmd.kitty_clipboard_protocol.readOption(.mime).?); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.DATA, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} + +test "OSC: 5522: example 15" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "5522;type=read:status=OK"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_clipboard_protocol); + try testing.expect(cmd.kitty_clipboard_protocol.payload == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.id) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.loc) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.mime) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.name) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.password) == null); + try testing.expect(cmd.kitty_clipboard_protocol.readOption(.pw) == null); + try testing.expectEqual(.OK, cmd.kitty_clipboard_protocol.readOption(.status).?); + try testing.expectEqual(.read, cmd.kitty_clipboard_protocol.readOption(.type).?); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_color.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_color.zig new file mode 100644 index 00000000..c59391ea --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_color.zig @@ -0,0 +1,212 @@ +const std = @import("std"); + +const assert = @import("../../../quirks.zig").inlineAssert; + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; +const kitty_color = @import("../../kitty/color.zig"); +const RGB = @import("../../color.zig").RGB; + +const log = std.log.scoped(.osc_kitty_color); + +/// Parse OSC 21, the Kitty Color Protocol. +pub fn parse(parser: *Parser, terminator_ch: ?u8) ?*Command { + assert(parser.state == .@"21"); + + const alloc = parser.alloc orelse { + parser.state = .invalid; + return null; + }; + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + parser.command = .{ + .kitty_color_protocol = .{ + .list = .empty, + .terminator = .init(terminator_ch), + }, + }; + const list = &parser.command.kitty_color_protocol.list; + const data = cap.trailing(); + var kv_it = std.mem.splitScalar(u8, data, ';'); + while (kv_it.next()) |kv| { + if (list.items.len >= @as(usize, kitty_color.Kind.max) * 2) { + log.warn("exceeded limit for number of keys in kitty color protocol, ignoring", .{}); + parser.state = .invalid; + return null; + } + var it = std.mem.splitScalar(u8, kv, '='); + const k = it.next() orelse continue; + if (k.len == 0) { + log.warn("zero length key in kitty color protocol", .{}); + continue; + } + const key = kitty_color.Kind.parse(k) orelse { + log.warn("unknown key in kitty color protocol: {s}", .{k}); + continue; + }; + const value = std.mem.trim(u8, it.rest(), " "); + if (value.len == 0) { + list.append(alloc, .{ .reset = key }) catch |err| { + log.warn("unable to append kitty color protocol option: {}", .{err}); + continue; + }; + } else if (std.mem.eql(u8, "?", value)) { + list.append(alloc, .{ .query = key }) catch |err| { + log.warn("unable to append kitty color protocol option: {}", .{err}); + continue; + }; + } else { + list.append(alloc, .{ + .set = .{ + .key = key, + .color = RGB.parse(value) catch |err| switch (err) { + error.InvalidFormat => { + log.warn("invalid color format in kitty color protocol: {s}", .{value}); + continue; + }, + }, + }, + }) catch |err| { + log.warn("unable to append kitty color protocol option: {}", .{err}); + continue; + }; + } + } + return &parser.command; +} + +test "OSC 21: kitty color protocol" { + const testing = std.testing; + const Kind = kitty_color.Kind; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "21;foreground=?;background=rgb:f0/f8/ff;cursor=aliceblue;cursor_text;visual_bell=;selection_foreground=#xxxyyzz;selection_background=?;selection_background=#aabbcc;2=?;3=rgbi:1.0/1.0/1.0"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_color_protocol); + try testing.expectEqual(@as(usize, 9), cmd.kitty_color_protocol.list.items.len); + { + const item = cmd.kitty_color_protocol.list.items[0]; + try testing.expect(item == .query); + try testing.expectEqual(Kind{ .special = .foreground }, item.query); + } + { + const item = cmd.kitty_color_protocol.list.items[1]; + try testing.expect(item == .set); + try testing.expectEqual(Kind{ .special = .background }, item.set.key); + try testing.expectEqual(@as(u8, 0xf0), item.set.color.r); + try testing.expectEqual(@as(u8, 0xf8), item.set.color.g); + try testing.expectEqual(@as(u8, 0xff), item.set.color.b); + } + { + const item = cmd.kitty_color_protocol.list.items[2]; + try testing.expect(item == .set); + try testing.expectEqual(Kind{ .special = .cursor }, item.set.key); + try testing.expectEqual(@as(u8, 0xf0), item.set.color.r); + try testing.expectEqual(@as(u8, 0xf8), item.set.color.g); + try testing.expectEqual(@as(u8, 0xff), item.set.color.b); + } + { + const item = cmd.kitty_color_protocol.list.items[3]; + try testing.expect(item == .reset); + try testing.expectEqual(Kind{ .special = .cursor_text }, item.reset); + } + { + const item = cmd.kitty_color_protocol.list.items[4]; + try testing.expect(item == .reset); + try testing.expectEqual(Kind{ .special = .visual_bell }, item.reset); + } + { + const item = cmd.kitty_color_protocol.list.items[5]; + try testing.expect(item == .query); + try testing.expectEqual(Kind{ .special = .selection_background }, item.query); + } + { + const item = cmd.kitty_color_protocol.list.items[6]; + try testing.expect(item == .set); + try testing.expectEqual(Kind{ .special = .selection_background }, item.set.key); + try testing.expectEqual(@as(u8, 0xaa), item.set.color.r); + try testing.expectEqual(@as(u8, 0xbb), item.set.color.g); + try testing.expectEqual(@as(u8, 0xcc), item.set.color.b); + } + { + const item = cmd.kitty_color_protocol.list.items[7]; + try testing.expect(item == .query); + try testing.expectEqual(Kind{ .palette = 2 }, item.query); + } + { + const item = cmd.kitty_color_protocol.list.items[8]; + try testing.expect(item == .set); + try testing.expectEqual(Kind{ .palette = 3 }, item.set.key); + try testing.expectEqual(@as(u8, 0xff), item.set.color.r); + try testing.expectEqual(@as(u8, 0xff), item.set.color.g); + try testing.expectEqual(@as(u8, 0xff), item.set.color.b); + } +} + +test "OSC 21: kitty color protocol without allocator" { + const testing = std.testing; + + var p: Parser = .init(null); + defer p.deinit(); + + const input = "21;foreground=?"; + for (input) |ch| p.next(ch); + try testing.expect(p.end('\x1b') == null); +} + +test "OSC 21: kitty color protocol double reset" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "21;foreground=?;background=rgb:f0/f8/ff;cursor=aliceblue;cursor_text;visual_bell=;selection_foreground=#xxxyyzz;selection_background=?;selection_background=#aabbcc;2=?;3=rgbi:1.0/1.0/1.0"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_color_protocol); + + p.reset(); + p.reset(); +} + +test "OSC 21: kitty color protocol reset after invalid" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "21;foreground=?;background=rgb:f0/f8/ff;cursor=aliceblue;cursor_text;visual_bell=;selection_foreground=#xxxyyzz;selection_background=?;selection_background=#aabbcc;2=?;3=rgbi:1.0/1.0/1.0"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_color_protocol); + + p.reset(); + + try testing.expectEqual(Parser.State.start, p.state); + p.next('X'); + try testing.expectEqual(Parser.State.invalid, p.state); + + p.reset(); +} + +test "OSC 21: kitty color protocol no key" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "21;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_color_protocol); + try testing.expectEqual(0, cmd.kitty_color_protocol.list.items.len); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_text_sizing.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_text_sizing.zig new file mode 100644 index 00000000..94f27100 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/kitty_text_sizing.zig @@ -0,0 +1,255 @@ +//! Kitty's text sizing protocol (OSC 66) +//! Specification: https://sw.kovidgoyal.net/kitty/text-sizing-protocol/ + +const std = @import("std"); + +const assert = @import("../../../quirks.zig").inlineAssert; + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; +const encoding = @import("../encoding.zig"); +const lib = @import("../../lib.zig"); + +const log = std.log.scoped(.kitty_text_sizing); + +pub const max_payload_length = 4096; + +pub const VAlign = lib.Enum(lib.target, &.{ + "top", + "bottom", + "center", +}); + +pub const HAlign = lib.Enum(lib.target, &.{ + "left", + "right", + "center", +}); + +pub const OSC = struct { + scale: u3 = 1, // 1 - 7 + width: u3 = 0, // 0 - 7 (0 means default) + numerator: u4 = 0, + denominator: u4 = 0, + valign: VAlign = .top, + halign: HAlign = .left, + text: [:0]const u8, + + /// We don't currently support encoding this to C in any way. + pub const C = void; + + pub fn cval(_: OSC) C { + return {}; + } + + fn update(self: *OSC, key: u8, value: []const u8) error{ + UnknownKey, + InvalidValue, + }!void { + // All values are numeric, so we can do a small hack here + const v = std.fmt.parseInt( + u4, + value, + 10, + ) catch return error.InvalidValue; + + switch (key) { + 's' => { + if (v == 0) return error.InvalidValue; + self.scale = std.math.cast(u3, v) orelse return error.InvalidValue; + }, + 'w' => self.width = std.math.cast(u3, v) orelse return error.InvalidValue, + 'n' => self.numerator = v, + 'd' => self.denominator = v, + 'v' => self.valign = std.enums.fromInt(VAlign, v) orelse return error.InvalidValue, + 'h' => self.halign = std.enums.fromInt(HAlign, v) orelse return error.InvalidValue, + else => return error.UnknownKey, + } + } +}; + +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + assert(parser.state == .@"66"); + + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + + // Write a NUL byte to ensure that `text` is NUL-terminated + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + + const payload_start = std.mem.indexOfScalar(u8, data, ';') orelse { + log.warn("missing semicolon before payload", .{}); + parser.state = .invalid; + return null; + }; + const payload = data[payload_start + 1 .. data.len - 1 :0]; + + // Payload has to be a URL-safe UTF-8 string, + // and be under the size limit. + if (payload.len > max_payload_length) { + log.warn("payload is too long", .{}); + parser.state = .invalid; + return null; + } + if (!encoding.isSafeUtf8(payload)) { + log.warn("payload is not escape code safe UTF-8", .{}); + parser.state = .invalid; + return null; + } + + parser.command = .{ + .kitty_text_sizing = .{ .text = payload }, + }; + const cmd = &parser.command.kitty_text_sizing; + + // Parse any arguments if given + if (payload_start > 0) { + var kv_it = std.mem.splitScalar( + u8, + data[0..payload_start], + ':', + ); + + while (kv_it.next()) |kv| { + var it = std.mem.splitScalar(u8, kv, '='); + const k = it.next() orelse { + log.warn("missing key", .{}); + continue; + }; + if (k.len != 1) { + log.warn("key must be a single character", .{}); + continue; + } + + const value = it.next() orelse { + log.warn("missing value", .{}); + continue; + }; + + cmd.update(k[0], value) catch |err| { + switch (err) { + error.UnknownKey => log.warn("unknown key: '{c}'", .{k[0]}), + error.InvalidValue => log.warn("invalid value for key '{c}': {}", .{ k[0], err }), + } + continue; + }; + } + } + + return &parser.command; +} + +test "OSC 66: empty parameters" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;;bobr"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_text_sizing); + try testing.expectEqual(1, cmd.kitty_text_sizing.scale); + try testing.expectEqualStrings("bobr", cmd.kitty_text_sizing.text); +} + +test "OSC 66: single parameter" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;s=2;kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_text_sizing); + try testing.expectEqual(2, cmd.kitty_text_sizing.scale); + try testing.expectEqualStrings("kurwa", cmd.kitty_text_sizing.text); +} + +test "OSC 66: multiple parameters" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;s=2:w=7:n=13:d=15:v=1:h=2;long"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_text_sizing); + try testing.expectEqual(2, cmd.kitty_text_sizing.scale); + try testing.expectEqual(7, cmd.kitty_text_sizing.width); + try testing.expectEqual(13, cmd.kitty_text_sizing.numerator); + try testing.expectEqual(15, cmd.kitty_text_sizing.denominator); + try testing.expectEqual(.bottom, cmd.kitty_text_sizing.valign); + try testing.expectEqual(.center, cmd.kitty_text_sizing.halign); + try testing.expectEqualStrings("long", cmd.kitty_text_sizing.text); +} + +test "OSC 66: scale is zero" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;s=0;nope"; + for (input) |ch| p.next(ch); + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .kitty_text_sizing); + try testing.expectEqual(1, cmd.kitty_text_sizing.scale); +} + +test "OSC 66: invalid parameters" { + const testing = std.testing; + + var p: Parser = .init(null); + + for ("66;w=8:v=3:n=16;") |ch| p.next(ch); + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .kitty_text_sizing); + try testing.expectEqual(0, cmd.kitty_text_sizing.width); + try testing.expect(cmd.kitty_text_sizing.valign == .top); + try testing.expectEqual(0, cmd.kitty_text_sizing.numerator); +} + +test "OSC 66: UTF-8" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;;👻魑魅魍魉ゴースッティ"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .kitty_text_sizing); + try testing.expectEqualStrings("👻魑魅魍魉ゴースッティ", cmd.kitty_text_sizing.text); +} + +test "OSC 66: unsafe UTF-8" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;;\n"; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} + +test "OSC 66: overlong UTF-8" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "66;;" ++ "bobr" ** 1025; + for (input) |ch| p.next(ch); + + try testing.expect(p.end('\x1b') == null); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/mouse_shape.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/mouse_shape.zig new file mode 100644 index 00000000..4b96c038 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/mouse_shape.zig @@ -0,0 +1,39 @@ +const std = @import("std"); + +const assert = @import("../../../quirks.zig").inlineAssert; + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +// Parse OSC 22 +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + assert(parser.state == .@"22"); + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + parser.command = .{ + .mouse_shape = .{ + .value = data[0 .. data.len - 1 :0], + }, + }; + return &parser.command; +} + +test "OSC 22: pointer cursor" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "22;pointer"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .mouse_shape); + try testing.expectEqualStrings("pointer", cmd.mouse_shape.value); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/osc9.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/osc9.zig new file mode 100644 index 00000000..4b8dda9b --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/osc9.zig @@ -0,0 +1,1141 @@ +const std = @import("std"); + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +/// Parse OSC 9, which could be an iTerm2 notification or a ConEmu extension. +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + const writer = cap.writer; + + // Check first to see if this is a ConEmu OSC + // https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC + conemu: { + var data = cap.trailing(); + if (data.len == 0) break :conemu; + switch (data[0]) { + // Check for OSC 9;1 9;10 9;11 9;12 + '1' => { + if (data.len < 2) break :conemu; + switch (data[1]) { + // OSC 9;1 sleep + ';' => { + parser.command = .{ + .conemu_sleep = .{ + .duration_ms = if (std.fmt.parseUnsigned(u16, data[2..], 10)) |num| @min(num, 10_000) else |_| 100, + }, + }; + return &parser.command; + }, + // OSC 9;10 xterm keyboard and output emulation + '0' => { + if (data.len == 2) { + parser.command = .{ + .conemu_xterm_emulation = .{ + .keyboard = true, + .output = true, + }, + }; + return &parser.command; + } + if (data.len < 4) break :conemu; + if (data[2] != ';') break :conemu; + switch (data[3]) { + '0' => { + parser.command = .{ + .conemu_xterm_emulation = .{ + .keyboard = false, + .output = false, + }, + }; + return &parser.command; + }, + '1' => { + parser.command = .{ + .conemu_xterm_emulation = .{ + .keyboard = true, + .output = true, + }, + }; + return &parser.command; + }, + '2' => { + parser.command = .{ + .conemu_xterm_emulation = .{ + .keyboard = null, + .output = false, + }, + }; + return &parser.command; + }, + '3' => { + parser.command = .{ + .conemu_xterm_emulation = .{ + .keyboard = null, + .output = true, + }, + }; + return &parser.command; + }, + else => break :conemu, + } + }, + // OSC 9;11 comment + '1' => { + if (data.len < 3) break :conemu; + if (data[2] != ';') break :conemu; + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .conemu_comment = data[3 .. data.len - 1 :0], + }; + return &parser.command; + }, + // OSC 9;12 mark prompt start + '2' => { + parser.command = .{ .semantic_prompt = .init(.fresh_line_new_prompt) }; + return &parser.command; + }, + else => break :conemu, + } + }, + // OSC 9;2 show message box + '2' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .conemu_show_message_box = data[2 .. data.len - 1 :0], + }; + return &parser.command; + }, + // OSC 9;3 change tab title + '3' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + if (data.len == 2) { + parser.command = .{ + .conemu_change_tab_title = .reset, + }; + return &parser.command; + } + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .conemu_change_tab_title = .{ + .value = data[2 .. data.len - 1 :0], + }, + }; + return &parser.command; + }, + // OSC 9;4 progress report + '4' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + if (data.len < 3) break :conemu; + switch (data[2]) { + '0' => { + parser.command = .{ + .conemu_progress_report = .{ + .state = .remove, + }, + }; + }, + '1' => { + parser.command = .{ + .conemu_progress_report = .{ + .state = .set, + .progress = 0, + }, + }; + }, + '2' => { + parser.command = .{ + .conemu_progress_report = .{ + .state = .@"error", + }, + }; + }, + '3' => { + parser.command = .{ + .conemu_progress_report = .{ + .state = .indeterminate, + }, + }; + }, + '4' => { + parser.command = .{ + .conemu_progress_report = .{ + .state = .pause, + }, + }; + }, + else => break :conemu, + } + switch (parser.command.conemu_progress_report.state) { + .remove, .indeterminate => {}, + .set, .@"error", .pause => progress: { + if (data.len < 4) break :progress; + if (data[3] != ';') break :progress; + // parse the progress value + parser.command.conemu_progress_report.progress = value: { + break :value @intCast(std.math.clamp( + std.fmt.parseUnsigned(usize, data[4..], 10) catch break :value null, + 0, + 100, + )); + }; + }, + } + return &parser.command; + }, + // OSC 9;5 wait for input + '5' => { + parser.command = .conemu_wait_input; + return &parser.command; + }, + // OSC 9;6 guimacro + '6' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .conemu_guimacro = data[2 .. data.len - 1 :0], + }; + return &parser.command; + }, + // OSC 9;7 run process + '7' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .conemu_run_process = data[2 .. data.len - 1 :0], + }; + return &parser.command; + }, + // OSC 9;8 output environment variable + '8' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .conemu_output_environment_variable = data[2 .. data.len - 1 :0], + }; + return &parser.command; + }, + // OSC 9;9 current working directory + '9' => { + if (data.len < 2) break :conemu; + if (data[1] != ';') break :conemu; + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + data = cap.trailing(); + parser.command = .{ + .report_pwd = .{ + .value = data[2 .. data.len - 1 :0], + }, + }; + return &parser.command; + }, + else => break :conemu, + } + } + + // If it's not a ConEmu OSC, it's an iTerm2 notification + + writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + parser.command = .{ + .show_desktop_notification = .{ + .title = "", + .body = data[0 .. data.len - 1 :0], + }, + }; + return &parser.command; +} + +test "OSC 9: show desktop notification" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;Hello world"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("", cmd.show_desktop_notification.title); + try testing.expectEqualStrings("Hello world", cmd.show_desktop_notification.body); +} + +test "OSC 9: show single character desktop notification" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;H"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("", cmd.show_desktop_notification.title); + try testing.expectEqualStrings("H", cmd.show_desktop_notification.body); +} + +test "OSC 9;1: ConEmu sleep" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;1;420"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .conemu_sleep); + try testing.expectEqual(420, cmd.conemu_sleep.duration_ms); +} + +test "OSC 9;1: ConEmu sleep with no value default to 100ms" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;1;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .conemu_sleep); + try testing.expectEqual(100, cmd.conemu_sleep.duration_ms); +} + +test "OSC 9;1: conemu sleep cannot exceed 10000ms" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;1;12345"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .conemu_sleep); + try testing.expectEqual(10000, cmd.conemu_sleep.duration_ms); +} + +test "OSC 9;1: conemu sleep invalid input" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;1;foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .conemu_sleep); + try testing.expectEqual(100, cmd.conemu_sleep.duration_ms); +} + +test "OSC 9;1: conemu sleep -> desktop notification 1" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;1"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("1", cmd.show_desktop_notification.body); +} + +test "OSC 9;1: conemu sleep -> desktop notification 2" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;1a"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("1a", cmd.show_desktop_notification.body); +} + +test "OSC 9;2: ConEmu message box" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;2;hello world"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_show_message_box); + try testing.expectEqualStrings("hello world", cmd.conemu_show_message_box); +} + +test "OSC 9;2: ConEmu message box invalid input" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;2"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("2", cmd.show_desktop_notification.body); +} + +test "OSC 9;2: ConEmu message box empty message" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;2;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_show_message_box); + try testing.expectEqualStrings("", cmd.conemu_show_message_box); +} + +test "OSC 9;2: ConEmu message box spaces only message" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;2; "; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_show_message_box); + try testing.expectEqualStrings(" ", cmd.conemu_show_message_box); +} + +test "OSC 9;2: message box -> desktop notification 1" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;2"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("2", cmd.show_desktop_notification.body); +} + +test "OSC 9;2: message box -> desktop notification 2" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;2a"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("2a", cmd.show_desktop_notification.body); +} + +test "OSC 9;3: ConEmu change tab title" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;3;foo bar"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_change_tab_title); + try testing.expectEqualStrings("foo bar", cmd.conemu_change_tab_title.value); +} + +test "OSC 9;3: ConEmu change tab title reset" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;3;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + const expected_command: Command = .{ .conemu_change_tab_title = .reset }; + try testing.expectEqual(expected_command, cmd); +} + +test "OSC 9;3: ConEmu change tab title spaces only" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;3; "; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .conemu_change_tab_title); + try testing.expectEqualStrings(" ", cmd.conemu_change_tab_title.value); +} + +test "OSC 9;3: change tab title -> desktop notification 1" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;3"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("3", cmd.show_desktop_notification.body); +} + +test "OSC 9;3: message box -> desktop notification 2" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;3a"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("3a", cmd.show_desktop_notification.body); +} + +test "OSC 9;4: ConEmu progress set" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;1;100"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .set); + try testing.expect(cmd.conemu_progress_report.progress == 100); +} + +test "OSC 9;4: ConEmu progress set overflow" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;1;900"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .set); + try testing.expectEqual(100, cmd.conemu_progress_report.progress); +} + +test "OSC 9;4: ConEmu progress set single digit" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;1;9"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .set); + try testing.expect(cmd.conemu_progress_report.progress == 9); +} + +test "OSC 9;4: ConEmu progress set double digit" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;1;94"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .set); + try testing.expectEqual(94, cmd.conemu_progress_report.progress); +} + +test "OSC 9;4: ConEmu progress set extra semicolon ignored" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;1;100"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .set); + try testing.expectEqual(100, cmd.conemu_progress_report.progress); +} + +test "OSC 9;4: ConEmu progress remove with no progress" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;0;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .remove); + try testing.expect(cmd.conemu_progress_report.progress == null); +} + +test "OSC 9;4: ConEmu progress remove with double semicolon" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;0;;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .remove); + try testing.expect(cmd.conemu_progress_report.progress == null); +} + +test "OSC 9;4: ConEmu progress remove ignores progress" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;0;100"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .remove); + try testing.expect(cmd.conemu_progress_report.progress == null); +} + +test "OSC 9;4: ConEmu progress remove extra semicolon" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;0;100;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .remove); +} + +test "OSC 9;4: ConEmu progress error" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;2"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .@"error"); + try testing.expect(cmd.conemu_progress_report.progress == null); +} + +test "OSC 9;4: ConEmu progress error with progress" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;2;100"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .@"error"); + try testing.expect(cmd.conemu_progress_report.progress == 100); +} + +test "OSC 9;4: progress pause" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;4"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .pause); + try testing.expect(cmd.conemu_progress_report.progress == null); +} + +test "OSC 9;4: ConEmu progress pause with progress" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;4;100"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_progress_report); + try testing.expect(cmd.conemu_progress_report.state == .pause); + try testing.expect(cmd.conemu_progress_report.progress == 100); +} + +test "OSC 9;4: progress -> desktop notification 1" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("4", cmd.show_desktop_notification.body); +} + +test "OSC 9;4: progress -> desktop notification 2" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("4;", cmd.show_desktop_notification.body); +} + +test "OSC 9;4: progress -> desktop notification 3" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;5"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("4;5", cmd.show_desktop_notification.body); +} + +test "OSC 9;4: progress -> desktop notification 4" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;4;5a"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("4;5a", cmd.show_desktop_notification.body); +} + +test "OSC 9;5: ConEmu wait input" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;5"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_wait_input); +} + +test "OSC 9;5: ConEmu wait ignores trailing characters" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "9;5;foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_wait_input); +} + +test "OSC 9;6: ConEmu guimacro 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;6;a"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_guimacro); + try testing.expectEqualStrings("a", cmd.conemu_guimacro); +} + +test "OSC: 9;6: ConEmu guimacro 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;6;ab"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_guimacro); + try testing.expectEqualStrings("ab", cmd.conemu_guimacro); +} + +test "OSC: 9;6: ConEmu guimacro 3 incomplete -> desktop notification" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;6"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("6", cmd.show_desktop_notification.body); +} + +test "OSC: 9;7: ConEmu run process 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;7;ab"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_run_process); + try testing.expectEqualStrings("ab", cmd.conemu_run_process); +} + +test "OSC: 9;7: ConEmu run process 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;7;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_run_process); + try testing.expectEqualStrings("", cmd.conemu_run_process); +} + +test "OSC: 9;7: ConEmu run process incomplete -> desktop notification" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;7"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("7", cmd.show_desktop_notification.body); +} + +test "OSC: 9;8: ConEmu output environment variable 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;8;ab"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_output_environment_variable); + try testing.expectEqualStrings("ab", cmd.conemu_output_environment_variable); +} + +test "OSC: 9;8: ConEmu output environment variable 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;8;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_output_environment_variable); + try testing.expectEqualStrings("", cmd.conemu_output_environment_variable); +} + +test "OSC: 9;8: ConEmu output environment variable incomplete -> desktop notification" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;8"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("8", cmd.show_desktop_notification.body); +} + +test "OSC: 9;9: ConEmu set current working directory" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;9;ab"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .report_pwd); + try testing.expectEqualStrings("ab", cmd.report_pwd.value); +} + +test "OSC: 9;9: ConEmu set current working directory incomplete -> desktop notification" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;9"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("9", cmd.show_desktop_notification.body); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_xterm_emulation); + try testing.expect(cmd.conemu_xterm_emulation.keyboard != null); + try testing.expect(cmd.conemu_xterm_emulation.keyboard.? == true); + try testing.expect(cmd.conemu_xterm_emulation.output != null); + try testing.expect(cmd.conemu_xterm_emulation.output.? == true); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;0"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_xterm_emulation); + try testing.expect(cmd.conemu_xterm_emulation.keyboard != null); + try testing.expect(cmd.conemu_xterm_emulation.keyboard.? == false); + try testing.expect(cmd.conemu_xterm_emulation.output != null); + try testing.expect(cmd.conemu_xterm_emulation.output.? == false); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 3" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;1"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_xterm_emulation); + try testing.expect(cmd.conemu_xterm_emulation.keyboard != null); + try testing.expect(cmd.conemu_xterm_emulation.keyboard.? == true); + try testing.expect(cmd.conemu_xterm_emulation.output != null); + try testing.expect(cmd.conemu_xterm_emulation.output.? == true); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 4" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;2"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_xterm_emulation); + try testing.expect(cmd.conemu_xterm_emulation.keyboard == null); + try testing.expect(cmd.conemu_xterm_emulation.output != null); + try testing.expect(cmd.conemu_xterm_emulation.output.? == false); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 5" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;3"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_xterm_emulation); + try testing.expect(cmd.conemu_xterm_emulation.keyboard == null); + try testing.expect(cmd.conemu_xterm_emulation.output != null); + try testing.expect(cmd.conemu_xterm_emulation.output.? == true); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 6" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;4"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("10;4", cmd.show_desktop_notification.body); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 7" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("10;", cmd.show_desktop_notification.body); +} + +test "OSC: 9;10: ConEmu xterm keyboard and output emulation 8" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;10;abc"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("10;abc", cmd.show_desktop_notification.body); +} + +test "OSC: 9;11: ConEmu comment" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;11;ab"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .conemu_comment); + try testing.expectEqualStrings("ab", cmd.conemu_comment); +} + +test "OSC: 9;11: ConEmu comment incomplete -> desktop notification" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;11"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings("11", cmd.show_desktop_notification.body); +} + +test "OSC: 9;12: ConEmu mark prompt start 1" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;12"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .semantic_prompt); +} + +test "OSC: 9;12: ConEmu mark prompt start 2" { + const testing = std.testing; + + var p: Parser = .init(testing.allocator); + defer p.deinit(); + + const input = "9;12;abc"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .semantic_prompt); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/report_pwd.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/report_pwd.zig new file mode 100644 index 00000000..f99bc894 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/report_pwd.zig @@ -0,0 +1,48 @@ +const std = @import("std"); + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +/// Parse OSC 7 +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + parser.command = .{ + .report_pwd = .{ + .value = data[0 .. data.len - 1 :0], + }, + }; + return &parser.command; +} + +test "OSC 7: report pwd" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "7;file:///tmp/example"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .report_pwd); + try testing.expectEqualStrings("file:///tmp/example", cmd.report_pwd.value); +} + +test "OSC 7: report pwd empty" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "7;"; + for (input) |ch| p.next(ch); + const cmd = p.end(null).?.*; + try testing.expect(cmd == .report_pwd); + try testing.expectEqualStrings("", cmd.report_pwd.value); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/rxvt_extension.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/rxvt_extension.zig new file mode 100644 index 00000000..f5b965c6 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/rxvt_extension.zig @@ -0,0 +1,59 @@ +const std = @import("std"); + +const Parser = @import("../../osc.zig").Parser; +const Command = @import("../../osc.zig").Command; + +const log = std.log.scoped(.osc_rxvt_extension); + +/// Parse OSC 777 +pub fn parse(parser: *Parser, _: ?u8) ?*Command { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + // ensure that we are sentinel terminated + cap.writer.writeByte(0) catch { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + const k = std.mem.indexOfScalar(u8, data, ';') orelse { + parser.state = .invalid; + return null; + }; + const ext = data[0..k]; + if (!std.mem.eql(u8, ext, "notify")) { + log.warn("unknown rxvt extension: {s}", .{ext}); + parser.state = .invalid; + return null; + } + const t = std.mem.indexOfScalarPos(u8, data, k + 1, ';') orelse { + log.warn("rxvt notify extension is missing the title", .{}); + parser.state = .invalid; + return null; + }; + data[t] = 0; + const title = data[k + 1 .. t :0]; + const body = data[t + 1 .. data.len - 1 :0]; + parser.command = .{ + .show_desktop_notification = .{ + .title = title, + .body = body, + }, + }; + return &parser.command; +} + +test "OSC: OSC 777 show desktop notification with title" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "777;notify;Title;Body"; + for (input) |ch| p.next(ch); + + const cmd = p.end('\x1b').?.*; + try testing.expect(cmd == .show_desktop_notification); + try testing.expectEqualStrings(cmd.show_desktop_notification.title, "Title"); + try testing.expectEqualStrings(cmd.show_desktop_notification.body, "Body"); +} diff --git a/vendor/libghostty-vt/src/terminal/osc/parsers/semantic_prompt.zig b/vendor/libghostty-vt/src/terminal/osc/parsers/semantic_prompt.zig new file mode 100644 index 00000000..25152d7c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/osc/parsers/semantic_prompt.zig @@ -0,0 +1,1264 @@ +//! https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md +const std = @import("std"); + +const Parser = @import("../../osc.zig").Parser; +const OSCCommand = @import("../../osc.zig").Command; +const string_encoding = @import("../../../os/string_encoding.zig"); + +const log = std.log.scoped(.osc_semantic_prompt); + +/// A single semantic prompt command. +/// +/// Technically according to the spec, not all commands have options +/// but it is easier to be "liberal in what we accept" here since +/// all except one do and the spec does also say to ignore unknown +/// options. So, I think this is a fair interpretation. +pub const Command = struct { + pub const C = void; + + action: Action, + options_unvalidated: []const u8, + + pub const Action = enum { + fresh_line, // 'L' + fresh_line_new_prompt, // 'A' + new_command, // 'N' + prompt_start, // 'P' + end_prompt_start_input, // 'B' + end_prompt_start_input_terminate_eol, // 'I' + end_input_start_output, // 'C' + end_command, // 'D' + }; + + pub fn init(action: Action) Command { + return .{ + .action = action, + .options_unvalidated = "", + }; + } + + /// Read an option for this command. Returns null if unset or invalid. + pub fn readOption( + self: Command, + comptime option: Option, + ) ?option.Type() { + return option.read(self.options_unvalidated); + } + + /// Write the decoded command line (if any) to the writer. If an error + /// occurs garbage may have been written to the writer. + pub fn writeCommandLine(self: Command, writer: *std.Io.Writer) (std.Io.Writer.Error || error{DecodeError})!void { + if (self.readOption(.cmdline)) |command_line| { + try string_encoding.printfQDecode(writer, command_line); + return; + } + if (self.readOption(.cmdline_url)) |command_line| { + try string_encoding.urlPercentDecode(writer, command_line); + return; + } + return; + } +}; + +pub const Option = enum { + aid, + cl, + prompt_kind, + err, + cmdline, + cmdline_url, + + // https://sw.kovidgoyal.net/kitty/shell-integration/#notes-for-shell-developers + // Kitty supports a "redraw" option for prompt_start. This is extended + // by Ghostty with the "last" option. See Redraw the type for more details. + redraw, + + // Use a special key instead of arrow keys to move the cursor on + // mouse click. Useful if arrow keys have side-effets like triggering + // auto-complete. The shell integration script should bind the special + // key as needed. + // See: https://sw.kovidgoyal.net/kitty/shell-integration/#notes-for-shell-developers + special_key, + + // If true, the shell is capable of handling mouse click events. + // Ghostty will then send a click event to the shell when the user + // clicks somewhere in the prompt. The shell can then move the cursor + // to that position or perform some other appropriate action. If false, + // Ghostty may generate a number of fake key events to move the cursor + // which is not very robust. + // See: https://sw.kovidgoyal.net/kitty/shell-integration/#notes-for-shell-developers + click_events, + + // Not technically an option that can be set with k=v and only + // present currently with command 'D' but its easier to just + // parse it into our options. + exit_code, + + pub fn Type(comptime self: Option) type { + return switch (self) { + .aid => []const u8, + .cl => Click, + .prompt_kind => PromptKind, + .err => []const u8, + .redraw => Redraw, + .special_key => bool, + .click_events => bool, + .cmdline => []const u8, + .cmdline_url => []const u8, + .exit_code => i32, + }; + } + + fn key(comptime self: Option) []const u8 { + return switch (self) { + .aid => "aid", + .cl => "cl", + .prompt_kind => "k", + .err => "err", + .redraw => "redraw", + .special_key => "special_key", + .click_events => "click_events", + .cmdline => "cmdline", + .cmdline_url => "cmdline_url", + + // special case, handled before ever calling key + .exit_code => unreachable, + }; + } + + /// Read the option value from the raw options string. + /// + /// The raw options string is the raw unparsed data after the + /// OSC 133 command. e.g. for `133;A;aid=14;cl=line`, the + /// raw options string would be `aid=14;cl=line`. + /// + /// Any errors in the raw string will return null since the OSC133 + /// specification says to ignore unknown or malformed options. + pub fn read( + comptime self: Option, + raw: []const u8, + ) ?self.Type() { + var remaining = raw; + while (remaining.len > 0) { + // Length of the next value is up to the `;` or the + // end of the string. + const len = std.mem.indexOfScalar( + u8, + remaining, + ';', + ) orelse remaining.len; + + // Grab our full value and move our cursor past the `;` + const full = remaining[0..len]; + + // If we're looking for exit_code we special case it. + // as the first value. + if (comptime self == .exit_code) { + return std.fmt.parseInt( + i32, + full, + 10, + ) catch null; + } + + // Parse our key=value and verify our key matches our + // expectation. + const value = value: { + if (std.mem.indexOfScalar( + u8, + full, + '=', + )) |eql_idx| { + if (std.mem.eql( + u8, + full[0..eql_idx], + self.key(), + )) { + break :value full[eql_idx + 1 ..]; + } + } + + // No match! + if (len < remaining.len) { + remaining = remaining[len + 1 ..]; + continue; + } + + break; + }; + + return switch (self) { + .aid => value, + .cl => .init(value), + .prompt_kind => if (value.len == 1) PromptKind.init(value[0]) else null, + .err => value, + .redraw => if (std.mem.eql(u8, value, "0")) + .false + else if (std.mem.eql(u8, value, "1")) + .true + else if (std.mem.eql(u8, value, "last")) + .last + else + null, + .special_key, .click_events => if (value.len == 1) switch (value[0]) { + '0' => false, + '1' => true, + else => null, + } else null, + .cmdline => value, + .cmdline_url => value, + // Handled above + .exit_code => unreachable, + }; + } + + // Not found + return null; + } +}; + +/// The `cl` option specifies what kind of cursor key sequences are handled +/// by the application for click-to-move-cursor functionality. +pub const Click = enum { + /// Value: "line". Allows motion within a single input line using standard + /// left/right arrow escape sequences. Only a single left/right sequence + /// should be emitted for double-width characters. + line, + + /// Value: "m". Allows movement between different lines in the same group, + /// but only using left/right arrow escape sequences. + multiple, + + /// Value: "v". Like `multiple` but cursor up/down should be used. The + /// terminal should be conservative when moving between lines: move the + /// cursor left to the start of line, emit the needed up/down sequences, + /// then move the cursor right to the clicked destination. + conservative_vertical, + + /// Value: "w". Like `conservative_vertical` but specifies that there are + /// no spurious spaces at the end of the line, and the application editor + /// handles "smart vertical movement" (moving 2 lines up from position 20, + /// where the intermediate line is 15 chars wide and the destination is + /// 18 chars wide, ends at position 18). + smart_vertical, + + pub fn init(value: []const u8) ?Click { + return if (value.len == 1) switch (value[0]) { + 'm' => .multiple, + 'v' => .conservative_vertical, + 'w' => .smart_vertical, + else => null, + } else if (std.mem.eql( + u8, + value, + "line", + )) .line else null; + } +}; + +pub const PromptKind = enum { + initial, + right, + continuation, + secondary, + + pub fn init(c: u8) ?PromptKind { + return switch (c) { + 'i' => .initial, + 'r' => .right, + 'c' => .continuation, + 's' => .secondary, + else => null, + }; + } +}; + +/// The values for the `redraw` extension to OSC133. This was +/// started by Kitty[1] and extended by Ghostty (the "last" option). +/// +/// [1]: https://sw.kovidgoyal.net/kitty/shell-integration/#notes-for-shell-developers +pub const Redraw = enum(u2) { + /// The shell supports redrawing the full prompt and all continuations. + /// This is the default value, it does not need to be explicitly set + /// unless it is to reset a prior other value. + true, + + /// The shell does NOT support redrawing. In this case, Ghostty will NOT + /// clear any prompt lines on resize. + false, + + /// The shell supports redrawing only the LAST line of the prompt. + /// Ghostty will only clear the last line of the prompt on resize. + /// + /// This is specifically introduced because Bash only redraws the last + /// line. It is literally the only shell that does this and it does this + /// because its bad and they should feel bad. Don't be like Bash. + last, +}; + +/// Parse OSC 133, semantic prompts +pub fn parse(parser: *Parser, _: ?u8) ?*OSCCommand { + const cap = if (parser.capture) |*c| c else { + parser.state = .invalid; + return null; + }; + const data = cap.trailing(); + if (data.len == 0) { + parser.state = .invalid; + return null; + } + + // All valid cases terminate within this block. Any fallthroughs + // are invalid. This makes some of our parse logic a little less + // repetitive. + valid: { + switch (data[0]) { + 'A' => fresh_line: { + parser.command = .{ .semantic_prompt = .init(.fresh_line_new_prompt) }; + if (data.len == 1) break :fresh_line; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + 'B' => end_prompt: { + parser.command = .{ .semantic_prompt = .init(.end_prompt_start_input) }; + if (data.len == 1) break :end_prompt; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + 'I' => end_prompt_line: { + parser.command = .{ .semantic_prompt = .init(.end_prompt_start_input_terminate_eol) }; + if (data.len == 1) break :end_prompt_line; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + 'C' => end_input: { + parser.command = .{ .semantic_prompt = .init(.end_input_start_output) }; + if (data.len == 1) break :end_input; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + 'D' => end_command: { + parser.command = .{ .semantic_prompt = .init(.end_command) }; + if (data.len == 1) break :end_command; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + 'L' => { + if (data.len > 1) break :valid; + parser.command = .{ .semantic_prompt = .init(.fresh_line) }; + }, + + 'N' => new_command: { + parser.command = .{ .semantic_prompt = .init(.new_command) }; + if (data.len == 1) break :new_command; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + 'P' => prompt_start: { + parser.command = .{ .semantic_prompt = .init(.prompt_start) }; + if (data.len == 1) break :prompt_start; + if (data[1] != ';') break :valid; + parser.command.semantic_prompt.options_unvalidated = data[2..]; + }, + + else => break :valid, + } + + return &parser.command; + } + + // Any fallthroughs are invalid + parser.state = .invalid; + return null; +} + +test "OSC 133: end_input_start_output" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;C"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expect(cmd.semantic_prompt.readOption(.aid) == null); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == null); +} + +test "OSC 133: end_input_start_output extra contents" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;Cextra"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 133: end_input_start_output with options" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;C;aid=foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); +} + +test "OSC 133: end_input_start_output with cmdline" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline=echo bobr kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr kurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline 3" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline=echo bobr\\nkurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr\nkurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline 4" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline=$'echo bobr kurwa'"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr kurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline 5" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline='echo bobr kurwa'"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr kurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline 6" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline='echo bobr kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: end_input_start_output with cmdline 7" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline=$'echo bobr kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: end_input_start_output with cmdline 8" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline=$'"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: end_input_start_output with cmdline 9" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline="; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline_url 1" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr kurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline_url 2" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr%20kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr kurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline_url 3" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr%3bkurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr;kurwa", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline_url 4" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr%3kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: end_input_start_output with cmdline_url 5" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr%kurwa"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: end_input_start_output with cmdline_url 6" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr kurwa%20"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + + try cmd.semantic_prompt.writeCommandLine(&w.writer); + try testing.expectEqualStrings("echo bobr kurwa ", w.written()); +} + +test "OSC 133: end_input_start_output with cmdline_url 7" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr kurwa%2"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: end_input_start_output with cmdline_url 8" { + const testing = std.testing; + + var w: std.Io.Writer.Allocating = .init(testing.allocator); + defer w.deinit(); + + var p: Parser = .init(null); + const input = "133;C;cmdline_url=echo bobr kurwa%"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_input_start_output); + try testing.expectError(error.DecodeError, cmd.semantic_prompt.writeCommandLine(&w.writer)); +} + +test "OSC 133: fresh_line" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;L"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line); +} + +test "OSC 133: fresh_line extra contents" { + const testing = std.testing; + + // Random + { + var p: Parser = .init(null); + const input = "133;Lol"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); + } + + // Options + { + var p: Parser = .init(null); + const input = "133;L;aid=foo"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); + } +} + +test "OSC 133: fresh_line_new_prompt" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.aid) == null); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == null); +} + +test "OSC 133: fresh_line_new_prompt with aid" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;aid=14"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expectEqualStrings("14", cmd.semantic_prompt.readOption(.aid).?); +} + +test "OSC 133: fresh_line_new_prompt with '=' in aid" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;aid=a=b"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expectEqualStrings("a=b", cmd.semantic_prompt.readOption(.aid).?); +} + +test "OSC 133: fresh_line_new_prompt with cl=line" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;cl=line"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == .line); +} + +test "OSC 133: fresh_line_new_prompt with cl=m" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;cl=m"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == .multiple); +} + +test "OSC 133: fresh_line_new_prompt with invalid cl" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;cl=invalid"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == null); +} + +test "OSC 133: fresh_line_new_prompt with trailing ;" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); +} + +test "OSC 133: fresh_line_new_prompt with bare key" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;barekey"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.aid) == null); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == null); +} + +test "OSC 133: fresh_line_new_prompt with multiple options" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;aid=foo;cl=line"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == .line); +} + +test "OSC 133: fresh_line_new_prompt default redraw" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.redraw) == null); +} + +test "OSC 133: fresh_line_new_prompt with redraw=0" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;redraw=0"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.redraw).? == .false); +} + +test "OSC 133: fresh_line_new_prompt with redraw=1" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;redraw=1"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.redraw).? == .true); +} + +test "OSC 133: fresh_line_new_prompt with invalid redraw" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;A;redraw=x"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .fresh_line_new_prompt); + try testing.expect(cmd.semantic_prompt.readOption(.redraw) == null); +} + +test "OSC 133: prompt_start" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;P"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .prompt_start); + try testing.expect(cmd.semantic_prompt.readOption(.prompt_kind) == null); +} + +test "OSC 133: prompt_start with k=i" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;P;k=i"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .prompt_start); + try testing.expect(cmd.semantic_prompt.readOption(.prompt_kind) == .initial); +} + +test "OSC 133: prompt_start with k=r" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;P;k=r"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .prompt_start); + try testing.expect(cmd.semantic_prompt.readOption(.prompt_kind) == .right); +} + +test "OSC 133: prompt_start with k=c" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;P;k=c"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .prompt_start); + try testing.expect(cmd.semantic_prompt.readOption(.prompt_kind) == .continuation); +} + +test "OSC 133: prompt_start with k=s" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;P;k=s"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .prompt_start); + try testing.expect(cmd.semantic_prompt.readOption(.prompt_kind) == .secondary); +} + +test "OSC 133: prompt_start with invalid k" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;P;k=x"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .prompt_start); + try testing.expect(cmd.semantic_prompt.readOption(.prompt_kind) == null); +} + +test "OSC 133: prompt_start extra contents" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;Pextra"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 133: new_command" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;N"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .new_command); + try testing.expect(cmd.semantic_prompt.readOption(.aid) == null); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == null); +} + +test "OSC 133: new_command with aid" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;N;aid=foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .new_command); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); +} + +test "OSC 133: new_command with cl=line" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;N;cl=line"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .new_command); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == .line); +} + +test "OSC 133: new_command with multiple options" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;N;aid=foo;cl=line"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .new_command); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); + try testing.expect(cmd.semantic_prompt.readOption(.cl) == .line); +} + +test "OSC 133: new_command extra contents" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;Nextra"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 133: end_prompt_start_input" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;B"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_prompt_start_input); +} + +test "OSC 133: end_prompt_start_input extra contents" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;Bextra"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 133: end_prompt_start_input with options" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;B;aid=foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_prompt_start_input); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); +} + +test "OSC 133: end_prompt_start_input_terminate_eol" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;I"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_prompt_start_input_terminate_eol); +} + +test "OSC 133: end_prompt_start_input_terminate_eol extra contents" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;Iextra"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 133: end_prompt_start_input_terminate_eol with options" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;I;aid=foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_prompt_start_input_terminate_eol); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); +} + +test "OSC 133: end_command" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;D"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_command); + try testing.expect(cmd.semantic_prompt.readOption(.exit_code) == null); + try testing.expect(cmd.semantic_prompt.readOption(.aid) == null); + try testing.expect(cmd.semantic_prompt.readOption(.err) == null); +} + +test "OSC 133: end_command extra contents" { + const testing = std.testing; + + var p: Parser = .init(null); + const input = "133;Dextra"; + for (input) |ch| p.next(ch); + try testing.expect(p.end(null) == null); +} + +test "OSC 133: end_command with exit code 0" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;D;0"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_command); + try testing.expect(cmd.semantic_prompt.readOption(.exit_code) == 0); +} + +test "OSC 133: end_command with exit code and aid" { + const testing = std.testing; + + var p: Parser = .init(null); + + const input = "133;D;12;aid=foo"; + for (input) |ch| p.next(ch); + + const cmd = p.end(null).?.*; + try testing.expect(cmd == .semantic_prompt); + try testing.expect(cmd.semantic_prompt.action == .end_command); + try testing.expectEqualStrings("foo", cmd.semantic_prompt.readOption(.aid).?); + try testing.expect(cmd.semantic_prompt.readOption(.exit_code) == 12); +} + +test "Option.read aid" { + const testing = std.testing; + try testing.expectEqualStrings("test123", Option.aid.read("aid=test123").?); + try testing.expectEqualStrings("myaid", Option.aid.read("cl=line;aid=myaid;k=i").?); + try testing.expect(Option.aid.read("cl=line;k=i") == null); + try testing.expectEqualStrings("", Option.aid.read("aid=").?); + try testing.expectEqualStrings("last", Option.aid.read("k=i;aid=last").?); + try testing.expectEqualStrings("first", Option.aid.read("aid=first;k=i").?); + try testing.expect(Option.aid.read("") == null); + try testing.expect(Option.aid.read("aid") == null); + try testing.expectEqualStrings("value", Option.aid.read(";;aid=value;;").?); +} + +test "Option.read cl" { + const testing = std.testing; + try testing.expect(Option.cl.read("cl=line").? == .line); + try testing.expect(Option.cl.read("cl=m").? == .multiple); + try testing.expect(Option.cl.read("cl=v").? == .conservative_vertical); + try testing.expect(Option.cl.read("cl=w").? == .smart_vertical); + try testing.expect(Option.cl.read("cl=invalid") == null); + try testing.expect(Option.cl.read("aid=foo") == null); +} + +test "Option.read prompt_kind" { + const testing = std.testing; + try testing.expect(Option.prompt_kind.read("k=i").? == .initial); + try testing.expect(Option.prompt_kind.read("k=r").? == .right); + try testing.expect(Option.prompt_kind.read("k=c").? == .continuation); + try testing.expect(Option.prompt_kind.read("k=s").? == .secondary); + try testing.expect(Option.prompt_kind.read("k=x") == null); + try testing.expect(Option.prompt_kind.read("k=ii") == null); + try testing.expect(Option.prompt_kind.read("k=") == null); +} + +test "Option.read err" { + const testing = std.testing; + try testing.expectEqualStrings("some_error", Option.err.read("err=some_error").?); + try testing.expect(Option.err.read("aid=foo") == null); +} + +test "Option.read redraw" { + const testing = std.testing; + try testing.expect(Option.redraw.read("redraw=1").? == .true); + try testing.expect(Option.redraw.read("redraw=0").? == .false); + try testing.expect(Option.redraw.read("redraw=last").? == .last); + try testing.expect(Option.redraw.read("redraw=2") == null); + try testing.expect(Option.redraw.read("redraw=10") == null); + try testing.expect(Option.redraw.read("redraw=") == null); +} + +test "Option.read special_key" { + const testing = std.testing; + try testing.expect(Option.special_key.read("special_key=1").? == true); + try testing.expect(Option.special_key.read("special_key=0").? == false); + try testing.expect(Option.special_key.read("special_key=x") == null); +} + +test "Option.read click_events" { + const testing = std.testing; + try testing.expect(Option.click_events.read("click_events=1").? == true); + try testing.expect(Option.click_events.read("click_events=0").? == false); + try testing.expect(Option.click_events.read("click_events=yes") == null); +} + +test "Option.read exit_code" { + const testing = std.testing; + try testing.expect(Option.exit_code.read("42").? == 42); + try testing.expect(Option.exit_code.read("0").? == 0); + try testing.expect(Option.exit_code.read("-1").? == -1); + try testing.expect(Option.exit_code.read("abc") == null); + try testing.expect(Option.exit_code.read("127;aid=foo").? == 127); +} diff --git a/vendor/libghostty-vt/src/terminal/page.zig b/vendor/libghostty-vt/src/terminal/page.zig new file mode 100644 index 00000000..0942e260 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/page.zig @@ -0,0 +1,3918 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const build_options = @import("terminal_options"); +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; +const assert = @import("../quirks.zig").inlineAssert; +const testing = std.testing; +const posix = std.posix; +const windows = std.os.windows; +const fastmem = @import("../fastmem.zig"); +const color = @import("color.zig"); +const hyperlink = @import("hyperlink.zig"); +const kitty = @import("kitty.zig"); +const stylepkg = @import("style.zig"); +const Style = stylepkg.Style; +const StyleId = stylepkg.Id; +const StyleSet = stylepkg.Set; +const size = @import("size.zig"); +const getOffset = size.getOffset; +const Offset = size.Offset; +const OffsetBuf = size.OffsetBuf; +const BitmapAllocator = @import("bitmap_allocator.zig").BitmapAllocator; +const hash_map = @import("hash_map.zig"); +const AutoOffsetHashMap = hash_map.AutoOffsetHashMap; +const alignForward = std.mem.alignForward; +const alignBackward = std.mem.alignBackward; + +const log = std.log.scoped(.page); + +/// Page-aligned allocator used for terminal page backing memory. Pages +/// require page-aligned, zeroed memory obtained directly from the OS +/// (not the Zig allocator) because the allocation fast-path is +/// performance-critical and the OS guarantees zeroed pages. +const PageAlloc = switch (builtin.os.tag) { + .windows => AllocWindows, + else => AllocPosix, +}; + +/// Allocate page-aligned, zeroed backing memory using mmap with +/// MAP_PRIVATE | MAP_ANONYMOUS which guarantees zeroed pages. +const AllocPosix = struct { + pub fn alloc(n: usize) ![]align(std.heap.page_size_min) u8 { + return try posix.mmap( + null, + n, + posix.PROT.READ | posix.PROT.WRITE, + .{ .TYPE = .PRIVATE, .ANONYMOUS = true }, + -1, + 0, + ); + } + + pub fn free(mem: []align(std.heap.page_size_min) u8) void { + posix.munmap(mem); + } +}; + +/// Allocate page-aligned, zeroed backing memory using VirtualAlloc with +/// MEM_COMMIT | MEM_RESERVE which guarantees zeroed pages. +const AllocWindows = struct { + pub fn alloc(n: usize) error{OutOfMemory}![]align(std.heap.page_size_min) u8 { + const addr = windows.VirtualAlloc( + null, + n, + windows.MEM_COMMIT | windows.MEM_RESERVE, + windows.PAGE_READWRITE, + ) catch return error.OutOfMemory; + + return @as( + [*]align(std.heap.page_size_min) u8, + @ptrCast(@alignCast(addr)), + )[0..n]; + } + + pub fn free(mem: []align(std.heap.page_size_min) u8) void { + windows.VirtualFree( + @ptrCast(@alignCast(mem.ptr)), + 0, + windows.MEM_RELEASE, + ); + } +}; + +/// The allocator to use for multi-codepoint grapheme data. We use +/// a chunk size of 4 codepoints. It'd be best to set this empirically +/// but it is currently set based on vibes. My thinking around 4 codepoints +/// is that most skin-tone emoji are <= 4 codepoints, letter combiners +/// are usually <= 4 codepoints, and 4 codepoints is a nice power of two +/// for alignment. +const grapheme_chunk_len = 4; +const grapheme_chunk = grapheme_chunk_len * @sizeOf(u21); +const GraphemeAlloc = BitmapAllocator(grapheme_chunk); +const grapheme_count_default = GraphemeAlloc.bitmap_bit_size; +pub const grapheme_bytes_default = grapheme_count_default * grapheme_chunk; +const GraphemeMap = AutoOffsetHashMap(Offset(Cell), Offset(u21).Slice); + +/// The allocator used for shared utf8-encoded strings within a page. +/// Note the chunk size below is the minimum size of a single allocation +/// and requires a single bit of metadata in our bitmap allocator. Therefore +/// it should be tuned carefully (too small and we waste metadata, too large +/// and we have fragmentation). We can probably use a better allocation +/// strategy in the future. +/// +/// At the time of writing this, the strings table is only used for OSC8 +/// IDs and URIs. IDs are usually short and URIs are usually longer. I chose +/// 32 bytes as a compromise between these two since it represents single +/// domain links quite well and is not too wasteful for short IDs. We can +/// continue to tune this as we see how it's used. +const string_chunk_len = 32; +const string_chunk = string_chunk_len * @sizeOf(u8); +const StringAlloc = BitmapAllocator(string_chunk); +const string_count_default = StringAlloc.bitmap_bit_size; +pub const string_bytes_default = string_count_default * string_chunk; + +/// Default number of hyperlinks we support. +/// +/// The cell multiplier is the number of cells per hyperlink entry that +/// we support. A hyperlink can be longer than this multiplier; the multiplier +/// just sets the total capacity to simplify adjustable size metrics. +const hyperlink_count_default = 4; +const hyperlink_bytes_default = hyperlink_count_default * @sizeOf(hyperlink.Set.Item); +const hyperlink_cell_multiplier = 16; + +/// A page represents a specific section of terminal screen. The primary +/// idea of a page is that it is a fully self-contained unit that can be +/// serialized, copied, etc. as a convenient way to represent a section +/// of the screen. +/// +/// This property is useful for renderers which want to copy just the pages +/// for the visible portion of the screen, or for infinite scrollback where +/// we may want to serialize and store pages that are sufficiently far +/// away from the current viewport. +/// +/// Pages are always backed by a single contiguous block of memory that is +/// aligned on a page boundary. This makes it easy and fast to copy pages +/// around. Within the contiguous block of memory, the contents of a page are +/// thoughtfully laid out to optimize primarily for terminal IO (VT streams) +/// and to minimize memory usage. +pub const Page = struct { + comptime { + // The alignment of our members. We want to ensure that the page + // alignment is always divisible by this. + assert(std.heap.page_size_min % @max( + @alignOf(Row), + @alignOf(Cell), + StyleSet.base_align.toByteUnits(), + ) == 0); + } + + /// The backing memory for the page. A page is always made up of a + /// a single contiguous block of memory that is aligned on a page + /// boundary and is a multiple of the system page size. + memory: []align(std.heap.page_size_min) u8, + + /// The array of rows in the page. The rows are always in row order + /// (i.e. index 0 is the top row, index 1 is the row below that, etc.) + rows: Offset(Row), + + /// The array of cells in the page. The cells are NOT in row order, + /// but they are in column order. To determine the mapping of cells + /// to row, you must use the `rows` field. From the pointer to the + /// first column, all cells in that row are laid out in column order. + cells: Offset(Cell), + + /// Set to true when an operation is performed that dirties all rows in + /// the page. See `Row.dirty` for more information on dirty tracking. + /// + /// NOTE: A value of false does NOT indicate that + /// the page has no dirty rows in it, only + /// that no full-page-dirtying operations + /// have occurred since it was last cleared. + dirty: bool, + + /// The string allocator for this page used for shared utf-8 encoded + /// strings. Liveness of strings and memory management is deferred to + /// the individual use case. + string_alloc: StringAlloc, + + /// The multi-codepoint grapheme data for this page. This is where + /// any cell that has more than one codepoint will be stored. This is + /// relatively rare (typically only emoji) so this defaults to a very small + /// size and we force page realloc when it grows. + grapheme_alloc: GraphemeAlloc, + + /// The mapping of cell to grapheme data. The exact mapping is the + /// cell offset to the grapheme data offset. Therefore, whenever a + /// cell is moved (i.e. `erase`) then the grapheme data must be updated. + /// Grapheme data is relatively rare so this is considered a slow + /// path. + grapheme_map: GraphemeMap, + + /// The available set of styles in use on this page. + styles: StyleSet, + + /// The structures used for tracking hyperlinks within the page. + /// The map maps cell offsets to hyperlink IDs and the IDs are in + /// the ref counted set. The strings within the hyperlink structures + /// are allocated in the string allocator. + hyperlink_map: hyperlink.Map, + hyperlink_set: hyperlink.Set, + + /// The current dimensions of the page. The capacity may be larger + /// than this. This allows us to allocate a larger page than necessary + /// and also to resize a page smaller without reallocating. + size: Size, + + /// The capacity of this page. This is the full size of the backing + /// memory and is fixed at page creation time. + capacity: Capacity, + + /// If this is true then verifyIntegrity will do nothing. This is + /// only present with runtime safety enabled. + pause_integrity_checks: if (build_options.slow_runtime_safety) usize else void = + if (build_options.slow_runtime_safety) 0 else {}, + + /// Initialize a new page, allocating the required backing memory. + /// The size of the initialized page defaults to the full capacity. + /// + /// The backing memory is always allocated using mmap directly. + /// You cannot use custom allocators with this structure because + /// it is critical to performance that we use mmap. + pub inline fn init(cap: Capacity) !Page { + const l = layout(cap); + + // We allocate page-aligned zeroed memory directly to avoid Zig + // allocator overhead (small but meaningful for this path). Both + // mmap (POSIX) and VirtualAlloc (Windows) guarantee zeroed pages, + // which is a critical property for us. + assert(l.total_size % std.heap.page_size_min == 0); + const backing = try PageAlloc.alloc(l.total_size); + errdefer PageAlloc.free(backing); + + const buf = OffsetBuf.init(backing); + return initBuf(buf, l); + } + + /// Initialize a new page using the given backing memory. + /// It is up to the caller to not call deinit on these pages. + pub inline fn initBuf(buf: OffsetBuf, l: Layout) Page { + const cap = l.capacity; + const rows = buf.member(Row, l.rows_start); + const cells = buf.member(Cell, l.cells_start); + + // We need to go through and initialize all the rows so that + // they point to a valid offset into the cells, since the rows + // zero-initialized aren't valid. + const cells_len = @as(usize, cap.cols) * @as(usize, cap.rows); + const cells_ptr = cells.ptr(buf)[0..cells_len]; + for (rows.ptr(buf)[0..cap.rows], 0..) |*row, y| { + const start = y * cap.cols; + row.* = .{ + .cells = getOffset(Cell, buf, &cells_ptr[start]), + }; + } + + return .{ + .memory = @alignCast(buf.start()[0..l.total_size]), + .rows = rows, + .cells = cells, + .styles = StyleSet.init( + buf.add(l.styles_start), + l.styles_layout, + .{}, + ), + .string_alloc = .init( + buf.add(l.string_alloc_start), + l.string_alloc_layout, + ), + .grapheme_alloc = .init( + buf.add(l.grapheme_alloc_start), + l.grapheme_alloc_layout, + ), + .grapheme_map = .init( + buf.add(l.grapheme_map_start), + l.grapheme_map_layout, + ), + .hyperlink_map = .init( + buf.add(l.hyperlink_map_start), + l.hyperlink_map_layout, + ), + .hyperlink_set = .init( + buf.add(l.hyperlink_set_start), + l.hyperlink_set_layout, + .{}, + ), + .size = .{ .cols = cap.cols, .rows = cap.rows }, + .capacity = cap, + .dirty = false, + }; + } + + /// Deinitialize the page, freeing any backing memory. Do NOT call + /// this if you allocated the backing memory yourself (i.e. you used + /// initBuf). + pub inline fn deinit(self: *Page) void { + PageAlloc.free(self.memory); + self.* = undefined; + } + + /// Reinitialize the page with the same capacity. + pub inline fn reinit(self: *Page) void { + // We zero the page memory as u64 instead of u8 because + // we can and it's empirically quite a bit faster. + @memset(@as([*]u64, @ptrCast(self.memory))[0 .. self.memory.len / 8], 0); + self.* = initBuf(.init(self.memory), layout(self.capacity)); + } + + pub const IntegrityError = error{ + ZeroRowCount, + ZeroColCount, + UnmarkedGraphemeRow, + MissingGraphemeData, + InvalidGraphemeCount, + UnmarkedGraphemeCell, + MissingStyle, + UnmarkedStyleRow, + MismatchedStyleRef, + InvalidStyleCount, + MissingHyperlinkData, + MismatchedHyperlinkRef, + UnmarkedHyperlinkCell, + UnmarkedHyperlinkRow, + InvalidSpacerTailLocation, + InvalidSpacerHeadLocation, + UnwrappedSpacerHead, + }; + + /// Temporarily pause integrity checks. This is useful when you are + /// doing a lot of operations that would trigger integrity check + /// violations but you know the page will end up in a consistent state. + pub inline fn pauseIntegrityChecks(self: *Page, v: bool) void { + if (build_options.slow_runtime_safety) { + if (v) { + self.pause_integrity_checks += 1; + } else { + self.pause_integrity_checks -= 1; + } + } + } + + /// A helper that can be used to assert the integrity of the page + /// when runtime safety is enabled. This is a no-op when runtime + /// safety is disabled. This uses the libc allocator. + pub inline fn assertIntegrity(self: *const Page) void { + if (comptime build_options.slow_runtime_safety) { + var debug_allocator: std.heap.DebugAllocator(.{}) = .init; + defer _ = debug_allocator.deinit(); + const alloc = debug_allocator.allocator(); + self.verifyIntegrity(alloc) catch |err| { + log.err("page integrity violation, crashing. err={}", .{err}); + @panic("page integrity violation"); + }; + } + } + + /// Verifies the integrity of the page data. This is not fast, + /// but it is useful for assertions, deserialization, etc. The + /// allocator is only used for temporary allocations -- all memory + /// is freed before this function returns. + /// + /// Integrity errors are also logged as warnings. + pub fn verifyIntegrity(self: *const Page, alloc_gpa: Allocator) !void { + // Some things that seem like we should check but do not: + // + // - We do not check that the style ref count is exact, only that + // it is at least what we see. We do this because some fast paths + // trim rows without clearing data. + // - We do not check that styles seen is exactly the same as the + // styles count in the page for the same reason as above. + // - We only check that we saw less graphemes than the total memory + // used for the same reason as styles above. + // + + // We don't run integrity checks on Valgrind because its soooooo slow, + // Valgrind is our integrity checker, and we run these during unit + // tests (non-Valgrind) anyways so we're verifying anyways. + if (std.valgrind.runningOnValgrind() > 0) return; + + if (build_options.slow_runtime_safety) { + if (self.pause_integrity_checks > 0) return; + } + + if (self.size.rows == 0) { + log.warn("page integrity violation zero row count", .{}); + return IntegrityError.ZeroRowCount; + } + if (self.size.cols == 0) { + log.warn("page integrity violation zero col count", .{}); + return IntegrityError.ZeroColCount; + } + + var arena = ArenaAllocator.init(alloc_gpa); + defer arena.deinit(); + const alloc = arena.allocator(); + + var graphemes_seen: usize = 0; + var styles_seen = std.AutoHashMap(StyleId, usize).init(alloc); + defer styles_seen.deinit(); + var hyperlinks_seen = std.AutoHashMap(hyperlink.Id, usize).init(alloc); + defer hyperlinks_seen.deinit(); + + const grapheme_count = self.graphemeCount(); + + const rows = self.rows.ptr(self.memory)[0..self.size.rows]; + for (rows, 0..) |*row, y| { + const graphemes_start = graphemes_seen; + const cells = row.cells.ptr(self.memory)[0..self.size.cols]; + for (cells, 0..) |*cell, x| { + if (cell.hasGrapheme()) { + // If a cell has grapheme data, it must be present in + // the grapheme map. + _ = self.lookupGrapheme(cell) orelse { + log.warn( + "page integrity violation y={} x={} grapheme data missing", + .{ y, x }, + ); + return IntegrityError.MissingGraphemeData; + }; + + graphemes_seen += 1; + } else if (grapheme_count > 0) { + // It should not have grapheme data if it isn't marked. + // The grapheme_count check above is just an optimization + // to speed up integrity checks. + if (self.lookupGrapheme(cell) != null) { + log.warn( + "page integrity violation y={} x={} cell not marked as grapheme", + .{ y, x }, + ); + return IntegrityError.UnmarkedGraphemeCell; + } + } + + if (cell.style_id != stylepkg.default_id) { + // If a cell has a style, it must be present in the styles + // set. Accessing it with `get` asserts that. + _ = self.styles.get( + self.memory, + cell.style_id, + ); + + if (!row.styled) { + log.warn( + "page integrity violation y={} x={} row not marked as styled", + .{ y, x }, + ); + return IntegrityError.UnmarkedStyleRow; + } + + const gop = try styles_seen.getOrPut(cell.style_id); + if (!gop.found_existing) gop.value_ptr.* = 0; + gop.value_ptr.* += 1; + } + + if (cell.hyperlink) { + const id = self.lookupHyperlink(cell) orelse { + log.warn( + "page integrity violation y={} x={} hyperlink data missing", + .{ y, x }, + ); + return IntegrityError.MissingHyperlinkData; + }; + + if (!row.hyperlink) { + log.warn( + "page integrity violation y={} x={} row not marked as hyperlink", + .{ y, x }, + ); + return IntegrityError.UnmarkedHyperlinkRow; + } + + const gop = try hyperlinks_seen.getOrPut(id); + if (!gop.found_existing) gop.value_ptr.* = 0; + gop.value_ptr.* += 1; + + // Hyperlink ID should be valid. This just straight crashes + // if this fails due to assertions. + _ = self.hyperlink_set.get(self.memory, id); + } else { + // It should not have hyperlink data if it isn't marked + if (self.lookupHyperlink(cell) != null) { + log.warn( + "page integrity violation y={} x={} cell not marked as hyperlink", + .{ y, x }, + ); + return IntegrityError.UnmarkedHyperlinkCell; + } + } + + switch (cell.wide) { + .narrow => {}, + .wide => {}, + + .spacer_tail => { + // Spacer tails can't be at the start because they follow + // a wide char. + if (x == 0) { + log.warn( + "page integrity violation y={} x={} spacer tail at start", + .{ y, x }, + ); + return IntegrityError.InvalidSpacerTailLocation; + } + + // Spacer tails must follow a wide char + const prev = cells[x - 1]; + if (prev.wide != .wide) { + log.warn( + "page integrity violation y={} x={} spacer tail not following wide", + .{ y, x }, + ); + return IntegrityError.InvalidSpacerTailLocation; + } + }, + + .spacer_head => { + // Spacer heads must be at the end + if (x != self.size.cols - 1) { + log.warn( + "page integrity violation y={} x={} spacer head not at end", + .{ y, x }, + ); + return IntegrityError.InvalidSpacerHeadLocation; + } + + // The row must be wrapped + if (!row.wrap) { + log.warn( + "page integrity violation y={} spacer head not wrapped", + .{y}, + ); + return IntegrityError.UnwrappedSpacerHead; + } + }, + } + } + + // Check row grapheme data + if (graphemes_seen > graphemes_start) { + // If a cell in a row has grapheme data, the row must + // be marked as having grapheme data. + if (!row.grapheme) { + log.warn( + "page integrity violation y={} grapheme data but row not marked", + .{y}, + ); + return IntegrityError.UnmarkedGraphemeRow; + } + } + } + + // Our graphemes seen should exactly match the grapheme count + if (graphemes_seen > self.graphemeCount()) { + log.warn( + "page integrity violation grapheme count mismatch expected={} actual={}", + .{ graphemes_seen, self.graphemeCount() }, + ); + return IntegrityError.InvalidGraphemeCount; + } + + // Verify all our styles have the correct ref count. + { + var it = styles_seen.iterator(); + while (it.next()) |entry| { + const ref_count = self.styles.refCount(self.memory, entry.key_ptr.*); + if (ref_count < entry.value_ptr.*) { + log.warn( + "page integrity violation style ref count mismatch id={} expected={} actual={}", + .{ entry.key_ptr.*, entry.value_ptr.*, ref_count }, + ); + return IntegrityError.MismatchedStyleRef; + } + } + } + + // Verify all our hyperlinks have the correct ref count. + { + var it = hyperlinks_seen.iterator(); + while (it.next()) |entry| { + const ref_count = self.hyperlink_set.refCount(self.memory, entry.key_ptr.*); + if (ref_count < entry.value_ptr.*) { + log.warn( + "page integrity violation hyperlink ref count mismatch id={} expected={} actual={}", + .{ entry.key_ptr.*, entry.value_ptr.*, ref_count }, + ); + return IntegrityError.MismatchedHyperlinkRef; + } + } + } + + // Verify there are no zombie styles, that is, styles in the + // set with ref counts > 0, which are not present in the page. + { + const styles_table = self.styles.table.ptr(self.memory)[0..self.styles.layout.table_cap]; + const styles_items = self.styles.items.ptr(self.memory)[0..self.styles.layout.cap]; + + var zombies: usize = 0; + + for (styles_table) |id| { + if (id == 0) continue; + const item = styles_items[id]; + if (item.meta.ref == 0) continue; + + const expected = styles_seen.get(id) orelse 0; + if (expected > 0) continue; + + if (item.meta.ref > expected) { + zombies += 1; + } + } + + // NOTE: This is currently disabled because @qwerasd says that + // certain fast paths can cause this but its okay. + // Just 1 zombie style might be the cursor style, so ignore it. + // if (zombies > 1) { + // log.warn( + // "page integrity violation zombie styles count={}", + // .{zombies}, + // ); + // return IntegrityError.ZombieStyles; + // } + } + } + + /// Clone the contents of this page. This will allocate new memory + /// using the page allocator. If you want to manage memory manually, + /// use cloneBuf. + pub inline fn clone(self: *const Page) !Page { + const backing = try PageAlloc.alloc(self.memory.len); + errdefer PageAlloc.free(backing); + return self.cloneBuf(backing); + } + + /// Clone the entire contents of this page. + /// + /// The buffer must be at least the size of self.memory. + pub inline fn cloneBuf(self: *const Page, buf: []align(std.heap.page_size_min) u8) Page { + assert(buf.len >= self.memory.len); + + // The entire concept behind a page is that everything is stored + // as offsets so we can do a simple linear copy of the backing + // memory and copy all the offsets and everything will work. + var result = self.*; + result.memory = buf[0..self.memory.len]; + + // This is a memcpy. We may want to investigate if there are + // faster ways to do this (i.e. copy-on-write tricks) but I suspect + // they'll be slower. I haven't experimented though. + // std.log.warn("copy bytes={}", .{self.memory.len}); + fastmem.copy(u8, result.memory, self.memory); + + return result; + } + + pub const StyleSetError = error{ + StyleSetOutOfMemory, + StyleSetNeedsRehash, + }; + + pub const HyperlinkError = error{ + StringAllocOutOfMemory, + HyperlinkSetOutOfMemory, + HyperlinkSetNeedsRehash, + HyperlinkMapOutOfMemory, + }; + + pub const GraphemeError = error{ + GraphemeMapOutOfMemory, + GraphemeAllocOutOfMemory, + }; + + pub const CloneFromError = + StyleSetError || + HyperlinkError || + GraphemeError; + + /// Compute the exact capacity required to store a range of rows from + /// this page. + /// + /// The returned capacity will have the same number of columns as this + /// page and the number of rows equal to the range given. The returned + /// capacity is by definition strictly less than or equal to this + /// page's capacity, so the layout is guaranteed to succeed. + /// + /// Preconditions: + /// - Range must be at least 1 row + /// - Start and end must be valid for this page + pub fn exactRowCapacity( + self: *const Page, + y_start: usize, + y_end: usize, + ) Capacity { + assert(y_start < y_end); + assert(y_end <= self.size.rows); + + // Track unique IDs using a bitset. Both style IDs and hyperlink IDs + // are CellCountInt (u16), so we reuse this set for both to save + // stack memory (~8KB instead of ~16KB). + const CellCountSet = std.StaticBitSet(std.math.maxInt(size.CellCountInt) + 1); + comptime assert(size.StyleCountInt == size.CellCountInt); + comptime assert(size.HyperlinkCountInt == size.CellCountInt); + + // Accumulators + var id_set: CellCountSet = .initEmpty(); + var grapheme_bytes: usize = 0; + var string_bytes: usize = 0; + + // First pass: count styles and grapheme bytes + const rows = self.rows.ptr(self.memory)[y_start..y_end]; + for (rows) |*row| { + const cells = row.cells.ptr(self.memory)[0..self.size.cols]; + for (cells) |*cell| { + if (cell.style_id != stylepkg.default_id) { + id_set.set(cell.style_id); + } + + if (cell.hasGrapheme()) { + if (self.lookupGrapheme(cell)) |cps| { + grapheme_bytes += GraphemeAlloc.bytesRequired(u21, cps.len); + } + } + } + } + const styles_cap = StyleSet.capacityForCount(id_set.count()); + + // Second pass: count hyperlinks and string bytes + // We count both unique hyperlinks (for hyperlink_set) and total + // hyperlink cells (for hyperlink_map capacity). + id_set = .initEmpty(); + var hyperlink_cells: usize = 0; + for (rows) |*row| { + const cells = row.cells.ptr(self.memory)[0..self.size.cols]; + for (cells) |*cell| { + if (cell.hyperlink) { + hyperlink_cells += 1; + if (self.lookupHyperlink(cell)) |id| { + // Only count each unique hyperlink once for set sizing + if (!id_set.isSet(id)) { + id_set.set(id); + + // Get the hyperlink entry to compute string bytes + const entry = self.hyperlink_set.get(self.memory, id); + string_bytes += StringAlloc.bytesRequired(u8, entry.uri.len); + + switch (entry.id) { + .implicit => {}, + .explicit => |slice| { + string_bytes += StringAlloc.bytesRequired(u8, slice.len); + }, + } + } + } + } + } + } + + // The hyperlink_map capacity in layout() is computed as: + // hyperlink_count * hyperlink_cell_multiplier (rounded to power of 2) + // We need enough hyperlink_bytes so that when layout() computes + // the map capacity, it can accommodate all hyperlink cells. This + // is unit tested. + const hyperlink_cap = cap: { + const hyperlink_count = id_set.count(); + const hyperlink_set_cap = hyperlink.Set.capacityForCount(hyperlink_count); + const hyperlink_map_min = std.math.divCeil( + usize, + hyperlink_cells, + hyperlink_cell_multiplier, + ) catch 0; + break :cap @max(hyperlink_set_cap, hyperlink_map_min); + }; + + // All the intCasts below are safe because we should have a + // capacity strictly less than or equal to this page's capacity. + return .{ + .cols = self.size.cols, + .rows = @intCast(y_end - y_start), + .styles = @intCast(styles_cap), + .grapheme_bytes = @intCast(grapheme_bytes), + .hyperlink_bytes = @intCast(hyperlink_cap * @sizeOf(hyperlink.Set.Item)), + .string_bytes = @intCast(string_bytes), + }; + } + + /// Clone the contents of another page into this page. The capacities + /// can be different, but the size of the other page must fit into + /// this page. + /// + /// The y_start and y_end parameters allow you to clone only a portion + /// of the other page. This is useful for splitting a page into two + /// or more pages. + /// + /// The column count of this page will always be the same as this page. + /// If the other page has more columns, the extra columns will be + /// truncated. If the other page has fewer columns, the extra columns + /// will be zeroed. + pub inline fn cloneFrom( + self: *Page, + other: *const Page, + y_start: usize, + y_end: usize, + ) CloneFromError!void { + assert(y_start <= y_end); + assert(y_end <= other.size.rows); + assert(y_end - y_start <= self.size.rows); + + const other_rows = other.rows.ptr(other.memory)[y_start..y_end]; + const rows = self.rows.ptr(self.memory)[0 .. y_end - y_start]; + for (rows, other_rows) |*dst_row, *src_row| { + try self.cloneRowFrom(other, dst_row, src_row); + } + + // We should remain consistent + self.assertIntegrity(); + } + + /// Clone a single row from another page into this page. + pub inline fn cloneRowFrom( + self: *Page, + other: *const Page, + dst_row: *Row, + src_row: *const Row, + ) CloneFromError!void { + try self.clonePartialRowFrom( + other, + dst_row, + src_row, + 0, + self.size.cols, + ); + } + + /// Clone a single row from another page into this page, supporting + /// partial copy. cloneRowFrom calls this. + pub fn clonePartialRowFrom( + self: *Page, + other: *const Page, + dst_row: *Row, + src_row: *const Row, + x_start: usize, + x_end_req: usize, + ) CloneFromError!void { + // This whole operation breaks integrity until the end. + self.pauseIntegrityChecks(true); + defer { + self.pauseIntegrityChecks(false); + self.assertIntegrity(); + } + + const cell_len = @min(self.size.cols, other.size.cols); + const x_end = @min(x_end_req, cell_len); + assert(x_start <= x_end); + const other_cells = src_row.cells.ptr(other.memory)[x_start..x_end]; + const cells = dst_row.cells.ptr(self.memory)[x_start..x_end]; + + // If our destination has styles or graphemes then we need to + // clear some state. This will free up the managed memory as well. + if (dst_row.managedMemory()) self.clearCells(dst_row, x_start, x_end); + + // Copy all the row metadata but keep our cells offset + dst_row.* = copy: { + var copy = src_row.*; + + // If we're not copying the full row then we want to preserve + // some original state from our dst row. + if ((x_end - x_start) < self.size.cols) { + copy.wrap = dst_row.wrap; + copy.wrap_continuation = dst_row.wrap_continuation; + copy.grapheme = dst_row.grapheme; + copy.hyperlink = dst_row.hyperlink; + copy.styled = dst_row.styled; + copy.dirty |= dst_row.dirty; + } + + // Our cell offset remains the same + copy.cells = dst_row.cells; + + break :copy copy; + }; + + // If we have no managed memory in the source, then we can just + // copy it directly. + if (!src_row.managedMemory()) { + // This is an integrity check: if the row claims it doesn't + // have managed memory then all cells must also not have + // managed memory. + if (build_options.slow_runtime_safety) { + for (other_cells) |cell| { + assert(!cell.hasGrapheme()); + assert(!cell.hyperlink); + assert(cell.style_id == stylepkg.default_id); + } + } + + fastmem.copy(Cell, cells, other_cells); + } else { + // We have managed memory, so we have to do a slower copy to + // get all of that right. + for (cells, other_cells) |*dst_cell, *src_cell| { + dst_cell.* = src_cell.*; + + // Reset any managed memory markers on the cell so that we don't + // hit an integrity check if we have to return an error because + // the page can't fit the new memory. + dst_cell.hyperlink = false; + dst_cell.style_id = stylepkg.default_id; + if (dst_cell.content_tag == .codepoint_grapheme) { + dst_cell.content_tag = .codepoint; + } + + if (src_cell.hasGrapheme()) { + // Copy the grapheme codepoints + const cps = other.lookupGrapheme(src_cell).?; + + // Safe to use setGraphemes because we cleared all + // managed memory for our destination cell range. + try self.setGraphemes(dst_row, dst_cell, cps); + } + if (src_cell.hyperlink) hyperlink: { + const id = other.lookupHyperlink(src_cell).?; + + // Fast-path: same page we can add with the same id. + if (other == self) { + self.hyperlink_set.use(self.memory, id); + try self.setHyperlink(dst_row, dst_cell, id); + break :hyperlink; + } + + // Slow-path: get the hyperlink from the other page, + // add it, and migrate. + + // If our page can't support an additional cell with + // a hyperlink then we have to return an error. + if (self.hyperlinkCount() >= self.hyperlinkCapacity()) { + // The hyperlink map capacity needs to be increased. + return error.HyperlinkMapOutOfMemory; + } + + const other_link = other.hyperlink_set.get(other.memory, id); + const dst_id = dst_id: { + // First check if the link already exists in our page, + // and increment its refcount if so, since we're about + // to use it. + if (self.hyperlink_set.lookupContext( + self.memory, + other_link.*, + .{ .page = self, .src_page = @constCast(other) }, + )) |i| { + self.hyperlink_set.use(self.memory, i); + break :dst_id i; + } + + // If we don't have this link in our page yet then + // we need to clone it over and add it to our set. + + // Clone the link. + const dst_link = other_link.dupe(other, self) catch |e| { + comptime assert(@TypeOf(e) == error{OutOfMemory}); + // The string alloc capacity needs to be increased. + return error.StringAllocOutOfMemory; + }; + + // Add it, preferring to use the same ID as the other + // page, since this *probably* speeds up full-page + // clones. + // + // TODO(qwerasd): verify the assumption that `addWithId` + // is ever actually useful, I think it may not be. + break :dst_id self.hyperlink_set.addWithIdContext( + self.memory, + dst_link, + id, + .{ .page = self }, + ) catch |e| switch (e) { + // The hyperlink set capacity needs to be increased. + error.OutOfMemory => return error.HyperlinkSetOutOfMemory, + + // The hyperlink set needs to be rehashed. + error.NeedsRehash => return error.HyperlinkSetNeedsRehash, + } orelse id; + }; + + try self.setHyperlink(dst_row, dst_cell, dst_id); + } + if (src_cell.style_id != stylepkg.default_id) style: { + dst_row.styled = true; + + if (other == self) { + // If it's the same page we don't have to worry about + // copying the style, we can use the style ID directly. + dst_cell.style_id = src_cell.style_id; + self.styles.use(self.memory, dst_cell.style_id); + break :style; + } + + // Slow path: Get the style from the other + // page and add it to this page's style set. + const other_style = other.styles.get(other.memory, src_cell.style_id); + dst_cell.style_id = self.styles.addWithId( + self.memory, + other_style.*, + src_cell.style_id, + ) catch |e| switch (e) { + // The style set capacity needs to be increased. + error.OutOfMemory => return error.StyleSetOutOfMemory, + + // The style set needs to be rehashed. + error.NeedsRehash => return error.StyleSetNeedsRehash, + } orelse src_cell.style_id; + } + if (comptime build_options.kitty_graphics) { + if (src_cell.codepoint() == kitty.graphics.unicode.placeholder) { + dst_row.kitty_virtual_placeholder = true; + } + } + } + } + + // If we are growing columns, then we need to ensure spacer heads + // are cleared. + if (self.size.cols > other.size.cols) { + const last = &cells[other.size.cols - 1]; + if (last.wide == .spacer_head) { + last.wide = .narrow; + } + } + } + + /// Get a single row. y must be valid. + pub inline fn getRow(self: *const Page, y: usize) *Row { + assert(y < self.size.rows); + return &self.rows.ptr(self.memory)[y]; + } + + /// Get the cells for a row. + pub inline fn getCells(self: *const Page, row: *Row) []Cell { + if (build_options.slow_runtime_safety) { + const rows = self.rows.ptr(self.memory); + const cells = self.cells.ptr(self.memory); + assert(@intFromPtr(row) >= @intFromPtr(rows)); + assert(@intFromPtr(row) < @intFromPtr(cells)); + } + + const cells = row.cells.ptr(self.memory); + return cells[0..self.size.cols]; + } + + /// Get the row and cell for the given X/Y within this page. + pub inline fn getRowAndCell(self: *const Page, x: usize, y: usize) struct { + row: *Row, + cell: *Cell, + } { + assert(y < self.size.rows); + assert(x < self.size.cols); + + const rows = self.rows.ptr(self.memory); + const row = &rows[y]; + const cell = &row.cells.ptr(self.memory)[x]; + + return .{ .row = row, .cell = cell }; + } + + /// Move a cell from one location to another. This will replace the + /// previous contents with a blank cell. Because this is a move, this + /// doesn't allocate and can't fail. + pub fn moveCells( + self: *Page, + src_row: *Row, + src_left: usize, + dst_row: *Row, + dst_left: usize, + len: usize, + ) void { + defer self.assertIntegrity(); + + const src_cells = src_row.cells.ptr(self.memory)[src_left .. src_left + len]; + const dst_cells = dst_row.cells.ptr(self.memory)[dst_left .. dst_left + len]; + + // Clear our destination now matter what + self.clearCells(dst_row, dst_left, dst_left + len); + + // If src has no managed memory, this is very fast. + if (!src_row.managedMemory()) { + fastmem.copy(Cell, dst_cells, src_cells); + } else { + // Source has graphemes or hyperlinks... + for (src_cells, dst_cells) |*src, *dst| { + dst.* = src.*; + if (src.hasGrapheme()) { + // Required for moveGrapheme assertions + dst.content_tag = .codepoint; + self.moveGrapheme(src, dst); + src.content_tag = .codepoint; + dst.content_tag = .codepoint_grapheme; + dst_row.grapheme = true; + } + if (src.hyperlink) { + dst.hyperlink = false; + self.moveHyperlink(src, dst); + dst.hyperlink = true; + dst_row.hyperlink = true; + } + if (comptime build_options.kitty_graphics) { + if (src.codepoint() == kitty.graphics.unicode.placeholder) { + dst_row.kitty_virtual_placeholder = true; + } + } + } + } + + // The destination row has styles if any of the cells are styled + if (!dst_row.styled) dst_row.styled = styled: for (dst_cells) |c| { + if (c.style_id != stylepkg.default_id) break :styled true; + } else false; + + // Clear our source row now that the copy is complete. We can NOT + // use clearCells here because clearCells will garbage collect our + // styles and graphames but we moved them above. + // + // Zero the cells as u64s since empirically this seems + // to be a bit faster than using @memset(src_cells, .{}) + @memset(@as([]u64, @ptrCast(src_cells)), 0); + if (src_cells.len == self.size.cols) { + src_row.grapheme = false; + src_row.hyperlink = false; + src_row.styled = false; + if (comptime build_options.kitty_graphics) { + src_row.kitty_virtual_placeholder = false; + } + } + } + + /// Swap two cells within the same row as quickly as possible. + pub inline fn swapCells( + self: *Page, + src: *Cell, + dst: *Cell, + ) void { + defer self.assertIntegrity(); + + // Graphemes are keyed by cell offset so we do have to move them. + // We do this first so that all our grapheme state is correct. + if (src.hasGrapheme() or dst.hasGrapheme()) { + if (src.hasGrapheme() and !dst.hasGrapheme()) { + self.moveGrapheme(src, dst); + } else if (!src.hasGrapheme() and dst.hasGrapheme()) { + self.moveGrapheme(dst, src); + } else { + // Both had graphemes, so we have to manually swap + const src_offset = getOffset(Cell, self.memory, src); + const dst_offset = getOffset(Cell, self.memory, dst); + var map = self.grapheme_map.map(self.memory); + const src_entry = map.getEntry(src_offset).?; + const dst_entry = map.getEntry(dst_offset).?; + const src_value = src_entry.value_ptr.*; + const dst_value = dst_entry.value_ptr.*; + src_entry.value_ptr.* = dst_value; + dst_entry.value_ptr.* = src_value; + } + } + + // Hyperlinks are keyed by cell offset. + if (src.hyperlink or dst.hyperlink) { + if (src.hyperlink and !dst.hyperlink) { + self.moveHyperlink(src, dst); + } else if (!src.hyperlink and dst.hyperlink) { + self.moveHyperlink(dst, src); + } else { + // Both had hyperlinks, so we have to manually swap + const src_offset = getOffset(Cell, self.memory, src); + const dst_offset = getOffset(Cell, self.memory, dst); + var map = self.hyperlink_map.map(self.memory); + const src_entry = map.getEntry(src_offset).?; + const dst_entry = map.getEntry(dst_offset).?; + const src_value = src_entry.value_ptr.*; + const dst_value = dst_entry.value_ptr.*; + src_entry.value_ptr.* = dst_value; + dst_entry.value_ptr.* = src_value; + } + } + + // Copy the metadata. Note that we do NOT have to worry about + // styles because styles are keyed by ID and we're preserving the + // exact ref count and row state here. + const old_dst = dst.*; + dst.* = src.*; + src.* = old_dst; + } + + /// Clear the cells in the given row. This will reclaim memory used + /// by graphemes and styles. Note that if the style cleared is still + /// active, Page cannot know this and it will still be ref counted down. + /// The best solution for this is to artificially increment the ref count + /// prior to calling this function. + pub inline fn clearCells( + self: *Page, + row: *Row, + left: usize, + end: usize, + ) void { + defer self.assertIntegrity(); + + const cells = row.cells.ptr(self.memory)[left..end]; + + // If we have managed memory (styles, graphemes, or hyperlinks) + // in this row then we go cell by cell and clear them if present. + if (row.grapheme) { + for (cells) |*cell| { + if (cell.hasGrapheme()) + @call(.always_inline, clearGrapheme, .{ self, cell }); + } + + // If we have no left/right scroll region we can be sure + // that we've cleared all the graphemes, so we clear the + // flag, otherwise we use the update function to update. + if (cells.len == self.size.cols) { + row.grapheme = false; + } else { + self.updateRowGraphemeFlag(row); + } + } + + if (row.hyperlink) { + for (cells) |*cell| { + if (cell.hyperlink) + @call(.always_inline, clearHyperlink, .{ self, cell }); + } + + // If we have no left/right scroll region we can be sure + // that we've cleared all the hyperlinks, so we clear the + // flag, otherwise we use the update function to update. + if (cells.len == self.size.cols) { + row.hyperlink = false; + } else { + self.updateRowHyperlinkFlag(row); + } + } + + if (row.styled) { + for (cells) |*cell| { + if (cell.hasStyling()) + self.styles.release(self.memory, cell.style_id); + } + + // If we have no left/right scroll region we can be sure + // that we've cleared all the styles, so we clear the + // flag, otherwise we use the update function to update. + if (cells.len == self.size.cols) { + row.styled = false; + } else { + self.updateRowStyledFlag(row); + } + } + + if (comptime build_options.kitty_graphics) { + if (row.kitty_virtual_placeholder and + cells.len == self.size.cols) + { + for (cells) |c| { + if (c.codepoint() == kitty.graphics.unicode.placeholder) { + break; + } + } else row.kitty_virtual_placeholder = false; + } + } + + // Zero the cells as u64s since empirically this seems + // to be a bit faster than using @memset(cells, .{}) + @memset(@as([]u64, @ptrCast(cells)), 0); + } + + /// Returns the hyperlink ID for the given cell. + pub inline fn lookupHyperlink(self: *const Page, cell: *const Cell) ?hyperlink.Id { + const cell_offset = getOffset(Cell, self.memory, cell); + const map = self.hyperlink_map.map(self.memory); + return map.get(cell_offset); + } + + /// Clear the hyperlink from the given cell. + /// + /// In order to update the hyperlink flag on the row, call + /// `updateRowHyperlinkFlag` after you finish clearing any + /// hyperlinks in the row. + pub fn clearHyperlink(self: *Page, cell: *Cell) void { + defer self.assertIntegrity(); + + // Get our ID + const cell_offset = getOffset(Cell, self.memory, cell); + var map = self.hyperlink_map.map(self.memory); + const entry = map.getEntry(cell_offset) orelse return; + + // Release our usage of this, free memory, unset flag + self.hyperlink_set.release(self.memory, entry.value_ptr.*); + map.removeByPtr(entry.key_ptr); + cell.hyperlink = false; + } + + /// Checks if the row contains any hyperlinks and sets + /// the hyperlink flag to false if none are found. + /// + /// Call after removing hyperlinks in a row. + pub inline fn updateRowHyperlinkFlag(self: *Page, row: *Row) void { + const cells = row.cells.ptr(self.memory)[0..self.size.cols]; + for (cells) |c| if (c.hyperlink) return; + row.hyperlink = false; + } + + pub const InsertHyperlinkError = error{ + /// string_alloc errors + StringsOutOfMemory, + + /// hyperlink_set errors + SetOutOfMemory, + SetNeedsRehash, + }; + + /// Convert a hyperlink into a page entry, returning the ID. + /// + /// This does not de-dupe any strings, so if the URI, explicit ID, + /// etc. is already in the strings table this will duplicate it. + /// + /// To release the memory associated with the given hyperlink, + /// release the ID from the `hyperlink_set`. If the refcount reaches + /// zero and the slot is needed then the context will reap the + /// memory. + pub fn insertHyperlink( + self: *Page, + link: hyperlink.Hyperlink, + ) InsertHyperlinkError!hyperlink.Id { + // Insert our URI into the page strings table. + const page_uri: Offset(u8).Slice = uri: { + const buf = self.string_alloc.alloc( + u8, + self.memory, + link.uri.len, + ) catch |err| switch (err) { + error.OutOfMemory => return error.StringsOutOfMemory, + }; + errdefer self.string_alloc.free(self.memory, buf); + @memcpy(buf, link.uri); + + break :uri .{ + .offset = size.getOffset(u8, self.memory, &buf[0]), + .len = link.uri.len, + }; + }; + errdefer self.string_alloc.free( + self.memory, + page_uri.slice(self.memory), + ); + + // Allocate an ID for our page memory if we have to. + const page_id: hyperlink.PageEntry.Id = switch (link.id) { + .explicit => |id| explicit: { + const buf = self.string_alloc.alloc( + u8, + self.memory, + id.len, + ) catch |err| switch (err) { + error.OutOfMemory => return error.StringsOutOfMemory, + }; + errdefer self.string_alloc.free(self.memory, buf); + @memcpy(buf, id); + + break :explicit .{ + .explicit = .{ + .offset = size.getOffset(u8, self.memory, &buf[0]), + .len = id.len, + }, + }; + }, + + .implicit => |id| .{ .implicit = id }, + }; + errdefer switch (page_id) { + .implicit => {}, + .explicit => |slice| self.string_alloc.free( + self.memory, + slice.slice(self.memory), + ), + }; + + // Build our entry + const entry: hyperlink.PageEntry = .{ + .id = page_id, + .uri = page_uri, + }; + + // Put our hyperlink into the hyperlink set to get an ID + const id = self.hyperlink_set.addContext( + self.memory, + entry, + .{ .page = self }, + ) catch |err| switch (err) { + error.OutOfMemory => return error.SetOutOfMemory, + error.NeedsRehash => return error.SetNeedsRehash, + }; + errdefer self.hyperlink_set.release(self.memory, id); + + return id; + } + + /// Set the hyperlink for the given cell. If the cell already has a + /// hyperlink, then this will handle memory management and refcount + /// update for the prior hyperlink. + /// + /// DOES NOT increment the reference count for the new hyperlink! + /// + /// Caller is responsible for updating the refcount in the hyperlink + /// set as necessary by calling `use` if the id was not acquired with + /// `add`. + pub inline fn setHyperlink(self: *Page, row: *Row, cell: *Cell, id: hyperlink.Id) error{HyperlinkMapOutOfMemory}!void { + defer self.assertIntegrity(); + + const cell_offset = getOffset(Cell, self.memory, cell); + var map = self.hyperlink_map.map(self.memory); + const gop = map.getOrPut(cell_offset) catch |e| { + comptime assert(@TypeOf(e) == error{OutOfMemory}); + // The hyperlink map capacity needs to be increased. + return error.HyperlinkMapOutOfMemory; + }; + + if (gop.found_existing) { + // Always release the old hyperlink, because even if it's actually + // the same as the one we're setting, we'd end up double-counting + // if we left the reference count be, because the caller does not + // know whether it's the same and will have increased the count + // outside of this function. + self.hyperlink_set.release(self.memory, gop.value_ptr.*); + + // If the hyperlink matches then we don't need to do anything. + if (gop.value_ptr.* == id) { + // It is possible for cell hyperlink to be false but row + // must never be false. The cell hyperlink can be false because + // in Terminal.print we clear the hyperlink for the cursor cell + // before writing the cell again, so if someone prints over + // a cell with a matching hyperlink this state can happen. + // This is tested in Terminal.zig. + assert(row.hyperlink); + cell.hyperlink = true; + return; + } + } + + // Set the hyperlink on the cell and in the map. + gop.value_ptr.* = id; + cell.hyperlink = true; + row.hyperlink = true; + } + + /// Move the hyperlink from one cell to another. This can't fail + /// because we avoid any allocations since we're just moving data. + /// Destination must NOT have a hyperlink. + inline fn moveHyperlink(self: *Page, src: *Cell, dst: *Cell) void { + assert(src.hyperlink); + assert(!dst.hyperlink); + + const src_offset = getOffset(Cell, self.memory, src); + const dst_offset = getOffset(Cell, self.memory, dst); + var map = self.hyperlink_map.map(self.memory); + const entry = map.getEntry(src_offset).?; + const value = entry.value_ptr.*; + map.removeByPtr(entry.key_ptr); + map.putAssumeCapacity(dst_offset, value); + + // NOTE: We must not set src/dst.hyperlink here because this + // function is used in various cases where we swap cell contents + // and its unsafe. The flip side: the caller must be careful + // to set the proper cell state to represent the move. + } + + /// Returns the number of hyperlinks in the page. This isn't the byte + /// size but the total number of unique cells that have hyperlink data. + pub inline fn hyperlinkCount(self: *const Page) usize { + return self.hyperlink_map.map(self.memory).count(); + } + + /// Returns the hyperlink capacity for the page. This isn't the byte + /// size but the number of unique cells that can have hyperlink data. + pub inline fn hyperlinkCapacity(self: *const Page) usize { + return self.hyperlink_map.map(self.memory).capacity(); + } + + /// Set the graphemes for the given cell. This asserts that the cell + /// has no graphemes set, and only contains a single codepoint. + pub inline fn setGraphemes( + self: *Page, + row: *Row, + cell: *Cell, + cps: []const u21, + ) GraphemeError!void { + defer self.assertIntegrity(); + + assert(cell.codepoint() > 0); + assert(cell.content_tag == .codepoint); + + const cell_offset = getOffset(Cell, self.memory, cell); + var map = self.grapheme_map.map(self.memory); + + const slice = self.grapheme_alloc.alloc(u21, self.memory, cps.len) catch |e| { + comptime assert(@TypeOf(e) == error{OutOfMemory}); + // The grapheme alloc capacity needs to be increased. + return error.GraphemeAllocOutOfMemory; + }; + errdefer self.grapheme_alloc.free(self.memory, slice); + @memcpy(slice, cps); + + map.putNoClobber(cell_offset, .{ + .offset = getOffset(u21, self.memory, @ptrCast(slice.ptr)), + .len = slice.len, + }) catch |e| { + comptime assert(@TypeOf(e) == error{OutOfMemory}); + // The grapheme map capacity needs to be increased. + return error.GraphemeMapOutOfMemory; + }; + errdefer map.remove(cell_offset); + + cell.content_tag = .codepoint_grapheme; + row.grapheme = true; + + return; + } + + /// Append a codepoint to the given cell as a grapheme. + pub fn appendGrapheme(self: *Page, row: *Row, cell: *Cell, cp: u21) Allocator.Error!void { + defer self.assertIntegrity(); + + if (build_options.slow_runtime_safety) assert(cell.codepoint() != 0); + + const cell_offset = getOffset(Cell, self.memory, cell); + var map = self.grapheme_map.map(self.memory); + + // If this cell has no graphemes, we can go faster by knowing we + // need to allocate a new grapheme slice and update the map. + if (cell.content_tag != .codepoint_grapheme) { + const cps = try self.grapheme_alloc.alloc(u21, self.memory, 1); + errdefer self.grapheme_alloc.free(self.memory, cps); + cps[0] = cp; + + try map.putNoClobber(cell_offset, .{ + .offset = getOffset(u21, self.memory, @ptrCast(cps.ptr)), + .len = 1, + }); + errdefer map.remove(cell_offset); + + cell.content_tag = .codepoint_grapheme; + row.grapheme = true; + + return; + } + + // The cell already has graphemes. We need to append to the existing + // grapheme slice and update the map. + assert(row.grapheme); + + const slice = map.getPtr(cell_offset).?; + + // If our slice len doesn't divide evenly by the grapheme chunk + // length then we can utilize the additional chunk space. + if (slice.len % grapheme_chunk_len != 0) { + const cps = slice.offset.ptr(self.memory); + cps[slice.len] = cp; + slice.len += 1; + return; + } + + // We are out of chunk space. There is no fast path here. We need + // to allocate a larger chunk. This is a very slow path. We expect + // most graphemes to fit within our chunk size. + const cps = try self.grapheme_alloc.alloc(u21, self.memory, slice.len + 1); + errdefer self.grapheme_alloc.free(self.memory, cps); + const old_cps = slice.slice(self.memory); + fastmem.copy(u21, cps[0..old_cps.len], old_cps); + cps[slice.len] = cp; + slice.* = .{ + .offset = getOffset(u21, self.memory, @ptrCast(cps.ptr)), + .len = slice.len + 1, + }; + + // Free our old chunk + self.grapheme_alloc.free(self.memory, old_cps); + } + + /// Returns the codepoints for the given cell. These are the codepoints + /// in addition to the first codepoint. The first codepoint is NOT + /// included since it is on the cell itself. + pub inline fn lookupGrapheme(self: *const Page, cell: *const Cell) ?[]u21 { + const cell_offset = getOffset(Cell, self.memory, cell); + const map = self.grapheme_map.map(self.memory); + const slice = map.get(cell_offset) orelse return null; + return slice.slice(self.memory); + } + + /// Move the graphemes from one cell to another. This can't fail + /// because we avoid any allocations since we're just moving data. + /// + /// WARNING: This will NOT change the content_tag on the cells because + /// there are scenarios where we want to move graphemes without changing + /// the content tag. Callers beware but assertIntegrity should catch this. + pub inline fn moveGrapheme(self: *Page, src: *Cell, dst: *Cell) void { + if (build_options.slow_runtime_safety) { + assert(src.hasGrapheme()); + assert(!dst.hasGrapheme()); + } + + const src_offset = getOffset(Cell, self.memory, src); + const dst_offset = getOffset(Cell, self.memory, dst); + var map = self.grapheme_map.map(self.memory); + const entry = map.getEntry(src_offset).?; + const value = entry.value_ptr.*; + map.removeByPtr(entry.key_ptr); + map.putAssumeCapacity(dst_offset, value); + } + + /// Clear the graphemes for a given cell. + /// + /// In order to update the grapheme flag on the row, call + /// `updateRowGraphemeFlag` after you finish clearing any + /// graphemes in the row. + pub fn clearGrapheme(self: *Page, cell: *Cell) void { + defer self.assertIntegrity(); + if (build_options.slow_runtime_safety) assert(cell.hasGrapheme()); + + // Get our entry in the map, which must exist + const cell_offset = getOffset(Cell, self.memory, cell); + var map = self.grapheme_map.map(self.memory); + const entry = map.getEntry(cell_offset).?; + + // Free our grapheme data + const cps = entry.value_ptr.slice(self.memory); + self.grapheme_alloc.free(self.memory, cps); + + // Remove the entry + map.removeByPtr(entry.key_ptr); + + // Mark that we no longer have graphemes by changing the content tag. + cell.content_tag = .codepoint; + } + + /// Checks if the row contains any graphemes and sets + /// the grapheme flag to false if none are found. + /// + /// Call after removing graphemes in a row. + pub inline fn updateRowGraphemeFlag(self: *Page, row: *Row) void { + const cells = row.cells.ptr(self.memory)[0..self.size.cols]; + for (cells) |c| if (c.hasGrapheme()) return; + row.grapheme = false; + } + + /// Returns the number of graphemes in the page. This isn't the byte + /// size but the total number of unique cells that have grapheme data. + pub inline fn graphemeCount(self: *const Page) usize { + return self.grapheme_map.map(self.memory).count(); + } + + /// Returns the grapheme capacity for the page. This isn't the byte + /// size but the number of unique cells that can have grapheme data. + pub inline fn graphemeCapacity(self: *const Page) usize { + return self.grapheme_map.map(self.memory).capacity(); + } + + /// Checks if the row contains any styles and sets + /// the styled flag to false if none are found. + /// + /// Call after removing styles in a row. + pub inline fn updateRowStyledFlag(self: *Page, row: *Row) void { + const cells = row.cells.ptr(self.memory)[0..self.size.cols]; + for (cells) |c| if (c.hasStyling()) return; + row.styled = false; + } + + /// Returns true if this page is dirty at all. + pub inline fn isDirty(self: *const Page) bool { + if (self.dirty) return true; + for (self.rows.ptr(self.memory)[0..self.size.rows]) |row| { + if (row.dirty) return true; + } + return false; + } + + pub const Layout = struct { + total_size: usize, + rows_start: usize, + rows_size: usize, + cells_start: usize, + cells_size: usize, + styles_start: usize, + styles_layout: StyleSet.Layout, + grapheme_alloc_start: usize, + grapheme_alloc_layout: GraphemeAlloc.Layout, + grapheme_map_start: usize, + grapheme_map_layout: GraphemeMap.Layout, + string_alloc_start: usize, + string_alloc_layout: StringAlloc.Layout, + hyperlink_map_start: usize, + hyperlink_map_layout: hyperlink.Map.Layout, + hyperlink_set_start: usize, + hyperlink_set_layout: hyperlink.Set.Layout, + capacity: Capacity, + }; + + /// The memory layout for a page given a desired minimum cols + /// and rows size. + pub inline fn layout(cap: Capacity) Layout { + const rows_count: usize = @intCast(cap.rows); + const rows_start = 0; + const rows_end: usize = rows_start + (rows_count * @sizeOf(Row)); + + const cells_count: usize = @as(usize, cap.cols) * @as(usize, cap.rows); + const cells_start = alignForward(usize, rows_end, @alignOf(Cell)); + const cells_end = cells_start + (cells_count * @sizeOf(Cell)); + + const styles_layout: StyleSet.Layout = .init(cap.styles); + const styles_start = alignForward(usize, cells_end, StyleSet.base_align.toByteUnits()); + const styles_end = styles_start + styles_layout.total_size; + + const grapheme_alloc_layout = GraphemeAlloc.layout(cap.grapheme_bytes); + const grapheme_alloc_start = alignForward(usize, styles_end, GraphemeAlloc.base_align.toByteUnits()); + const grapheme_alloc_end = grapheme_alloc_start + grapheme_alloc_layout.total_size; + + const grapheme_count: usize = count: { + if (cap.grapheme_bytes == 0) break :count 0; + // Use divCeil to match GraphemeAlloc.layout() which uses alignForward, + // ensuring grapheme_map has capacity when grapheme_alloc has chunks. + const base = std.math.divCeil(usize, cap.grapheme_bytes, grapheme_chunk) catch unreachable; + break :count std.math.ceilPowerOfTwo(usize, base) catch unreachable; + }; + const grapheme_map_layout = GraphemeMap.layout(@intCast(grapheme_count)); + const grapheme_map_start = alignForward(usize, grapheme_alloc_end, GraphemeMap.base_align.toByteUnits()); + const grapheme_map_end = grapheme_map_start + grapheme_map_layout.total_size; + + const string_layout = StringAlloc.layout(cap.string_bytes); + const string_start = alignForward(usize, grapheme_map_end, StringAlloc.base_align.toByteUnits()); + const string_end = string_start + string_layout.total_size; + + const hyperlink_count = @divFloor(cap.hyperlink_bytes, @sizeOf(hyperlink.Set.Item)); + const hyperlink_set_layout: hyperlink.Set.Layout = .init(@intCast(hyperlink_count)); + const hyperlink_set_start = alignForward(usize, string_end, hyperlink.Set.base_align.toByteUnits()); + const hyperlink_set_end = hyperlink_set_start + hyperlink_set_layout.total_size; + + const hyperlink_map_count: u32 = count: { + if (hyperlink_count == 0) break :count 0; + const mult = std.math.cast( + u32, + hyperlink_count * hyperlink_cell_multiplier, + ) orelse break :count std.math.maxInt(u32); + break :count std.math.ceilPowerOfTwoAssert(u32, mult); + }; + const hyperlink_map_layout = hyperlink.Map.layout(hyperlink_map_count); + const hyperlink_map_start = alignForward(usize, hyperlink_set_end, hyperlink.Map.base_align.toByteUnits()); + const hyperlink_map_end = hyperlink_map_start + hyperlink_map_layout.total_size; + + const total_size = alignForward(usize, hyperlink_map_end, std.heap.page_size_min); + + return .{ + .total_size = total_size, + .rows_start = rows_start, + .rows_size = rows_end - rows_start, + .cells_start = cells_start, + .cells_size = cells_end - cells_start, + .styles_start = styles_start, + .styles_layout = styles_layout, + .grapheme_alloc_start = grapheme_alloc_start, + .grapheme_alloc_layout = grapheme_alloc_layout, + .grapheme_map_start = grapheme_map_start, + .grapheme_map_layout = grapheme_map_layout, + .string_alloc_start = string_start, + .string_alloc_layout = string_layout, + .hyperlink_map_start = hyperlink_map_start, + .hyperlink_map_layout = hyperlink_map_layout, + .hyperlink_set_start = hyperlink_set_start, + .hyperlink_set_layout = hyperlink_set_layout, + .capacity = cap, + }; + } +}; + +/// The standard capacity for a page that doesn't have special +/// requirements. This is enough to support a very large number of cells. +/// The standard capacity is chosen as the fast-path for allocation since +/// pages of standard capacity use a pooled allocator instead of single-use +/// mmaps. +pub const std_capacity: Capacity = .{ + .cols = 215, + .rows = 215, + .styles = 128, + .grapheme_bytes = if (builtin.is_test) 512 else 8192, +}; + +/// The size of this page. +pub const Size = struct { + cols: size.CellCountInt, + rows: size.CellCountInt, +}; + +/// Capacity of this page. +/// +/// This capacity can be maxed out (every field max) and still fit +/// within a 64-bit memory space. If you need more than this, you will +/// need to split data across separate pages. +/// +/// For 32-bit systems, it is possible to overflow the addressable +/// space and this is something we still need to address in the future +/// likely by limiting the maximum capacity on 32-bit systems further. +pub const Capacity = struct { + /// Number of columns and rows we can know about. + cols: size.CellCountInt, + rows: size.CellCountInt, + + /// Number of unique styles that can be used on this page. + styles: size.StyleCountInt = 16, + + /// Number of bytes to allocate for hyperlink data. Note that the + /// amount of data used for hyperlinks in total is more than this because + /// hyperlinks use string data as well as a small amount of lookup metadata. + /// This number is a rough approximation. + hyperlink_bytes: size.HyperlinkCountInt = hyperlink_bytes_default, + + /// Number of bytes to allocate for grapheme data. + grapheme_bytes: size.GraphemeBytesInt = grapheme_bytes_default, + + /// Number of bytes to allocate for strings. + string_bytes: size.StringBytesInt = string_bytes_default, + + pub const Adjustment = struct { + cols: ?size.CellCountInt = null, + }; + + /// Returns the maximum number of columns that can be used with this + /// capacity while still fitting at least one row. Returns null if even + /// a single column cannot fit (which would indicate an unusable capacity). + /// + /// Note that this is the maximum number of columns that never increases + /// the amount of memory the original capacity will take. If you modify + /// the original capacity to add rows, then you can fit more columns. + pub fn maxCols(self: Capacity) ?size.CellCountInt { + const available_bits = self.availableBitsForGrid(); + + // If we can't even fit the row metadata, return null + if (available_bits <= @bitSizeOf(Row)) return null; + + // We do the math of how many columns we can fit in the remaining + // bits ignoring the metadata of a row. + const remaining_bits = available_bits - @bitSizeOf(Row); + const max_cols = remaining_bits / @bitSizeOf(Cell); + + // Clamp to CellCountInt max + return @min(std.math.maxInt(size.CellCountInt), max_cols); + } + + /// Adjust the capacity parameters while retaining the same total size. + /// + /// Adjustments always happen by limiting the rows in the page. Everything + /// else can grow. If it is impossible to achieve the desired adjustment, + /// OutOfMemory is returned. + pub fn adjust(self: Capacity, req: Adjustment) Allocator.Error!Capacity { + var adjusted = self; + if (req.cols) |cols| { + const available_bits = self.availableBitsForGrid(); + + // The size per row is: + // - The row metadata itself + // - The cells per row (n=cols) + const bits_per_row: usize = @bitSizeOf(Row) + @bitSizeOf(Cell) * @as(usize, @intCast(cols)); + const new_rows: usize = @divFloor(available_bits, bits_per_row); + + // If our rows go to zero then we can't fit any row metadata + // for the desired number of columns. + if (new_rows == 0) return error.OutOfMemory; + + adjusted.cols = cols; + adjusted.rows = @intCast(new_rows); + } + + return adjusted; + } + + /// Computes the number of bits available for rows and cells in the page. + /// + /// This is done by laying out the "meta" members (styles, graphemes, + /// hyperlinks, strings) from the end of the page and finding where they + /// start, which gives us the space available for rows and cells. + fn availableBitsForGrid(self: Capacity) usize { + // The math below only works if there is no alignment gap between + // the end of the rows array and the start of the cells array. + // + // To guarantee this, we assert that Row's size is a multiple of + // Cell's alignment, so that any length array of Rows will end on + // a valid alignment for the start of the Cell array. + assert(@sizeOf(Row) % @alignOf(Cell) == 0); + + const l = Page.layout(self); + + // Layout meta members from the end to find styles_start + const hyperlink_map_start = alignBackward(usize, l.total_size - l.hyperlink_map_layout.total_size, hyperlink.Map.base_align.toByteUnits()); + const hyperlink_set_start = alignBackward(usize, hyperlink_map_start - l.hyperlink_set_layout.total_size, hyperlink.Set.base_align.toByteUnits()); + const string_alloc_start = alignBackward(usize, hyperlink_set_start - l.string_alloc_layout.total_size, StringAlloc.base_align.toByteUnits()); + const grapheme_map_start = alignBackward(usize, string_alloc_start - l.grapheme_map_layout.total_size, GraphemeMap.base_align.toByteUnits()); + const grapheme_alloc_start = alignBackward(usize, grapheme_map_start - l.grapheme_alloc_layout.total_size, GraphemeAlloc.base_align.toByteUnits()); + const styles_start = alignBackward(usize, grapheme_alloc_start - l.styles_layout.total_size, StyleSet.base_align.toByteUnits()); + + // Multiply by 8 to convert bytes to bits + return styles_start * 8; + } +}; + +pub const Row = packed struct(u64) { + /// The cells in the row offset from the page. + cells: Offset(Cell), + + /// True if this row is soft-wrapped. The first cell of the next + /// row is a continuation of this row. + wrap: bool = false, + + /// True if the previous row to this one is soft-wrapped and + /// this row is a continuation of that row. + wrap_continuation: bool = false, + + /// True if any of the cells in this row have multi-codepoint + /// grapheme clusters. If this is true, some fast paths are not + /// possible because erasing for example may need to clear existing + /// grapheme data. + grapheme: bool = false, + + /// True if any of the cells in this row have a ref-counted style. + /// This can have false positives but never a false negative. Meaning: + /// this will be set to true the first time a style is used, but it + /// will not be set to false if the style is no longer used, because + /// checking for that condition is too expensive. + /// + /// Why have this weird false positive flag at all? This makes VT operations + /// that erase cells (such as insert lines, delete lines, erase chars, + /// etc.) MUCH MUCH faster in the case that the row was never styled. + /// At the time of writing this, the speed difference is around 4x. + styled: bool = false, + + /// True if any of the cells in this row are part of a hyperlink. + /// This is similar to styled: it can have false positives but never + /// false negatives. This is used to optimize hyperlink operations. + hyperlink: bool = false, + + /// The semantic prompt state for this row. + /// + /// This is ONLY meant to note if there are ANY cells in this + /// row that are part of a prompt. This is an optimization for more + /// efficiently implementing jump-to-prompt operations. + /// + /// This may contain false positives but never false negatives. If + /// this is set, you should still check individual cells to see if they + /// have prompt semantics. + semantic_prompt: SemanticPrompt = .none, + + /// True if this row contains a virtual placeholder for the Kitty + /// graphics protocol. (U+10EEEE) + // Note: We keep this as memory-using even if the kitty graphics + // feature is disabled because we want to keep our padding and + // everything throughout the same. + kitty_virtual_placeholder: bool = false, + + /// True if this row is dirty and requires a redraw. This is set to true + /// by any operation that modifies the row's contents or position, and + /// consumers of the page are expected to clear it when they redraw. + /// + /// Dirty status is only ever meant to convey that one or more cells in + /// the row have changed visually. A cell which changes in a way that + /// doesn't affect the visual representation may not be marked as dirty. + /// + /// Dirty tracking may have false positives but should never have false + /// negatives. A false negative would result in a visual artifact on the + /// screen. + dirty: bool = false, + + _padding: u23 = 0, + + /// The semantic prompt state of the row. See `semantic_prompt`. + pub const SemanticPrompt = enum(u2) { + /// No prompt cells in this row. + none = 0, + /// Prompt cells exist in this row and this is a primary prompt + /// line. A primary prompt line is one that is not a continuation + /// and is the beginning of a prompt. + prompt = 1, + /// Prompt cells exist in this row that had k=c set (continuation) + /// line. This is used as a way to detect when a line should + /// be considered part of some prior prompt. If no prior prompt + /// is found, the last (most historical) prompt continuation line is + /// considered the prompt. + prompt_continuation = 2, + }; + + /// C ABI type. + pub const C = u64; + + /// Returns this row as a C ABI value. + pub fn cval(self: Row) C { + return @bitCast(self); + } + + /// Returns true if this row has any managed memory outside of the + /// row structure (graphemes, styles, etc.) + pub inline fn managedMemory(self: Row) bool { + // Ordered on purpose for likelihood. + return self.styled or self.hyperlink or self.grapheme; + } +}; + +/// A cell represents a single terminal grid cell. +/// +/// The zero value of this struct must be a valid cell representing empty, +/// since we zero initialize the backing memory for a page. +pub const Cell = packed struct(u64) { + /// The content tag dictates the active tag in content and possibly + /// some other behaviors. + content_tag: ContentTag = .codepoint, + + /// The content of the cell. This is a union based on content_tag. + content: packed union { + /// The codepoint that this cell contains. If `grapheme` is false, + /// then this is the only codepoint in the cell. If `grapheme` is + /// true, then this is the first codepoint in the grapheme cluster. + codepoint: u21, + + /// The content is an empty cell with a background color. + color_palette: u8, + color_rgb: RGB, + } = .{ .codepoint = 0 }, + + /// The style ID to use for this cell within the style map. Zero + /// is always the default style so no lookup is required. + style_id: StyleId = 0, + + /// The wide property of this cell, for wide characters. Characters in + /// a terminal grid can only be 1 or 2 cells wide. A wide character + /// is always next to a spacer. This is used to determine both the width + /// and spacer properties of a cell. + wide: Wide = .narrow, + + /// Whether this was written with the protection flag set. + protected: bool = false, + + /// Whether this cell is a hyperlink. If this is true then you must + /// look up the hyperlink ID in the page hyperlink_map and the ID in + /// the hyperlink_set to get the actual hyperlink data. + hyperlink: bool = false, + + /// The semantic type of the content of this cell. This is used + /// by the semantic prompt (OSC 133) set of sequences to understand + /// boundary points for content. + semantic_content: SemanticContent = .output, + + _padding: u16 = 0, + + pub const ContentTag = enum(u2) { + /// A single codepoint, could be zero to be empty cell. + codepoint = 0, + + /// A codepoint that is part of a multi-codepoint grapheme cluster. + /// The codepoint tag is active in content, but also expect more + /// codepoints in the grapheme data. + codepoint_grapheme = 1, + + /// The cell has no text but only a background color. This is an + /// optimization so that cells with only backgrounds don't take up + /// style map space and also don't require a style map lookup. + bg_color_palette = 2, + bg_color_rgb = 3, + }; + + pub const RGB = packed struct { + r: u8, + g: u8, + b: u8, + }; + + pub const Wide = enum(u2) { + /// Not a wide character, cell width 1. + narrow = 0, + + /// Wide character, cell width 2. + wide = 1, + + /// Spacer after wide character. Do not render. + spacer_tail = 2, + + /// Spacer at the end of a soft-wrapped line to indicate that a wide + /// character is continued on the next line. + spacer_head = 3, + }; + + pub const SemanticContent = enum(u2) { + /// Regular output content, such as command output. + output = 0, + + /// Content that is part of user input, such as the command + /// to execute at a prompt. + input = 1, + + /// Content that is part of prompt emitted by the interactive + /// application, such as "user@host >" + prompt = 2, + }; + + /// C ABI type. + pub const C = u64; + + /// Returns this cell as a C ABI value. + pub fn cval(self: Cell) C { + return @bitCast(self); + } + + /// Helper to make a cell that just has a codepoint. + pub fn init(cp: u21) Cell { + // We have to use this bitCast here to ensure that our memory is + // zeroed. Otherwise, the content below will leave some uninitialized + // memory in the packed union. Valgrind verifies this. + var cell: Cell = @bitCast(@as(u64, 0)); + cell.content_tag = .codepoint; + cell.content = .{ .codepoint = cp }; + return cell; + } + + pub inline fn isZero(self: Cell) bool { + return @as(u64, @bitCast(self)) == 0; + } + + /// Returns true if this cell represents a cell with text to render. + /// + /// Cases this returns false: + /// - Cell text is blank + /// - Cell is styled but only with a background color and no text + /// - Cell has a unicode placeholder for Kitty graphics protocol + pub inline fn hasText(self: Cell) bool { + return switch (self.content_tag) { + .codepoint, + .codepoint_grapheme, + => self.content.codepoint != 0, + + .bg_color_palette, + .bg_color_rgb, + => false, + }; + } + + pub inline fn codepoint(self: Cell) u21 { + return switch (self.content_tag) { + .codepoint, + .codepoint_grapheme, + => self.content.codepoint, + + .bg_color_palette, + .bg_color_rgb, + => 0, + }; + } + + /// The width in grid cells that this cell takes up. + pub inline fn gridWidth(self: Cell) u2 { + return switch (self.wide) { + .narrow, .spacer_head, .spacer_tail => 1, + .wide => 2, + }; + } + + pub inline fn hasStyling(self: Cell) bool { + return self.style_id != stylepkg.default_id; + } + + /// Returns true if the cell has no text or styling. + pub fn isEmpty(self: Cell) bool { + return switch (self.content_tag) { + // Textual cells are empty if they have no text and are narrow. + // The "narrow" requirement is because wide spacers are meaningful. + .codepoint, + .codepoint_grapheme, + => !self.hasText() and self.wide == .narrow, + + .bg_color_palette, + .bg_color_rgb, + => false, + }; + } + + pub inline fn hasGrapheme(self: Cell) bool { + return self.content_tag == .codepoint_grapheme; + } + + /// Returns true if the set of cells has text in it. + pub inline fn hasTextAny(cells: []const Cell) bool { + for (cells) |cell| { + if (cell.hasText()) return true; + } + + return false; + } +}; + +// Uncomment this when you want to do some math. +// test "Page size calculator" { +// const total_size = alignForward( +// usize, +// Page.layout(.{ +// .cols = 250, +// .rows = 250, +// .styles = 128, +// .grapheme_bytes = 1024, +// }).total_size, +// std.heap.page_size_min, +// ); +// +// std.log.warn("total_size={} pages={}", .{ +// total_size, +// total_size / std.heap.page_size_min, +// }); +// } +// +// test "Page std size" { +// // We want to ensure that the standard capacity is what we +// // expect it to be. Changing this is fine but should be done with care +// // so we fail a test if it changes. +// const total_size = Page.layout(std_capacity).total_size; +// try testing.expectEqual(@as(usize, 524_288), total_size); // 512 KiB +// //const pages = total_size / std.heap.page_size_min; +// } + +test "Page.layout can take a maxed capacity" { + // Our intention is for a maxed-out capacity to always fit + // within a page layout without triggering runtime safety on any + // overflow. This simplifies some of our handling downstream of the + // call (relevant to: https://github.com/ghostty-org/ghostty/issues/10258) + var cap: Capacity = undefined; + inline for (@typeInfo(Capacity).@"struct".fields) |field| { + @field(cap, field.name) = std.math.maxInt(field.type); + } + + // Note that a max capacity will exceed our max_page_size so we + // can't init a page with it, but it should layout. + _ = Page.layout(cap); +} + +test "Cell is zero by default" { + const cell = Cell.init(0); + const cell_int: u64 = @bitCast(cell); + try std.testing.expectEqual(@as(u64, 0), cell_int); + + // The zero value should be output type for semantic content. + // This is very important for our assumptions elsewhere. + try std.testing.expectEqual(Cell.SemanticContent.output, cell.semantic_content); +} + +test "Page capacity adjust cols down" { + const original = std_capacity; + const original_size = Page.layout(original).total_size; + const adjusted = try original.adjust(.{ .cols = original.cols / 2 }); + const adjusted_size = Page.layout(adjusted).total_size; + try testing.expectEqual(original_size, adjusted_size); + // If we layout a page with 1 more row and it's still the same size + // then adjust is not producing enough rows. + var bigger = adjusted; + bigger.rows += 1; + const bigger_size = Page.layout(bigger).total_size; + try testing.expect(bigger_size > original_size); +} + +test "Page capacity adjust cols down to 1" { + const original = std_capacity; + const original_size = Page.layout(original).total_size; + const adjusted = try original.adjust(.{ .cols = 1 }); + const adjusted_size = Page.layout(adjusted).total_size; + try testing.expectEqual(original_size, adjusted_size); + // If we layout a page with 1 more row and it's still the same size + // then adjust is not producing enough rows. + var bigger = adjusted; + bigger.rows += 1; + const bigger_size = Page.layout(bigger).total_size; + try testing.expect(bigger_size > original_size); +} + +test "Page capacity adjust cols up" { + const original = std_capacity; + const original_size = Page.layout(original).total_size; + const adjusted = try original.adjust(.{ .cols = original.cols * 2 }); + const adjusted_size = Page.layout(adjusted).total_size; + try testing.expectEqual(original_size, adjusted_size); + // If we layout a page with 1 more row and it's still the same size + // then adjust is not producing enough rows. + var bigger = adjusted; + bigger.rows += 1; + const bigger_size = Page.layout(bigger).total_size; + try testing.expect(bigger_size > original_size); +} + +test "Page capacity adjust cols sweep" { + var cap = std_capacity; + const original_cols = cap.cols; + const original_size = Page.layout(cap).total_size; + for (1..original_cols * 2) |c| { + cap = try cap.adjust(.{ .cols = @as(u16, @intCast(c)) }); + const adjusted_size = Page.layout(cap).total_size; + try testing.expectEqual(original_size, adjusted_size); + // If we layout a page with 1 more row and it's still the same size + // then adjust is not producing enough rows. + var bigger = cap; + bigger.rows += 1; + const bigger_size = Page.layout(bigger).total_size; + try testing.expect(bigger_size > original_size); + } +} + +test "Page capacity adjust cols too high" { + const original = std_capacity; + try testing.expectError( + error.OutOfMemory, + original.adjust(.{ .cols = std.math.maxInt(size.CellCountInt) }), + ); +} + +test "Capacity maxCols basic" { + const cap = std_capacity; + const max = cap.maxCols().?; + + // maxCols should be >= current cols (since current capacity is valid) + try testing.expect(max >= cap.cols); + + // Adjusting to maxCols should succeed with at least 1 row + const adjusted = try cap.adjust(.{ .cols = max }); + try testing.expect(adjusted.rows >= 1); + + // Adjusting to maxCols + 1 should fail + try testing.expectError( + error.OutOfMemory, + cap.adjust(.{ .cols = max + 1 }), + ); +} + +test "Capacity maxCols preserves total size" { + const cap = std_capacity; + const original_size = Page.layout(cap).total_size; + const max = cap.maxCols().?; + const adjusted = try cap.adjust(.{ .cols = max }); + const adjusted_size = Page.layout(adjusted).total_size; + try testing.expectEqual(original_size, adjusted_size); +} + +test "Capacity maxCols with 1 row exactly" { + const cap = std_capacity; + const max = cap.maxCols().?; + const adjusted = try cap.adjust(.{ .cols = max }); + try testing.expectEqual(@as(size.CellCountInt, 1), adjusted.rows); +} + +test "Page init" { + var page = try Page.init(.{ + .cols = 120, + .rows = 80, + .styles = 32, + }); + defer page.deinit(); +} + +test "Page read and write cells" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Read it again + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } +} + +test "Page appendGrapheme small" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .init(0x09); + + // One + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + try testing.expect(rac.row.grapheme); + try testing.expect(rac.cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0x0A}, page.lookupGrapheme(rac.cell).?); + + // Two + try page.appendGrapheme(rac.row, rac.cell, 0x0B); + try testing.expect(rac.row.grapheme); + try testing.expect(rac.cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{ 0x0A, 0x0B }, page.lookupGrapheme(rac.cell).?); + + // Clear it + page.clearGrapheme(rac.cell); + page.updateRowGraphemeFlag(rac.row); + try testing.expect(!rac.row.grapheme); + try testing.expect(!rac.cell.hasGrapheme()); +} + +test "Page appendGrapheme larger than chunk" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .init(0x09); + + const count = grapheme_chunk_len * 10; + for (0..count) |i| { + try page.appendGrapheme(rac.row, rac.cell, @intCast(0x0A + i)); + } + + const cps = page.lookupGrapheme(rac.cell).?; + try testing.expectEqual(@as(usize, count), cps.len); + for (0..count) |i| { + try testing.expectEqual(@as(u21, @intCast(0x0A + i)), cps[i]); + } +} + +test "Page clearGrapheme not all cells" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .init(0x09); + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + + const rac2 = page.getRowAndCell(1, 0); + rac2.cell.* = .init(0x09); + try page.appendGrapheme(rac2.row, rac2.cell, 0x0A); + + // Clear it + page.clearGrapheme(rac.cell); + page.updateRowGraphemeFlag(rac.row); + try testing.expect(rac.row.grapheme); + try testing.expect(!rac.cell.hasGrapheme()); + try testing.expect(rac2.cell.hasGrapheme()); +} + +test "Page clone" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Clone + var page2 = try page.clone(); + defer page2.deinit(); + try testing.expectEqual(page2.capacity, page.capacity); + + // Read it again + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } + + // Write again + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + }; + } + + // Read it again, should be unchanged + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } + + // Read the original + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + } +} + +test "Page clone graphemes" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Append some graphemes + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .init(0x09); + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + try page.appendGrapheme(rac.row, rac.cell, 0x0B); + } + + // Clone it + var page2 = try page.clone(); + defer page2.deinit(); + { + const rac = page2.getRowAndCell(0, 0); + try testing.expect(rac.row.grapheme); + try testing.expect(rac.cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{ 0x0A, 0x0B }, page2.lookupGrapheme(rac.cell).?); + } +} + +test "Page clone styles" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write with some styles + { + const id = try page.styles.add(page.memory, .{ .flags = .{ + .bold = true, + } }); + + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.row.styled = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + .style_id = id, + }; + page.styles.use(page.memory, id); + } + } + + // Clone it + var page2 = try page.clone(); + defer page2.deinit(); + { + const id: u16 = style: { + const rac = page2.getRowAndCell(0, 0); + break :style rac.cell.style_id; + }; + + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + try testing.expect(rac.row.styled); + try testing.expectEqual(id, rac.cell.style_id); + } + + const style = page.styles.get( + page.memory, + id, + ); + try testing.expect((Style{ .flags = .{ + .bold = true, + } }).eql(style.*)); + } +} + +test "Page cloneFrom" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + try page2.cloneFrom(&page, 0, page.size.rows); + + // Read it again + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } + + // Write again + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + }; + } + + // Read it again, should be unchanged + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } + + // Read the original + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + } +} + +test "Page cloneFrom shrink columns" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Clone + var page2 = try Page.init(.{ + .cols = 5, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + try page2.cloneFrom(&page, 0, page.size.rows); + try testing.expectEqual(@as(size.CellCountInt, 5), page2.size.cols); + + // Read it again + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } +} + +test "Page cloneFrom partial" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y) }, + }; + } + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + try page2.cloneFrom(&page, 0, 5); + + // Read it again + for (0..5) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y)), rac.cell.content.codepoint); + } + for (5..page2.size.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + } +} + +test "Page cloneFrom hyperlinks exact capacity" { + var page = try Page.init(.{ + .cols = 50, + .rows = 50, + }); + defer page.deinit(); + + // Ensure our page can accommodate the capacity. + const hyperlink_cap = page.hyperlinkCapacity(); + try testing.expect(hyperlink_cap <= page.size.cols * page.size.rows); + + // Create a hyperlink. + const hyperlink_id = try page.insertHyperlink(.{ + .id = .{ .implicit = 0 }, + .uri = "https://example.com", + }); + + // Fill the exact cap with cells. + fill: for (0..page.size.cols) |x| { + for (0..page.size.rows) |y| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 42 }, + }; + try page.setHyperlink(rac.row, rac.cell, hyperlink_id); + page.hyperlink_set.use(page.memory, hyperlink_id); + + if (page.hyperlinkCount() == hyperlink_cap) { + break :fill; + } + } + } + try testing.expectEqual(page.hyperlinkCount(), page.hyperlinkCapacity()); + + // Clone the full page + var page2 = try Page.init(page.capacity); + defer page2.deinit(); + try page2.cloneFrom(&page, 0, page.size.rows); + + // We should have the same number of hyperlinks + try testing.expectEqual(page2.hyperlinkCount(), page.hyperlinkCount()); +} + +test "Page cloneFrom graphemes" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y + 1) }, + }; + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + } + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + try page2.cloneFrom(&page, 0, page.size.rows); + + // Read it again + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y + 1)), rac.cell.content.codepoint); + try testing.expect(rac.row.grapheme); + try testing.expect(rac.cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0x0A}, page2.lookupGrapheme(rac.cell).?); + } + + // Write again + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + page.clearGrapheme(rac.cell); + page.updateRowGraphemeFlag(rac.row); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0 }, + }; + } + + // Read it again, should be unchanged + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y + 1)), rac.cell.content.codepoint); + try testing.expect(rac.row.grapheme); + try testing.expect(rac.cell.hasGrapheme()); + try testing.expectEqualSlices(u21, &.{0x0A}, page2.lookupGrapheme(rac.cell).?); + } + + // Read the original + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, 0), rac.cell.content.codepoint); + } +} + +test "Page cloneFrom frees dst graphemes" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + for (0..page.capacity.rows) |y| { + const rac = page.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y + 1) }, + }; + } + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(y + 1) }, + }; + try page2.appendGrapheme(rac.row, rac.cell, 0x0A); + } + + // Clone from page which has no graphemes. + try page2.cloneFrom(&page, 0, page.size.rows); + + // Read it again + for (0..page2.capacity.rows) |y| { + const rac = page2.getRowAndCell(1, y); + try testing.expectEqual(@as(u21, @intCast(y + 1)), rac.cell.content.codepoint); + try testing.expect(!rac.row.grapheme); + try testing.expect(!rac.cell.hasGrapheme()); + } + try testing.expectEqual(@as(usize, 0), page2.graphemeCount()); +} + +test "Page cloneRowFrom partial" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + { + const y = 0; + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + } + } + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + try page2.clonePartialRowFrom( + &page, + page2.getRow(0), + page.getRow(0), + 2, + 8, + ); + + // Read it again + { + const y = 0; + for (0..page2.size.cols) |x| { + const expected: u21 = if (x >= 2 and x < 8) @intCast(x + 1) else 0; + const rac = page2.getRowAndCell(x, y); + try testing.expectEqual(expected, rac.cell.content.codepoint); + } + } +} + +test "Page cloneRowFrom partial grapheme in non-copied source region" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + { + const y = 0; + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + } + { + const rac = page.getRowAndCell(0, y); + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + } + { + const rac = page.getRowAndCell(9, y); + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + } + } + try testing.expectEqual(@as(usize, 2), page.graphemeCount()); + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + try page2.clonePartialRowFrom( + &page, + page2.getRow(0), + page.getRow(0), + 2, + 8, + ); + + // Read it again + { + const y = 0; + for (0..page2.size.cols) |x| { + const expected: u21 = if (x >= 2 and x < 8) @intCast(x + 1) else 0; + const rac = page2.getRowAndCell(x, y); + try testing.expectEqual(expected, rac.cell.content.codepoint); + try testing.expect(!rac.cell.hasGrapheme()); + } + { + const rac = page2.getRowAndCell(9, y); + try testing.expect(!rac.row.grapheme); + } + } + try testing.expectEqual(@as(usize, 0), page2.graphemeCount()); +} + +test "Page cloneRowFrom partial grapheme in non-copied dest region" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + { + const y = 0; + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + } + } + try testing.expectEqual(@as(usize, 0), page.graphemeCount()); + + // Clone + var page2 = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page2.deinit(); + { + const y = 0; + for (0..page2.size.cols) |x| { + const rac = page2.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = 0xBB }, + }; + } + { + const rac = page2.getRowAndCell(0, y); + try page2.appendGrapheme(rac.row, rac.cell, 0x0A); + } + { + const rac = page2.getRowAndCell(9, y); + try page2.appendGrapheme(rac.row, rac.cell, 0x0A); + } + } + try page2.clonePartialRowFrom( + &page, + page2.getRow(0), + page.getRow(0), + 2, + 8, + ); + + // Read it again + { + const y = 0; + for (0..page2.size.cols) |x| { + const expected: u21 = if (x >= 2 and x < 8) @intCast(x + 1) else 0xBB; + const rac = page2.getRowAndCell(x, y); + try testing.expectEqual(expected, rac.cell.content.codepoint); + } + { + const rac = page2.getRowAndCell(9, y); + try testing.expect(rac.row.grapheme); + } + } + try testing.expectEqual(@as(usize, 2), page2.graphemeCount()); +} + +test "Page cloneRowFrom partial hyperlink in same page copy" { + var page = try Page.init(.{ .cols = 10, .rows = 10 }); + defer page.deinit(); + + // We need to create a hyperlink. + const hyperlink_id = try page.hyperlink_set.addContext( + page.memory, + .{ .id = .{ .implicit = 0 }, .uri = .{} }, + .{ .page = &page }, + ); + + // Write + { + const y = 0; + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + } + + // Hyperlink in a single cell + { + const rac = page.getRowAndCell(7, y); + try page.setHyperlink(rac.row, rac.cell, hyperlink_id); + } + } + try testing.expectEqual(@as(usize, 1), page.hyperlinkCount()); + + // Clone into the same page + try page.clonePartialRowFrom( + &page, + page.getRow(1), + page.getRow(0), + 2, + 8, + ); + + // Read it again + { + const y = 1; + for (0..page.size.cols) |x| { + const expected: u21 = if (x >= 2 and x < 8) @intCast(x + 1) else 0; + const rac = page.getRowAndCell(x, y); + try testing.expectEqual(expected, rac.cell.content.codepoint); + } + { + const rac = page.getRowAndCell(7, y); + try testing.expect(rac.row.hyperlink); + try testing.expect(rac.cell.hyperlink); + } + } + try testing.expectEqual(@as(usize, 2), page.hyperlinkCount()); +} + +test "Page cloneRowFrom partial hyperlink in same page omit" { + var page = try Page.init(.{ .cols = 10, .rows = 10 }); + defer page.deinit(); + + // We need to create a hyperlink. + const hyperlink_id = try page.hyperlink_set.addContext( + page.memory, + .{ .id = .{ .implicit = 0 }, .uri = .{} }, + .{ .page = &page }, + ); + + // Write + { + const y = 0; + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, y); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + } + + // Hyperlink in a single cell + { + const rac = page.getRowAndCell(7, y); + try page.setHyperlink(rac.row, rac.cell, hyperlink_id); + } + } + try testing.expectEqual(@as(usize, 1), page.hyperlinkCount()); + + // Clone into the same page + try page.clonePartialRowFrom( + &page, + page.getRow(1), + page.getRow(0), + 2, + 6, + ); + + // Read it again + { + const y = 1; + for (0..page.size.cols) |x| { + const expected: u21 = if (x >= 2 and x < 6) @intCast(x + 1) else 0; + const rac = page.getRowAndCell(x, y); + try testing.expectEqual(expected, rac.cell.content.codepoint); + } + { + const rac = page.getRowAndCell(7, y); + try testing.expect(!rac.row.hyperlink); + try testing.expect(!rac.cell.hyperlink); + } + } + try testing.expectEqual(@as(usize, 1), page.hyperlinkCount()); +} + +test "Page moveCells text-only" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.capacity.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + } + + const src = page.getRow(0); + const dst = page.getRow(1); + page.moveCells(src, 0, dst, 0, page.capacity.cols); + + // New rows should have text + for (0..page.capacity.cols) |x| { + const rac = page.getRowAndCell(x, 1); + try testing.expectEqual( + @as(u21, @intCast(x + 1)), + rac.cell.content.codepoint, + ); + } + + // Old row should be blank + for (0..page.capacity.cols) |x| { + const rac = page.getRowAndCell(x, 0); + try testing.expectEqual( + @as(u21, 0), + rac.cell.content.codepoint, + ); + } +} + +test "Page moveCells graphemes" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + } + const original_count = page.graphemeCount(); + + const src = page.getRow(0); + const dst = page.getRow(1); + page.moveCells(src, 0, dst, 0, page.size.cols); + try testing.expectEqual(original_count, page.graphemeCount()); + + // New rows should have text + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 1); + try testing.expectEqual( + @as(u21, @intCast(x + 1)), + rac.cell.content.codepoint, + ); + try testing.expectEqualSlices( + u21, + &.{0x0A}, + page.lookupGrapheme(rac.cell).?, + ); + } + + // Old row should be blank + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + try testing.expectEqual( + @as(u21, 0), + rac.cell.content.codepoint, + ); + } +} + +test "Page verifyIntegrity graphemes good" { + // Too slow, and not really necessary because the integrity tests are + // only run in debug builds and unit tests verify they work well enough. + if (std.valgrind.runningOnValgrind() > 0) return error.SkipZigTest; + + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + } + + try page.verifyIntegrity(testing.allocator); +} + +test "Page verifyIntegrity grapheme row not marked" { + // Too slow, and not really necessary because the integrity tests are + // only run in debug builds and unit tests verify they work well enough. + if (std.valgrind.runningOnValgrind() > 0) return error.SkipZigTest; + + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Write + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + }; + try page.appendGrapheme(rac.row, rac.cell, 0x0A); + } + + // Make invalid by unmarking the row + page.getRow(0).grapheme = false; + + try testing.expectError( + Page.IntegrityError.UnmarkedGraphemeRow, + page.verifyIntegrity(testing.allocator), + ); +} + +test "Page verifyIntegrity styles good" { + // Too slow, and not really necessary because the integrity tests are + // only run in debug builds and unit tests verify they work well enough. + if (std.valgrind.runningOnValgrind() > 0) return error.SkipZigTest; + + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Upsert a style we'll use + const id = try page.styles.add(page.memory, .{ .flags = .{ + .bold = true, + } }); + + // Write + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.row.styled = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + .style_id = id, + }; + page.styles.use(page.memory, id); + } + + // The original style add would have incremented the + // ref count too, so release it to balance that out. + page.styles.release(page.memory, id); + + try page.verifyIntegrity(testing.allocator); +} + +test "Page verifyIntegrity styles ref count mismatch" { + // Too slow, and not really necessary because the integrity tests are + // only run in debug builds and unit tests verify they work well enough. + if (std.valgrind.runningOnValgrind() > 0) return error.SkipZigTest; + + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Upsert a style we'll use + const id = try page.styles.add(page.memory, .{ .flags = .{ + .bold = true, + } }); + + // Write + for (0..page.size.cols) |x| { + const rac = page.getRowAndCell(x, 0); + rac.row.styled = true; + rac.cell.* = .{ + .content_tag = .codepoint, + .content = .{ .codepoint = @intCast(x + 1) }, + .style_id = id, + }; + page.styles.use(page.memory, id); + } + + // The original style add would have incremented the + // ref count too, so release it to balance that out. + page.styles.release(page.memory, id); + + // Miss a ref + page.styles.release(page.memory, id); + + try testing.expectError( + Page.IntegrityError.MismatchedStyleRef, + page.verifyIntegrity(testing.allocator), + ); +} + +test "Page verifyIntegrity zero rows" { + // Too slow, and not really necessary because the integrity tests are + // only run in debug builds and unit tests verify they work well enough. + if (std.valgrind.runningOnValgrind() > 0) return error.SkipZigTest; + + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + page.size.rows = 0; + try testing.expectError( + Page.IntegrityError.ZeroRowCount, + page.verifyIntegrity(testing.allocator), + ); +} + +test "Page verifyIntegrity zero cols" { + // Too slow, and not really necessary because the integrity tests are + // only run in debug builds and unit tests verify they work well enough. + if (std.valgrind.runningOnValgrind() > 0) return error.SkipZigTest; + + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + page.size.cols = 0; + try testing.expectError( + Page.IntegrityError.ZeroColCount, + page.verifyIntegrity(testing.allocator), + ); +} + +test "Page exactRowCapacity empty rows" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + .hyperlink_bytes = 32 * @sizeOf(hyperlink.Set.Item), + .string_bytes = 512, + }); + defer page.deinit(); + + // Empty page: all capacity fields should be 0 (except cols/rows) + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(10, cap.cols); + try testing.expectEqual(5, cap.rows); + try testing.expectEqual(0, cap.styles); + try testing.expectEqual(0, cap.grapheme_bytes); + try testing.expectEqual(0, cap.hyperlink_bytes); + try testing.expectEqual(0, cap.string_bytes); +} + +test "Page exactRowCapacity styles" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // No styles: capacity should be 0 + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(0, cap.styles); + } + + // Add one style to a cell + const style1_id = try page.styles.add(page.memory, .{ .flags = .{ .bold = true } }); + { + const rac = page.getRowAndCell(0, 0); + rac.row.styled = true; + rac.cell.style_id = style1_id; + } + + // One unique style - capacity accounts for load factor + const cap_one_style = page.exactRowCapacity(0, 5); + { + try testing.expectEqual(StyleSet.capacityForCount(1), cap_one_style.styles); + } + + // Add same style to another cell (duplicate) - capacity unchanged + { + const rac = page.getRowAndCell(1, 0); + rac.cell.style_id = style1_id; + } + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(cap_one_style.styles, cap.styles); + } + + // Add a different style + const style2_id = try page.styles.add(page.memory, .{ .flags = .{ .italic = true } }); + { + const rac = page.getRowAndCell(2, 0); + rac.cell.style_id = style2_id; + } + + // Two unique styles - capacity accounts for load factor + const cap_two_styles = page.exactRowCapacity(0, 5); + { + try testing.expectEqual(StyleSet.capacityForCount(2), cap_two_styles.styles); + try testing.expect(cap_two_styles.styles > cap_one_style.styles); + } + + // Style outside the row range should not be counted + { + const rac = page.getRowAndCell(0, 7); + rac.row.styled = true; + rac.cell.style_id = try page.styles.add(page.memory, .{ .flags = .{ .underline = .single } }); + } + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(cap_two_styles.styles, cap.styles); + } + + // Full range includes the new style + { + const cap = page.exactRowCapacity(0, 10); + try testing.expectEqual(StyleSet.capacityForCount(3), cap.styles); + } + + // Verify clone works with exact capacity and produces same result + { + const cap = page.exactRowCapacity(0, 5); + var cloned = try Page.init(cap); + defer cloned.deinit(); + for (0..5) |y| { + const src_row = &page.rows.ptr(page.memory)[y]; + const dst_row = &cloned.rows.ptr(cloned.memory)[y]; + try cloned.cloneRowFrom(&page, dst_row, src_row); + } + const cloned_cap = cloned.exactRowCapacity(0, 5); + try testing.expectEqual(cap, cloned_cap); + } +} + +test "Page exactRowCapacity single style clone" { + // Regression test: verify a single style can be cloned with exact capacity. + // This tests that capacityForCount properly accounts for ID 0 being reserved. + var page = try Page.init(.{ + .cols = 10, + .rows = 2, + .styles = 8, + }); + defer page.deinit(); + + // Add exactly one style to row 0 + const style_id = try page.styles.add(page.memory, .{ .flags = .{ .bold = true } }); + { + const rac = page.getRowAndCell(0, 0); + rac.row.styled = true; + rac.cell.style_id = style_id; + } + + // exactRowCapacity for just row 0 should give capacity for 1 style + const cap = page.exactRowCapacity(0, 1); + try testing.expectEqual(StyleSet.capacityForCount(1), cap.styles); + + // Create a new page with exact capacity and clone + var cloned = try Page.init(cap); + defer cloned.deinit(); + + const src_row = &page.rows.ptr(page.memory)[0]; + const dst_row = &cloned.rows.ptr(cloned.memory)[0]; + + // This must not fail with StyleSetOutOfMemory + try cloned.cloneRowFrom(&page, dst_row, src_row); + + // Verify the style was cloned correctly + const cloned_cell = &cloned.rows.ptr(cloned.memory)[0].cells.ptr(cloned.memory)[0]; + try testing.expect(cloned_cell.style_id != stylepkg.default_id); +} + +test "Page exactRowCapacity styles max single row" { + var page = try Page.init(.{ + .cols = std.math.maxInt(size.CellCountInt), + .rows = 1, + .styles = std.math.maxInt(size.StyleCountInt), + }); + defer page.deinit(); + + // Style our first row + const row = &page.rows.ptr(page.memory)[0]; + row.styled = true; + + // Fill cells with styles until we get OOM, but limit to a reasonable count + // to avoid overflow when computing capacityForCount near maxInt + const cells = row.cells.ptr(page.memory)[0..page.size.cols]; + var count: usize = 0; + const max_count: usize = 1000; // Limit to avoid overflow in capacity calculation + for (cells, 0..) |*cell, i| { + if (count >= max_count) break; + const style_id = page.styles.add(page.memory, .{ + .fg_color = .{ .rgb = .{ + .r = @intCast(i & 0xFF), + .g = @intCast((i >> 8) & 0xFF), + .b = 0, + } }, + }) catch break; + cell.style_id = style_id; + count += 1; + } + + // Verify we added a meaningful number of styles + try testing.expect(count > 0); + + // Capacity should be at least count (adjusted for load factor) + const cap = page.exactRowCapacity(0, 1); + try testing.expectEqual(StyleSet.capacityForCount(count), cap.styles); +} + +test "Page exactRowCapacity grapheme_bytes" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // No graphemes: capacity should be 0 + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(0, cap.grapheme_bytes); + } + + // Add one grapheme (1 codepoint) to a cell - rounds up to grapheme_chunk + { + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .init('a'); + try page.appendGrapheme(rac.row, rac.cell, 0x0301); // combining acute accent + } + { + const cap = page.exactRowCapacity(0, 5); + // 1 codepoint = 4 bytes, rounds up to grapheme_chunk (16) + try testing.expectEqual(grapheme_chunk, cap.grapheme_bytes); + } + + // Add another grapheme to a different cell - should sum + { + const rac = page.getRowAndCell(1, 0); + rac.cell.* = .init('e'); + try page.appendGrapheme(rac.row, rac.cell, 0x0300); // combining grave accent + } + { + const cap = page.exactRowCapacity(0, 5); + // 2 graphemes, each 1 codepoint = 2 * grapheme_chunk + try testing.expectEqual(grapheme_chunk * 2, cap.grapheme_bytes); + } + + // Add a larger grapheme (multiple codepoints) that fits in one chunk + { + const rac = page.getRowAndCell(2, 0); + rac.cell.* = .init('o'); + try page.appendGrapheme(rac.row, rac.cell, 0x0301); + try page.appendGrapheme(rac.row, rac.cell, 0x0302); + try page.appendGrapheme(rac.row, rac.cell, 0x0303); + } + { + const cap = page.exactRowCapacity(0, 5); + // First two cells: 2 * grapheme_chunk + // Third cell: 3 codepoints = 12 bytes, rounds up to grapheme_chunk + try testing.expectEqual(grapheme_chunk * 3, cap.grapheme_bytes); + } + + // Grapheme outside the row range should not be counted + { + const rac = page.getRowAndCell(0, 7); + rac.cell.* = .init('x'); + try page.appendGrapheme(rac.row, rac.cell, 0x0304); + } + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(grapheme_chunk * 3, cap.grapheme_bytes); + } + + // Full range includes the new grapheme + { + const cap = page.exactRowCapacity(0, 10); + try testing.expectEqual(grapheme_chunk * 4, cap.grapheme_bytes); + } + + // Verify clone works with exact capacity and produces same result + { + const cap = page.exactRowCapacity(0, 5); + var cloned = try Page.init(cap); + defer cloned.deinit(); + for (0..5) |y| { + const src_row = &page.rows.ptr(page.memory)[y]; + const dst_row = &cloned.rows.ptr(cloned.memory)[y]; + try cloned.cloneRowFrom(&page, dst_row, src_row); + } + const cloned_cap = cloned.exactRowCapacity(0, 5); + try testing.expectEqual(cap, cloned_cap); + } +} + +test "Page exactRowCapacity grapheme_bytes larger than chunk" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + }); + defer page.deinit(); + + // Add a grapheme larger than one chunk (grapheme_chunk_len = 4 codepoints) + const rac = page.getRowAndCell(0, 0); + rac.cell.* = .init('a'); + + // Add 6 codepoints - requires 2 chunks (6 * 4 = 24 bytes, rounds up to 32) + for (0..6) |i| { + try page.appendGrapheme(rac.row, rac.cell, @intCast(0x0300 + i)); + } + + const cap = page.exactRowCapacity(0, 1); + // 6 codepoints = 24 bytes, alignForward(24, 16) = 32 + try testing.expectEqual(32, cap.grapheme_bytes); + + // Verify clone works with exact capacity and produces same result + var cloned = try Page.init(cap); + defer cloned.deinit(); + const src_row = &page.rows.ptr(page.memory)[0]; + const dst_row = &cloned.rows.ptr(cloned.memory)[0]; + try cloned.cloneRowFrom(&page, dst_row, src_row); + const cloned_cap = cloned.exactRowCapacity(0, 1); + try testing.expectEqual(cap, cloned_cap); +} + +test "Page exactRowCapacity hyperlinks" { + var page = try Page.init(.{ + .cols = 10, + .rows = 10, + .styles = 8, + .hyperlink_bytes = 32 * @sizeOf(hyperlink.Set.Item), + .string_bytes = 512, + }); + defer page.deinit(); + + // No hyperlinks: capacity should be 0 + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(0, cap.hyperlink_bytes); + try testing.expectEqual(0, cap.string_bytes); + } + + // Add one hyperlink with implicit ID + const uri1 = "https://example.com"; + const id1 = blk: { + const rac = page.getRowAndCell(0, 0); + + // Create and add hyperlink entry + const id = try page.insertHyperlink(.{ + .id = .{ .implicit = 1 }, + .uri = uri1, + }); + try page.setHyperlink(rac.row, rac.cell, id); + break :blk id; + }; + // 1 hyperlink - capacity accounts for load factor + const cap_one_link = page.exactRowCapacity(0, 5); + { + try testing.expectEqual(hyperlink.Set.capacityForCount(1) * @sizeOf(hyperlink.Set.Item), cap_one_link.hyperlink_bytes); + // URI "https://example.com" = 19 bytes, rounds up to string_chunk (32) + try testing.expectEqual(string_chunk, cap_one_link.string_bytes); + } + + // Add same hyperlink to another cell (duplicate ID) - capacity unchanged + { + const rac = page.getRowAndCell(1, 0); + + // Use the same hyperlink ID for another cell + page.hyperlink_set.use(page.memory, id1); + try page.setHyperlink(rac.row, rac.cell, id1); + } + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(cap_one_link.hyperlink_bytes, cap.hyperlink_bytes); + try testing.expectEqual(cap_one_link.string_bytes, cap.string_bytes); + } + + // Add a different hyperlink with explicit ID + const uri2 = "https://other.example.org/path"; + const explicit_id = "my-link-id"; + { + const rac = page.getRowAndCell(2, 0); + + const id = try page.insertHyperlink(.{ + .id = .{ .explicit = explicit_id }, + .uri = uri2, + }); + try page.setHyperlink(rac.row, rac.cell, id); + } + // 2 hyperlinks - capacity accounts for load factor + const cap_two_links = page.exactRowCapacity(0, 5); + { + try testing.expectEqual(hyperlink.Set.capacityForCount(2) * @sizeOf(hyperlink.Set.Item), cap_two_links.hyperlink_bytes); + // First URI: 19 bytes -> 32, Second URI: 30 bytes -> 32, Explicit ID: 10 bytes -> 32 + try testing.expectEqual(string_chunk * 3, cap_two_links.string_bytes); + } + + // Hyperlink outside the row range should not be counted + { + const rac = page.getRowAndCell(0, 7); // row 7 is outside range [0, 5) + + const id = try page.insertHyperlink(.{ + .id = .{ .implicit = 99 }, + .uri = "https://outside.example.com", + }); + try page.setHyperlink(rac.row, rac.cell, id); + } + { + const cap = page.exactRowCapacity(0, 5); + try testing.expectEqual(cap_two_links.hyperlink_bytes, cap.hyperlink_bytes); + try testing.expectEqual(cap_two_links.string_bytes, cap.string_bytes); + } + + // Full range includes the new hyperlink + { + const cap = page.exactRowCapacity(0, 10); + try testing.expectEqual(hyperlink.Set.capacityForCount(3) * @sizeOf(hyperlink.Set.Item), cap.hyperlink_bytes); + // Third URI: 27 bytes -> 32 + try testing.expectEqual(string_chunk * 4, cap.string_bytes); + } + + // Verify clone works with exact capacity and produces same result + { + const cap = page.exactRowCapacity(0, 5); + var cloned = try Page.init(cap); + defer cloned.deinit(); + for (0..5) |y| { + const src_row = &page.rows.ptr(page.memory)[y]; + const dst_row = &cloned.rows.ptr(cloned.memory)[y]; + try cloned.cloneRowFrom(&page, dst_row, src_row); + } + const cloned_cap = cloned.exactRowCapacity(0, 5); + try testing.expectEqual(cap, cloned_cap); + } +} + +test "Page exactRowCapacity single hyperlink clone" { + // Regression test: verify a single hyperlink can be cloned with exact capacity. + // This tests that capacityForCount properly accounts for ID 0 being reserved. + var page = try Page.init(.{ + .cols = 10, + .rows = 2, + .styles = 8, + .hyperlink_bytes = 32 * @sizeOf(hyperlink.Set.Item), + .string_bytes = 512, + }); + defer page.deinit(); + + // Add exactly one hyperlink to row 0 + const uri = "https://example.com"; + const id = blk: { + const rac = page.getRowAndCell(0, 0); + const link_id = try page.insertHyperlink(.{ + .id = .{ .implicit = 1 }, + .uri = uri, + }); + try page.setHyperlink(rac.row, rac.cell, link_id); + break :blk link_id; + }; + _ = id; + + // exactRowCapacity for just row 0 should give capacity for 1 hyperlink + const cap = page.exactRowCapacity(0, 1); + try testing.expectEqual(hyperlink.Set.capacityForCount(1) * @sizeOf(hyperlink.Set.Item), cap.hyperlink_bytes); + + // Create a new page with exact capacity and clone + var cloned = try Page.init(cap); + defer cloned.deinit(); + + const src_row = &page.rows.ptr(page.memory)[0]; + const dst_row = &cloned.rows.ptr(cloned.memory)[0]; + + // This must not fail with HyperlinkSetOutOfMemory + try cloned.cloneRowFrom(&page, dst_row, src_row); + + // Verify the hyperlink was cloned correctly + const cloned_cell = &cloned.rows.ptr(cloned.memory)[0].cells.ptr(cloned.memory)[0]; + try testing.expect(cloned_cell.hyperlink); +} + +test "Page exactRowCapacity hyperlink map capacity for many cells" { + // A single hyperlink spanning many cells requires hyperlink_map capacity + // based on cell count, not unique hyperlink count. + const cols = 50; + var page = try Page.init(.{ + .cols = cols, + .rows = 2, + .styles = 8, + .hyperlink_bytes = 32 * @sizeOf(hyperlink.Set.Item), + .string_bytes = 512, + }); + defer page.deinit(); + + // Add one hyperlink spanning all 50 columns in row 0 + const uri = "https://example.com"; + const id = blk: { + const rac = page.getRowAndCell(0, 0); + const link_id = try page.insertHyperlink(.{ + .id = .{ .implicit = 1 }, + .uri = uri, + }); + try page.setHyperlink(rac.row, rac.cell, link_id); + break :blk link_id; + }; + + // Apply same hyperlink to remaining cells in row 0 + for (1..cols) |x| { + const rac = page.getRowAndCell(@intCast(x), 0); + page.hyperlink_set.use(page.memory, id); + try page.setHyperlink(rac.row, rac.cell, id); + } + + // exactRowCapacity must account for 50 hyperlink cells, not just 1 unique hyperlink + const cap = page.exactRowCapacity(0, 1); + + // The hyperlink_bytes must be large enough that layout() computes sufficient + // hyperlink_map capacity. With hyperlink_cell_multiplier=16, we need at least + // ceil(50/16) = 4 hyperlink entries worth of bytes for the map. + const min_for_map = std.math.divCeil(usize, cols, hyperlink_cell_multiplier) catch 0; + const min_hyperlink_bytes = min_for_map * @sizeOf(hyperlink.Set.Item); + try testing.expect(cap.hyperlink_bytes >= min_hyperlink_bytes); + + // Create a new page with exact capacity and clone - must not fail + var cloned = try Page.init(cap); + defer cloned.deinit(); + + const src_row = &page.rows.ptr(page.memory)[0]; + const dst_row = &cloned.rows.ptr(cloned.memory)[0]; + + // This must not fail with HyperlinkMapOutOfMemory + try cloned.cloneRowFrom(&page, dst_row, src_row); + + // Verify all hyperlinks were cloned correctly + for (0..cols) |x| { + const cloned_cell = &cloned.rows.ptr(cloned.memory)[0].cells.ptr(cloned.memory)[x]; + try testing.expect(cloned_cell.hyperlink); + } +} diff --git a/vendor/libghostty-vt/src/terminal/parse_table.zig b/vendor/libghostty-vt/src/terminal/parse_table.zig new file mode 100644 index 00000000..01bd569c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/parse_table.zig @@ -0,0 +1,388 @@ +//! The primary export of this file is "table", which contains a +//! comptime-generated state transition table for VT emulation. +//! +//! This is based on the vt100.net state machine: +//! https://vt100.net/emu/dec_ansi_parser +//! But has some modifications: +//! +//! * csi_param accepts the colon character (':') since the SGR command +//! accepts colon as a valid parameter value. +//! + +const std = @import("std"); +const parser = @import("Parser.zig"); +const State = parser.State; +const Action = parser.TransitionAction; + +/// The state transition table. The type is [u8][State]Transition but +/// comptime-generated to be exactly-sized. +pub const table = genTable(); + +/// Table is the type of the state table. This is dynamically (comptime) +/// generated to be exactly sized. +pub const Table = genTableType(false); + +/// OptionalTable is private to this file. We use this to accumulate and +/// detect invalid transitions created. +const OptionalTable = genTableType(true); + +// Transition is the transition to take within the table +pub const Transition = struct { + state: State, + action: Action, +}; + +/// Table is the type of the state transition table. +fn genTableType(comptime optional: bool) type { + const max_u8 = std.math.maxInt(u8); + const stateInfo = @typeInfo(State); + const max_state = stateInfo.@"enum".fields.len; + const Elem = if (optional) ?Transition else Transition; + return [max_u8 + 1][max_state]Elem; +} + +/// Function to generate the full state transition table for VT emulation. +fn genTable() Table { + @setEvalBranchQuota(20000); + + // We accumulate using an "optional" table so we can detect duplicates. + var result: OptionalTable = undefined; + for (0..result.len) |i| { + for (0..result[0].len) |j| { + result[i][j] = null; + } + } + + // anywhere transitions + const stateInfo = @typeInfo(State); + inline for (stateInfo.@"enum".fields) |field| { + const source: State = @enumFromInt(field.value); + + // anywhere => ground + single(&result, 0x18, source, .ground, .execute); + single(&result, 0x1A, source, .ground, .execute); + range(&result, 0x80, 0x8F, source, .ground, .execute); + range(&result, 0x91, 0x97, source, .ground, .execute); + single(&result, 0x99, source, .ground, .execute); + single(&result, 0x9A, source, .ground, .execute); + single(&result, 0x9C, source, .ground, .none); + + // anywhere => escape + single(&result, 0x1B, source, .escape, .none); + + // anywhere => sos_pm_apc_string + single(&result, 0x98, source, .sos_pm_apc_string, .none); + single(&result, 0x9E, source, .sos_pm_apc_string, .none); + single(&result, 0x9F, source, .sos_pm_apc_string, .none); + + // anywhere => csi_entry + single(&result, 0x9B, source, .csi_entry, .none); + + // anywhere => dcs_entry + single(&result, 0x90, source, .dcs_entry, .none); + + // anywhere => osc_string + single(&result, 0x9D, source, .osc_string, .none); + } + + // ground + { + // events + single(&result, 0x19, .ground, .ground, .execute); + range(&result, 0, 0x17, .ground, .ground, .execute); + range(&result, 0x1C, 0x1F, .ground, .ground, .execute); + range(&result, 0x20, 0x7F, .ground, .ground, .print); + } + + // escape_intermediate + { + const source = State.escape_intermediate; + + single(&result, 0x19, source, source, .execute); + range(&result, 0, 0x17, source, source, .execute); + range(&result, 0x1C, 0x1F, source, source, .execute); + range(&result, 0x20, 0x2F, source, source, .collect); + single(&result, 0x7F, source, source, .ignore); + + // => ground + range(&result, 0x30, 0x7E, source, .ground, .esc_dispatch); + } + + // sos_pm_apc_string + { + const source = State.sos_pm_apc_string; + + // events + single(&result, 0x19, source, source, .apc_put); + range(&result, 0, 0x17, source, source, .apc_put); + range(&result, 0x1C, 0x1F, source, source, .apc_put); + range(&result, 0x20, 0x7F, source, source, .apc_put); + } + + // escape + { + const source = State.escape; + + // events + single(&result, 0x19, source, source, .execute); + range(&result, 0, 0x17, source, source, .execute); + range(&result, 0x1C, 0x1F, source, source, .execute); + single(&result, 0x7F, source, source, .ignore); + + // => ground + range(&result, 0x30, 0x4F, source, .ground, .esc_dispatch); + range(&result, 0x51, 0x57, source, .ground, .esc_dispatch); + range(&result, 0x60, 0x7E, source, .ground, .esc_dispatch); + single(&result, 0x59, source, .ground, .esc_dispatch); + single(&result, 0x5A, source, .ground, .esc_dispatch); + single(&result, 0x5C, source, .ground, .esc_dispatch); + + // => escape_intermediate + range(&result, 0x20, 0x2F, source, .escape_intermediate, .collect); + + // => sos_pm_apc_string + single(&result, 0x58, source, .sos_pm_apc_string, .none); + single(&result, 0x5E, source, .sos_pm_apc_string, .none); + single(&result, 0x5F, source, .sos_pm_apc_string, .none); + + // => dcs_entry + single(&result, 0x50, source, .dcs_entry, .none); + + // => csi_entry + single(&result, 0x5B, source, .csi_entry, .none); + + // => osc_string + single(&result, 0x5D, source, .osc_string, .none); + } + + // dcs_entry + { + const source = State.dcs_entry; + + // events + single(&result, 0x19, source, source, .ignore); + range(&result, 0, 0x17, source, source, .ignore); + range(&result, 0x1C, 0x1F, source, source, .ignore); + single(&result, 0x7F, source, source, .ignore); + + // => dcs_intermediate + range(&result, 0x20, 0x2F, source, .dcs_intermediate, .collect); + + // => dcs_ignore + single(&result, 0x3A, source, .dcs_ignore, .none); + + // => dcs_param + range(&result, 0x30, 0x39, source, .dcs_param, .param); + single(&result, 0x3B, source, .dcs_param, .param); + range(&result, 0x3C, 0x3F, source, .dcs_param, .collect); + + // => dcs_passthrough + range(&result, 0x40, 0x7E, source, .dcs_passthrough, .none); + } + + // dcs_intermediate + { + const source = State.dcs_intermediate; + + // events + single(&result, 0x19, source, source, .ignore); + range(&result, 0, 0x17, source, source, .ignore); + range(&result, 0x1C, 0x1F, source, source, .ignore); + range(&result, 0x20, 0x2F, source, source, .collect); + single(&result, 0x7F, source, source, .ignore); + + // => dcs_ignore + range(&result, 0x30, 0x3F, source, .dcs_ignore, .none); + + // => dcs_passthrough + range(&result, 0x40, 0x7E, source, .dcs_passthrough, .none); + } + + // dcs_ignore + { + const source = State.dcs_ignore; + + // events + single(&result, 0x19, source, source, .ignore); + range(&result, 0, 0x17, source, source, .ignore); + range(&result, 0x1C, 0x1F, source, source, .ignore); + } + + // dcs_param + { + const source = State.dcs_param; + + // events + single(&result, 0x19, source, source, .ignore); + range(&result, 0, 0x17, source, source, .ignore); + range(&result, 0x1C, 0x1F, source, source, .ignore); + range(&result, 0x30, 0x39, source, source, .param); + single(&result, 0x3B, source, source, .param); + single(&result, 0x7F, source, source, .ignore); + + // => dcs_ignore + single(&result, 0x3A, source, .dcs_ignore, .none); + range(&result, 0x3C, 0x3F, source, .dcs_ignore, .none); + + // => dcs_intermediate + range(&result, 0x20, 0x2F, source, .dcs_intermediate, .collect); + + // => dcs_passthrough + range(&result, 0x40, 0x7E, source, .dcs_passthrough, .none); + } + + // dcs_passthrough + { + const source = State.dcs_passthrough; + + // events + single(&result, 0x19, source, source, .put); + range(&result, 0, 0x17, source, source, .put); + range(&result, 0x1C, 0x1F, source, source, .put); + range(&result, 0x20, 0x7E, source, source, .put); + single(&result, 0x7F, source, source, .ignore); + } + + // csi_param + { + const source = State.csi_param; + + // events + single(&result, 0x19, source, source, .execute); + range(&result, 0, 0x17, source, source, .execute); + range(&result, 0x1C, 0x1F, source, source, .execute); + range(&result, 0x30, 0x39, source, source, .param); + single(&result, 0x3A, source, source, .param); + single(&result, 0x3B, source, source, .param); + single(&result, 0x7F, source, source, .ignore); + + // => ground + range(&result, 0x40, 0x7E, source, .ground, .csi_dispatch); + + // => csi_ignore + range(&result, 0x3C, 0x3F, source, .csi_ignore, .none); + + // => csi_intermediate + range(&result, 0x20, 0x2F, source, .csi_intermediate, .collect); + } + + // csi_ignore + { + const source = State.csi_ignore; + + // events + single(&result, 0x19, source, source, .execute); + range(&result, 0, 0x17, source, source, .execute); + range(&result, 0x1C, 0x1F, source, source, .execute); + range(&result, 0x20, 0x3F, source, source, .ignore); + single(&result, 0x7F, source, source, .ignore); + + // => ground + range(&result, 0x40, 0x7E, source, .ground, .none); + } + + // csi_intermediate + { + const source = State.csi_intermediate; + + // events + single(&result, 0x19, source, source, .execute); + range(&result, 0, 0x17, source, source, .execute); + range(&result, 0x1C, 0x1F, source, source, .execute); + range(&result, 0x20, 0x2F, source, source, .collect); + single(&result, 0x7F, source, source, .ignore); + + // => ground + range(&result, 0x40, 0x7E, source, .ground, .csi_dispatch); + + // => csi_ignore + range(&result, 0x30, 0x3F, source, .csi_ignore, .none); + } + + // csi_entry + { + const source = State.csi_entry; + + // events + single(&result, 0x19, source, source, .execute); + range(&result, 0, 0x17, source, source, .execute); + range(&result, 0x1C, 0x1F, source, source, .execute); + single(&result, 0x7F, source, source, .ignore); + + // => ground + range(&result, 0x40, 0x7E, source, .ground, .csi_dispatch); + + // => csi_ignore + single(&result, 0x3A, source, .csi_ignore, .none); + + // => csi_intermediate + range(&result, 0x20, 0x2F, source, .csi_intermediate, .collect); + + // => csi_param + range(&result, 0x30, 0x39, source, .csi_param, .param); + single(&result, 0x3B, source, .csi_param, .param); + range(&result, 0x3C, 0x3F, source, .csi_param, .collect); + } + + // osc_string + { + const source = State.osc_string; + + // events + single(&result, 0x19, source, source, .ignore); + range(&result, 0, 0x06, source, source, .ignore); + range(&result, 0x08, 0x17, source, source, .ignore); + range(&result, 0x1C, 0x1F, source, source, .ignore); + range(&result, 0x20, 0xFF, source, source, .osc_put); + + // XTerm accepts either BEL or ST for terminating OSC + // sequences, and when returning information, uses the same + // terminator used in a query. + single(&result, 0x07, source, .ground, .none); + } + + // Create our immutable version + var final: Table = undefined; + for (0..final.len) |i| { + for (0..final[0].len) |j| { + final[i][j] = result[i][j] orelse transition(@enumFromInt(j), .none); + } + } + + return final; +} + +fn single(t: *OptionalTable, c: u8, s0: State, s1: State, a: Action) void { + const s0_int = @intFromEnum(s0); + + // TODO: enable this but it thinks we're in runtime right now + // if (t[c][s0_int]) |existing| { + // @compileLog(c); + // @compileLog(s0); + // @compileLog(s1); + // @compileLog(existing); + // @compileError("transition set multiple times"); + // } + + t[c][s0_int] = transition(s1, a); +} + +fn range(t: *OptionalTable, from: u8, to: u8, s0: State, s1: State, a: Action) void { + var i = from; + while (i <= to) : (i += 1) { + single(t, i, s0, s1, a); + // If 'to' is 0xFF, our next pass will overflow. Return early to prevent + // the loop from executing it's continue expression + if (i == to) break; + } +} + +fn transition(state: State, action: Action) Transition { + return .{ .state = state, .action = action }; +} + +test { + // This forces comptime-evaluation of table, so we're just testing + // that it succeeds in creation. + _ = table; +} diff --git a/vendor/libghostty-vt/src/terminal/point.zig b/vendor/libghostty-vt/src/terminal/point.zig new file mode 100644 index 00000000..4297bf5b --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/point.zig @@ -0,0 +1,94 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const lib = @import("lib.zig"); +const size = @import("size.zig"); + +/// The possible reference locations for a point. When someone says "(42, 80)" +/// in the context of a terminal, that could mean multiple things: it is in the +/// current visible viewport? the current active area of the screen where the +/// cursor is? the entire scrollback history? etc. +/// +/// This tag is used to differentiate those cases. +pub const Tag = lib.Enum(lib.target, &.{ + // Top-left is part of the active area where a running program can + // jump the cursor and make changes. The active area is the "editable" + // part of the screen. + // + // The bottom-right of the active tag differs from all other tags + // because it includes the full height (rows) of the screen, including + // rows that may not be written yet. This is required because the active + // area is fully "addressable" by the running program (see below) whereas + // the other tags are used primarily for reading/modifying past-written + // data so they can't address unwritten rows. + // + // Note for those less familiar with terminal functionality: there + // are escape sequences to move the cursor to any position on + // the screen, but it is limited to the size of the viewport and + // the bottommost part of the screen. Terminal programs can't -- + // with sequences at the time of writing this comment -- modify + // anything in the scrollback, visible viewport (if it differs + // from the active area), etc. + "active", + + // Top-left is the visible viewport. This means that if the user + // has scrolled in any direction, top-left changes. The bottom-right + // is the last written row from the top-left. + "viewport", + + // Top-left is the furthest back in the scrollback history + // supported by the screen and the bottom-right is the bottom-right + // of the last written row. Note this last point is important: the + // bottom right is NOT necessarily the same as "active" because + // "active" always allows referencing the full rows tall of the + // screen whereas "screen" only contains written rows. + "screen", + + // The top-left is the same as "screen" but the bottom-right is + // the line just before the top of "active". This contains only + // the scrollback history. + "history", +}); + +/// An x/y point in the terminal for some definition of location (tag). +pub const Point = union(Tag) { + active: Coordinate, + viewport: Coordinate, + screen: Coordinate, + history: Coordinate, + + pub inline fn coord(self: Point) Coordinate { + return switch (self) { + .active, + .viewport, + .screen, + .history, + => |v| v, + }; + } + + const c_union = lib.TaggedUnion( + lib.target, + @This(), + // Padding: largest variant is Coordinate (u16 + u32 = 6 bytes). + // Use [2]u64 (16 bytes) for future expansion. + [2]u64, + ); + pub const C = c_union.C; + pub const CValue = c_union.CValue; + pub const cval = c_union.cval; +}; + +pub const Coordinate = extern struct { + /// x can use size.CellCountInt because the number of columns + /// can't ever be more than a valid number of columns in a Page. + x: size.CellCountInt = 0, + + /// y does not use size.CellCountInt because certain coordinate + /// usage such as screen/history can have more rows than are possible + /// in a single page. + y: u32 = 0, + + pub fn eql(self: Coordinate, other: Coordinate) bool { + return self.x == other.x and self.y == other.y; + } +}; diff --git a/vendor/libghostty-vt/src/terminal/ref_counted_set.zig b/vendor/libghostty-vt/src/terminal/ref_counted_set.zig new file mode 100644 index 00000000..8040039a --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/ref_counted_set.zig @@ -0,0 +1,714 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; + +const size = @import("size.zig"); +const Offset = size.Offset; +const OffsetBuf = size.OffsetBuf; + +/// A reference counted set. +/// +/// This set is created with some capacity in mind. You can determine +/// the exact memory requirement of a given capacity by calling `layout` +/// and checking the total size. +/// +/// When the set exceeds capacity, an `OutOfMemory` or `NeedsRehash` error +/// is returned from any memory-using methods. The caller is responsible +/// for determining a path forward. +/// +/// This set is reference counted. Each item in the set has an associated +/// reference count. The caller is responsible for calling release for an +/// item when it is no longer being used. Items with 0 references will be +/// kept until another item is written to their bucket. This allows items +/// to be resurrected if they are re-added before they get overwritten. +/// +/// The backing data structure of this set is an open addressed hash table +/// with linear probing and Robin Hood hashing, and a flat array of items. +/// +/// The table maps values to item IDs, which are indices in the item array +/// which contain the item's value and its reference count. Item IDs can be +/// used to efficiently access an item and update its reference count after +/// it has been added to the table, to avoid having to use the hash map to +/// look the value back up. +/// +/// ID 0 is reserved and will never be assigned. +/// +/// Parameters: +/// +/// `Context` +/// A type containing methods to define behaviors. +/// +/// - `fn hash(*Context, T) u64` - Return a hash for an item. +/// +/// - `fn eql(*Context, T, T) bool` - Check two items for equality. +/// The first of the two items passed in is guaranteed to be from +/// a value passed in to an `add` or `lookup` function, the second +/// is guaranteed to be a value already resident in the set. +/// +/// - `fn deleted(*Context, T) void` - [OPTIONAL] Deletion callback. +/// If present, called whenever an item is finally deleted. +/// Useful if the item has memory that needs to be freed. +/// +pub fn RefCountedSet( + comptime T: type, + comptime IdT: type, + comptime RefCountInt: type, + comptime ContextT: type, +) type { + return struct { + const Self = @This(); + + pub const base_align: std.mem.Alignment = .fromByteUnits(@max( + @alignOf(Context), + @alignOf(Layout), + @alignOf(Item), + @alignOf(Id), + )); + + /// This is the max load until the set returns OutOfMemory and + /// requires more capacity. + /// + /// Experimentally, this load factor works quite well. + pub const load_factor = 0.8125; + + /// Returns the minimum capacity needed to store `n` items, + /// accounting for the load factor and the reserved ID 0. + pub fn capacityForCount(n: usize) usize { + if (n == 0) return 0; + // +1 because ID 0 is reserved, so we need at least n+1 slots. + return @intFromFloat(@ceil(@as(f64, @floatFromInt(n + 1)) / load_factor)); + } + + /// Set item + pub const Item = struct { + /// The value this item represents. + value: T = undefined, + + /// Metadata for this item. + meta: Metadata = .{}, + + pub const Metadata = struct { + /// The bucket in the hash table where this item + /// is referenced. + bucket: Id = std.math.maxInt(Id), + + /// The length of the probe sequence between this + /// item's starting bucket and the bucket it's in, + /// used for Robin Hood hashing. + psl: Id = 0, + + /// The reference count for this item. + ref: RefCountInt = 0, + }; + }; + + // Re-export these types so they can be referenced by the caller. + pub const Id = IdT; + pub const Context = ContextT; + + /// A hash table of item indices + table: Offset(Id), + + /// By keeping track of the max probe sequence length + /// we can bail out early when looking up values that + /// aren't present. + max_psl: Id = 0, + + /// We keep track of how many items have a PSL of any + /// given length, so that we can shrink max_psl when + /// we delete items. + /// + /// A probe sequence of length 32 or more is astronomically + /// unlikely. Roughly a (1/table_cap)^32 -- with any normal + /// table capacity that is so unlikely that it's not worth + /// handling. + /// + /// However, that assumes a uniform hash function, which + /// is not guaranteed and can be subverted with a crafted + /// input. We handle this gracefully by returning an error + /// anywhere where we're about to insert if there's any + /// item with a PSL in the last slot of the stats array. + psl_stats: [32]Id = @splat(0), + + /// The backing store of items + items: Offset(Item), + + /// The number of living items currently stored in the set. + living: usize = 0, + + /// The next index to store an item at. + /// Id 0 is reserved for unused items. + next_id: Id = 1, + + layout: Layout, + + /// An instance of the context structure. + context: Context, + + pub const Layout = struct { + cap: usize, + table_cap: usize, + table_mask: Id, + table_start: usize, + items_start: usize, + total_size: usize, + + /// Returns the memory layout for the given base offset and + /// desired capacity. The layout can be used by the caller to + /// determine how much memory to allocate, and the layout must + /// be used to initialize the set so that the set knows all + /// the offsets for the various buffers. + /// + /// The capacity passed for cap will be used for the hash table, + /// which has a load factor of `0.8125` (13/16), so the number of + /// items which can actually be stored in the set will be smaller. + /// + /// The laid out capacity will be at least `cap`, but may be higher, + /// since it is rounded up to the next power of 2 for efficiency. + /// + /// The returned layout `cap` property will be 1 more than the number + /// of items that the set can actually store, since ID 0 is reserved. + pub fn init(cap: usize) Layout { + assert(cap <= @as(usize, @intCast(std.math.maxInt(Id))) + 1); + + // Zero-cap set is valid, return special case + if (cap == 0) return .{ + .cap = 0, + .table_cap = 0, + .table_mask = 0, + .table_start = 0, + .items_start = 0, + .total_size = 0, + }; + + const table_cap: usize = std.math.ceilPowerOfTwoAssert(usize, cap); + const items_cap: usize = @intFromFloat(load_factor * @as(f64, @floatFromInt(table_cap))); + + const table_mask: Id = @intCast((@as(usize, 1) << std.math.log2_int(usize, table_cap)) - 1); + + const table_start = 0; + const table_end = table_start + table_cap * @sizeOf(Id); + + const items_start = std.mem.alignForward(usize, table_end, @alignOf(Item)); + const items_end = items_start + items_cap * @sizeOf(Item); + + const total_size = items_end; + + return .{ + .cap = items_cap, + .table_cap = table_cap, + .table_mask = table_mask, + .table_start = table_start, + .items_start = items_start, + .total_size = total_size, + }; + } + }; + + pub fn init(base: OffsetBuf, l: Layout, context: Context) Self { + const table = base.member(Id, l.table_start); + const items = base.member(Item, l.items_start); + + @memset(table.ptr(base)[0..l.table_cap], 0); + @memset(items.ptr(base)[0..l.cap], .{}); + + return .{ + .table = table, + .items = items, + .layout = l, + .context = context, + }; + } + + /// Possible errors for `add` and `addWithId`. + pub const AddError = error{ + /// There is not enough memory to add a new item. + /// Remove items or grow and reinitialize. + OutOfMemory, + + /// The set needs to be rehashed, as there are many dead + /// items with lower IDs which are inaccessible for reuse. + NeedsRehash, + }; + + /// Add an item to the set if not present and increment its ref count. + /// + /// Returns the item's ID. + /// + /// If the set has no more room, then an OutOfMemory error is returned. + pub fn add(self: *Self, base: anytype, value: T) AddError!Id { + return try self.addContext(base, value, self.context); + } + pub fn addContext(self: *Self, base: anytype, value: T, ctx: Context) AddError!Id { + const items = self.items.ptr(base); + + // Trim dead items from the end of the list. + while (self.next_id > 1 and items[self.next_id - 1].meta.ref == 0) { + self.next_id -= 1; + self.deleteItem(base, self.next_id, ctx); + } + + // If the item already exists, return it. + if (self.lookupContext(base, value, ctx)) |id| { + // Notify the context that the value is "deleted" because + // we're reusing the existing value in the set. This allows + // callers to clean up any resources associated with the value. + if (comptime @hasDecl(Context, "deleted")) ctx.deleted(value); + + items[id].meta.ref += 1; + return id; + } + + // While it should be statistically impossible to exceed the + // bounds of `psl_stats`, the hash function is not perfect and + // in such a case we want to remain stable. If we're about to + // insert an item and there's something with a PSL of `len - 1`, + // we may end up with a PSL of `len` which would exceed the bounds. + // In such a case, we claim to be out of memory. + if (self.psl_stats[self.psl_stats.len - 1] > 0) { + @branchHint(.cold); + return AddError.OutOfMemory; + } + + // If the item doesn't exist, we need an available ID. + if (self.next_id >= self.layout.cap) { + // Arbitrarily chosen, threshold for rehashing. + // If less than 90% of currently allocated IDs + // correspond to living items, we should rehash. + // Otherwise, claim we're out of memory because + // we assume that we'll end up running out of + // memory or rehashing again very soon if we + // rehash with only a few IDs left. + const rehash_threshold = 0.9; + if (self.living < @as(Id, @intFromFloat(@as(f64, @floatFromInt(self.layout.cap)) * rehash_threshold))) { + return AddError.NeedsRehash; + } + + // If we don't have at least 10% dead items then + // we claim we're out of memory. + return AddError.OutOfMemory; + } + + const id = self.insert(base, value, self.next_id, ctx); + items[id].meta.ref += 1; + assert(items[id].meta.ref == 1); + self.living += 1; + + // Its possible insert returns a different ID by reusing a + // dead item so we only need to update next id if we used it. + if (id == self.next_id) self.next_id += 1; + + return id; + } + + /// Add an item to the set if not present and increment its + /// ref count. If possible, use the provided ID. + /// + /// Returns the item's ID, or null if the provided ID was used. + /// + /// If the set has no more room, then an OutOfMemory error is returned. + pub fn addWithId(self: *Self, base: anytype, value: T, id: Id) AddError!?Id { + return try self.addWithIdContext(base, value, id, self.context); + } + pub fn addWithIdContext(self: *Self, base: anytype, value: T, id: Id, ctx: Context) AddError!?Id { + const items = self.items.ptr(base); + + assert(id > 0); + + if (id < self.next_id) { + if (items[id].meta.ref == 0) { + // See comment in `addContext` for details. + if (self.psl_stats[self.psl_stats.len - 1] > 0) { + @branchHint(.cold); + return AddError.OutOfMemory; + } + + self.deleteItem(base, id, ctx); + + const added_id = self.upsert(base, value, id, ctx); + + items[added_id].meta.ref += 1; + + self.living += 1; + + return if (added_id == id) null else added_id; + } else if (ctx.eql(value, items[id].value)) { + // Notify the context that the value is "deleted" because + // we're reusing the existing value in the set. This allows + // callers to clean up any resources associated with the value. + if (comptime @hasDecl(Context, "deleted")) ctx.deleted(value); + + items[id].meta.ref += 1; + + return null; + } + } + + return try self.addContext(base, value, ctx); + } + + /// Increment an item's reference count by 1. + /// + /// Asserts that the item's reference count is greater than 0. + pub fn use(self: *const Self, base: anytype, id: Id) void { + assert(id > 0); + assert(id < self.layout.cap); + + const items = self.items.ptr(base); + const item = &items[id]; + + // If `use` is being called on an item with 0 references, then + // either someone forgot to call it before, released too early + // or lied about releasing. In any case something is wrong and + // shouldn't be allowed. + assert(item.meta.ref > 0); + + item.meta.ref += 1; + } + + /// Increment an item's reference count by a specified number. + /// + /// Asserts that the item's reference count is greater than 0. + pub fn useMultiple(self: *const Self, base: anytype, id: Id, n: RefCountInt) void { + assert(id > 0); + assert(id < self.layout.cap); + + const items = self.items.ptr(base); + const item = &items[id]; + + // If `use` is being called on an item with 0 references, then + // either someone forgot to call it before, released too early + // or lied about releasing. In any case something is wrong and + // shouldn't be allowed. + assert(item.meta.ref > 0); + + item.meta.ref += n; + } + + /// Get an item by its ID without incrementing its reference count. + /// + /// Asserts that the item's reference count is greater than 0. + pub fn get(self: *const Self, base: anytype, id: Id) *T { + assert(id > 0); + assert(id < self.layout.cap); + + const items = self.items.ptr(base); + const item = &items[id]; + + assert(item.meta.ref > 0); + + return @ptrCast(&item.value); + } + + /// Releases a reference to an item by its ID. + /// + /// Asserts that the item's reference count is greater than 0. + pub fn release(self: *Self, base: anytype, id: Id) void { + assert(id > 0); + assert(id < self.layout.cap); + + const items = self.items.ptr(base); + const item = &items[id]; + + assert(item.meta.ref > 0); + item.meta.ref -= 1; + if (item.meta.ref == 0) self.living -= 1; + } + + /// Release a specified number of references to an item by its ID. + /// + /// Asserts that the item's reference count is at least `n`. + pub fn releaseMultiple(self: *Self, base: anytype, id: Id, n: Id) void { + assert(id > 0); + assert(id < self.layout.cap); + + const items = self.items.ptr(base); + const item = &items[id]; + + assert(item.meta.ref >= n); + item.meta.ref -= n; + + if (item.meta.ref == 0) { + self.living -= 1; + } + } + + /// Get the ref count for an item by its ID. + pub fn refCount(self: *const Self, base: anytype, id: Id) RefCountInt { + assert(id > 0); + assert(id < self.layout.cap); + + const items = self.items.ptr(base); + const item = &items[id]; + return item.meta.ref; + } + + /// Get the current number of non-dead items in the set. + pub fn count(self: *const Self) usize { + return self.living; + } + + /// Delete an item, removing any references from + /// the table, and freeing its ID to be reused. + fn deleteItem(self: *Self, base: anytype, id: Id, ctx: Context) void { + const table = self.table.ptr(base); + const items = self.items.ptr(base); + + const item = items[id]; + + if (item.meta.bucket > self.layout.table_cap) return; + + assert(table[item.meta.bucket] == id); + + if (comptime @hasDecl(Context, "deleted")) { + // Inform the context struct that we're + // deleting the dead item's value for good. + ctx.deleted(item.value); + } + + self.psl_stats[item.meta.psl] -= 1; + table[item.meta.bucket] = 0; + items[id] = .{}; + + var p: Id = item.meta.bucket; + var n: Id = (p +% 1) & self.layout.table_mask; + + while (table[n] != 0 and items[table[n]].meta.psl > 0) { + items[table[n]].meta.bucket = p; + self.psl_stats[items[table[n]].meta.psl] -= 1; + items[table[n]].meta.psl -= 1; + self.psl_stats[items[table[n]].meta.psl] += 1; + table[p] = table[n]; + p = n; + n = (p +% 1) & self.layout.table_mask; + } + + while (self.max_psl > 0 and self.psl_stats[self.max_psl] == 0) { + self.max_psl -= 1; + } + + table[p] = 0; + + self.assertIntegrity(base, ctx); + } + + /// Find an item in the table and return its ID. + /// If the item does not exist in the table, null is returned. + pub fn lookup(self: *const Self, base: anytype, value: T) ?Id { + return self.lookupContext(base, value, self.context); + } + pub fn lookupContext(self: *const Self, base: anytype, value: T, ctx: Context) ?Id { + const table = self.table.ptr(base); + const items = self.items.ptr(base); + + const hash: u64 = ctx.hash(value); + + for (0..self.max_psl + 1) |i| { + const p: usize = @intCast((hash +% i) & self.layout.table_mask); + const id = table[p]; + + // Empty bucket, our item cannot have probed to + // any point after this, meaning it's not present. + if (id == 0) { + return null; + } + + const item = items[id]; + + // An item with a shorter probe sequence length would never + // end up in the middle of another sequence, since it would + // be swapped out if inserted before the new sequence, and + // would not be swapped in if inserted afterwards. + // + // As such, our item cannot be present. + if (item.meta.psl < i) { + return null; + } + + // If the item is a part of the same probe sequence, + // we make sure it's not dead and then check to see + // if it matches the value we're looking for. + if (item.meta.psl == i and + item.meta.ref > 0 and + ctx.eql(value, item.value)) + { + return id; + } + } + + return null; + } + + /// Find the provided value in the hash table, or add a new item + /// for it if not present. If a new item is added, `new_id` will + /// be used as the ID. If an existing item is found, the `new_id` + /// is ignored and the existing item's ID is returned. + fn upsert(self: *Self, base: anytype, value: T, new_id: Id, ctx: Context) Id { + // If the item already exists, return it. + if (self.lookupContext(base, value, ctx)) |id| { + // Notify the context that the value is "deleted" because + // we're reusing the existing value in the set. This allows + // callers to clean up any resources associated with the value. + if (comptime @hasDecl(Context, "deleted")) ctx.deleted(value); + + return id; + } + + return self.insert(base, value, new_id, ctx); + } + + /// Insert the given value into the hash table with the given ID. + /// + /// If runtime safety is enabled, asserts that + /// the value is not already present in the table. + fn insert(self: *Self, base: anytype, value: T, new_id: Id, ctx: Context) Id { + if (comptime std.debug.runtime_safety) + assert(self.lookupContext(base, value, ctx) == null); + + const table = self.table.ptr(base); + const items = self.items.ptr(base); + + // The new item that we'll put in to the table. + var new_item: Item = .{ + .value = value, + .meta = .{ .psl = 0, .ref = 0 }, + }; + + const hash: u64 = ctx.hash(value); + + var held_id: Id = new_id; + var held_item: *Item = &new_item; + + var chosen_id: Id = new_id; + + for (0..self.layout.table_cap - 1) |i| { + const p: Id = @intCast((hash +% i) & self.layout.table_mask); + const id = table[p]; + + // Empty bucket, put our held item in to it and break. + if (id == 0) { + table[p] = held_id; + held_item.meta.bucket = p; + self.psl_stats[held_item.meta.psl] += 1; + self.max_psl = @max(self.max_psl, held_item.meta.psl); + break; + } + + const item = &items[id]; + + // If there's a dead item then we resurrect it + // for our value so that we can reuse its ID, + // unless its ID is greater than the one we're + // given (i.e. prefer smaller IDs). + if (item.meta.ref == 0) { + // Dead items aren't super common relative + // to other places to insert/swap the held + // item in to the set. + @branchHint(.unlikely); + + if (comptime @hasDecl(Context, "deleted")) { + // Inform the context struct that we're + // deleting the dead item's value for good. + ctx.deleted(item.value); + } + + // Reap the dead item. + self.psl_stats[item.meta.psl] -= 1; + item.* = .{}; + + // Only resurrect this item if it has a + // smaller id than the one we were given. + if (id < new_id) chosen_id = id; + + // Put the currently held item in to the + // bucket of the item that we just reaped. + table[p] = held_id; + held_item.meta.bucket = p; + self.psl_stats[held_item.meta.psl] += 1; + self.max_psl = @max(self.max_psl, held_item.meta.psl); + + break; + } + + // If this item has a lower PSL, or has equal PSL and lower ref + // count, then we swap it out with our held item. By doing this, + // items with high reference counts are prioritized for earlier + // placement. The assumption is that an item which has a higher + // reference count will be accessed more frequently, so we want + // to minimize the time it takes to find it. + if (item.meta.psl < held_item.meta.psl or + item.meta.psl == held_item.meta.psl and + item.meta.ref < held_item.meta.ref) + { + // Put our held item in the bucket. + table[p] = held_id; + held_item.meta.bucket = p; + self.psl_stats[held_item.meta.psl] += 1; + self.max_psl = @max(self.max_psl, held_item.meta.psl); + + // Pick up the item that has a lower PSL. + held_id = id; + held_item = item; + self.psl_stats[item.meta.psl] -= 1; + } + + // Advance to the next probe position for our held item. + held_item.meta.psl += 1; + } + + // Our chosen ID may have changed if we decided + // to reuse a dead item's ID, so we make sure + // the chosen bucket contains the correct ID. + table[new_item.meta.bucket] = chosen_id; + + // Finally place our new item in to our array. + items[chosen_id] = new_item; + + self.assertIntegrity(base, ctx); + + return chosen_id; + } + + fn assertIntegrity( + self: *const Self, + base: anytype, + ctx: Context, + ) void { + // Disabled because this is excessively slow, only enable + // if debugging a RefCountedSet issue or modifying its logic. + if (false and std.debug.runtime_safety) { + const table = self.table.ptr(base); + const items = self.items.ptr(base); + + var psl_stats: [32]Id = @splat(0); + + for (items[0..self.layout.cap], 0..) |item, id| { + if (item.meta.bucket < std.math.maxInt(Id)) { + assert(table[item.meta.bucket] == id); + psl_stats[item.meta.psl] += 1; + } + } + + std.testing.expectEqualSlices(Id, &psl_stats, &self.psl_stats) catch assert(false); + + assert(std.mem.eql(Id, &psl_stats, &self.psl_stats)); + + psl_stats = @splat(0); + + for (table[0..self.layout.table_cap], 0..) |id, bucket| { + const item = items[id]; + if (item.meta.bucket < std.math.maxInt(Id)) { + assert(item.meta.bucket == bucket); + + const hash: u64 = ctx.hash(item.value); + const p: usize = @intCast((hash +% item.meta.psl) & self.layout.table_mask); + assert(p == bucket); + + psl_stats[item.meta.psl] += 1; + } + } + + std.testing.expectEqualSlices(Id, &psl_stats, &self.psl_stats) catch assert(false); + } + } + }; +} diff --git a/vendor/libghostty-vt/src/terminal/render.zig b/vendor/libghostty-vt/src/terminal/render.zig new file mode 100644 index 00000000..98e14224 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/render.zig @@ -0,0 +1,1465 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; +const fastmem = @import("../fastmem.zig"); +const lib = @import("lib.zig"); +const color = @import("color.zig"); +const cursor = @import("cursor.zig"); +const highlight = @import("highlight.zig"); +const point = @import("point.zig"); +const size = @import("size.zig"); +const page = @import("page.zig"); +const PageList = @import("PageList.zig"); +const Selection = @import("Selection.zig"); +const Screen = @import("Screen.zig"); +const ScreenSet = @import("ScreenSet.zig"); +const Style = @import("style.zig").Style; +const Terminal = @import("Terminal.zig"); + +// Developer note: this is in src/terminal and not src/renderer because +// the goal is that this remains generic to multiple renderers. This can +// aid specifically with libghostty-vt with converting terminal state to +// a renderable form. + +/// Contains the state required to render the screen, including optimizing +/// for repeated render calls and only rendering dirty regions. +/// +/// Previously, our renderer would use `clone` to clone the screen within +/// the viewport to perform rendering. This worked well enough that we kept +/// it all the way up through the Ghostty 1.2.x series, but the clone time +/// was repeatedly a bottleneck blocking IO. +/// +/// Rather than a generic clone that tries to clone all screen state per call +/// (within a region), a stateful approach that optimizes for only what a +/// renderer needs to do makes more sense. +/// +/// To use this, initialize the render state to empty, then call `update` +/// on each frame to update the state to the latest terminal state. +/// +/// var state: RenderState = .empty; +/// defer state.deinit(alloc); +/// state.update(alloc, &terminal); +/// +/// Note: the render state retains as much memory as possible between updates +/// to prevent future allocations. If a very large frame is rendered once, +/// the render state will retain that much memory until deinit. To avoid +/// waste, it is recommended that the caller `deinit` and start with an +/// empty render state every so often. +pub const RenderState = struct { + /// The current screen dimensions. It is possible that these don't match + /// the renderer's current dimensions in grid cells because resizing + /// can happen asynchronously. For example, for Metal, our NSView resizes + /// at a different time than when our internal terminal state resizes. + /// This can lead to a one or two frame mismatch a renderer needs to + /// handle. + /// + /// The viewport is always exactly equal to the active area size so this + /// is also the viewport size. + rows: size.CellCountInt, + cols: size.CellCountInt, + + /// The color state for the terminal. + colors: Colors, + + /// Cursor state within the viewport. + cursor: Cursor, + + /// The rows (y=0 is top) of the viewport. Guaranteed to be `rows` length. + /// + /// This is a MultiArrayList because only the update cares about + /// the allocators. Callers care about all the other properties, and + /// this better optimizes cache locality for read access for those + /// use cases. + row_data: std.MultiArrayList(Row), + + /// The dirty state of the render state. This is set by the update method. + /// The renderer/caller should set this to false when it has handled + /// the dirty state. + dirty: Dirty, + + /// The screen type that this state represents. This is used primarily + /// to detect changes. + screen: ScreenSet.Key, + + /// The last viewport pin used to generate this state. This is NOT + /// a tracked pin and is generally NOT safe to read other than the direct + /// values for comparison. + viewport_pin: ?PageList.Pin = null, + + /// The cached selection so we can avoid expensive selection calculations + /// if possible. + selection_cache: ?SelectionCache = null, + + /// Initial state. + pub const empty: RenderState = .{ + .rows = 0, + .cols = 0, + .colors = .{ + .background = .{ .r = 0, .g = 0, .b = 0 }, + .foreground = .{ .r = 0xff, .g = 0xff, .b = 0xff }, + .cursor = null, + .palette = color.default, + }, + .cursor = .{ + .active = .{ .x = 0, .y = 0 }, + .viewport = null, + .cell = .{}, + .style = undefined, + .visual_style = .block, + .password_input = false, + .visible = true, + .blinking = false, + }, + .row_data = .empty, + .dirty = .false, + .screen = .primary, + }; + + /// The color state for the terminal. + /// + /// The background/foreground will be reversed if the terminal reverse + /// color mode is on! You do not need to handle that manually! + pub const Colors = struct { + background: color.RGB, + foreground: color.RGB, + cursor: ?color.RGB, + palette: color.Palette, + }; + + pub const Cursor = struct { + /// The x/y position of the cursor within the active area. + active: point.Coordinate, + + /// The x/y position of the cursor within the viewport. This + /// may be null if the cursor is not visible within the viewport. + viewport: ?Viewport, + + /// The cell data for the cursor position. Managed memory is not + /// safe to access from this. + cell: page.Cell, + + /// The style, always valid even if the cell is default style. + style: Style, + + /// The visual style of the cursor itself, such as a block or + /// bar. + visual_style: cursor.Style, + + /// True if the cursor is detected to be at a password input field. + password_input: bool, + + /// Cursor visibility state determined by the terminal mode. + visible: bool, + + /// Cursor blink state determined by the terminal mode. + blinking: bool, + + pub const Viewport = struct { + /// The x/y position of the cursor within the viewport. + x: size.CellCountInt, + y: size.CellCountInt, + + /// Whether the cursor is part of a wide character and + /// on the tail of it. If so, some renderers may use this + /// to move the cursor back one. + wide_tail: bool, + }; + }; + + /// A row within the viewport. + pub const Row = struct { + /// Arena used for any heap allocations for cell contents + /// in this row. Importantly, this is NOT used for the MultiArrayList + /// itself. We do this on purpose so that we can easily clear rows, + /// but retain cached MultiArrayList capacities since grid sizes don't + /// change often. + arena: ArenaAllocator.State, + + /// The page pin. This is not safe to read unless you can guarantee + /// the terminal state hasn't changed since the last `update` call. + pin: PageList.Pin, + + /// Raw row data. + raw: page.Row, + + /// The cells in this row. Guaranteed to be `cols` length. + cells: std.MultiArrayList(Cell), + + /// A dirty flag that can be used by the renderer to track + /// its own draw state. `update` will mark this true whenever + /// this row is changed, too. + dirty: bool, + + /// The x range of the selection within this row. + selection: ?[2]size.CellCountInt, + + /// The highlights within this row. + highlights: std.ArrayList(Highlight), + }; + + pub const Highlight = struct { + /// A special tag that can be used by the caller to differentiate + /// different highlight types. The value is opaque to the RenderState. + tag: u8, + + /// The x ranges of highlights within this row. + range: [2]size.CellCountInt, + }; + + pub const Cell = struct { + /// Always set, this is the raw copied cell data from page.Cell. + /// The managed memory (hyperlinks, graphames, etc.) is NOT safe + /// to access from here. It is duplicated into the other fields if + /// it exists. + raw: page.Cell, + + /// Grapheme data for the cell. This is undefined unless the + /// raw cell's content_tag is `codepoint_grapheme`. + grapheme: []const u21, + + /// The style data for the cell. This is undefined unless + /// the style_id is non-default on raw. + style: Style, + }; + + // Dirty state. + pub const Dirty = lib.Enum(lib.target, &.{ + // Not dirty at all. Can skip rendering if prior state was + // already rendered. + "false", + + // Some rows changed but not all. None of the global state + // changed such as colors. + "partial", + + // Global state changed or dimensions changed. All rows should + // be redrawn. + "full", + }); + + const SelectionCache = struct { + selection: Selection, + tl_pin: PageList.Pin, + br_pin: PageList.Pin, + }; + + pub fn deinit(self: *RenderState, alloc: Allocator) void { + for ( + self.row_data.items(.arena), + self.row_data.items(.cells), + ) |state, *cells| { + var arena: ArenaAllocator = state.promote(alloc); + arena.deinit(); + cells.deinit(alloc); + } + self.row_data.deinit(alloc); + } + + /// Update the render state to the latest terminal state. + /// + /// This will reset the terminal dirty state since it is consumed + /// by this render state update. + pub fn update( + self: *RenderState, + alloc: Allocator, + t: *Terminal, + ) Allocator.Error!void { + const s: *Screen = t.screens.active; + const viewport_pin = s.pages.getTopLeft(.viewport); + const redraw = redraw: { + // If our screen key changed, we need to do a full rebuild + // because our render state is viewport-specific. + if (t.screens.active_key != self.screen) break :redraw true; + + // If our terminal is dirty at all, we do a full rebuild. These + // dirty values are full-terminal dirty values. + { + const Int = @typeInfo(Terminal.Dirty).@"struct".backing_integer.?; + const v: Int = @bitCast(t.flags.dirty); + if (v > 0) break :redraw true; + } + + // If our screen is dirty at all, we do a full rebuild. This is + // a full screen dirty tracker. + { + const Int = @typeInfo(Screen.Dirty).@"struct".backing_integer.?; + const v: Int = @bitCast(t.screens.active.dirty); + if (v > 0) break :redraw true; + } + + // If our dimensions changed, we do a full rebuild. + if (self.rows != s.pages.rows or + self.cols != s.pages.cols) + { + break :redraw true; + } + + // If our viewport pin changed, we do a full rebuild. + if (self.viewport_pin) |old| { + if (!old.eql(viewport_pin)) break :redraw true; + } + + break :redraw false; + }; + + // Always set our cheap fields, its more expensive to compare + self.rows = s.pages.rows; + self.cols = s.pages.cols; + self.viewport_pin = viewport_pin; + self.cursor.active = .{ .x = s.cursor.x, .y = s.cursor.y }; + self.cursor.cell = s.cursor.page_cell.*; + self.cursor.style = s.cursor.style; + self.cursor.visual_style = s.cursor.cursor_style; + self.cursor.password_input = t.flags.password_input; + self.cursor.visible = t.modes.get(.cursor_visible); + self.cursor.blinking = t.modes.get(.cursor_blinking); + + // Always reset the cursor viewport position. In the future we can + // probably cache this by comparing the cursor pin and viewport pin + // but may not be worth it. + self.cursor.viewport = null; + + // Colors. + self.colors.cursor = t.colors.cursor.get(); + self.colors.palette = t.colors.palette.current; + bg_fg: { + // Background/foreground can be unset initially which would + // depend on "default" background/foreground. The expected use + // case of Terminal is that the caller set their own configured + // defaults on load so this doesn't happen. + const bg = t.colors.background.get() orelse break :bg_fg; + const fg = t.colors.foreground.get() orelse break :bg_fg; + if (t.modes.get(.reverse_colors)) { + self.colors.background = fg; + self.colors.foreground = bg; + } else { + self.colors.background = bg; + self.colors.foreground = fg; + } + } + + // Ensure our row length is exactly our height, freeing or allocating + // data as necessary. In most cases we'll have a perfectly matching + // size. + if (self.row_data.len != self.rows) { + @branchHint(.unlikely); + + if (self.row_data.len < self.rows) { + // Resize our rows to the desired length, marking any added + // values undefined. + const old_len = self.row_data.len; + try self.row_data.resize(alloc, self.rows); + + // Initialize all our values. Its faster to use slice() + set() + // because appendAssumeCapacity does this multiple times. + var row_data = self.row_data.slice(); + for (old_len..self.rows) |y| { + row_data.set(y, .{ + .arena = .{}, + .pin = undefined, + .raw = undefined, + .cells = .empty, + .dirty = true, + .selection = null, + .highlights = .empty, + }); + } + } else { + const row_data = self.row_data.slice(); + for ( + row_data.items(.arena)[self.rows..], + row_data.items(.cells)[self.rows..], + ) |state, *cell| { + var arena: ArenaAllocator = state.promote(alloc); + arena.deinit(); + cell.deinit(alloc); + } + self.row_data.shrinkRetainingCapacity(self.rows); + } + } + + // Break down our row data + const row_data = self.row_data.slice(); + const row_arenas = row_data.items(.arena); + const row_pins = row_data.items(.pin); + const row_rows = row_data.items(.raw); + const row_cells = row_data.items(.cells); + const row_sels = row_data.items(.selection); + const row_highlights = row_data.items(.highlights); + const row_dirties = row_data.items(.dirty); + + // Track the last page that we know was dirty. This lets us + // more quickly do the full-page dirty check. + var last_dirty_page: ?*page.Page = null; + + // Go through and setup our rows. + var row_it = s.pages.rowIterator( + .right_down, + .{ .viewport = .{} }, + null, + ); + var y: size.CellCountInt = 0; + var any_dirty: bool = false; + while (row_it.next()) |row_pin| : (y = y + 1) { + // Find our cursor if we haven't found it yet. We do this even + // if the row is not dirty because the cursor is unrelated. + if (self.cursor.viewport == null and + row_pin.node == s.cursor.page_pin.node and + row_pin.y == s.cursor.page_pin.y) + { + self.cursor.viewport = .{ + .y = y, + .x = s.cursor.x, + + // Future: we should use our own state here to look this + // up rather than calling this. + .wide_tail = if (s.cursor.x > 0) + s.cursorCellLeft(1).wide == .wide + else + false, + }; + } + + // Store our pin. We have to store these even if we're not dirty + // because dirty is only a renderer optimization. It doesn't + // apply to memory movement. This will let us remap any cell + // pins back to an exact entry in our RenderState. + row_pins[y] = row_pin; + + // Get all our cells in the page. + const p: *page.Page = &row_pin.node.data; + const page_rac = row_pin.rowAndCell(); + + dirty: { + // If we're redrawing then we're definitely dirty. + if (redraw) break :dirty; + + // If our page is the same as last time then its dirty. + if (p == last_dirty_page) break :dirty; + if (p.dirty) { + // If this page is dirty then clear the dirty flag + // of the last page and then store this one. This benchmarks + // faster than iterating pages again later. + if (last_dirty_page) |last_p| last_p.dirty = false; + last_dirty_page = p; + break :dirty; + } + + // If our row is dirty then we're dirty. + if (page_rac.row.dirty) break :dirty; + + // Not dirty! + continue; + } + + // Set that at least one row was dirty. + any_dirty = true; + + // Clear our row dirty, we'll clear our page dirty later. + // We can't clear it now because we have more rows to go through. + page_rac.row.dirty = false; + + // Promote our arena. State is copied by value so we need to + // restore it on all exit paths so we don't leak memory. + var arena = row_arenas[y].promote(alloc); + defer row_arenas[y] = arena.state; + + // Reset our cells if we're rebuilding this row. + if (row_cells[y].len > 0) { + _ = arena.reset(.retain_capacity); + row_cells[y].clearRetainingCapacity(); + row_sels[y] = null; + row_highlights[y] = .empty; + } + row_dirties[y] = true; + + // Get all our cells in the page. + const page_cells: []const page.Cell = p.getCells(page_rac.row); + assert(page_cells.len == self.cols); + + // Copy our raw row data + row_rows[y] = page_rac.row.*; + + // Note: our cells MultiArrayList uses our general allocator. + // We do this on purpose because as rows become dirty, we do + // not want to reallocate space for cells (which are large). This + // was a source of huge slowdown. + // + // Our per-row arena is only used for temporary allocations + // pertaining to cells directly (e.g. graphemes, hyperlinks). + const cells: *std.MultiArrayList(Cell) = &row_cells[y]; + try cells.resize(alloc, self.cols); + + // We always copy our raw cell data. In the case we have no + // managed memory, we can skip setting any other fields. + // + // This is an important optimization. For plain-text screens + // this ends up being something around 300% faster based on + // the `screen-clone` benchmark. + const cells_slice = cells.slice(); + fastmem.copy( + page.Cell, + cells_slice.items(.raw), + page_cells, + ); + if (!page_rac.row.managedMemory()) continue; + + const arena_alloc = arena.allocator(); + const cells_grapheme = cells_slice.items(.grapheme); + const cells_style = cells_slice.items(.style); + for (page_cells, 0..) |*page_cell, x| { + // Append assuming its a single-codepoint, styled cell + // (most common by far). + if (page_cell.style_id > 0) cells_style[x] = p.styles.get( + p.memory, + page_cell.style_id, + ).*; + + // Switch on our content tag to handle less likely cases. + switch (page_cell.content_tag) { + .codepoint => { + @branchHint(.likely); + // Primary codepoint goes into `raw` field. + }, + + // If we have a multi-codepoint grapheme, look it up and + // set our content type. + .codepoint_grapheme => { + @branchHint(.unlikely); + cells_grapheme[x] = try arena_alloc.dupe( + u21, + p.lookupGrapheme(page_cell) orelse &.{}, + ); + }, + + .bg_color_rgb => { + @branchHint(.unlikely); + cells_style[x] = .{ .bg_color = .{ .rgb = .{ + .r = page_cell.content.color_rgb.r, + .g = page_cell.content.color_rgb.g, + .b = page_cell.content.color_rgb.b, + } } }; + }, + + .bg_color_palette => { + @branchHint(.unlikely); + cells_style[x] = .{ .bg_color = .{ + .palette = page_cell.content.color_palette, + } }; + }, + } + } + } + assert(y == self.rows); + + // If our screen has a selection, then mark the rows with the + // selection. We do this outside of the loop above because its unlikely + // a selection exists and because the way our selections are structured + // today is very inefficient. + // + // NOTE: To improve the performance of the block below, we'll need + // to rethink how we model selections in general. + // + // There are performance improvements that can be made here, though. + // For example, `containedRow` recalculates a bunch of information + // we can cache. + if (s.selection) |*sel| selection: { + @branchHint(.unlikely); + + // Populate our selection cache to avoid some expensive + // recalculation. + const cache: *const SelectionCache = cache: { + if (self.selection_cache) |*c| cache_check: { + // If we're redrawing, we recalculate the cache just to + // be safe. + if (redraw) break :cache_check; + + // If our selection isn't equal, we aren't cached! + if (!c.selection.eql(sel.*)) break :cache_check; + + // If we have no dirty rows, we can not recalculate. + if (!any_dirty) break :selection; + + // We have dirty rows, we can utilize the cache. + break :cache c; + } + + // Create a new cache + const tl_pin = sel.topLeft(s); + const br_pin = sel.bottomRight(s); + self.selection_cache = .{ + .selection = .init(tl_pin, br_pin, sel.rectangle), + .tl_pin = tl_pin, + .br_pin = br_pin, + }; + break :cache &self.selection_cache.?; + }; + + // Grab the inefficient data we need from the selection. At + // least we can cache it. + const tl = s.pages.pointFromPin(.screen, cache.tl_pin).?.screen; + const br = s.pages.pointFromPin(.screen, cache.br_pin).?.screen; + + // We need to determine if our selection is within the viewport. + // The viewport is generally very small so the efficient way to + // do this is to traverse the viewport pages and check for the + // matching selection pages. + for ( + row_pins, + row_sels, + ) |pin, *sel_bounds| { + const p = s.pages.pointFromPin(.screen, pin).?.screen; + const row_sel = sel.containedRowCached( + s, + cache.tl_pin, + cache.br_pin, + pin, + tl, + br, + p, + ) orelse continue; + const start = row_sel.start(); + const end = row_sel.end(); + assert(start.node == end.node); + assert(start.x <= end.x); + assert(start.y == end.y); + sel_bounds.* = .{ start.x, end.x }; + } + } + + // Handle dirty state. + if (redraw) { + // Fully redraw resets some other state. + self.screen = t.screens.active_key; + self.dirty = .full; + + // Note: we don't clear any row_data here because our rebuild + // above did this. + } else if (any_dirty and self.dirty == .false) { + self.dirty = .partial; + } + + // Finalize our final dirty page + if (last_dirty_page) |last_p| last_p.dirty = false; + + // Clear our dirty flags + t.flags.dirty = .{}; + s.dirty = .{}; + } + + /// Update the highlights in the render state from the given flattened + /// highlights. Because this uses flattened highlights, it does not require + /// reading from the terminal state so it should be done outside of + /// any critical sections. + /// + /// This will not clear any previous highlights, so the caller must + /// manually clear them if desired. + pub fn updateHighlightsFlattened( + self: *RenderState, + alloc: Allocator, + tag: u8, + hls: []const highlight.Flattened, + ) Allocator.Error!void { + // Fast path, we have no highlights! + if (hls.len == 0) return; + + // This is, admittedly, horrendous. This is some low hanging fruit + // to optimize. In my defense, screens are usually small, the number + // of highlights is usually small, and this only happens on the + // viewport outside of a locked area. Still, I'd love to see this + // improved someday. + + // We need to track whether any row had a match so we can mark + // the dirty state. + var any_dirty: bool = false; + + const row_data = self.row_data.slice(); + const row_arenas = row_data.items(.arena); + const row_dirties = row_data.items(.dirty); + const row_pins = row_data.items(.pin); + const row_highlights_slice = row_data.items(.highlights); + for ( + row_arenas, + row_pins, + row_highlights_slice, + row_dirties, + ) |*row_arena, row_pin, *row_highlights, *dirty| { + for (hls) |hl| { + const chunks_slice = hl.chunks.slice(); + const nodes = chunks_slice.items(.node); + const starts = chunks_slice.items(.start); + const ends = chunks_slice.items(.end); + for (0.., nodes) |i, node| { + // If this node doesn't match or we're not within + // the row range, skip it. + if (node != row_pin.node or + row_pin.y < starts[i] or + row_pin.y >= ends[i]) continue; + + // We're a match! + var arena = row_arena.promote(alloc); + defer row_arena.* = arena.state; + const arena_alloc = arena.allocator(); + try row_highlights.append( + arena_alloc, + .{ + .tag = tag, + .range = .{ + if (i == 0 and + row_pin.y == starts[0]) + hl.top_x + else + 0, + if (i == nodes.len - 1 and + row_pin.y == ends[nodes.len - 1] - 1) + hl.bot_x + else + self.cols - 1, + }, + }, + ); + + dirty.* = true; + any_dirty = true; + } + } + } + + // Mark our dirty state. + if (any_dirty and self.dirty == .false) self.dirty = .partial; + } + + pub const StringMap = std.ArrayListUnmanaged(point.Coordinate); + + /// Convert the current render state contents to a UTF-8 encoded + /// string written to the given writer. This will unwrap all the wrapped + /// rows. This is useful for a minimal viewport search. + /// + /// This currently writes empty cell contents as \x00 and writes all + /// blank lines. This is fine for our current usage (link search) but + /// we can adjust this later. + /// + /// NOTE: There is a limitation in that wrapped lines before/after + /// the top/bottom line of the viewport are not included, since + /// the render state cuts them off. + pub fn string( + self: *const RenderState, + writer: *std.Io.Writer, + map: ?struct { + alloc: Allocator, + map: *StringMap, + }, + ) (Allocator.Error || std.Io.Writer.Error)!void { + const row_slice = self.row_data.slice(); + const row_rows = row_slice.items(.raw); + const row_cells = row_slice.items(.cells); + + for ( + 0.., + row_rows, + row_cells, + ) |y, row, cells| { + const cells_slice = cells.slice(); + for ( + 0.., + cells_slice.items(.raw), + cells_slice.items(.grapheme), + ) |x, cell, graphemes| { + var len: usize = std.unicode.utf8CodepointSequenceLength(cell.codepoint()) catch + return error.WriteFailed; + try writer.print("{u}", .{cell.codepoint()}); + if (cell.hasGrapheme()) { + for (graphemes) |cp| { + len += std.unicode.utf8CodepointSequenceLength(cp) catch + return error.WriteFailed; + try writer.print("{u}", .{cp}); + } + } + + if (map) |m| try m.map.appendNTimes(m.alloc, .{ + .x = @intCast(x), + .y = @intCast(y), + }, len); + } + + if (!row.wrap) { + try writer.writeAll("\n"); + if (map) |m| try m.map.append(m.alloc, .{ + .x = @intCast(cells_slice.len), + .y = @intCast(y), + }); + } + } + } + + /// A set of coordinates representing cells. + pub const CellSet = std.AutoArrayHashMapUnmanaged(point.Coordinate, void); + + /// Returns a map of the cells that match to an OSC8 hyperlink over the + /// given point in the render state. + /// + /// IMPORTANT: The terminal must not have updated since the last call to + /// `update`. If there is any chance the terminal has updated, the caller + /// must first call `update` again to refresh the render state. + /// + /// For example, you may want to hold a lock for the duration of the + /// update and hyperlink lookup to ensure no updates happen in between. + pub fn linkCells( + self: *const RenderState, + alloc: Allocator, + viewport_point: point.Coordinate, + ) Allocator.Error!CellSet { + var result: CellSet = .empty; + errdefer result.deinit(alloc); + + const row_slice = self.row_data.slice(); + const row_pins = row_slice.items(.pin); + const row_cells = row_slice.items(.cells); + + // Our viewport point is sent in by the caller and can't be trusted. + // If it is outside the valid area then just return empty because + // we can't possibly have a link there. + if (viewport_point.x >= self.cols or + viewport_point.y >= row_pins.len) return result; + + // Grab our link ID + const link_pin: PageList.Pin = row_pins[viewport_point.y]; + const link_page: *page.Page = &link_pin.node.data; + const link = link: { + const rac = link_page.getRowAndCell( + viewport_point.x, + link_pin.y, + ); + + // The likely scenario is that our mouse isn't even over a link. + if (!rac.cell.hyperlink) { + @branchHint(.likely); + return result; + } + + const link_id = link_page.lookupHyperlink(rac.cell) orelse + return result; + break :link link_page.hyperlink_set.get( + link_page.memory, + link_id, + ); + }; + + for ( + 0.., + row_pins, + row_cells, + ) |y, pin, cells| { + for (0.., cells.items(.raw)) |x, cell| { + if (!cell.hyperlink) continue; + + const other_page: *page.Page = &pin.node.data; + const other = link: { + const rac = other_page.getRowAndCell(x, pin.y); + const link_id = other_page.lookupHyperlink(rac.cell) orelse continue; + break :link other_page.hyperlink_set.get( + other_page.memory, + link_id, + ); + }; + + if (link.eql( + link_page.memory, + other, + other_page.memory, + )) try result.put(alloc, .{ + .y = @intCast(y), + .x = @intCast(x), + }, {}); + } + } + + return result; + } +}; + +test "styled" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 80, + .rows = 24, + }); + defer t.deinit(alloc); + + // This fills the screen up + try t.decaln(); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); +} + +test "basic text" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("ABCD"); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + // Verify we have the right number of rows + const row_data = state.row_data.slice(); + try testing.expectEqual(3, row_data.len); + + // All rows should have cols cells + const cells = row_data.items(.cells); + try testing.expectEqual(10, cells[0].len); + try testing.expectEqual(10, cells[1].len); + try testing.expectEqual(10, cells[2].len); + + // Row zero should contain our text + try testing.expectEqual('A', cells[0].get(0).raw.codepoint()); + try testing.expectEqual('B', cells[0].get(1).raw.codepoint()); + try testing.expectEqual('C', cells[0].get(2).raw.codepoint()); + try testing.expectEqual('D', cells[0].get(3).raw.codepoint()); + try testing.expectEqual(0, cells[0].get(4).raw.codepoint()); +} + +test "styled text" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("\x1b[1mA"); // Bold + s.nextSlice("\x1b[0;3mB"); // Italic + s.nextSlice("\x1b[0;4mC"); // Underline + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + // Verify we have the right number of rows + const row_data = state.row_data.slice(); + try testing.expectEqual(3, row_data.len); + + // All rows should have cols cells + const cells = row_data.items(.cells); + try testing.expectEqual(10, cells[0].len); + try testing.expectEqual(10, cells[1].len); + try testing.expectEqual(10, cells[2].len); + + // Row zero should contain our text + { + const cell = cells[0].get(0); + try testing.expectEqual('A', cell.raw.codepoint()); + try testing.expect(cell.style.flags.bold); + } + { + const cell = cells[0].get(1); + try testing.expectEqual('B', cell.raw.codepoint()); + try testing.expect(!cell.style.flags.bold); + try testing.expect(cell.style.flags.italic); + } + try testing.expectEqual('C', cells[0].get(2).raw.codepoint()); + try testing.expectEqual(0, cells[0].get(3).raw.codepoint()); +} + +test "grapheme" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("A"); + s.nextSlice("👨‍"); // this has a ZWJ + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + // Verify we have the right number of rows + const row_data = state.row_data.slice(); + try testing.expectEqual(3, row_data.len); + + // All rows should have cols cells + const cells = row_data.items(.cells); + try testing.expectEqual(10, cells[0].len); + try testing.expectEqual(10, cells[1].len); + try testing.expectEqual(10, cells[2].len); + + // Row zero should contain our text + { + const cell = cells[0].get(0); + try testing.expectEqual('A', cell.raw.codepoint()); + } + { + const cell = cells[0].get(1); + try testing.expectEqual(0x1F468, cell.raw.codepoint()); + try testing.expectEqual(.wide, cell.raw.wide); + try testing.expectEqualSlices(u21, &.{0x200D}, cell.grapheme); + } + { + const cell = cells[0].get(2); + try testing.expectEqual(0, cell.raw.codepoint()); + try testing.expectEqual(.spacer_tail, cell.raw.wide); + } +} + +test "cursor state in viewport" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("A\x1b[H"); + + var state: RenderState = .empty; + defer state.deinit(alloc); + + // Initial update + try state.update(alloc, &t); + try testing.expectEqual(0, state.cursor.active.x); + try testing.expectEqual(0, state.cursor.active.y); + try testing.expectEqual(0, state.cursor.viewport.?.x); + try testing.expectEqual(0, state.cursor.viewport.?.y); + try testing.expectEqual('A', state.cursor.cell.codepoint()); + try testing.expect(state.cursor.style.default()); + + // Set a style on the cursor + s.nextSlice("\x1b[1m"); // Bold + try state.update(alloc, &t); + try testing.expect(!state.cursor.style.default()); + try testing.expect(state.cursor.style.flags.bold); + s.nextSlice("\x1b[0m"); // Reset style + + // Move cursor to 2,1 + s.nextSlice("\x1b[2;3H"); + try state.update(alloc, &t); + try testing.expectEqual(2, state.cursor.active.x); + try testing.expectEqual(1, state.cursor.active.y); + try testing.expectEqual(2, state.cursor.viewport.?.x); + try testing.expectEqual(1, state.cursor.viewport.?.y); +} + +test "cursor state out of viewport" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 2, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("A\r\nB\r\nC\r\nD\r\n"); + + var state: RenderState = .empty; + defer state.deinit(alloc); + + // Initial update + try state.update(alloc, &t); + try testing.expectEqual(0, state.cursor.active.x); + try testing.expectEqual(1, state.cursor.active.y); + try testing.expectEqual(0, state.cursor.viewport.?.x); + try testing.expectEqual(1, state.cursor.viewport.?.y); + + // Scroll the viewport + t.scrollViewport(.top); + try state.update(alloc, &t); + + // Set a style on the cursor + try testing.expectEqual(0, state.cursor.active.x); + try testing.expectEqual(1, state.cursor.active.y); + try testing.expect(state.cursor.viewport == null); +} + +test "dirty state" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + var state: RenderState = .empty; + defer state.deinit(alloc); + + // First update should trigger redraw due to resize + try state.update(alloc, &t); + try testing.expectEqual(.full, state.dirty); + + // Reset dirty flag and dirty rows + state.dirty = .false; + { + const row_data = state.row_data.slice(); + const dirty = row_data.items(.dirty); + @memset(dirty, false); + } + + // Second update with no changes - no dirty rows + try state.update(alloc, &t); + try testing.expectEqual(.false, state.dirty); + { + const row_data = state.row_data.slice(); + const dirty = row_data.items(.dirty); + for (dirty) |d| try testing.expect(!d); + } + + // Write to first line + s.nextSlice("A"); + try state.update(alloc, &t); + try testing.expectEqual(.partial, state.dirty); + { + const row_data = state.row_data.slice(); + const dirty = row_data.items(.dirty); + try testing.expect(dirty[0]); // First row dirty + try testing.expect(!dirty[1]); // Second row clean + } +} + +test "colors" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + var state: RenderState = .empty; + defer state.deinit(alloc); + + // Default colors + try state.update(alloc, &t); + + // Change cursor color + s.nextSlice("\x1b]12;#FF0000\x07"); + try state.update(alloc, &t); + + const c = state.colors.cursor.?; + try testing.expectEqual(0xFF, c.r); + try testing.expectEqual(0, c.g); + try testing.expectEqual(0, c.b); + + // Change palette color 0 to White + s.nextSlice("\x1b]4;0;#FFFFFF\x07"); + try state.update(alloc, &t); + const p0 = state.colors.palette[0]; + try testing.expectEqual(0xFF, p0.r); + try testing.expectEqual(0xFF, p0.g); + try testing.expectEqual(0xFF, p0.b); +} + +test "selection single line" { + const testing = std.testing; + const alloc = testing.allocator; + + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + const screen: *Screen = t.screens.active; + try screen.select(.init( + screen.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + screen.pages.pin(.{ .active = .{ .x = 2, .y = 1 } }).?, + false, + )); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + const row_data = state.row_data.slice(); + const sels = row_data.items(.selection); + try testing.expectEqual(null, sels[0]); + try testing.expectEqualSlices(size.CellCountInt, &.{ 0, 2 }, &sels[1].?); + try testing.expectEqual(null, sels[2]); + + // Clear the selection + try screen.select(null); + try state.update(alloc, &t); + try testing.expectEqual(null, sels[0]); + try testing.expectEqual(null, sels[1]); + try testing.expectEqual(null, sels[2]); +} + +test "selection multiple lines" { + const testing = std.testing; + const alloc = testing.allocator; + + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + const screen: *Screen = t.screens.active; + try screen.select(.init( + screen.pages.pin(.{ .active = .{ .x = 0, .y = 1 } }).?, + screen.pages.pin(.{ .active = .{ .x = 2, .y = 2 } }).?, + false, + )); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + const row_data = state.row_data.slice(); + const sels = row_data.items(.selection); + try testing.expectEqual(null, sels[0]); + try testing.expectEqualSlices( + size.CellCountInt, + &.{ 0, screen.pages.cols - 1 }, + &sels[1].?, + ); + try testing.expectEqualSlices( + size.CellCountInt, + &.{ 0, 2 }, + &sels[2].?, + ); +} + +test "linkCells" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + var state: RenderState = .empty; + defer state.deinit(alloc); + + // Create a hyperlink + s.nextSlice("\x1b]8;;http://example.com\x1b\\LINK\x1b]8;;\x1b\\"); + try state.update(alloc, &t); + + // Query link at 0,0 + var cells = try state.linkCells(alloc, .{ .x = 0, .y = 0 }); + defer cells.deinit(alloc); + + try testing.expectEqual(4, cells.count()); + try testing.expect(cells.contains(.{ .x = 0, .y = 0 })); + try testing.expect(cells.contains(.{ .x = 1, .y = 0 })); + try testing.expect(cells.contains(.{ .x = 2, .y = 0 })); + try testing.expect(cells.contains(.{ .x = 3, .y = 0 })); + + // Query no link + var cells2 = try state.linkCells(alloc, .{ .x = 4, .y = 0 }); + defer cells2.deinit(alloc); + try testing.expectEqual(0, cells2.count()); +} + +test "string" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 5, + .rows = 2, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("AB"); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + var w = std.Io.Writer.Allocating.init(alloc); + defer w.deinit(); + + try state.string(&w.writer, null); + + const result = try w.toOwnedSlice(); + defer alloc.free(result); + + const expected = "AB\x00\x00\x00\n\x00\x00\x00\x00\x00\n"; + try testing.expectEqualStrings(expected, result); +} + +test "linkCells with scrollback spanning pages" { + const testing = std.testing; + const alloc = testing.allocator; + + const viewport_rows: size.CellCountInt = 10; + const tail_rows: size.CellCountInt = 5; + + var t = try Terminal.init(alloc, .{ + .cols = page.std_capacity.cols, + .rows = viewport_rows, + .max_scrollback = 10_000, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const pages = &t.screens.active.pages; + const first_page_cap = pages.pages.first.?.data.capacity.rows; + + // Fill first page + for (0..first_page_cap - 1) |_| s.nextSlice("\r\n"); + + // Create second page with hyperlink + s.nextSlice("\r\n"); + s.nextSlice("\x1b]8;;http://example.com\x1b\\LINK\x1b]8;;\x1b\\"); + for (0..(tail_rows - 1)) |_| s.nextSlice("\r\n"); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + const expected_viewport_y: usize = viewport_rows - tail_rows; + // BUG: This crashes without the fix + var cells = try state.linkCells(alloc, .{ + .x = 0, + .y = expected_viewport_y, + }); + defer cells.deinit(alloc); + try testing.expectEqual(@as(usize, 4), cells.count()); +} + +test "linkCells with invalid viewport point" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 5, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + // Row out of bound + { + var cells = try state.linkCells( + alloc, + .{ .x = 0, .y = t.rows + 10 }, + ); + defer cells.deinit(alloc); + try testing.expectEqual(0, cells.count()); + } + + // Col out of bound + { + var cells = try state.linkCells( + alloc, + .{ .x = t.cols + 10, .y = 0 }, + ); + defer cells.deinit(alloc); + try testing.expectEqual(0, cells.count()); + } +} + +test "dirty row resets highlights" { + const testing = std.testing; + const alloc = testing.allocator; + + var t = try Terminal.init(alloc, .{ + .cols = 10, + .rows = 3, + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("ABC"); + + var state: RenderState = .empty; + defer state.deinit(alloc); + try state.update(alloc, &t); + + // Reset dirty state + state.dirty = .false; + { + const row_data = state.row_data.slice(); + const dirty = row_data.items(.dirty); + @memset(dirty, false); + } + + // Manually add a highlight to row 0 + { + const row_data = state.row_data.slice(); + const row_arenas = row_data.items(.arena); + const row_highlights = row_data.items(.highlights); + var arena = row_arenas[0].promote(alloc); + defer row_arenas[0] = arena.state; + try row_highlights[0].append(arena.allocator(), .{ + .tag = 1, + .range = .{ 0, 2 }, + }); + } + + // Verify we have a highlight + { + const row_data = state.row_data.slice(); + const row_highlights = row_data.items(.highlights); + try testing.expectEqual(1, row_highlights[0].items.len); + } + + // Write to row 0 to make it dirty + s.nextSlice("\x1b[H"); // Move to home + s.nextSlice("X"); + try state.update(alloc, &t); + + // Verify the highlight was reset on the dirty row + { + const row_data = state.row_data.slice(); + const row_highlights = row_data.items(.highlights); + try testing.expectEqual(0, row_highlights[0].items.len); + } +} diff --git a/vendor/libghostty-vt/src/terminal/res/glitch.txt b/vendor/libghostty-vt/src/terminal/res/glitch.txt new file mode 100644 index 00000000..f401c088 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/res/glitch.txt @@ -0,0 +1 @@ +Ḡ̴͎͍̜͎͔͕̩̗͕͖̟̜͑̊̌̇̑͒͋͑̄̈́͐̈́́̽͌͂̎̀̔͋̓́̅̌̇͘̕͜͝͝h̶̡̞̫͉̳̬̜̱̥͕͑̾͛̒̆̒̉̒̑͂̄͘ͅǫ̷̨̥͔͔͖̭͚͙̯̟̭̘͇̫̰͚̺̳̙̳̟͚̫̱̹̱͒̂̑͒͜͠ͅş̴̖̰̜̱̹͙̅͒̀̏͆̐̋͂̓͋̃̈̔̂̈͛̐̿̔́̔̄͑̇͑̋̈́͌͋̾̃̽̈́̕͘̚͘͘͘͠͠t̵̢̜̱̦͇͉̬̮̼͖̳̗̥̝̬͇͕̥̜͕̳̱̥̮͉̮̩̘̰̪̤͉͎̲͈͍̳̟̠͈̝̫͋̊̀͐̍̅̀̄̃̈́̔̇̈́̄̃̽̂̌̅̄̋͒̃̈́̍̀̍̇̽̐͊̾̆̅̈̿̓͒̄̾͌̚͝͝͝͝͝t̴̥̼̳̗̬̬͔͎̯͉͇̮̰͖͇̝͔̳̳̗̰͇͎͉̬͇̝̺̯͎͖͔̍͆͒̊̒̔̊̈́̿̊̅͂̐͋̿͂̈̒̄͜͠͠ÿ̴̢̗̜̥͇͖̰͎̝̹̗̪̙̞̣̳͎̯̹͚̲̝̗̳̳̗̖͎̗̬͈͙̝̟͍̥̤͖͇̰͈̺͛̒̂͌̌̏̈̾̓̈́̿͐̂̓̔̓̂̈́͑͛͊͋̔̿̊͑͌̊̏͘͘̕͘͠͝ diff --git a/vendor/libghostty-vt/src/terminal/res/rgb.txt b/vendor/libghostty-vt/src/terminal/res/rgb.txt new file mode 100644 index 00000000..70966437 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/res/rgb.txt @@ -0,0 +1,782 @@ +255 250 250 snow +248 248 255 ghost white +248 248 255 GhostWhite +245 245 245 white smoke +245 245 245 WhiteSmoke +220 220 220 gainsboro +255 250 240 floral white +255 250 240 FloralWhite +253 245 230 old lace +253 245 230 OldLace +250 240 230 linen +250 235 215 antique white +250 235 215 AntiqueWhite +255 239 213 papaya whip +255 239 213 PapayaWhip +255 235 205 blanched almond +255 235 205 BlanchedAlmond +255 228 196 bisque +255 218 185 peach puff +255 218 185 PeachPuff +255 222 173 navajo white +255 222 173 NavajoWhite +255 228 181 moccasin +255 248 220 cornsilk +255 255 240 ivory +255 250 205 lemon chiffon +255 250 205 LemonChiffon +255 245 238 seashell +240 255 240 honeydew +245 255 250 mint cream +245 255 250 MintCream +240 255 255 azure +240 248 255 alice blue +240 248 255 AliceBlue +230 230 250 lavender +255 240 245 lavender blush +255 240 245 LavenderBlush +255 228 225 misty rose +255 228 225 MistyRose +255 255 255 white + 0 0 0 black + 47 79 79 dark slate gray + 47 79 79 DarkSlateGray + 47 79 79 dark slate grey + 47 79 79 DarkSlateGrey +105 105 105 dim gray +105 105 105 DimGray +105 105 105 dim grey +105 105 105 DimGrey +112 128 144 slate gray +112 128 144 SlateGray +112 128 144 slate grey +112 128 144 SlateGrey +119 136 153 light slate gray +119 136 153 LightSlateGray +119 136 153 light slate grey +119 136 153 LightSlateGrey +190 190 190 gray +190 190 190 grey +190 190 190 x11 gray +190 190 190 X11Gray +190 190 190 x11 grey +190 190 190 X11Grey +128 128 128 web gray +128 128 128 WebGray +128 128 128 web grey +128 128 128 WebGrey +211 211 211 light grey +211 211 211 LightGrey +211 211 211 light gray +211 211 211 LightGray + 25 25 112 midnight blue + 25 25 112 MidnightBlue + 0 0 128 navy + 0 0 128 navy blue + 0 0 128 NavyBlue +100 149 237 cornflower blue +100 149 237 CornflowerBlue + 72 61 139 dark slate blue + 72 61 139 DarkSlateBlue +106 90 205 slate blue +106 90 205 SlateBlue +123 104 238 medium slate blue +123 104 238 MediumSlateBlue +132 112 255 light slate blue +132 112 255 LightSlateBlue + 0 0 205 medium blue + 0 0 205 MediumBlue + 65 105 225 royal blue + 65 105 225 RoyalBlue + 0 0 255 blue + 30 144 255 dodger blue + 30 144 255 DodgerBlue + 0 191 255 deep sky blue + 0 191 255 DeepSkyBlue +135 206 235 sky blue +135 206 235 SkyBlue +135 206 250 light sky blue +135 206 250 LightSkyBlue + 70 130 180 steel blue + 70 130 180 SteelBlue +176 196 222 light steel blue +176 196 222 LightSteelBlue +173 216 230 light blue +173 216 230 LightBlue +176 224 230 powder blue +176 224 230 PowderBlue +175 238 238 pale turquoise +175 238 238 PaleTurquoise + 0 206 209 dark turquoise + 0 206 209 DarkTurquoise + 72 209 204 medium turquoise + 72 209 204 MediumTurquoise + 64 224 208 turquoise + 0 255 255 cyan + 0 255 255 aqua +224 255 255 light cyan +224 255 255 LightCyan + 95 158 160 cadet blue + 95 158 160 CadetBlue +102 205 170 medium aquamarine +102 205 170 MediumAquamarine +127 255 212 aquamarine + 0 100 0 dark green + 0 100 0 DarkGreen + 85 107 47 dark olive green + 85 107 47 DarkOliveGreen +143 188 143 dark sea green +143 188 143 DarkSeaGreen + 46 139 87 sea green + 46 139 87 SeaGreen + 60 179 113 medium sea green + 60 179 113 MediumSeaGreen + 32 178 170 light sea green + 32 178 170 LightSeaGreen +152 251 152 pale green +152 251 152 PaleGreen + 0 255 127 spring green + 0 255 127 SpringGreen +124 252 0 lawn green +124 252 0 LawnGreen + 0 255 0 green + 0 255 0 lime + 0 255 0 x11 green + 0 255 0 X11Green + 0 128 0 web green + 0 128 0 WebGreen +127 255 0 chartreuse + 0 250 154 medium spring green + 0 250 154 MediumSpringGreen +173 255 47 green yellow +173 255 47 GreenYellow + 50 205 50 lime green + 50 205 50 LimeGreen +154 205 50 yellow green +154 205 50 YellowGreen + 34 139 34 forest green + 34 139 34 ForestGreen +107 142 35 olive drab +107 142 35 OliveDrab +189 183 107 dark khaki +189 183 107 DarkKhaki +240 230 140 khaki +238 232 170 pale goldenrod +238 232 170 PaleGoldenrod +250 250 210 light goldenrod yellow +250 250 210 LightGoldenrodYellow +255 255 224 light yellow +255 255 224 LightYellow +255 255 0 yellow +255 215 0 gold +238 221 130 light goldenrod +238 221 130 LightGoldenrod +218 165 32 goldenrod +184 134 11 dark goldenrod +184 134 11 DarkGoldenrod +188 143 143 rosy brown +188 143 143 RosyBrown +205 92 92 indian red +205 92 92 IndianRed +139 69 19 saddle brown +139 69 19 SaddleBrown +160 82 45 sienna +205 133 63 peru +222 184 135 burlywood +245 245 220 beige +245 222 179 wheat +244 164 96 sandy brown +244 164 96 SandyBrown +210 180 140 tan +210 105 30 chocolate +178 34 34 firebrick +165 42 42 brown +233 150 122 dark salmon +233 150 122 DarkSalmon +250 128 114 salmon +255 160 122 light salmon +255 160 122 LightSalmon +255 165 0 orange +255 140 0 dark orange +255 140 0 DarkOrange +255 127 80 coral +240 128 128 light coral +240 128 128 LightCoral +255 99 71 tomato +255 69 0 orange red +255 69 0 OrangeRed +255 0 0 red +255 105 180 hot pink +255 105 180 HotPink +255 20 147 deep pink +255 20 147 DeepPink +255 192 203 pink +255 182 193 light pink +255 182 193 LightPink +219 112 147 pale violet red +219 112 147 PaleVioletRed +176 48 96 maroon +176 48 96 x11 maroon +176 48 96 X11Maroon +128 0 0 web maroon +128 0 0 WebMaroon +199 21 133 medium violet red +199 21 133 MediumVioletRed +208 32 144 violet red +208 32 144 VioletRed +255 0 255 magenta +255 0 255 fuchsia +238 130 238 violet +221 160 221 plum +218 112 214 orchid +186 85 211 medium orchid +186 85 211 MediumOrchid +153 50 204 dark orchid +153 50 204 DarkOrchid +148 0 211 dark violet +148 0 211 DarkViolet +138 43 226 blue violet +138 43 226 BlueViolet +160 32 240 purple +160 32 240 x11 purple +160 32 240 X11Purple +128 0 128 web purple +128 0 128 WebPurple +147 112 219 medium purple +147 112 219 MediumPurple +216 191 216 thistle +255 250 250 snow1 +238 233 233 snow2 +205 201 201 snow3 +139 137 137 snow4 +255 245 238 seashell1 +238 229 222 seashell2 +205 197 191 seashell3 +139 134 130 seashell4 +255 239 219 AntiqueWhite1 +238 223 204 AntiqueWhite2 +205 192 176 AntiqueWhite3 +139 131 120 AntiqueWhite4 +255 228 196 bisque1 +238 213 183 bisque2 +205 183 158 bisque3 +139 125 107 bisque4 +255 218 185 PeachPuff1 +238 203 173 PeachPuff2 +205 175 149 PeachPuff3 +139 119 101 PeachPuff4 +255 222 173 NavajoWhite1 +238 207 161 NavajoWhite2 +205 179 139 NavajoWhite3 +139 121 94 NavajoWhite4 +255 250 205 LemonChiffon1 +238 233 191 LemonChiffon2 +205 201 165 LemonChiffon3 +139 137 112 LemonChiffon4 +255 248 220 cornsilk1 +238 232 205 cornsilk2 +205 200 177 cornsilk3 +139 136 120 cornsilk4 +255 255 240 ivory1 +238 238 224 ivory2 +205 205 193 ivory3 +139 139 131 ivory4 +240 255 240 honeydew1 +224 238 224 honeydew2 +193 205 193 honeydew3 +131 139 131 honeydew4 +255 240 245 LavenderBlush1 +238 224 229 LavenderBlush2 +205 193 197 LavenderBlush3 +139 131 134 LavenderBlush4 +255 228 225 MistyRose1 +238 213 210 MistyRose2 +205 183 181 MistyRose3 +139 125 123 MistyRose4 +240 255 255 azure1 +224 238 238 azure2 +193 205 205 azure3 +131 139 139 azure4 +131 111 255 SlateBlue1 +122 103 238 SlateBlue2 +105 89 205 SlateBlue3 + 71 60 139 SlateBlue4 + 72 118 255 RoyalBlue1 + 67 110 238 RoyalBlue2 + 58 95 205 RoyalBlue3 + 39 64 139 RoyalBlue4 + 0 0 255 blue1 + 0 0 238 blue2 + 0 0 205 blue3 + 0 0 139 blue4 + 30 144 255 DodgerBlue1 + 28 134 238 DodgerBlue2 + 24 116 205 DodgerBlue3 + 16 78 139 DodgerBlue4 + 99 184 255 SteelBlue1 + 92 172 238 SteelBlue2 + 79 148 205 SteelBlue3 + 54 100 139 SteelBlue4 + 0 191 255 DeepSkyBlue1 + 0 178 238 DeepSkyBlue2 + 0 154 205 DeepSkyBlue3 + 0 104 139 DeepSkyBlue4 +135 206 255 SkyBlue1 +126 192 238 SkyBlue2 +108 166 205 SkyBlue3 + 74 112 139 SkyBlue4 +176 226 255 LightSkyBlue1 +164 211 238 LightSkyBlue2 +141 182 205 LightSkyBlue3 + 96 123 139 LightSkyBlue4 +198 226 255 SlateGray1 +185 211 238 SlateGray2 +159 182 205 SlateGray3 +108 123 139 SlateGray4 +202 225 255 LightSteelBlue1 +188 210 238 LightSteelBlue2 +162 181 205 LightSteelBlue3 +110 123 139 LightSteelBlue4 +191 239 255 LightBlue1 +178 223 238 LightBlue2 +154 192 205 LightBlue3 +104 131 139 LightBlue4 +224 255 255 LightCyan1 +209 238 238 LightCyan2 +180 205 205 LightCyan3 +122 139 139 LightCyan4 +187 255 255 PaleTurquoise1 +174 238 238 PaleTurquoise2 +150 205 205 PaleTurquoise3 +102 139 139 PaleTurquoise4 +152 245 255 CadetBlue1 +142 229 238 CadetBlue2 +122 197 205 CadetBlue3 + 83 134 139 CadetBlue4 + 0 245 255 turquoise1 + 0 229 238 turquoise2 + 0 197 205 turquoise3 + 0 134 139 turquoise4 + 0 255 255 cyan1 + 0 238 238 cyan2 + 0 205 205 cyan3 + 0 139 139 cyan4 +151 255 255 DarkSlateGray1 +141 238 238 DarkSlateGray2 +121 205 205 DarkSlateGray3 + 82 139 139 DarkSlateGray4 +127 255 212 aquamarine1 +118 238 198 aquamarine2 +102 205 170 aquamarine3 + 69 139 116 aquamarine4 +193 255 193 DarkSeaGreen1 +180 238 180 DarkSeaGreen2 +155 205 155 DarkSeaGreen3 +105 139 105 DarkSeaGreen4 + 84 255 159 SeaGreen1 + 78 238 148 SeaGreen2 + 67 205 128 SeaGreen3 + 46 139 87 SeaGreen4 +154 255 154 PaleGreen1 +144 238 144 PaleGreen2 +124 205 124 PaleGreen3 + 84 139 84 PaleGreen4 + 0 255 127 SpringGreen1 + 0 238 118 SpringGreen2 + 0 205 102 SpringGreen3 + 0 139 69 SpringGreen4 + 0 255 0 green1 + 0 238 0 green2 + 0 205 0 green3 + 0 139 0 green4 +127 255 0 chartreuse1 +118 238 0 chartreuse2 +102 205 0 chartreuse3 + 69 139 0 chartreuse4 +192 255 62 OliveDrab1 +179 238 58 OliveDrab2 +154 205 50 OliveDrab3 +105 139 34 OliveDrab4 +202 255 112 DarkOliveGreen1 +188 238 104 DarkOliveGreen2 +162 205 90 DarkOliveGreen3 +110 139 61 DarkOliveGreen4 +255 246 143 khaki1 +238 230 133 khaki2 +205 198 115 khaki3 +139 134 78 khaki4 +255 236 139 LightGoldenrod1 +238 220 130 LightGoldenrod2 +205 190 112 LightGoldenrod3 +139 129 76 LightGoldenrod4 +255 255 224 LightYellow1 +238 238 209 LightYellow2 +205 205 180 LightYellow3 +139 139 122 LightYellow4 +255 255 0 yellow1 +238 238 0 yellow2 +205 205 0 yellow3 +139 139 0 yellow4 +255 215 0 gold1 +238 201 0 gold2 +205 173 0 gold3 +139 117 0 gold4 +255 193 37 goldenrod1 +238 180 34 goldenrod2 +205 155 29 goldenrod3 +139 105 20 goldenrod4 +255 185 15 DarkGoldenrod1 +238 173 14 DarkGoldenrod2 +205 149 12 DarkGoldenrod3 +139 101 8 DarkGoldenrod4 +255 193 193 RosyBrown1 +238 180 180 RosyBrown2 +205 155 155 RosyBrown3 +139 105 105 RosyBrown4 +255 106 106 IndianRed1 +238 99 99 IndianRed2 +205 85 85 IndianRed3 +139 58 58 IndianRed4 +255 130 71 sienna1 +238 121 66 sienna2 +205 104 57 sienna3 +139 71 38 sienna4 +255 211 155 burlywood1 +238 197 145 burlywood2 +205 170 125 burlywood3 +139 115 85 burlywood4 +255 231 186 wheat1 +238 216 174 wheat2 +205 186 150 wheat3 +139 126 102 wheat4 +255 165 79 tan1 +238 154 73 tan2 +205 133 63 tan3 +139 90 43 tan4 +255 127 36 chocolate1 +238 118 33 chocolate2 +205 102 29 chocolate3 +139 69 19 chocolate4 +255 48 48 firebrick1 +238 44 44 firebrick2 +205 38 38 firebrick3 +139 26 26 firebrick4 +255 64 64 brown1 +238 59 59 brown2 +205 51 51 brown3 +139 35 35 brown4 +255 140 105 salmon1 +238 130 98 salmon2 +205 112 84 salmon3 +139 76 57 salmon4 +255 160 122 LightSalmon1 +238 149 114 LightSalmon2 +205 129 98 LightSalmon3 +139 87 66 LightSalmon4 +255 165 0 orange1 +238 154 0 orange2 +205 133 0 orange3 +139 90 0 orange4 +255 127 0 DarkOrange1 +238 118 0 DarkOrange2 +205 102 0 DarkOrange3 +139 69 0 DarkOrange4 +255 114 86 coral1 +238 106 80 coral2 +205 91 69 coral3 +139 62 47 coral4 +255 99 71 tomato1 +238 92 66 tomato2 +205 79 57 tomato3 +139 54 38 tomato4 +255 69 0 OrangeRed1 +238 64 0 OrangeRed2 +205 55 0 OrangeRed3 +139 37 0 OrangeRed4 +255 0 0 red1 +238 0 0 red2 +205 0 0 red3 +139 0 0 red4 +255 20 147 DeepPink1 +238 18 137 DeepPink2 +205 16 118 DeepPink3 +139 10 80 DeepPink4 +255 110 180 HotPink1 +238 106 167 HotPink2 +205 96 144 HotPink3 +139 58 98 HotPink4 +255 181 197 pink1 +238 169 184 pink2 +205 145 158 pink3 +139 99 108 pink4 +255 174 185 LightPink1 +238 162 173 LightPink2 +205 140 149 LightPink3 +139 95 101 LightPink4 +255 130 171 PaleVioletRed1 +238 121 159 PaleVioletRed2 +205 104 137 PaleVioletRed3 +139 71 93 PaleVioletRed4 +255 52 179 maroon1 +238 48 167 maroon2 +205 41 144 maroon3 +139 28 98 maroon4 +255 62 150 VioletRed1 +238 58 140 VioletRed2 +205 50 120 VioletRed3 +139 34 82 VioletRed4 +255 0 255 magenta1 +238 0 238 magenta2 +205 0 205 magenta3 +139 0 139 magenta4 +255 131 250 orchid1 +238 122 233 orchid2 +205 105 201 orchid3 +139 71 137 orchid4 +255 187 255 plum1 +238 174 238 plum2 +205 150 205 plum3 +139 102 139 plum4 +224 102 255 MediumOrchid1 +209 95 238 MediumOrchid2 +180 82 205 MediumOrchid3 +122 55 139 MediumOrchid4 +191 62 255 DarkOrchid1 +178 58 238 DarkOrchid2 +154 50 205 DarkOrchid3 +104 34 139 DarkOrchid4 +155 48 255 purple1 +145 44 238 purple2 +125 38 205 purple3 + 85 26 139 purple4 +171 130 255 MediumPurple1 +159 121 238 MediumPurple2 +137 104 205 MediumPurple3 + 93 71 139 MediumPurple4 +255 225 255 thistle1 +238 210 238 thistle2 +205 181 205 thistle3 +139 123 139 thistle4 + 0 0 0 gray0 + 0 0 0 grey0 + 3 3 3 gray1 + 3 3 3 grey1 + 5 5 5 gray2 + 5 5 5 grey2 + 8 8 8 gray3 + 8 8 8 grey3 + 10 10 10 gray4 + 10 10 10 grey4 + 13 13 13 gray5 + 13 13 13 grey5 + 15 15 15 gray6 + 15 15 15 grey6 + 18 18 18 gray7 + 18 18 18 grey7 + 20 20 20 gray8 + 20 20 20 grey8 + 23 23 23 gray9 + 23 23 23 grey9 + 26 26 26 gray10 + 26 26 26 grey10 + 28 28 28 gray11 + 28 28 28 grey11 + 31 31 31 gray12 + 31 31 31 grey12 + 33 33 33 gray13 + 33 33 33 grey13 + 36 36 36 gray14 + 36 36 36 grey14 + 38 38 38 gray15 + 38 38 38 grey15 + 41 41 41 gray16 + 41 41 41 grey16 + 43 43 43 gray17 + 43 43 43 grey17 + 46 46 46 gray18 + 46 46 46 grey18 + 48 48 48 gray19 + 48 48 48 grey19 + 51 51 51 gray20 + 51 51 51 grey20 + 54 54 54 gray21 + 54 54 54 grey21 + 56 56 56 gray22 + 56 56 56 grey22 + 59 59 59 gray23 + 59 59 59 grey23 + 61 61 61 gray24 + 61 61 61 grey24 + 64 64 64 gray25 + 64 64 64 grey25 + 66 66 66 gray26 + 66 66 66 grey26 + 69 69 69 gray27 + 69 69 69 grey27 + 71 71 71 gray28 + 71 71 71 grey28 + 74 74 74 gray29 + 74 74 74 grey29 + 77 77 77 gray30 + 77 77 77 grey30 + 79 79 79 gray31 + 79 79 79 grey31 + 82 82 82 gray32 + 82 82 82 grey32 + 84 84 84 gray33 + 84 84 84 grey33 + 87 87 87 gray34 + 87 87 87 grey34 + 89 89 89 gray35 + 89 89 89 grey35 + 92 92 92 gray36 + 92 92 92 grey36 + 94 94 94 gray37 + 94 94 94 grey37 + 97 97 97 gray38 + 97 97 97 grey38 + 99 99 99 gray39 + 99 99 99 grey39 +102 102 102 gray40 +102 102 102 grey40 +105 105 105 gray41 +105 105 105 grey41 +107 107 107 gray42 +107 107 107 grey42 +110 110 110 gray43 +110 110 110 grey43 +112 112 112 gray44 +112 112 112 grey44 +115 115 115 gray45 +115 115 115 grey45 +117 117 117 gray46 +117 117 117 grey46 +120 120 120 gray47 +120 120 120 grey47 +122 122 122 gray48 +122 122 122 grey48 +125 125 125 gray49 +125 125 125 grey49 +127 127 127 gray50 +127 127 127 grey50 +130 130 130 gray51 +130 130 130 grey51 +133 133 133 gray52 +133 133 133 grey52 +135 135 135 gray53 +135 135 135 grey53 +138 138 138 gray54 +138 138 138 grey54 +140 140 140 gray55 +140 140 140 grey55 +143 143 143 gray56 +143 143 143 grey56 +145 145 145 gray57 +145 145 145 grey57 +148 148 148 gray58 +148 148 148 grey58 +150 150 150 gray59 +150 150 150 grey59 +153 153 153 gray60 +153 153 153 grey60 +156 156 156 gray61 +156 156 156 grey61 +158 158 158 gray62 +158 158 158 grey62 +161 161 161 gray63 +161 161 161 grey63 +163 163 163 gray64 +163 163 163 grey64 +166 166 166 gray65 +166 166 166 grey65 +168 168 168 gray66 +168 168 168 grey66 +171 171 171 gray67 +171 171 171 grey67 +173 173 173 gray68 +173 173 173 grey68 +176 176 176 gray69 +176 176 176 grey69 +179 179 179 gray70 +179 179 179 grey70 +181 181 181 gray71 +181 181 181 grey71 +184 184 184 gray72 +184 184 184 grey72 +186 186 186 gray73 +186 186 186 grey73 +189 189 189 gray74 +189 189 189 grey74 +191 191 191 gray75 +191 191 191 grey75 +194 194 194 gray76 +194 194 194 grey76 +196 196 196 gray77 +196 196 196 grey77 +199 199 199 gray78 +199 199 199 grey78 +201 201 201 gray79 +201 201 201 grey79 +204 204 204 gray80 +204 204 204 grey80 +207 207 207 gray81 +207 207 207 grey81 +209 209 209 gray82 +209 209 209 grey82 +212 212 212 gray83 +212 212 212 grey83 +214 214 214 gray84 +214 214 214 grey84 +217 217 217 gray85 +217 217 217 grey85 +219 219 219 gray86 +219 219 219 grey86 +222 222 222 gray87 +222 222 222 grey87 +224 224 224 gray88 +224 224 224 grey88 +227 227 227 gray89 +227 227 227 grey89 +229 229 229 gray90 +229 229 229 grey90 +232 232 232 gray91 +232 232 232 grey91 +235 235 235 gray92 +235 235 235 grey92 +237 237 237 gray93 +237 237 237 grey93 +240 240 240 gray94 +240 240 240 grey94 +242 242 242 gray95 +242 242 242 grey95 +245 245 245 gray96 +245 245 245 grey96 +247 247 247 gray97 +247 247 247 grey97 +250 250 250 gray98 +250 250 250 grey98 +252 252 252 gray99 +252 252 252 grey99 +255 255 255 gray100 +255 255 255 grey100 +169 169 169 dark grey +169 169 169 DarkGrey +169 169 169 dark gray +169 169 169 DarkGray + 0 0 139 dark blue + 0 0 139 DarkBlue + 0 139 139 dark cyan + 0 139 139 DarkCyan +139 0 139 dark magenta +139 0 139 DarkMagenta +139 0 0 dark red +139 0 0 DarkRed +144 238 144 light green +144 238 144 LightGreen +220 20 60 crimson + 75 0 130 indigo +128 128 0 olive +102 51 153 rebecca purple +102 51 153 RebeccaPurple +192 192 192 silver + 0 128 128 teal diff --git a/vendor/libghostty-vt/src/terminal/search.zig b/vendor/libghostty-vt/src/terminal/search.zig new file mode 100644 index 00000000..e69603c2 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search.zig @@ -0,0 +1,22 @@ +//! Search functionality for the terminal. + +pub const options = @import("terminal_options"); + +pub const Active = @import("search/active.zig").ActiveSearch; +pub const PageList = @import("search/pagelist.zig").PageListSearch; +pub const Screen = @import("search/screen.zig").ScreenSearch; +pub const Viewport = @import("search/viewport.zig").ViewportSearch; + +// The search thread is not available in libghostty due to the xev dep +// for now. +pub const Thread = switch (options.artifact) { + .ghostty => @import("search/Thread.zig"), + .lib => void, +}; + +test { + @import("std").testing.refAllDecls(@This()); + + // Non-public APIs + _ = @import("search/sliding_window.zig"); +} diff --git a/vendor/libghostty-vt/src/terminal/search/Thread.zig b/vendor/libghostty-vt/src/terminal/search/Thread.zig new file mode 100644 index 00000000..fa09af5f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/Thread.zig @@ -0,0 +1,905 @@ +//! Search thread that handles searching a terminal for a string match. +//! This is expected to run on a dedicated thread to try to prevent too much +//! overhead to other terminal read/write operations. +//! +//! The current architecture of search does acquire global locks for accessing +//! terminal data, so there's still added contention, but we do our best to +//! minimize this by trading off memory usage (copying data to minimize lock +//! time). +pub const Thread = @This(); + +const std = @import("std"); +const builtin = @import("builtin"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; +const Mutex = std.Thread.Mutex; +const xev = @import("../../global.zig").xev; +const internal_os = @import("../../os/main.zig"); +const BlockingQueue = @import("../../datastruct/main.zig").BlockingQueue; +const MessageData = @import("../../datastruct/main.zig").MessageData; +const point = @import("../point.zig"); +const FlattenedHighlight = @import("../highlight.zig").Flattened; +const UntrackedHighlight = @import("../highlight.zig").Untracked; +const ScreenSet = @import("../ScreenSet.zig"); +const Selection = @import("../Selection.zig"); +const Terminal = @import("../Terminal.zig"); + +const ScreenSearch = @import("screen.zig").ScreenSearch; +const ViewportSearch = @import("viewport.zig").ViewportSearch; + +const log = std.log.scoped(.search_thread); + +// TODO: Some stuff that could be improved: +// - pause the refresh timer when the terminal isn't focused +// - we probably want to know our progress through the search +// for viewport matches so we can show n/total UI. +// - notifications should be coalesced to avoid spamming a massive +// amount of events if the terminal is changing rapidly. + +/// The interval at which we refresh the terminal state to check if +/// there are any changes that require us to re-search. This should be +/// balanced to be fast enough to be responsive but not so fast that +/// we hold the terminal lock too often. +const REFRESH_INTERVAL = 24; // 40 FPS + +/// Allocator used for some state +alloc: std.mem.Allocator, + +/// The mailbox that can be used to send this thread messages. Note +/// this is a blocking queue so if it is full you will get errors (or block). +mailbox: *Mailbox, + +/// The event loop for the search thread. +loop: xev.Loop, + +/// This can be used to wake up the renderer and force a render safely from +/// any thread. +wakeup: xev.Async, +wakeup_c: xev.Completion = .{}, + +/// This can be used to stop the thread on the next loop iteration. +stop: xev.Async, +stop_c: xev.Completion = .{}, + +/// The timer used for refreshing the terminal state to determine if +/// we have a stale active area, viewport, screen change, etc. This is +/// CPU intensive so we stop doing this under certain conditions. +refresh: xev.Timer, +refresh_c: xev.Completion = .{}, +refresh_active: bool = false, + +/// Search state. Starts as null and is populated when a search is +/// started (a needle is given). +search: ?Search = null, + +/// The options used to initialize this thread. +opts: Options, + +/// Initialize the thread. This does not START the thread. This only sets +/// up all the internal state necessary prior to starting the thread. It +/// is up to the caller to start the thread with the threadMain entrypoint. +pub fn init(alloc: Allocator, opts: Options) !Thread { + // The mailbox for messaging this thread + var mailbox = try Mailbox.create(alloc); + errdefer mailbox.destroy(alloc); + + // Create our event loop. + var loop = try xev.Loop.init(.{}); + errdefer loop.deinit(); + + // This async handle is used to "wake up" the renderer and force a render. + var wakeup_h = try xev.Async.init(); + errdefer wakeup_h.deinit(); + + // This async handle is used to stop the loop and force the thread to end. + var stop_h = try xev.Async.init(); + errdefer stop_h.deinit(); + + // Refresh timer, see comments. + var refresh_h = try xev.Timer.init(); + errdefer refresh_h.deinit(); + + return .{ + .alloc = alloc, + .mailbox = mailbox, + .loop = loop, + .wakeup = wakeup_h, + .stop = stop_h, + .refresh = refresh_h, + .opts = opts, + }; +} + +/// Clean up the thread. This is only safe to call once the thread +/// completes executing; the caller must join prior to this. +pub fn deinit(self: *Thread) void { + self.refresh.deinit(); + self.wakeup.deinit(); + self.stop.deinit(); + self.loop.deinit(); + // Nothing can possibly access the mailbox anymore, destroy it. + self.mailbox.destroy(self.alloc); + + if (self.search) |*s| s.deinit(); +} + +/// The main entrypoint for the thread. +pub fn threadMain(self: *Thread) void { + // Call child function so we can use errors... + self.threadMain_() catch |err| { + // In the future, we should expose this on the thread struct. + log.warn("search thread err={}", .{err}); + }; +} + +fn threadMain_(self: *Thread) !void { + defer log.debug("search thread exited", .{}); + + // Right now, on Darwin, `std.Thread.setName` can only name the current + // thread, and we have no way to get the current thread from within it, + // so instead we use this code to name the thread instead. + if (comptime builtin.os.tag.isDarwin()) { + internal_os.macos.pthread_setname_np(&"search".*); + + // We can run with lower priority than other threads. + const class: internal_os.macos.QosClass = .utility; + if (internal_os.macos.setQosClass(class)) { + log.debug("thread QoS class set class={}", .{class}); + } else |err| { + log.warn("error setting QoS class err={}", .{err}); + } + } + + // Start the async handlers + self.wakeup.wait(&self.loop, &self.wakeup_c, Thread, self, wakeupCallback); + self.stop.wait(&self.loop, &self.stop_c, Thread, self, stopCallback); + + // Send an initial wakeup so we drain our mailbox immediately. + try self.wakeup.notify(); + + // Start the refresh timer + self.startRefreshTimer(); + + // Run + log.debug("starting search thread", .{}); + defer { + log.debug("starting search thread shutdown", .{}); + + // Send the quit message + if (self.opts.event_cb) |cb| { + cb(.quit, self.opts.event_userdata); + } + } + + // Unlike some of our other threads, we interleave search work + // with our xev loop so that we can try to make forward search progress + // while also listening for messages. + while (true) { + // If our loop is canceled then we drain our messages and quit. + if (self.loop.stopped()) { + while (self.mailbox.pop()) |message| { + log.debug("mailbox message ignored during shutdown={}", .{message}); + } + + return; + } + + const s: *Search = if (self.search) |*s| s else { + // If we're not actively searching, we can block the loop + // until it does some work. + try self.loop.run(.once); + continue; + }; + + // If we have an active search, we always send any pending + // notifications. Even if the search is complete, there may be + // notifications to send. + if (self.opts.event_cb) |cb| { + s.notify( + self.alloc, + cb, + self.opts.event_userdata, + ); + } + + if (s.isComplete()) { + // If our search is complete, there's no more work to do, we + // can block until we have an xev action. + try self.loop.run(.once); + continue; + } + + // Tick the search. This will trigger any event callbacks, lock + // for data loading, etc. + switch (s.tick()) { + // We're complete now when we were not before. Notify! + .complete => {}, + + // Forward progress was made. + .progress => {}, + + // All searches are blocked. Let's grab the lock and feed data. + .blocked => { + self.opts.mutex.lock(); + defer self.opts.mutex.unlock(); + s.feed(self.alloc, self.opts.terminal); + }, + } + + // We have an active search, so we only want to process messages + // we have but otherwise return immediately so we can continue the + // search. If the above completed the search, we still want to + // go around the loop as quickly as possible to send notifications, + // and then we'll block on the loop next time. + try self.loop.run(.no_wait); + } +} + +/// Drain the mailbox. +fn drainMailbox(self: *Thread) !void { + while (self.mailbox.pop()) |message| { + log.debug("mailbox message={}", .{message}); + switch (message) { + .change_needle => |v| { + defer v.deinit(); + try self.changeNeedle(v.slice()); + }, + .select => |v| try self.select(v), + } + } +} + +fn select(self: *Thread, sel: ScreenSearch.Select) !void { + const s = if (self.search) |*s| s else return; + const screen_search = s.screens.getPtr(s.last_screen.key) orelse return; + + self.opts.mutex.lock(); + defer self.opts.mutex.unlock(); + + // Make the selection. Ignore the result because we don't + // care if the selection didn't change. + _ = try screen_search.select(sel); + + // Grab our match if we have one. If we don't have a selection + // then we do nothing. + const flattened = screen_search.selectedMatch() orelse return; + + // No matter what we reset our selected match cache. This will + // trigger a callback which will trigger the renderer to wake up + // so it can be notified the screen scrolled. + s.last_screen.selected = null; + + // Grab the current screen and see if this match is visible within + // the viewport already. If it is, we do nothing. + const screen = self.opts.terminal.screens.get( + s.last_screen.key, + ) orelse return; + + // Grab the viewport. Viewports and selections are usually small + // so this check isn't very expensive, despite appearing O(N^2), + // both Ns are usually equal to 1. + var it = screen.pages.pageIterator( + .right_down, + .{ .viewport = .{} }, + null, + ); + const hl_chunks = flattened.chunks.slice(); + while (it.next()) |chunk| { + for (0..hl_chunks.len) |i| { + const hl_chunk = hl_chunks.get(i); + if (chunk.overlaps(.{ + .node = hl_chunk.node, + .start = hl_chunk.start, + .end = hl_chunk.end, + })) return; + } + } + + screen.scroll(.{ .pin = flattened.startPin() }); +} + +/// Change the search term to the given value. +fn changeNeedle(self: *Thread, needle: []const u8) !void { + log.debug("changing search needle to '{s}'", .{needle}); + + // Stop the previous search + if (self.search) |*s| { + // If our search is unchanged, do nothing. + if (std.ascii.eqlIgnoreCase(s.viewport.needle(), needle)) return; + + s.deinit(); + self.search = null; + + // When the search changes then we need to emit that it stopped. + if (self.opts.event_cb) |cb| { + cb( + .{ .total_matches = 0 }, + self.opts.event_userdata, + ); + cb( + .{ .selected_match = null }, + self.opts.event_userdata, + ); + cb( + .{ .viewport_matches = &.{} }, + self.opts.event_userdata, + ); + } + } + + // No needle means stop the search. + if (needle.len == 0) return; + + // Setup our search state. + self.search = try .init(self.alloc, needle); + + // We need to grab the terminal lock and do an initial feed. + self.opts.mutex.lock(); + defer self.opts.mutex.unlock(); + self.search.?.feed(self.alloc, self.opts.terminal); +} + +fn startRefreshTimer(self: *Thread) void { + // Set our active state so it knows we're running. We set this before + // even checking the active state in case we have a pending shutdown. + self.refresh_active = true; + + // If our timer is already active, then we don't have to do anything. + if (self.refresh_c.state() == .active) return; + + // Start the timer which loops + self.refresh.run( + &self.loop, + &self.refresh_c, + REFRESH_INTERVAL, + Thread, + self, + refreshCallback, + ); +} + +fn stopRefreshTimer(self: *Thread) void { + // This will stop the refresh on the next iteration. + self.refresh_active = false; +} + +fn wakeupCallback( + self_: ?*Thread, + _: *xev.Loop, + _: *xev.Completion, + r: xev.Async.WaitError!void, +) xev.CallbackAction { + _ = r catch |err| { + log.warn("error in wakeup err={}", .{err}); + return .rearm; + }; + + const self = self_.?; + + // When we wake up, we drain the mailbox. Mailbox producers should + // wake up our thread after publishing. + self.drainMailbox() catch |err| + log.warn("error draining mailbox err={}", .{err}); + + return .rearm; +} + +fn stopCallback( + self_: ?*Thread, + _: *xev.Loop, + _: *xev.Completion, + r: xev.Async.WaitError!void, +) xev.CallbackAction { + _ = r catch unreachable; + self_.?.loop.stop(); + return .disarm; +} + +fn refreshCallback( + self_: ?*Thread, + _: *xev.Loop, + _: *xev.Completion, + r: xev.Timer.RunError!void, +) xev.CallbackAction { + _ = r catch unreachable; + const self: *Thread = self_ orelse { + // This shouldn't happen so we log it. + log.warn("refresh callback fired without data set", .{}); + return .disarm; + }; + + // Run our feed if we have a search active. + if (self.search) |*s| { + self.opts.mutex.lock(); + defer self.opts.mutex.unlock(); + s.feed(self.alloc, self.opts.terminal); + } + + // Only continue if we're still active + if (self.refresh_active) self.refresh.run( + &self.loop, + &self.refresh_c, + REFRESH_INTERVAL, + Thread, + self, + refreshCallback, + ); + + return .disarm; +} + +pub const Options = struct { + /// Mutex that must be held while reading/writing the terminal. + mutex: *Mutex, + + /// The terminal data to search. + terminal: *Terminal, + + /// The callback for events from the search thread along with optional + /// userdata. This can be null if you don't want to receive events, + /// which could be useful for a one-time search (although, odd, you + /// should use our search structures directly then). + event_cb: ?EventCallback = null, + event_userdata: ?*anyopaque = null, +}; + +pub const EventCallback = *const fn (event: Event, userdata: ?*anyopaque) void; + +/// The type used for sending messages to the thread. +pub const Mailbox = BlockingQueue(Message, 64); + +/// The messages that can be sent to the thread. +pub const Message = union(enum) { + /// Represents a write request. Magic number comes from the max size + /// we want this union to be. + pub const WriteReq = MessageData(u8, 255); + + /// Change the search term. If no prior search term is given this + /// will start a search. If an existing search term is given this will + /// stop the prior search and start a new one. + change_needle: WriteReq, + + /// Select a search result. + select: ScreenSearch.Select, +}; + +/// Events that can be emitted from the search thread. The caller +/// chooses to handle these as they see fit. +pub const Event = union(enum) { + /// Search is quitting. The search thread is exiting. + quit, + + /// Search is complete for the given needle on all screens. + complete, + + /// Total matches on the current active screen have changed. + total_matches: usize, + + /// Selected match changed. + selected_match: ?SelectedMatch, + + /// Matches in the viewport have changed. The memory is owned by the + /// search thread and is only valid during the callback. + viewport_matches: []const FlattenedHighlight, + + pub const SelectedMatch = struct { + idx: usize, + highlight: FlattenedHighlight, + }; +}; + +/// Search state. +const Search = struct { + /// Active viewport search for the active screen. + viewport: ViewportSearch, + + /// The searchers for all the screens. + screens: std.EnumMap(ScreenSet.Key, ScreenSearch), + + /// All state related to screen switches, collected so that when + /// we switch screens it makes everything related stale, too. + last_screen: ScreenState, + + /// True if we sent the complete notification yet. + last_complete: bool, + + /// The last viewport matches we found. + stale_viewport_matches: bool, + + const ScreenState = struct { + /// Last active screen key + key: ScreenSet.Key, + + /// Last notified total matches count + total: ?usize = null, + + /// Last notified selected match index + selected: ?SelectedMatch = null, + + const SelectedMatch = struct { + idx: usize, + highlight: UntrackedHighlight, + }; + }; + + pub fn init( + alloc: Allocator, + needle: []const u8, + ) Allocator.Error!Search { + var vp: ViewportSearch = try .init(alloc, needle); + errdefer vp.deinit(); + + // We use dirty tracking for active area changes. Start with it + // dirty so the first change is re-searched. + vp.active_dirty = true; + + return .{ + .viewport = vp, + .screens = .init(.{}), + .last_screen = .{ .key = .primary }, + .last_complete = false, + .stale_viewport_matches = true, + }; + } + + pub fn deinit(self: *Search) void { + self.viewport.deinit(); + var it = self.screens.iterator(); + while (it.next()) |entry| entry.value.deinit(); + } + + /// Returns true if all searches on all screens are complete. + pub fn isComplete(self: *Search) bool { + var it = self.screens.iterator(); + while (it.next()) |entry| { + if (!entry.value.state.isComplete()) return false; + } + + return true; + } + + pub const Tick = enum { + /// All searches are complete. + complete, + + /// Progress was made on at least one screen. + progress, + + /// All incomplete searches are blocked on feed. + blocked, + }; + + /// Tick the search forward as much as possible without acquiring + /// the big lock. Returns the overall tick progress. + pub fn tick(self: *Search) Tick { + var result: Tick = .complete; + var it = self.screens.iterator(); + while (it.next()) |entry| { + if (entry.value.tick()) { + result = .progress; + } else |err| switch (err) { + // Ignore... nothing we can do. + error.OutOfMemory => log.warn( + "error ticking screen search key={} err={}", + .{ entry.key, err }, + ), + + // Ignore, good for us. State remains whatever it is. + error.SearchComplete => {}, + + // Ignore, too, progressed + error.FeedRequired => switch (result) { + // If we think we're complete, we're not because we're + // blocked now (nothing made progress). + .complete => result = .blocked, + + // If we made some progress, we remain in progress + // since blocked means no progress at all. + .progress => {}, + + // If we're blocked already then we remain blocked. + .blocked => {}, + }, + } + } + + // log.debug("tick result={}", .{result}); + return result; + } + + /// Grab the mutex and update any state that requires it, such as + /// feeding additional data to the searches or updating the active screen. + pub fn feed( + self: *Search, + alloc: Allocator, + t: *Terminal, + ) void { + // Update our active screen + if (t.screens.active_key != self.last_screen.key) { + // The default values will force resets of a bunch of other + // state too to force recalculations and notifications. + self.last_screen = .{ .key = t.screens.active_key }; + } + + // Reconcile our screens with the terminal screens. Remove + // searchers for screens that no longer exist and add searchers + // for screens that do exist but we don't have yet. + { + // Remove screens we have that no longer exist or changed. + var it = self.screens.iterator(); + while (it.next()) |entry| { + const remove: bool = remove: { + // If the screen doesn't exist at all, remove it. + const actual = t.screens.all.get(entry.key) orelse break :remove true; + + // If the screen pointer changed, remove it, the screen + // was totally reinitialized. + break :remove actual != entry.value.screen; + }; + + if (remove) { + entry.value.deinit(); + _ = self.screens.remove(entry.key); + } + } + } + { + // Add screens that exist but we don't have yet. + var it = t.screens.all.iterator(); + while (it.next()) |entry| { + if (self.screens.contains(entry.key)) continue; + self.screens.put(entry.key, ScreenSearch.init( + alloc, + entry.value.*, + self.viewport.needle(), + ) catch |err| switch (err) { + error.OutOfMemory => { + // OOM is probably going to sink the entire ship but + // we can just ignore it and wait on the next + // reconciliation to try again. + log.warn( + "error initializing screen search for key={} err={}", + .{ entry.key, err }, + ); + continue; + }, + }); + } + } + + // See the `search_viewport_dirty` flag on the terminal to know + // what exactly this is for. But, if this is set, we know the renderer + // found the viewport/active area dirty, so we should mark it as + // dirty in our viewport searcher so it forces a re-search. + if (t.flags.search_viewport_dirty) { + t.flags.search_viewport_dirty = false; + + // Mark our viewport dirty so it researches the active + self.viewport.active_dirty = true; + + // Reload our active area for our active screen + if (self.screens.getPtr(t.screens.active_key)) |screen_search| { + screen_search.reloadActive() catch |err| switch (err) { + error.OutOfMemory => log.warn( + "error reloading active area for screen key={} err={}", + .{ t.screens.active_key, err }, + ), + }; + } + } + + // Check our viewport for changes. + if (self.viewport.update(&t.screens.active.pages)) |updated| { + if (updated) self.stale_viewport_matches = true; + } else |err| switch (err) { + error.OutOfMemory => log.warn( + "error updating viewport search err={}", + .{err}, + ), + } + + // Feed data + var it = self.screens.iterator(); + while (it.next()) |entry| { + if (entry.value.state.needsFeed()) { + entry.value.feed() catch |err| switch (err) { + error.OutOfMemory => log.warn( + "error feeding screen search key={} err={}", + .{ entry.key, err }, + ), + }; + } + } + } + + /// Notify about any changes to the search state. + /// + /// This doesn't require any locking as it only reads internal state. + pub fn notify( + self: *Search, + alloc: Allocator, + cb: EventCallback, + ud: ?*anyopaque, + ) void { + const screen_search = self.screens.get(self.last_screen.key) orelse return; + + // Check our total match data + const total = screen_search.matchesLen(); + if (total != self.last_screen.total) { + log.debug("notifying total matches={}", .{total}); + self.last_screen.total = total; + cb(.{ .total_matches = total }, ud); + } + + // Check our viewport matches. If they're stale, we do the + // viewport search now. We do this as part of notify and not + // tick because the viewport search is very fast and doesn't + // require ticked progress or feeds. + if (self.stale_viewport_matches) viewport: { + // We always make stale as false. Even if we fail below + // we require a re-feed to re-search the viewport. The feed + // process will make it stale again. + self.stale_viewport_matches = false; + + var arena: ArenaAllocator = .init(alloc); + defer arena.deinit(); + const arena_alloc = arena.allocator(); + var results: std.ArrayList(FlattenedHighlight) = .empty; + while (self.viewport.next()) |hl| { + const hl_cloned = hl.clone(arena_alloc) catch continue; + results.append(arena_alloc, hl_cloned) catch |err| switch (err) { + error.OutOfMemory => { + log.warn( + "error collecting viewport matches err={}", + .{err}, + ); + + // Reset the viewport so we force an update on the + // next feed. + self.viewport.reset(); + break :viewport; + }, + }; + } + + log.debug("notifying viewport matches len={}", .{results.items.len}); + cb(.{ .viewport_matches = results.items }, ud); + } + + // Check our last selected match data. + if (screen_search.selected) |m| match: { + const flattened = screen_search.selectedMatch() orelse break :match; + const untracked = flattened.untracked(); + if (self.last_screen.selected) |prev| { + if (prev.idx == m.idx and prev.highlight.eql(untracked)) { + // Same selection, don't update it. + break :match; + } + } + + // New selection, notify! + self.last_screen.selected = .{ + .idx = m.idx, + .highlight = untracked, + }; + + log.debug("notifying selection updated idx={}", .{m.idx}); + cb( + .{ .selected_match = .{ + .idx = m.idx, + .highlight = flattened, + } }, + ud, + ); + } else if (self.last_screen.selected != null) { + log.debug("notifying selection cleared", .{}); + self.last_screen.selected = null; + cb( + .{ .selected_match = null }, + ud, + ); + } + + // Send our complete notification if we just completed. + if (!self.last_complete and self.isComplete()) { + log.debug("notifying search complete", .{}); + self.last_complete = true; + cb(.complete, ud); + } + } +}; + +const TestUserData = struct { + const Self = @This(); + reset: std.Thread.ResetEvent = .{}, + total: usize = 0, + selected: ?Event.SelectedMatch = null, + viewport: []FlattenedHighlight = &.{}, + + fn deinit(self: *Self) void { + for (self.viewport) |*hl| hl.deinit(testing.allocator); + testing.allocator.free(self.viewport); + } + + fn callback(event: Event, userdata: ?*anyopaque) void { + const ud: *Self = @ptrCast(@alignCast(userdata.?)); + switch (event) { + .quit => {}, + .complete => ud.reset.set(), + .total_matches => |v| ud.total = v, + .selected_match => |v| ud.selected = v, + .viewport_matches => |v| { + for (ud.viewport) |*hl| hl.deinit(testing.allocator); + testing.allocator.free(ud.viewport); + + ud.viewport = testing.allocator.alloc( + FlattenedHighlight, + v.len, + ) catch unreachable; + for (ud.viewport, v) |*dst, src| { + dst.* = src.clone(testing.allocator) catch unreachable; + } + }, + } + } +}; + +test { + const alloc = testing.allocator; + var mutex: std.Thread.Mutex = .{}; + var t: Terminal = try .init(alloc, .{ .cols = 20, .rows = 2 }); + defer t.deinit(alloc); + + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice("Hello, world"); + + var ud: TestUserData = .{}; + defer ud.deinit(); + var thread: Thread = try .init(alloc, .{ + .mutex = &mutex, + .terminal = &t, + .event_cb = &TestUserData.callback, + .event_userdata = &ud, + }); + defer thread.deinit(); + + var os_thread = try std.Thread.spawn( + .{}, + threadMain, + .{&thread}, + ); + + // Start our search + _ = thread.mailbox.push( + .{ .change_needle = try .init( + alloc, + @as([]const u8, "world"), + ) }, + .forever, + ); + try thread.wakeup.notify(); + + // Wait for completion + try ud.reset.timedWait(100 * std.time.ns_per_ms); + + // Stop the thread + try thread.stop.notify(); + os_thread.join(); + + // 1 total matches + try testing.expectEqual(1, ud.total); + try testing.expectEqual(1, ud.viewport.len); + { + const sel = ud.viewport[0].untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 7, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 11, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} diff --git a/vendor/libghostty-vt/src/terminal/search/active.zig b/vendor/libghostty-vt/src/terminal/search/active.zig new file mode 100644 index 00000000..692a10e1 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/active.zig @@ -0,0 +1,175 @@ +const std = @import("std"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const point = @import("../point.zig"); +const size = @import("../size.zig"); +const FlattenedHighlight = @import("../highlight.zig").Flattened; +const PageList = @import("../PageList.zig"); +const SlidingWindow = @import("sliding_window.zig").SlidingWindow; +const Terminal = @import("../Terminal.zig"); + +/// Searches for a substring within the active area of a PageList. +/// +/// The distinction for "active area" is important because it is the +/// only part of a PageList that is mutable. Therefore, its the only part +/// of the terminal that needs to be repeatedly searched as the contents +/// change. +/// +/// This struct specializes in searching only within that active area, +/// and handling the active area moving as new lines are added to the bottom. +pub const ActiveSearch = struct { + window: SlidingWindow, + + pub fn init( + alloc: Allocator, + needle: []const u8, + ) Allocator.Error!ActiveSearch { + // We just do a forward search since the active area is usually + // pretty small so search results are instant anyways. This avoids + // a small amount of work to reverse things. + var window: SlidingWindow = try .init(alloc, .forward, needle); + errdefer window.deinit(); + return .{ .window = window }; + } + + pub fn deinit(self: *ActiveSearch) void { + self.window.deinit(); + } + + /// Update the active area to reflect the current state of the PageList. + /// + /// This doesn't do the search, it only copies the necessary data + /// to perform the search later. This lets the caller hold the lock + /// on the PageList for a minimal amount of time. + /// + /// This returns the first page (in reverse order) covered by this + /// search. This allows the history search to overlap and search history. + /// There CAN BE duplicates, and this page CAN BE mutable, so the history + /// search results should prune anything that's in the active area. + /// + /// If the return value is null it means the active area covers the entire + /// PageList, currently. + pub fn update( + self: *ActiveSearch, + list: *const PageList, + ) Allocator.Error!?*PageList.List.Node { + // Clear our previous sliding window + self.window.clearAndRetainCapacity(); + + // First up, add enough pages to cover the active area. + var rem: usize = list.rows; + var node_ = list.pages.last; + var last_node: ?*PageList.List.Node = null; + while (node_) |node| : (node_ = node.prev) { + _ = try self.window.append(node); + last_node = node; + + // If we reached our target amount, then this is the last + // page that contains the active area. We go to the previous + // page once more since its the first page of our required + // overlap. + if (rem <= node.data.size.rows) { + node_ = node.prev; + break; + } + + rem -= node.data.size.rows; + } + + // Next, add enough overlap to cover needle.len - 1 bytes (if it + // exists) so we can cover the overlap. + while (node_) |node| : (node_ = node.prev) { + // If the last row of this node isn't wrapped we can't overlap. + const row = node.data.getRow(node.data.size.rows - 1); + if (!row.wrap) break; + + // We could be more accurate here and count bytes since the + // last wrap but its complicated and unlikely multiple pages + // wrap so this should be fine. + const added = try self.window.append(node); + if (added >= self.window.needle.len - 1) break; + } + + // Return the last node we added to our window. + return last_node; + } + + /// Find the next match for the needle in the active area. This returns + /// null when there are no more matches. + pub fn next(self: *ActiveSearch) ?FlattenedHighlight { + return self.window.next(); + } +}; + +test "simple search" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ActiveSearch = try .init(alloc, "Fizz"); + defer search.deinit(); + _ = try search.update(&t.screens.active.pages); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(search.next() == null); +} + +test "clear screen and search" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ActiveSearch = try .init(alloc, "Fizz"); + defer search.deinit(); + _ = try search.update(&t.screens.active.pages); + + s.nextSlice("\x1b[2J"); // Clear screen + s.nextSlice("\x1b[H"); // Move cursor home + s.nextSlice("Buzz\r\nFizz\r\nBuzz"); + _ = try search.update(&t.screens.active.pages); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(search.next() == null); +} diff --git a/vendor/libghostty-vt/src/terminal/search/pagelist.zig b/vendor/libghostty-vt/src/terminal/search/pagelist.zig new file mode 100644 index 00000000..f76ad4e4 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/pagelist.zig @@ -0,0 +1,441 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const testing = std.testing; +const terminal = @import("../main.zig"); +const point = terminal.point; +const FlattenedHighlight = @import("../highlight.zig").Flattened; +const Page = terminal.Page; +const PageList = terminal.PageList; +const Pin = PageList.Pin; +const Selection = terminal.Selection; +const Screen = terminal.Screen; +const Terminal = @import("../Terminal.zig"); +const SlidingWindow = @import("sliding_window.zig").SlidingWindow; + +/// Searches for a term in a PageList structure. +/// +/// This searches in reverse order starting from the given node. +/// +/// This assumes that nodes do not change contents. For nodes that change +/// contents, look at ActiveSearch, which is designed to re-search the active +/// area since it assumed to change. When integrating ActiveSearch with +/// PageListSearch, the caller should start the PageListSearch from the +/// returned node from ActiveSearch.update(). +/// +/// Concurrent access to a PageList or nodes in a PageList are not allowed, +/// so the caller should ensure that necessary locks are held. Each function +/// documents whether it accesses the PageList or not. For example, you can +/// safely call `next()` without holding a lock, but you must hold a lock +/// while calling `feed()`. +pub const PageListSearch = struct { + /// The list we're searching. + list: *PageList, + + /// The sliding window of page contents and nodes to search. + window: SlidingWindow, + + /// The tracked pin for our current position in the pagelist. This + /// will always point to the CURRENT node we're searching from so that + /// we can track if we move. + pin: *Pin, + + /// Initialize the page list search. The needle is copied so it can + /// be freed immediately. + /// + /// Accesses the PageList/Node so the caller must ensure it is safe + /// to do so if there is any concurrent access. + pub fn init( + alloc: Allocator, + needle: []const u8, + list: *PageList, + start: *PageList.List.Node, + ) Allocator.Error!PageListSearch { + // We put a tracked pin into the node that we're starting from. + // By using a tracked pin, we can keep our pagelist references safe + // because if the pagelist prunes pages, the tracked pin will + // be moved somewhere safe. + const pin = try list.trackPin(.{ + .node = start, + .y = start.data.size.rows - 1, + .x = start.data.size.cols - 1, + }); + errdefer list.untrackPin(pin); + + // Create our sliding window we'll use for searching. + var window: SlidingWindow = try .init(alloc, .reverse, needle); + errdefer window.deinit(); + + // We always feed our initial page data into the window, because + // we have the lock anyways and this lets our `pin` point to our + // current node and feed to work properly. + _ = try window.append(start); + + return .{ + .list = list, + .window = window, + .pin = pin, + }; + } + + /// Modifies the PageList (to untrack a pin) so the caller must ensure + /// that it is safe to do so. + pub fn deinit(self: *PageListSearch) void { + self.window.deinit(); + self.list.untrackPin(self.pin); + } + + /// Return the next match in the loaded page nodes. If this returns + /// null then the PageList search needs to be fed the next node(s). + /// Call, `feed` to do this. + /// + /// Beware that the selection returned may point to a node that + /// is freed if the caller does not hold necessary locks on the + /// PageList while searching. The pins should be validated prior to + /// final use. + /// + /// This does NOT access the PageList, so it can be called without + /// a lock held. + pub fn next(self: *PageListSearch) ?FlattenedHighlight { + return self.window.next(); + } + + /// Feed more data to the sliding window from the pagelist. This will + /// feed enough data to cover at least one match (needle length) if it + /// exists; this doesn't perform the search, it only feeds data. + /// + /// This accesses nodes in the PageList, so the caller must ensure + /// it is safe to do so (i.e. hold necessary locks). + /// + /// This returns false if there is no more data to feed. This essentially + /// means we've searched the entire pagelist. + pub fn feed(self: *PageListSearch) Allocator.Error!bool { + // If our pin becomes garbage it means wherever we were next + // was reused and we can't make sense of our progress anymore. + // It is effectively equivalent to reaching the end of the PageList. + if (self.pin.garbage) return false; + + // Add at least enough data to find a single match. + var rem = self.window.needle.len; + + // Start at our previous node and then continue adding until we + // get our desired amount of data. + var node_: ?*PageList.List.Node = self.pin.node.prev; + while (node_) |node| : (node_ = node.prev) { + rem -|= try self.window.append(node); + + // Move our tracked pin to the new node. + self.pin.node = node; + + if (rem == 0) break; + } + + // True if we fed any data. + return rem < self.window.needle.len; + } +}; + +test "simple search" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: PageListSearch = try .init( + alloc, + "Fizz", + &t.screens.active.pages, + t.screens.active.pages.pages.last.?, + ); + defer search.deinit(); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(search.next() == null); + + // We should not be able to feed since we have one page + try testing.expect(!try search.feed()); +} + +test "feed multiple pages with matches" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Fill up first page + const first_page_rows = t.screens.active.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("Fizz"); + try testing.expect(t.screens.active.pages.pages.first == t.screens.active.pages.pages.last); + + // Create second page + s.nextSlice("\r\n"); + try testing.expect(t.screens.active.pages.pages.first != t.screens.active.pages.pages.last); + s.nextSlice("Buzz\r\nFizz"); + + var search: PageListSearch = try .init( + alloc, + "Fizz", + &t.screens.active.pages, + t.screens.active.pages.pages.last.?, + ); + defer search.deinit(); + + // First match on the last page + const sel1 = search.next(); + try testing.expect(sel1 != null); + try testing.expect(search.next() == null); + + // Feed should succeed and load the first page + try testing.expect(try search.feed()); + + // Now we should find the match on the first page + const sel2 = search.next(); + try testing.expect(sel2 != null); + try testing.expect(search.next() == null); + + // No more pages to feed + try testing.expect(!try search.feed()); +} + +test "feed multiple pages no matches" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Fill up first page + const first_page_rows = t.screens.active.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("Hello"); + + // Create second page + s.nextSlice("\r\n"); + try testing.expect(t.screens.active.pages.pages.first != t.screens.active.pages.pages.last); + s.nextSlice("World"); + + var search: PageListSearch = try .init( + alloc, + "Nope", + &t.screens.active.pages, + t.screens.active.pages.pages.last.?, + ); + defer search.deinit(); + + // No matches on last page + try testing.expect(search.next() == null); + + // Feed first page + try testing.expect(try search.feed()); + + // Still no matches + try testing.expect(search.next() == null); + + // No more pages + try testing.expect(!try search.feed()); +} + +test "feed iteratively through multiple matches" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 80, .rows = 24 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const first_page_rows = t.screens.active.pages.pages.first.?.data.capacity.rows; + + // Fill first page with a match at the end + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + s.nextSlice("Page1Test"); + try testing.expect(t.screens.active.pages.pages.first == t.screens.active.pages.pages.last); + + // Create second page with a match + s.nextSlice("\r\n"); + try testing.expect(t.screens.active.pages.pages.first != t.screens.active.pages.pages.last); + s.nextSlice("Page2Test"); + + var search: PageListSearch = try .init( + alloc, + "Test", + &t.screens.active.pages, + t.screens.active.pages.pages.last.?, + ); + defer search.deinit(); + + // Match on page 2 + try testing.expect(search.next() != null); + try testing.expect(search.next() == null); + + // Feed page 1 + try testing.expect(try search.feed()); + try testing.expect(search.next() != null); + try testing.expect(search.next() == null); + + // No more pages + try testing.expect(!try search.feed()); +} + +test "feed with match spanning page boundary" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 80, .rows = 24 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const first_page_rows = t.screens.active.pages.pages.first.?.data.capacity.rows; + + // Fill first page ending with "Te" + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + for (0..t.screens.active.pages.cols - 2) |_| s.nextSlice("x"); + s.nextSlice("Te"); + try testing.expect(t.screens.active.pages.pages.first == t.screens.active.pages.pages.last); + + // Second page starts with "st" + s.nextSlice("st"); + try testing.expect(t.screens.active.pages.pages.first != t.screens.active.pages.pages.last); + + var search: PageListSearch = try .init( + alloc, + "Test", + &t.screens.active.pages, + t.screens.active.pages.pages.last.?, + ); + defer search.deinit(); + + // No complete match on last page alone (only has "st") + try testing.expect(search.next() == null); + + // Feed first page - this should give us enough data to find "Test" + try testing.expect(try search.feed()); + + // Should find the spanning match + const h = search.next().?; + const sel = h.untracked(); + try testing.expect(sel.start.node != sel.end.node); + { + const str = try t.screens.active.selectionString( + alloc, + .{ .sel = .init(sel.start, sel.end, false) }, + ); + defer alloc.free(str); + try testing.expectEqualStrings(str, "Test"); + } + + // No more matches + try testing.expect(search.next() == null); + + // No more pages + try testing.expect(!try search.feed()); +} + +test "feed with match spanning page boundary with newline" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 80, .rows = 24 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + const first_page_rows = t.screens.active.pages.pages.first.?.data.capacity.rows; + + // Fill first page ending with "Te" + for (0..first_page_rows - 1) |_| s.nextSlice("\r\n"); + for (0..t.screens.active.pages.cols - 2) |_| s.nextSlice("x"); + s.nextSlice("Te"); + try testing.expect(t.screens.active.pages.pages.first == t.screens.active.pages.pages.last); + + // Second page starts with "st" + s.nextSlice("\r\n"); + try testing.expect(t.screens.active.pages.pages.first != t.screens.active.pages.pages.last); + s.nextSlice("st"); + + var search: PageListSearch = try .init( + alloc, + "Test", + &t.screens.active.pages, + t.screens.active.pages.pages.last.?, + ); + defer search.deinit(); + + // Should not find any matches since we broke with an explicit newline. + try testing.expect(search.next() == null); + try testing.expect(try search.feed()); + try testing.expect(search.next() == null); + try testing.expect(!try search.feed()); +} + +test "feed with pruned page" { + const alloc = testing.allocator; + + // Zero here forces minimum max size to effectively two pages. + var p: PageList = try .init(alloc, 80, 24, 0); + defer p.deinit(); + + // Grow to capacity + const page1_node = p.pages.last.?; + const page1 = page1_node.data; + for (0..page1.capacity.rows - page1.size.rows) |_| { + try testing.expect(try p.grow() == null); + } + + // Grow and allocate one more page. Then fill that page up. + const page2_node = (try p.grow()).?; + const page2 = page2_node.data; + for (0..page2.capacity.rows - page2.size.rows) |_| { + try testing.expect(try p.grow() == null); + } + + // Setup search and feed until we can't + var search: PageListSearch = try .init( + alloc, + "Test", + &p, + p.pages.last.?, + ); + defer search.deinit(); + try testing.expect(try search.feed()); + try testing.expect(!try search.feed()); + + // Next should create a new page, but it should reuse our first + // page since we're at max size. + const new = (try p.grow()).?; + try testing.expect(p.pages.last.? == new); + + // Our first should now be page2 and our last should be page1 + try testing.expectEqual(page2_node, p.pages.first.?); + try testing.expectEqual(page1_node, p.pages.last.?); + + // Feed should still do nothing + try testing.expect(!try search.feed()); +} diff --git a/vendor/libghostty-vt/src/terminal/search/screen.zig b/vendor/libghostty-vt/src/terminal/search/screen.zig new file mode 100644 index 00000000..3e7e316f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/screen.zig @@ -0,0 +1,1552 @@ +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const testing = std.testing; +const tripwire = @import("../../tripwire.zig"); +const Allocator = std.mem.Allocator; +const point = @import("../point.zig"); +const highlight = @import("../highlight.zig"); +const size = @import("../size.zig"); +const FlattenedHighlight = highlight.Flattened; +const TrackedHighlight = highlight.Tracked; +const PageList = @import("../PageList.zig"); +const Pin = PageList.Pin; +const Screen = @import("../Screen.zig"); +const Terminal = @import("../Terminal.zig"); +const ActiveSearch = @import("active.zig").ActiveSearch; +const PageListSearch = @import("pagelist.zig").PageListSearch; +const SlidingWindow = @import("sliding_window.zig").SlidingWindow; + +const log = std.log.scoped(.search_screen); + +const reloadActive_tw = tripwire.module(enum { + history_append_new, + history_append_existing, +}, ScreenSearch.reloadActive); + +/// Searches for a needle within a Screen, handling active area updates, +/// pages being pruned from the screen (e.g. scrollback limits), and more. +/// +/// Unlike our lower-level searchers (like ActiveSearch and PageListSearch), +/// this will cache and store all search results so the caller can re-access +/// them as needed. This structure does this because it is intended to help +/// the caller handle the case where the Screen is changing while the user +/// is searching. +/// +/// An inactive screen can continue to be searched in the background, and when +/// screen state changes, the renderer/caller can access the existing search +/// results without needing to re-search everything. This prevents a particularly +/// nasty UX where going to alt screen (e.g. neovim) and then back would +/// restart the full scrollback search. +pub const ScreenSearch = struct { + /// The screen being searched. + screen: *Screen, + + /// The active area search state + active: ActiveSearch, + + /// The history (scrollback) search state. May be null if there is + /// no history yet. + history: ?HistorySearch, + + /// Current state of the search, a state machine. + state: State, + + /// The currently selected match, if any. As the screen contents + /// change or get pruned, the screen search will do its best to keep + /// this accurate. + selected: ?SelectedMatch = null, + + /// The results found so far. These are stored separately because history + /// is mostly immutable once found, while active area results may + /// change. This lets us easily reset the active area results for a + /// re-search scenario. + history_results: std.ArrayList(FlattenedHighlight), + active_results: std.ArrayList(FlattenedHighlight), + + /// The dimensions of the screen. When this changes we need to + /// restart the whole search, currently. + rows: size.CellCountInt, + cols: size.CellCountInt, + + pub const SelectedMatch = struct { + /// Index from the end of the match list (0 = most recent match) + idx: usize, + + /// Tracked highlight so we can detect movement. + highlight: TrackedHighlight, + + pub fn deinit(self: *SelectedMatch, screen: *Screen) void { + self.highlight.deinit(screen); + } + }; + + /// History search state. + const HistorySearch = struct { + /// The actual searcher state. + searcher: PageListSearch, + + /// The pin for the first node that this searcher is searching from. + /// We use this when the active area changes to find the diff between + /// the top of the new active area and the previous start point + /// to determine if we need to search more history. + start_pin: *Pin, + + pub fn deinit(self: *HistorySearch, screen: *Screen) void { + self.searcher.deinit(); + screen.pages.untrackPin(self.start_pin); + } + }; + + /// Search state machine + const State = enum { + /// Currently searching the active area + active, + + /// Currently searching the history area + history, + + /// History search is waiting for more data to be fed before + /// it can progress. + history_feed, + + /// Search is complete given the current terminal state. + complete, + + pub fn isComplete(self: State) bool { + return switch (self) { + .complete => true, + else => false, + }; + } + + pub fn needsFeed(self: State) bool { + return switch (self) { + .history_feed => true, + + // Not obvious but complete search states will prune + // stale history results on feed. + .complete => true, + + else => false, + }; + } + }; + + // Initialize a screen search for the given screen and needle. + pub fn init( + alloc: Allocator, + screen: *Screen, + needle_unowned: []const u8, + ) Allocator.Error!ScreenSearch { + var result: ScreenSearch = .{ + .screen = screen, + .rows = screen.pages.rows, + .cols = screen.pages.cols, + .active = try .init(alloc, needle_unowned), + .history = null, + .state = .active, + .active_results = .empty, + .history_results = .empty, + }; + errdefer result.deinit(); + + // Update our initial active area state + try result.reloadActive(); + + return result; + } + + pub fn deinit(self: *ScreenSearch) void { + const alloc = self.allocator(); + self.active.deinit(); + if (self.history) |*h| h.deinit(self.screen); + if (self.selected) |*m| m.deinit(self.screen); + for (self.active_results.items) |*hl| hl.deinit(alloc); + self.active_results.deinit(alloc); + for (self.history_results.items) |*hl| hl.deinit(alloc); + self.history_results.deinit(alloc); + } + + fn allocator(self: *ScreenSearch) Allocator { + return self.active.window.alloc; + } + + /// The needle that this search is using. + pub fn needle(self: *const ScreenSearch) []const u8 { + assert(self.active.window.direction == .forward); + return self.active.window.needle; + } + + /// Returns the total number of matches found so far. + pub fn matchesLen(self: *const ScreenSearch) usize { + return self.active_results.items.len + self.history_results.items.len; + } + + /// Returns all matches as an owned slice (caller must free). + /// The matches are ordered from most recent to oldest (e.g. bottom + /// of the screen to top of the screen). + pub fn matches( + self: *ScreenSearch, + alloc: Allocator, + ) Allocator.Error![]FlattenedHighlight { + const active_results = self.active_results.items; + const history_results = self.history_results.items; + const results = try alloc.alloc( + FlattenedHighlight, + active_results.len + history_results.len, + ); + errdefer alloc.free(results); + + // Active does a forward search, so we add the active results then + // reverse them. There are usually not many active results so this + // is fast enough compared to adding them in reverse order. + assert(self.active.window.direction == .forward); + @memcpy( + results[0..active_results.len], + active_results, + ); + std.mem.reverse(FlattenedHighlight, results[0..active_results.len]); + + // History does a backward search, so we can just append them + // after. + @memcpy( + results[active_results.len..], + history_results, + ); + + return results; + } + + /// Search the full screen state. This will block until the search + /// is complete. For performance, it is recommended to use `tick` and + /// `feed` to incrementally make progress on the search instead. + pub fn searchAll(self: *ScreenSearch) Allocator.Error!void { + while (true) { + self.tick() catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.FeedRequired => try self.feed(), + error.SearchComplete => return, + }; + } + } + + pub const TickError = Allocator.Error || error{ + FeedRequired, + SearchComplete, + }; + + /// Make incremental progress on the search without accessing any + /// screen state (so no lock is required). + /// + /// This will return error.FeedRequired if the search cannot make progress + /// without being fed more data. In this case, the caller should call + /// the `feed` function to provide more data to the searcher. + /// + /// This will return error.SearchComplete if the search is fully complete. + /// This is to signal to the caller that it can move to a more efficient + /// sleep/wait state until there is more work to do (e.g. new data to feed). + pub fn tick(self: *ScreenSearch) TickError!void { + switch (self.state) { + .active => try self.tickActive(), + .history => try self.tickHistory(), + .history_feed => return error.FeedRequired, + .complete => return error.SearchComplete, + } + } + + /// Feed more data to the searcher so it can continue searching. This + /// accesses the screen state, so the caller must hold the necessary locks. + /// + /// Feed on a complete screen search will perform some cleanup of + /// potentially stale history results (pruned) and reclaim some memory. + pub fn feed(self: *ScreenSearch) Allocator.Error!void { + // If the screen resizes, we have to reset our entire search. That + // isn't ideal but we don't have a better way right now to handle + // reflowing the search results beyond putting a tracked pin for + // every single result. + if (self.screen.pages.rows != self.rows or + self.screen.pages.cols != self.cols) + { + // Reinit + const new: ScreenSearch = try .init( + self.allocator(), + self.screen, + self.needle(), + ); + + // Deinit/reinit + self.deinit(); + self.* = new; + + // New result should have matching dimensions + assert(self.screen.pages.rows == self.rows); + assert(self.screen.pages.cols == self.cols); + } + + const history: *PageListSearch = if (self.history) |*h| &h.searcher else { + // No history to feed, search is complete. + self.state = .complete; + return; + }; + + // Future: we may want to feed multiple pages at once here to + // lower the frequency of lock acquisitions. + if (!try history.feed()) { + // No more data to feed, search is complete. + self.state = .complete; + + // We use this opportunity to also clean up older history + // results that may be gone due to scrollback pruning, though. + self.pruneHistory(); + + return; + } + + // Depending on our state handle where feed goes + switch (self.state) { + // If we're searching active or history, then feeding doesn't + // change the state. + .active, .history => {}, + + // Feed goes back to searching history. + .history_feed => self.state = .history, + + // If we're complete then the feed call above should always + // return false and we can't reach this. + .complete => unreachable, + } + } + + fn pruneHistory(self: *ScreenSearch) void { + // Go through our history results in order (newest to oldest) to find + // any result that contains an invalid serial. Prune up to that + // point. + for (0..self.history_results.items.len) |i| { + const hl = &self.history_results.items[i]; + const serials = hl.chunks.items(.serial); + const lowest = serials[0]; + if (lowest < self.screen.pages.page_serial_min) { + // Everything from here forward we assume is invalid because + // our history results only get older. + const alloc = self.allocator(); + for (self.history_results.items[i..]) |*prune_hl| prune_hl.deinit(alloc); + self.history_results.shrinkAndFree(alloc, i); + return; + } + } + } + + fn tickActive(self: *ScreenSearch) Allocator.Error!void { + // For the active area, we consume the entire search in one go + // because the active area is generally small. + const alloc = self.allocator(); + while (self.active.next()) |hl| { + // If this fails, then we miss a result since `active.next()` + // moves forward and prunes data. In the future, we may want + // to have some more robust error handling but the only + // scenario this would fail is OOM and we're probably in + // deeper trouble at that point anyways. + var hl_cloned = try hl.clone(alloc); + errdefer hl_cloned.deinit(alloc); + try self.active_results.append(alloc, hl_cloned); + } + + // We've consumed the entire active area, move to history. + self.state = .history; + } + + fn tickHistory(self: *ScreenSearch) Allocator.Error!void { + const history: *HistorySearch = if (self.history) |*h| h else { + // No history to search, we're done. + self.state = .complete; + return; + }; + + // Try to consume all the loaded matches in one go, because + // the search is generally fast for loaded data. + const alloc = self.allocator(); + while (history.searcher.next()) |hl| { + // Ignore selections that are found within the starting + // node since those are covered by the active area search. + if (hl.chunks.items(.node)[0] == history.start_pin.node) continue; + + // Same note as tickActive for error handling. + var hl_cloned = try hl.clone(alloc); + errdefer hl_cloned.deinit(alloc); + try self.history_results.append(alloc, hl_cloned); + + // Since history only appends to our results in reverse order, + // we don't need to update any selected match state. The index + // and prior results are unaffected. + } + + // We need to be fed more data. + self.state = .history_feed; + } + + /// Reload the active area because it has changed. + /// + /// Since it is very fast, this will also do the full active area + /// search again, too. This avoids any complexity around the search + /// state machine. + /// + /// The caller must hold the necessary locks to access the screen state. + pub fn reloadActive(self: *ScreenSearch) Allocator.Error!void { + const tw = reloadActive_tw; + + // If our selection pin became garbage it means we scrolled off + // the end. Clear our selection and on exit of this function, + // try to select the last match. + const select_prev: bool = select_prev: { + const m = if (self.selected) |*m| m else break :select_prev false; + if (!m.highlight.start.garbage and + !m.highlight.end.garbage) break :select_prev false; + + m.deinit(self.screen); + self.selected = null; + break :select_prev true; + }; + defer if (select_prev) { + _ = self.select(.prev) catch |err| { + log.info("reload failed to reset search selection err={}", .{err}); + }; + }; + + const alloc = self.allocator(); + const list: *PageList = &self.screen.pages; + if (try self.active.update(list)) |history_node| history: { + // We need to account for any active area growth that would + // cause new pages to move into our history. If there are new + // pages then we need to re-search the pages and add it to + // our history results. + + // If our screen has no scrollback then we have no history. + if (self.screen.no_scrollback) { + assert(self.history == null); + break :history; + } + + const history_: ?*HistorySearch = if (self.history) |*h| state: { + // If our start pin became garbage, it means we pruned all + // the way up through it, so we have no history anymore. + // Reset our history state. + if (h.start_pin.garbage) { + h.deinit(self.screen); + self.history = null; + for (self.history_results.items) |*hl| hl.deinit(alloc); + self.history_results.clearRetainingCapacity(); + break :state null; + } + + break :state h; + } else null; + + const history = history_ orelse { + // No history search yet, but we now have history. So let's + // initialize. + + var search: PageListSearch = try .init( + alloc, + self.needle(), + list, + history_node, + ); + errdefer search.deinit(); + + const pin = try list.trackPin(.{ .node = history_node }); + errdefer list.untrackPin(pin); + + self.history = .{ + .searcher = search, + .start_pin = pin, + }; + + // We don't need to update any history since we had no history + // before, so we can break out of the whole conditional. + break :history; + }; + + if (history.start_pin.node == history_node) { + // No change in the starting node, we're done. + break :history; + } + + // Do a forward search from our prior node to this one. We + // collect all the results into a new list. We ASSUME that + // reloadActive is being called frequently enough that there isn't + // a massive amount of history to search here. + var window: SlidingWindow = try .init( + alloc, + .forward, + self.needle(), + ); + defer window.deinit(); + while (true) { + _ = try window.append(history.start_pin.node); + if (history.start_pin.node == history_node) break; + const next = history.start_pin.node.next orelse break; + history.start_pin.node = next; + } + assert(history.start_pin.node == history_node); + + var results: std.ArrayList(FlattenedHighlight) = try .initCapacity( + alloc, + self.history_results.items.len, + ); + errdefer { + for (results.items) |*hl| hl.deinit(alloc); + results.deinit(alloc); + } + while (window.next()) |hl| { + if (hl.chunks.items(.node)[0] == history_node) continue; + + var hl_cloned = try hl.clone(alloc); + errdefer hl_cloned.deinit(alloc); + try tw.check(.history_append_new); + try results.append(alloc, hl_cloned); + } + + // If we have no matches then there is nothing to change + // in our history (fast path) + if (results.items.len == 0) break :history; + + // The number added to our history. Needed for updating + // our selection if we have one. + const added_len = results.items.len; + + // Matches! Reverse our list then append all the remaining + // history items that didn't start on our original node. + std.mem.reverse(FlattenedHighlight, results.items); + try tw.check(.history_append_existing); + try results.appendSlice(alloc, self.history_results.items); + self.history_results.deinit(alloc); + self.history_results = results; + + // If our prior selection was in the history area, update + // the offset. + if (self.selected) |*m| selected: { + const active_len = self.active_results.items.len; + if (m.idx < active_len) break :selected; + m.idx += added_len; + + // Moving the idx should not change our targeted result + // since the history is immutable. + if (comptime std.debug.runtime_safety) { + const hl = self.history_results.items[m.idx - active_len]; + assert(m.highlight.start.eql(hl.startPin())); + } + } + } else { + // No history node means we have no history + if (self.history) |*h| { + h.deinit(self.screen); + self.history = null; + for (self.history_results.items) |*hl| hl.deinit(alloc); + self.history_results.clearRetainingCapacity(); + } + + // If we have a selection in the history area, we need to + // move it to the end of the active area. + if (self.selected) |*m| selected: { + const active_len = self.active_results.items.len; + if (m.idx < active_len) break :selected; + m.deinit(self.screen); + self.selected = null; + _ = self.select(.prev) catch |err| { + log.info("reload failed to reset search selection err={}", .{err}); + }; + } + } + + // Figure out if we need to fixup our selection later because + // it was in the active area. + const old_active_len = self.active_results.items.len; + const old_selection_idx: ?usize = if (self.selected) |m| m.idx else null; + errdefer if (old_selection_idx != null and + old_selection_idx.? < old_active_len) + { + // This is the error scenario. If something fails below, + // our active area is probably gone, so we just go back + // to the first result because our selection can't be trusted. + if (self.selected) |*m| { + m.deinit(self.screen); + self.selected = null; + _ = self.select(.next) catch |err| { + log.info("reload failed to reset search selection err={}", .{err}); + }; + } + }; + + // Reset our active search results and search again. + for (self.active_results.items) |*hl| hl.deinit(alloc); + self.active_results.clearRetainingCapacity(); + switch (self.state) { + // If we're in the active state we run a normal tick so + // we can move into a better state. + .active => try self.tickActive(), + + // Otherwise, just tick it and move back to whatever state + // we were in. + else => { + const old_state = self.state; + defer self.state = old_state; + try self.tickActive(); + }, + } + + // If we have no scrollback, we need to prune any active results + // that aren't in the actual active area. We only do this for the + // no scrollback scenario because with scrollback we actually + // rely on our active search searching by page to find history + // items as well. This is all related to the fact that PageList + // scrollback limits are discrete by page size except we special + // case zero. + if (self.screen.no_scrollback and + self.active_results.items.len > 0) + active_prune: { + const items = self.active_results.items; + const tl = self.screen.pages.getTopLeft(.active); + for (0.., items) |i, *hl| { + if (!tl.before(hl.endPin())) { + // Deinit because its going to be pruned no matter + // what at some point for not being in the active area. + hl.deinit(alloc); + continue; + } + + // In the active area! Since our results are sorted + // that means everything after this is also in the active + // area, so we prune up to this i. + if (i > 0) self.active_results.replaceRangeAssumeCapacity( + 0, + i, + &.{}, + ); + + break :active_prune; + } + + // None are in the active area... + self.active_results.clearRetainingCapacity(); + } + + // Now we have to fixup our selection if we had one. + fixup: { + const old_idx = old_selection_idx orelse break :fixup; + const m = if (self.selected) |*m| m else break :fixup; + + // If our old selection wasn't in the active area, then we + // need to fix up our offsets. + if (old_idx >= old_active_len) { + m.idx -= old_active_len; + m.idx += self.active_results.items.len; + break :fixup; + } + + // We search for the matching highlight in the new active results. + for (0.., self.active_results.items) |i, hl| { + const untracked = hl.untracked(); + if (m.highlight.start.eql(untracked.start) and + m.highlight.end.eql(untracked.end)) + { + // Found it! Update our index. + m.idx = self.active_results.items.len - 1 - i; + break :fixup; + } + } + + // No match, just go back to the first match. + m.deinit(self.screen); + self.selected = null; + _ = self.select(.next) catch |err| { + log.info("reload failed to reset search selection err={}", .{err}); + }; + } + } + + /// Return the selected match. + /// + /// This does not require read/write access to the underlying screen. + pub fn selectedMatch(self: *const ScreenSearch) ?FlattenedHighlight { + const sel = self.selected orelse return null; + const active_len = self.active_results.items.len; + if (sel.idx < active_len) { + return self.active_results.items[active_len - 1 - sel.idx]; + } + + const history_len = self.history_results.items.len; + if (sel.idx < active_len + history_len) { + return self.history_results.items[sel.idx - active_len]; + } + + return null; + } + + pub const Select = enum { + /// Next selection, in reverse order (newest to oldest), + /// non-wrapping. + next, + + /// Prev selection, in forward order (oldest to newest), + /// non-wrapping. + prev, + }; + + /// Select the next or previous search result. This requires read/write + /// access to the underlying screen, since we utilize tracked pins to + /// ensure our selection sticks with contents changing. + pub fn select(self: *ScreenSearch, to: Select) Allocator.Error!bool { + // All selection requires valid pins so we prune history and + // reload our active area immediately. This ensures all search + // results point to valid nodes. + try self.reloadActive(); + self.pruneHistory(); + + return switch (to) { + .next => try self.selectNext(), + .prev => try self.selectPrev(), + }; + } + + fn selectNext(self: *ScreenSearch) Allocator.Error!bool { + // Get our previous match so we can change it. If we have no + // prior match, we have the easy task of getting the first. + var prev = if (self.selected) |*m| m else { + // Get our highlight + const hl: FlattenedHighlight = hl: { + if (self.active_results.items.len > 0) { + // Active is in forward order + const len = self.active_results.items.len; + break :hl self.active_results.items[len - 1]; + } else if (self.history_results.items.len > 0) { + // History is in reverse order + break :hl self.history_results.items[0]; + } else { + // No matches at all. Can't select anything. + return false; + } + }; + + // Pin it so we can track any movement + const tracked = try hl.untracked().track(self.screen); + errdefer tracked.deinit(self.screen); + + // Our selection is index zero since we just started and + // we store our selection. + self.selected = .{ + .idx = 0, + .highlight = tracked, + }; + return true; + }; + + const active_len = self.active_results.items.len; + const history_len = self.history_results.items.len; + const next_idx = if (prev.idx + 1 >= active_len + history_len) 0 else prev.idx + 1; + const hl: FlattenedHighlight = if (next_idx < active_len) + self.active_results.items[active_len - 1 - next_idx] + else + self.history_results.items[next_idx - active_len]; + + // Pin it so we can track any movement + const tracked = try hl.untracked().track(self.screen); + errdefer tracked.deinit(self.screen); + + // Free our previous match and setup our new selection + prev.deinit(self.screen); + self.selected = .{ + .idx = next_idx, + .highlight = tracked, + }; + + return true; + } + + fn selectPrev(self: *ScreenSearch) Allocator.Error!bool { + // Get our previous match so we can change it. If we have no + // prior match, we have the easy task of getting the last. + var prev = if (self.selected) |*m| m else { + // Get our highlight (oldest match) + const hl: FlattenedHighlight = hl: { + if (self.history_results.items.len > 0) { + // History is in reverse order, so last item is oldest + const len = self.history_results.items.len; + break :hl self.history_results.items[len - 1]; + } else if (self.active_results.items.len > 0) { + // Active is in forward order, so first item is oldest + break :hl self.active_results.items[0]; + } else { + // No matches at all. Can't select anything. + return false; + } + }; + + // Pin it so we can track any movement + const tracked = try hl.untracked().track(self.screen); + errdefer tracked.deinit(self.screen); + + // Our selection is the last index since we just started + // and we store our selection. + const active_len = self.active_results.items.len; + const history_len = self.history_results.items.len; + self.selected = .{ + .idx = active_len + history_len - 1, + .highlight = tracked, + }; + return true; + }; + + const active_len = self.active_results.items.len; + const history_len = self.history_results.items.len; + const next_idx = if (prev.idx != 0) prev.idx - 1 else active_len - 1 + history_len; + + const hl: FlattenedHighlight = if (next_idx < active_len) + self.active_results.items[active_len - 1 - next_idx] + else + self.history_results.items[next_idx - active_len]; + + // Pin it so we can track any movement + const tracked = try hl.untracked().track(self.screen); + errdefer tracked.deinit(self.screen); + + // Free our previous match and setup our new selection + prev.deinit(self.screen); + self.selected = .{ + .idx = next_idx, + .highlight = tracked, + }; + + return true; + } +}; + +test "simple search" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + try testing.expectEqual(2, search.active_results.items.len); + // We don't test history results since there is overlap + + // Get all matches + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(2, matches.len); + + { + const sel = matches[0].untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + { + const sel = matches[1].untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "simple search with history" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("Fizz\r\n"); + while (list.totalPages() < 3) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("hello."); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + try testing.expectEqual(0, search.active_results.items.len); + + // Get all matches + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(1, matches.len); + + { + const sel = matches[0].untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "reload active with history change" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\n"); + + // Start up our search which will populate our initial active area. + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + { + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(1, matches.len); + } + + // Grow into two pages so our history pin will move. + while (list.totalPages() < 2) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("2Fizz"); + + // Active area changed so reload + try search.reloadActive(); + try search.searchAll(); + + // Get all matches + { + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(2, matches.len); + { + const sel = matches[1].untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + { + const sel = matches[0].untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 4, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + } + + // Reset the screen which will make our pin garbage. + t.fullReset(); + s.nextSlice("WeFizzing"); + try search.reloadActive(); + try search.searchAll(); + + { + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(1, matches.len); + { + const sel = matches[0].untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 2, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 5, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + } +} + +test "active change contents" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fuzz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + try testing.expectEqual(1, search.active_results.items.len); + + // Erase the screen, move our cursor to the top, and change contents. + s.nextSlice("\x1b[2J\x1b[H"); // Clear screen and move home + s.nextSlice("Bang\r\nFizz\r\nHello!"); + + try search.reloadActive(); + try search.searchAll(); + try testing.expectEqual(1, search.active_results.items.len); + + // Get all matches + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(1, matches.len); + + { + const sel = matches[0].untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "select next" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + + // Initially no selection + try testing.expect(search.selectedMatch() == null); + + // Select our next match (first) + try search.searchAll(); + _ = try search.select(.next); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Next match + _ = try search.select(.next); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Next match (wrap) + _ = try search.select(.next); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "select in active changes contents completely" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 5 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + _ = try search.select(.next); + _ = try search.select(.next); + { + // Initial selection is the first fizz + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Erase the screen, move our cursor to the top, and change contents. + s.nextSlice("\x1b[2J\x1b[H"); // Clear screen and move home + s.nextSlice("Fuzz\r\nFizz\r\nHello!"); + + try search.reloadActive(); + { + // Our selection should move to the first + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Erase the screen, redraw with same contents. + s.nextSlice("\x1b[2J\x1b[H"); // Clear screen and move home + s.nextSlice("Fuzz\r\nFizz\r\nFizz"); + + try search.reloadActive(); + { + // Our selection should not move to the first + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "select into history" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("Fizz\r\n"); + while (list.totalPages() < 3) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("hello."); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + + // Get all matches + _ = try search.select(.next); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Erase the screen, redraw with same contents. + s.nextSlice("\x1b[2J\x1b[H"); // Clear screen and move home + s.nextSlice("yo yo"); + + try search.reloadActive(); + { + // Our selection should not move since the history is still active. + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Create some new history by adding more lines. + s.nextSlice("\r\nfizz\r\nfizz\r\nfizz"); // Clear screen and move home + try search.reloadActive(); + { + // Our selection should not move since the history is still not + // pruned. + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "select prev" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + + // Initially no selection + try testing.expect(search.selectedMatch() == null); + + // Select prev (oldest first) + try search.searchAll(); + _ = try search.select(.prev); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Prev match (towards newest) + _ = try search.select(.prev); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Prev match (wrap) + _ = try search.select(.prev); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } +} + +test "select prev then next" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + + // Select next (newest first) + _ = try search.select(.next); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + } + + // Select next (older) + _ = try search.select(.next); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + } + + // Select prev (back to newer) + _ = try search.select(.prev); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + } +} + +test "select prev with history" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + s.nextSlice("Fizz\r\n"); + while (list.totalPages() < 3) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("Fizz."); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + + // Select prev (oldest first, should be in history) + _ = try search.select(.prev); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + + // Select prev (towards newer, should move to active area) + _ = try search.select(.prev); + { + const sel = search.selectedMatch().?.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } +} + +test "screen search no scrollback has no history" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = 0, + }); + defer t.deinit(alloc); + + // Alt screen has no scrollback + _ = try t.switchScreen(.alternate); + + var s = t.vtStream(); + defer s.deinit(); + + // This will probably stop working at some point and we'll have + // no way to test it using public APIs, but at the time of writing + // this test, CSI 22 J (scroll complete) pushes into scrollback + // with alt screen. + s.nextSlice("Fizz\r\n"); + s.nextSlice("\x1b[22J"); + s.nextSlice("hello."); + + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + try testing.expectEqual(0, search.active_results.items.len); + + // Get all matches + const matches = try search.matches(alloc); + defer alloc.free(matches); + try testing.expectEqual(0, matches.len); +} + +test "reloadActive partial history cleanup on appendSlice error" { + // This test verifies that when reloadActive fails at appendSlice (after + // the loop), all FlattenedHighlight items are properly cleaned up. + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + // Write multiple "Fizz" matches that will end up in history. + // We need enough content to push "Fizz" entries into scrollback. + s.nextSlice("Fizz\r\nFizz\r\n"); + while (list.totalPages() < 3) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("Fizz."); + + // Complete initial search + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + + // Now trigger reloadActive by adding more content that changes the + // active/history boundary. First add more "Fizz" entries to history. + s.nextSlice("\r\nFizz\r\nFizz\r\n"); + while (list.totalPages() < 4) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + + // Arm the tripwire to fail at appendSlice (after the loop completes). + // At this point, there are FlattenedHighlight items in the results list + // that need cleanup. + const tw = reloadActive_tw; + defer tw.end(.reset) catch unreachable; + tw.errorAlways(.history_append_existing, error.OutOfMemory); + + // reloadActive is called by select(), which should trigger the error path. + // If the bug exists, testing.allocator will report a memory leak + // because FlattenedHighlight items weren't cleaned up. + try testing.expectError(error.OutOfMemory, search.select(.next)); +} + +test "reloadActive partial history cleanup on loop append error" { + // This test verifies that when reloadActive fails inside the loop + // (after some items have been appended), all FlattenedHighlight items + // are properly cleaned up. + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + // Write multiple "Fizz" matches that will end up in history. + // We need enough content to push "Fizz" entries into scrollback. + s.nextSlice("Fizz\r\nFizz\r\n"); + while (list.totalPages() < 3) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("Fizz."); + + // Complete initial search + var search: ScreenSearch = try .init(alloc, t.screens.active, "Fizz"); + defer search.deinit(); + try search.searchAll(); + + // Now trigger reloadActive by adding more content that changes the + // active/history boundary. First add more "Fizz" entries to history. + s.nextSlice("\r\nFizz\r\nFizz\r\n"); + while (list.totalPages() < 4) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + + // Arm the tripwire to fail after the first loop append succeeds. + // This leaves at least one FlattenedHighlight in the results list + // that needs cleanup. + const tw = reloadActive_tw; + defer tw.end(.reset) catch unreachable; + tw.errorAfter(.history_append_new, error.OutOfMemory, 1); + + // reloadActive is called by select(), which should trigger the error path. + // If the bug exists, testing.allocator will report a memory leak + // because FlattenedHighlight items weren't cleaned up. + try testing.expectError(error.OutOfMemory, search.select(.next)); +} + +test "select after clearing scrollback" { + // Regression test for: https://github.com/ghostty-org/ghostty/issues/11957 + // After clearing scrollback (CSI 3J), selecting next/prev should not crash. + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + // Write enough content to push matches into scrollback history. + s.nextSlice("error\r\n"); + while (list.totalPages() < 3) s.nextSlice("error\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("error."); + + // Start search and find all matches. + var search: ScreenSearch = try .init(alloc, t.screens.active, "error"); + defer search.deinit(); + try search.searchAll(); + + // Should have matches in both history and active areas. + try testing.expect(search.history_results.items.len > 0); + try testing.expect(search.active_results.items.len > 0); + + // Select a match first (so we have a selection). + _ = try search.select(.next); + try testing.expect(search.selected != null); + + // Clear scrollback (equivalent to CSI 3J / Cmd+K erasing scrollback). + t.eraseDisplay(.scrollback, false); + + // Selecting next/prev after clearing scrollback should not crash. + // Before the fix, this would hit an assertion in trackPin because + // the FlattenedHighlight contained dangling node pointers. + _ = try search.select(.next); + _ = try search.select(.prev); +} diff --git a/vendor/libghostty-vt/src/terminal/search/sliding_window.zig b/vendor/libghostty-vt/src/terminal/search/sliding_window.zig new file mode 100644 index 00000000..93a606fd --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/sliding_window.zig @@ -0,0 +1,1676 @@ +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const Allocator = std.mem.Allocator; +const CircBuf = @import("../../datastruct/main.zig").CircBuf; +const terminal = @import("../main.zig"); +const point = terminal.point; +const size = terminal.size; +const PageList = terminal.PageList; +const Pin = PageList.Pin; +const Selection = terminal.Selection; +const Screen = terminal.Screen; +const Terminal = terminal.Terminal; +const PageFormatter = @import("../formatter.zig").PageFormatter; +const FlattenedHighlight = terminal.highlight.Flattened; + +/// Searches page nodes via a sliding window. The sliding window maintains +/// the invariant that data isn't pruned until (1) we've searched it and +/// (2) we've accounted for overlaps across pages to fit the needle. +/// +/// The sliding window is first initialized empty. Pages are then appended +/// in the order to search them. The sliding window supports both a forward +/// and reverse order specified via `init`. The pages should be appended +/// in the correct order matching the search direction. +/// +/// All appends grow the window. The window is only pruned when a search +/// is done (positive or negative match) via `next()`. +/// +/// To avoid unnecessary memory growth, the recommended usage is to +/// call `next()` until it returns null and then `append` the next page +/// and repeat the process. This will always maintain the minimum +/// required memory to search for the needle. +/// +/// The caller is responsible for providing the pages and ensuring they're +/// in the proper order. The SlidingWindow itself doesn't own the pages, but +/// it will contain pointers to them in order to return selections. If any +/// pages become invalid, the caller should clear the sliding window and +/// start over. +pub const SlidingWindow = struct { + /// The allocator to use for all the data within this window. We + /// store this rather than passing it around because its already + /// part of multiple elements (eg. Meta's CellMap) and we want to + /// ensure we always use a consistent allocator. Additionally, only + /// a small amount of sliding windows are expected to be in use + /// at any one time so the memory overhead isn't that large. + alloc: Allocator, + + /// The data buffer is a circular buffer of u8 that contains the + /// encoded page text that we can use to search for the needle. + data: DataBuf, + + /// The meta buffer is a circular buffer that contains the metadata + /// about the pages we're searching. This usually isn't that large + /// so callers must iterate through it to find the offset to map + /// data to meta. + meta: MetaBuf, + + /// Buffer that can fit any amount of chunks necessary for next + /// to never fail allocation. + chunk_buf: std.MultiArrayList(FlattenedHighlight.Chunk), + + /// Offset into data for our current state. This handles the + /// situation where our search moved through meta[0] but didn't + /// do enough to prune it. + data_offset: usize = 0, + + /// The needle we're searching for. Does own the memory. + needle: []const u8, + + /// The search direction. If the direction is forward then pages should + /// be appended in forward linked list order from the PageList. If the + /// direction is reverse then pages should be appended in reverse order. + /// + /// This is important because in most cases, a reverse search is going + /// to be more desirable to search from the end of the active area + /// backwards so more recent data is found first. Supporting both is + /// trivial though and will let us do more complex optimizations in the + /// future (e.g. starting from the viewport and doing a forward/reverse + /// concurrently from that point). + direction: Direction, + + /// A buffer to store the overlap search data. This is used to search + /// overlaps between pages where the match starts on one page and + /// ends on another. The length is always `needle.len * 2`. + overlap_buf: []u8, + + const Direction = enum { forward, reverse }; + const DataBuf = CircBuf(u8, 0); + const MetaBuf = CircBuf(Meta, undefined); + const Meta = struct { + node: *PageList.List.Node, + serial: u64, + cell_map: std.ArrayList(point.Coordinate), + + pub fn deinit(self: *Meta, alloc: Allocator) void { + self.cell_map.deinit(alloc); + } + }; + + pub fn init( + alloc: Allocator, + direction: Direction, + needle_unowned: []const u8, + ) Allocator.Error!SlidingWindow { + var data = try DataBuf.init(alloc, 0); + errdefer data.deinit(alloc); + + var meta = try MetaBuf.init(alloc, 0); + errdefer meta.deinit(alloc); + + const needle = try alloc.dupe(u8, needle_unowned); + errdefer alloc.free(needle); + switch (direction) { + .forward => {}, + .reverse => std.mem.reverse(u8, needle), + } + + const overlap_buf = try alloc.alloc(u8, needle.len * 2); + errdefer alloc.free(overlap_buf); + + return .{ + .alloc = alloc, + .data = data, + .meta = meta, + .chunk_buf = .empty, + .needle = needle, + .direction = direction, + .overlap_buf = overlap_buf, + }; + } + + pub fn deinit(self: *SlidingWindow) void { + self.alloc.free(self.overlap_buf); + self.alloc.free(self.needle); + self.chunk_buf.deinit(self.alloc); + self.data.deinit(self.alloc); + + var meta_it = self.meta.iterator(.forward); + while (meta_it.next()) |meta| meta.deinit(self.alloc); + self.meta.deinit(self.alloc); + } + + /// Clear all data but retain allocated capacity. + pub fn clearAndRetainCapacity(self: *SlidingWindow) void { + var meta_it = self.meta.iterator(.forward); + while (meta_it.next()) |meta| meta.deinit(self.alloc); + self.meta.clear(); + self.data.clear(); + self.data_offset = 0; + } + + /// Search the window for the next occurrence of the needle. As + /// the window moves, the window will prune itself while maintaining + /// the invariant that the window is always big enough to contain + /// the needle. + /// + /// This returns a flattened highlight on a match. The + /// flattened highlight requires allocation and is therefore more expensive + /// than a normal selection, but it is more efficient to render since it + /// has all the information without having to dereference pointers into + /// the terminal state. + /// + /// The flattened highlight chunks reference internal memory for this + /// sliding window and are only valid until the next call to `next()` + /// or `append()`. If the caller wants to retain the flattened highlight + /// then they should clone it. + pub fn next(self: *SlidingWindow) ?FlattenedHighlight { + const slices = slices: { + // If we have less data then the needle then we can't possibly match + const data_len = self.data.len(); + if (data_len < self.needle.len) return null; + + break :slices self.data.getPtrSlice( + self.data_offset, + data_len - self.data_offset, + ); + }; + + // Search the first slice for the needle. + if (std.ascii.indexOfIgnoreCase(slices[0], self.needle)) |idx| { + return self.highlight( + idx, + self.needle.len, + ); + } + + // Search the overlap buffer for the needle. + if (slices[0].len > 0 and slices[1].len > 0) overlap: { + // Get up to needle.len - 1 bytes from each side (as much as + // we can) and store it in the overlap buffer. + const prefix: []const u8 = prefix: { + const len = @min(slices[0].len, self.needle.len - 1); + const idx = slices[0].len - len; + break :prefix slices[0][idx..]; + }; + const suffix: []const u8 = suffix: { + const len = @min(slices[1].len, self.needle.len - 1); + break :suffix slices[1][0..len]; + }; + const overlap_len = prefix.len + suffix.len; + assert(overlap_len <= self.overlap_buf.len); + @memcpy(self.overlap_buf[0..prefix.len], prefix); + @memcpy(self.overlap_buf[prefix.len..overlap_len], suffix); + + // Search the overlap + const idx = std.ascii.indexOfIgnoreCase( + self.overlap_buf[0..overlap_len], + self.needle, + ) orelse break :overlap; + + // We found a match in the overlap buffer. We need to map the + // index back to the data buffer in order to get our selection. + return self.highlight( + slices[0].len - prefix.len + idx, + self.needle.len, + ); + } + + // Search the last slice for the needle. + if (std.ascii.indexOfIgnoreCase(slices[1], self.needle)) |idx| { + return self.highlight( + slices[0].len + idx, + self.needle.len, + ); + } + + // Special case 1-lengthed needles to delete the entire buffer. + if (self.needle.len == 1) { + self.clearAndRetainCapacity(); + self.assertIntegrity(); + return null; + } + + // No match. We keep `needle.len - 1` bytes available to + // handle the future overlap case. + prune: { + var meta_it = self.meta.iterator(.reverse); + var saved: usize = 0; + while (meta_it.next()) |meta| { + const needed = self.needle.len - 1 - saved; + if (meta.cell_map.items.len >= needed) { + // We save up to this meta. We set our data offset + // to exactly where it needs to be to continue + // searching. + self.data_offset = meta.cell_map.items.len - needed; + break; + } + + saved += meta.cell_map.items.len; + } else { + // If we exited the while loop naturally then we + // never got the amount we needed and so there is + // nothing to prune. + assert(saved < self.needle.len - 1); + break :prune; + } + + const prune_count = self.meta.len() - meta_it.idx; + if (prune_count == 0) { + // This can happen if we need to save up to the first + // meta value to retain our window. + break :prune; + } + + // We can now delete all the metas up to but NOT including + // the meta we found through meta_it. + meta_it = self.meta.iterator(.forward); + var prune_data_len: usize = 0; + for (0..prune_count) |_| { + const meta = meta_it.next().?; + prune_data_len += meta.cell_map.items.len; + meta.deinit(self.alloc); + } + self.meta.deleteOldest(prune_count); + self.data.deleteOldest(prune_data_len); + } + + // Our data offset now moves to needle.len - 1 from the end so + // that we can handle the overlap case. + self.data_offset = self.data.len() - self.needle.len + 1; + + self.assertIntegrity(); + return null; + } + + /// Return a flattened highlight for the given start and length. + /// + /// The flattened highlight can be used to render the highlight + /// in the most efficient way because it doesn't require a terminal + /// lock to access terminal data to compare whether some viewport + /// matches the highlight (because it doesn't need to traverse + /// the page nodes). + /// + /// The start index is assumed to be relative to the offset. i.e. + /// index zero is actually at `self.data[self.data_offset]`. The + /// selection will account for the offset. + fn highlight( + self: *SlidingWindow, + start_offset: usize, + len: usize, + ) terminal.highlight.Flattened { + const start = start_offset + self.data_offset; + const end = start + len - 1; + if (comptime std.debug.runtime_safety) { + assert(start < self.data.len()); + assert(start + len <= self.data.len()); + } + + // Clear our previous chunk buffer to store this result + self.chunk_buf.clearRetainingCapacity(); + var result: terminal.highlight.Flattened = .empty; + + // Go through the meta nodes to find our start. + const tl: struct { + /// If non-null, we need to continue searching for the bottom-right. + br: ?struct { + it: MetaBuf.Iterator, + consumed: usize, + }, + + /// Data to prune, both are lengths. + prune: struct { + meta: usize, + data: usize, + }, + } = tl: { + var meta_it = self.meta.iterator(.forward); + var meta_consumed: usize = 0; + while (meta_it.next()) |meta| { + // Always increment our consumed count so that our index + // is right for the end search if we do it. + const prior_meta_consumed = meta_consumed; + meta_consumed += meta.cell_map.items.len; + + // meta_i is the index we expect to find the match in the + // cell map within this meta if it contains it. + const meta_i = start - prior_meta_consumed; + + // This meta doesn't contain the match. This means we + // can also prune this set of data because we only look + // forward. + if (meta_i >= meta.cell_map.items.len) continue; + + // Now we look for the end. In MOST cases it is the same as + // our starting chunk because highlights are usually small and + // not on a boundary, so let's optimize for that. + const end_i = end - prior_meta_consumed; + if (end_i < meta.cell_map.items.len) { + @branchHint(.likely); + + // The entire highlight is within this meta. + const start_map = meta.cell_map.items[meta_i]; + const end_map = meta.cell_map.items[end_i]; + result.top_x = start_map.x; + result.bot_x = end_map.x; + self.chunk_buf.appendAssumeCapacity(.{ + .node = meta.node, + .serial = meta.serial, + .start = @intCast(start_map.y), + .end = @intCast(end_map.y + 1), + }); + + break :tl .{ + .br = null, + .prune = .{ + .meta = meta_it.idx - 1, + .data = prior_meta_consumed, + }, + }; + } else { + // We found the meta that contains the start of the match + // only. Consume this entire node from our start offset. + const map = meta.cell_map.items[meta_i]; + result.top_x = map.x; + self.chunk_buf.appendAssumeCapacity(.{ + .node = meta.node, + .serial = meta.serial, + .start = @intCast(map.y), + .end = meta.node.data.size.rows, + }); + + break :tl .{ + .br = .{ + .it = meta_it, + .consumed = meta_consumed, + }, + .prune = .{ + .meta = meta_it.idx - 1, + .data = prior_meta_consumed, + }, + }; + } + } else { + // Precondition that the start index is within the data buffer. + unreachable; + } + }; + + // Search for our end. + if (tl.br) |br| { + var meta_it = br.it; + var meta_consumed: usize = br.consumed; + while (meta_it.next()) |meta| { + // meta_i is the index we expect to find the match in the + // cell map within this meta if it contains it. + const meta_i = end - meta_consumed; + if (meta_i >= meta.cell_map.items.len) { + // This meta doesn't contain the match. We still add it + // to our results because we want the full flattened list. + self.chunk_buf.appendAssumeCapacity(.{ + .node = meta.node, + .serial = meta.serial, + .start = 0, + .end = meta.node.data.size.rows, + }); + + meta_consumed += meta.cell_map.items.len; + continue; + } + + // We found it + const map = meta.cell_map.items[meta_i]; + result.bot_x = map.x; + self.chunk_buf.appendAssumeCapacity(.{ + .node = meta.node, + .serial = meta.serial, + .start = 0, + .end = @intCast(map.y + 1), + }); + break; + } else { + // Precondition that the end index is within the data buffer. + unreachable; + } + } + + // Our offset into the current meta block is the start index + // minus the amount of data fully consumed. We then add one + // to move one past the match so we don't repeat it. + self.data_offset = start - tl.prune.data + 1; + + // If we went beyond our initial meta node we can prune. + if (tl.prune.meta > 0) { + // Deinit all our memory in the meta blocks prior to our + // match. + var meta_it = self.meta.iterator(.forward); + var meta_consumed: usize = 0; + for (0..tl.prune.meta) |_| { + const meta: *Meta = meta_it.next().?; + meta_consumed += meta.cell_map.items.len; + meta.deinit(self.alloc); + } + if (comptime std.debug.runtime_safety) { + assert(meta_it.idx == tl.prune.meta); + assert(meta_it.next().?.node == self.chunk_buf.items(.node)[0]); + } + self.meta.deleteOldest(tl.prune.meta); + + // Delete all the data up to our current index. + assert(tl.prune.data > 0); + self.data.deleteOldest(tl.prune.data); + } + + switch (self.direction) { + .forward => {}, + .reverse => { + const slice = self.chunk_buf.slice(); + const nodes = slice.items(.node); + const starts = slice.items(.start); + const ends = slice.items(.end); + + if (self.chunk_buf.len > 1) { + // Reverse all our chunks. This should be pretty obvious why. + std.mem.reverse(*PageList.List.Node, nodes); + std.mem.reverse(size.CellCountInt, starts); + std.mem.reverse(size.CellCountInt, ends); + + // Now normally with forward traversal with multiple pages, + // the suffix of the first page and the prefix of the last + // page are used. + // + // For a reverse traversal, this is inverted (since the + // pages are in reverse order we get the suffix of the last + // page and the prefix of the first page). So we need to + // invert this. + // + // We DON'T need to do this for any middle pages because + // they always use the full page. + // + // This is a fixup that makes our start/end match the + // same logic as the loops above if they were in forward + // order. + assert(nodes.len >= 2); + starts[0] = ends[0] - 1; + ends[0] = nodes[0].data.size.rows; + ends[nodes.len - 1] = starts[nodes.len - 1] + 1; + starts[nodes.len - 1] = 0; + } else { + // For a single chunk, the y values are in reverse order + // (start is the screen-end, end is the screen-start). + // Swap them to get proper top-to-bottom order. + const start_y = starts[0]; + starts[0] = ends[0] - 1; + ends[0] = start_y + 1; + } + + // X values also need to be reversed since the top/bottom + // are swapped for the nodes. + const top_x = result.top_x; + result.top_x = result.bot_x; + result.bot_x = top_x; + }, + } + + // Copy over our MultiArrayList so it points to the proper memory. + result.chunks = self.chunk_buf; + return result; + } + + /// Add a new node to the sliding window. This will always grow + /// the sliding window; data isn't pruned until it is consumed + /// via a search (via next()). + /// + /// Returns the number of bytes of content added to the sliding window. + /// The total bytes will be larger since this omits metadata, but it is + /// an accurate measure of the text content size added. + pub fn append( + self: *SlidingWindow, + node: *PageList.List.Node, + ) Allocator.Error!usize { + // Initialize our metadata for the node. + var meta: Meta = .{ + .node = node, + .serial = node.serial, + .cell_map = .empty, + }; + errdefer meta.deinit(self.alloc); + + // This is suboptimal but we need to encode the page once to + // temporary memory, and then copy it into our circular buffer. + // In the future, we should benchmark and see if we can encode + // directly into the circular buffer. + var encoded: std.Io.Writer.Allocating = .init(self.alloc); + defer encoded.deinit(); + + // Encode the page into the buffer. + const formatter: PageFormatter = formatter: { + var formatter: PageFormatter = .init(&meta.node.data, .{ + .emit = .plain, + .unwrap = true, + }); + formatter.point_map = .{ + .alloc = self.alloc, + .map = &meta.cell_map, + }; + break :formatter formatter; + }; + formatter.format(&encoded.writer) catch { + // writer uses anyerror but the only realistic error on + // an ArrayList is out of memory. + return error.OutOfMemory; + }; + assert(meta.cell_map.items.len == encoded.written().len); + + // If the node we're adding isn't soft-wrapped, we add the + // trailing newline. + const row = node.data.getRow(node.data.size.rows - 1); + if (!row.wrap) { + encoded.writer.writeByte('\n') catch return error.OutOfMemory; + try meta.cell_map.append( + self.alloc, + meta.cell_map.getLastOrNull() orelse .{ + .x = 0, + .y = 0, + }, + ); + } + + // If our written data is empty, then there is nothing to + // add to our data set. + const written = encoded.written(); + if (written.len == 0) { + self.assertIntegrity(); + return 0; + } + + // Get our written data. If we're doing a reverse search then we + // need to reverse all our encodings. + switch (self.direction) { + .forward => {}, + .reverse => { + std.mem.reverse(u8, written); + std.mem.reverse(point.Coordinate, meta.cell_map.items); + }, + } + + // Ensure our buffers are big enough to store what we need. + try self.data.ensureUnusedCapacity(self.alloc, written.len); + try self.meta.ensureUnusedCapacity(self.alloc, 1); + try self.chunk_buf.ensureTotalCapacity(self.alloc, self.meta.capacity()); + + // Append our new node to the circular buffer. + self.data.appendSliceAssumeCapacity(written); + self.meta.appendAssumeCapacity(meta); + + self.assertIntegrity(); + return written.len; + } + + /// Only for tests! + fn testChangeNeedle(self: *SlidingWindow, new: []const u8) void { + assert(new.len == self.needle.len); + self.alloc.free(self.needle); + self.needle = self.alloc.dupe(u8, new) catch unreachable; + } + + fn assertIntegrity(self: *const SlidingWindow) void { + if (comptime !std.debug.runtime_safety) return; + + // We don't run integrity checks on Valgrind because its soooooo slow, + // Valgrind is our integrity checker, and we run these during unit + // tests (non-Valgrind) anyways so we're verifying anyways. + if (std.valgrind.runningOnValgrind() > 0) return; + + // Integrity check: verify our data matches our metadata exactly. + var meta_it = self.meta.iterator(.forward); + var data_len: usize = 0; + while (meta_it.next()) |m| data_len += m.cell_map.items.len; + assert(data_len == self.data.len()); + + // Integrity check: verify our data offset is within bounds. + assert(self.data.len() == 0 or self.data_offset < self.data.len()); + } +}; + +test "SlidingWindow empty on init" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "boo!"); + defer w.deinit(); + try testing.expectEqual(0, w.data.len()); + try testing.expectEqual(0, w.meta.len()); +} + +test "SlidingWindow single append" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "boo!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello. boo! hello. boo!"); + + // We want to test single-page cases. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + + // We should be able to find two matches. + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 10, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end)); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 22, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end)); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append case insensitive ASCII" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "Boo!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello. boo! hello. boo!"); + + // We want to test single-page cases. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + + // We should be able to find two matches. + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 10, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end)); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 22, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end)); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append single char" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "b"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello. boo! hello. boo!"); + + // We want to test single-page cases. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + + // We should be able to find two matches. + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end)); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end)); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append no match" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "nope!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello. boo! hello. boo!"); + + // We want to test single-page cases. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + + // No matches + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // Should still keep the page + try testing.expectEqual(1, w.meta.len()); +} + +test "SlidingWindow two pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "boo!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Add both pages + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node.next.?); + + // Search should find two matches + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 76, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 79, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 10, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow two pages single char" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "b"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Add both pages + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node.next.?); + + // Search should find two matches + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 76, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 76, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow two pages match across boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "hello, world"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("hell"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("o, world!"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + + // Add both pages + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node.next.?); + + // Search should find a match + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 76, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // We shouldn't prune because we don't have enough space + try testing.expectEqual(2, w.meta.len()); +} + +test "SlidingWindow two pages no match across boundary with newline" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "hello, world"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("hell"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\no, world!"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + + // Add both pages + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node.next.?); + + // Search should NOT find a match + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // We shouldn't prune because we don't have enough space + try testing.expectEqual(2, w.meta.len()); +} + +test "SlidingWindow two pages no match across boundary with newline reverse" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "hello, world"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("hell"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\no, world!"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + + // Add both pages in reverse order + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node.next.?); + _ = try w.append(node); + + // Search should NOT find a match + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow two pages no match prunes first page" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "nope!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Add both pages + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node.next.?); + + // Search should find nothing + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // We should've pruned our page because the second page + // has enough text to contain our needle. + try testing.expectEqual(1, w.meta.len()); +} + +test "SlidingWindow two pages no match keeps both pages" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Imaginary needle for search. Doesn't match! + var needle_list: std.ArrayList(u8) = .empty; + defer needle_list.deinit(alloc); + try needle_list.appendNTimes(alloc, 'x', first_page_rows * s.pages.cols); + const needle: []const u8 = needle_list.items; + + var w: SlidingWindow = try .init(alloc, .forward, needle); + defer w.deinit(); + + // Add both pages + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node.next.?); + + // Search should find nothing + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // No pruning because both pages are needed to fit needle. + try testing.expectEqual(2, w.meta.len()); +} + +test "SlidingWindow single append across circular buffer boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "abc"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("XXXXXXXXXXXXXXXXXXXboo!XXXXX"); + + // We are trying to break a circular buffer boundary so the way we + // do this is to duplicate the data then do a failing search. This + // will cause the first page to be pruned. The next time we append we'll + // put it in the middle of the circ buffer. We assert this so that if + // our implementation changes our test will fail. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node); + { + // No wrap around yet + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len == 0); + } + + // Search non-match, prunes page + try testing.expect(w.next() == null); + try testing.expectEqual(1, w.meta.len()); + + // Change the needle, just needs to be the same length (not a real API) + w.testChangeNeedle("boo"); + + // Add new page, now wraps + _ = try w.append(node); + { + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len > 0); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 21, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append match on boundary" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "abcd"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("o!XXXXXXXXXXXXXXXXXXXbo"); + + // We need to surgically modify the last row to be soft-wrapped + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + node.data.getRow(node.data.size.rows - 1).wrap = true; + + // We are trying to break a circular buffer boundary so the way we + // do this is to duplicate the data then do a failing search. This + // will cause the first page to be pruned. The next time we append we'll + // put it in the middle of the circ buffer. We assert this so that if + // our implementation changes our test will fail. + _ = try w.append(node); + _ = try w.append(node); + { + // No wrap around yet + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len == 0); + } + + // Search non-match, prunes page + try testing.expect(w.next() == null); + try testing.expectEqual(1, w.meta.len()); + + // Change the needle, just needs to be the same length (not a real API) + w.testChangeNeedle("boo!"); + + // Add new page, now wraps + _ = try w.append(node); + { + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len > 0); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 21, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "boo!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello. boo! hello. boo!"); + + // We want to test single-page cases. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + + // We should be able to find two matches. + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 22, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 10, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append no match reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "nope!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("hello. boo! hello. boo!"); + + // We want to test single-page cases. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + + // No matches + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // Should still keep the page + try testing.expectEqual(1, w.meta.len()); +} + +test "SlidingWindow two pages reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "boo!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Add both pages in reverse order + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node.next.?); + _ = try w.append(node); + + // Search should find two matches (in reverse order) + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 10, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 76, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 79, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow two pages match across boundary reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "hello, world"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "hell" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("hell"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("o, world!"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + + // Add both pages in reverse order + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node.next.?); + _ = try w.append(node); + + // Search should find a match + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 76, + .y = 22, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 7, + .y = 23, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // In reverse mode, the last appended meta (first original page) is large + // enough to contain needle.len - 1 bytes, so pruning occurs + try testing.expectEqual(1, w.meta.len()); +} + +test "SlidingWindow two pages no match prunes first page reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "nope!"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Add both pages in reverse order + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node.next.?); + _ = try w.append(node); + + // Search should find nothing + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // We should've pruned our page because the second page + // has enough text to contain our needle. + try testing.expectEqual(1, w.meta.len()); +} + +test "SlidingWindow two pages no match keeps both pages reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + defer s.deinit(); + + // Fill up the first page. The final bytes in the first page + // are "boo!" + const first_page_rows = s.pages.pages.first.?.data.capacity.rows; + for (0..first_page_rows - 1) |_| try s.testWriteString("\n"); + for (0..s.pages.cols - 4) |_| try s.testWriteString("x"); + try s.testWriteString("boo!"); + try testing.expect(s.pages.pages.first == s.pages.pages.last); + try s.testWriteString("\n"); + try testing.expect(s.pages.pages.first != s.pages.pages.last); + try s.testWriteString("hello. boo!"); + + // Imaginary needle for search. Doesn't match! + var needle_list: std.ArrayList(u8) = .empty; + defer needle_list.deinit(alloc); + try needle_list.appendNTimes(alloc, 'x', first_page_rows * s.pages.cols); + const needle: []const u8 = needle_list.items; + + var w: SlidingWindow = try .init(alloc, .reverse, needle); + defer w.deinit(); + + // Add both pages in reverse order + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node.next.?); + _ = try w.append(node); + + // Search should find nothing + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); + + // No pruning because both pages are needed to fit needle. + try testing.expectEqual(2, w.meta.len()); +} + +test "SlidingWindow single append across circular buffer boundary reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "abc"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("XXXXXXXXXXXXXXXXXXXboo!XXXXX"); + + // We are trying to break a circular buffer boundary so the way we + // do this is to duplicate the data then do a failing search. This + // will cause the first page to be pruned. The next time we append we'll + // put it in the middle of the circ buffer. We assert this so that if + // our implementation changes our test will fail. + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + _ = try w.append(node); + _ = try w.append(node); + { + // No wrap around yet + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len == 0); + } + + // Search non-match, prunes page + try testing.expect(w.next() == null); + try testing.expectEqual(1, w.meta.len()); + + // Change the needle, just needs to be the same length (not a real API) + // testChangeNeedle doesn't reverse, so pass reversed needle for reverse mode + w.testChangeNeedle("oob"); + + // Add new page, now wraps + _ = try w.append(node); + { + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len > 0); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 19, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 21, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append match on boundary reversed" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "abcd"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + defer s.deinit(); + try s.testWriteString("o!XXXXXXXXXXXXXXXXXXXbo"); + + // We need to surgically modify the last row to be soft-wrapped + try testing.expect(s.pages.pages.first == s.pages.pages.last); + const node: *PageList.List.Node = s.pages.pages.first.?; + node.data.getRow(node.data.size.rows - 1).wrap = true; + + // We are trying to break a circular buffer boundary so the way we + // do this is to duplicate the data then do a failing search. This + // will cause the first page to be pruned. The next time we append we'll + // put it in the middle of the circ buffer. We assert this so that if + // our implementation changes our test will fail. + _ = try w.append(node); + _ = try w.append(node); + { + // No wrap around yet + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len == 0); + } + + // Search non-match, prunes page + try testing.expect(w.next() == null); + try testing.expectEqual(1, w.meta.len()); + + // Change the needle, just needs to be the same length (not a real API) + // testChangeNeedle doesn't reverse, so pass reversed needle for reverse mode + w.testChangeNeedle("!oob"); + + // Add new page, now wraps + _ = try w.append(node); + { + const slices = w.data.getPtrSlice(0, w.data.len()); + try testing.expect(slices[0].len > 0); + try testing.expect(slices[1].len > 0); + } + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 21, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 0, + } }, s.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append soft wrapped" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "boo!"); + defer w.deinit(); + + var t: Terminal = try .init(alloc, .{ .cols = 4, .rows = 5 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("A\r\nxxboo!\r\nC"); + + // We want to test single-page cases. + const screen = t.screens.active; + try testing.expect(screen.pages.pages.first == screen.pages.pages.last); + const node: *PageList.List.Node = screen.pages.pages.first.?; + _ = try w.append(node); + + // We should be able to find two matches. + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 2, + .y = 1, + } }, screen.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 2, + } }, screen.pages.pointFromPin(.active, sel.end)); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +test "SlidingWindow single append reversed soft wrapped" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .reverse, "boo!"); + defer w.deinit(); + + var t: Terminal = try .init(alloc, .{ .cols = 4, .rows = 5 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("A\r\nxxboo!\r\nC"); + + // We want to test single-page cases. + const screen = t.screens.active; + try testing.expect(screen.pages.pages.first == screen.pages.pages.last); + const node: *PageList.List.Node = screen.pages.pages.first.?; + _ = try w.append(node); + + // We should be able to find two matches. + { + const h = w.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 2, + .y = 1, + } }, screen.pages.pointFromPin(.active, sel.start)); + try testing.expectEqual(point.Point{ .active = .{ + .x = 1, + .y = 2, + } }, screen.pages.pointFromPin(.active, sel.end)); + } + try testing.expect(w.next() == null); + try testing.expect(w.next() == null); +} + +// This tests a real bug that occurred where a whitespace-only page +// that encodes to zero bytes would crash. +test "SlidingWindow append whitespace only node" { + const testing = std.testing; + const alloc = testing.allocator; + + var w: SlidingWindow = try .init(alloc, .forward, "x"); + defer w.deinit(); + + var s = try Screen.init(alloc, .{ + .cols = 80, + .rows = 24, + .max_scrollback = 0, + }); + defer s.deinit(); + + // By setting the empty page to wrap we get a zero-byte page. + // This is invasive but its otherwise hard to reproduce naturally + // without creating a slow test. + const node: *PageList.List.Node = s.pages.pages.first.?; + const last_row = node.data.getRow(node.data.size.rows - 1); + last_row.wrap = true; + + try testing.expect(s.pages.pages.first == s.pages.pages.last); + _ = try w.append(node); + + // No matches expected + try testing.expect(w.next() == null); +} diff --git a/vendor/libghostty-vt/src/terminal/search/viewport.zig b/vendor/libghostty-vt/src/terminal/search/viewport.zig new file mode 100644 index 00000000..35dd9331 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/viewport.zig @@ -0,0 +1,384 @@ +const std = @import("std"); +const assert = @import("../../quirks.zig").inlineAssert; +const testing = std.testing; +const Allocator = std.mem.Allocator; +const point = @import("../point.zig"); +const size = @import("../size.zig"); +const FlattenedHighlight = @import("../highlight.zig").Flattened; +const PageList = @import("../PageList.zig"); +const SlidingWindow = @import("sliding_window.zig").SlidingWindow; +const Terminal = @import("../Terminal.zig"); + +/// Searches for a substring within the viewport of a PageList. +/// +/// This contains logic to efficiently detect when the viewport changes +/// and only re-search when necessary. +/// +/// The specialization for "viewport" is because the viewport is the +/// only part of the search where the user can actively see the results, +/// usually. In that case, it is more efficient to re-search only the +/// viewport rather than store all the results for the entire screen. +/// +/// Note that this searches all the pages that viewport covers, so +/// this can include extra matches outside the viewport if the data +/// lives in the same page. +pub const ViewportSearch = struct { + window: SlidingWindow, + fingerprint: ?Fingerprint, + + /// If this is null, then active dirty tracking is disabled and if the + /// viewport overlaps the active area we always re-search. If this is + /// non-null, then we only re-search if the active area is dirty. Dirty + /// marking is up to the caller. + active_dirty: ?bool, + + pub fn init( + alloc: Allocator, + needle_unowned: []const u8, + ) Allocator.Error!ViewportSearch { + // We just do a forward search since the viewport is usually + // pretty small so search results are instant anyways. This avoids + // a small amount of work to reverse things. + var window: SlidingWindow = try .init(alloc, .forward, needle_unowned); + errdefer window.deinit(); + return .{ + .window = window, + .fingerprint = null, + .active_dirty = null, + }; + } + + pub fn deinit(self: *ViewportSearch) void { + if (self.fingerprint) |*fp| fp.deinit(self.window.alloc); + self.window.deinit(); + } + + /// Reset our fingerprint and results so that the next update will + /// always re-search. + pub fn reset(self: *ViewportSearch) void { + if (self.fingerprint) |*fp| fp.deinit(self.window.alloc); + self.fingerprint = null; + self.window.clearAndRetainCapacity(); + } + + /// The needle that this search is using. + pub fn needle(self: *const ViewportSearch) []const u8 { + assert(self.window.direction == .forward); + return self.window.needle; + } + + /// Update the sliding window to reflect the current viewport. This + /// will do nothing if the viewport hasn't changed since the last + /// search. + /// + /// The PageList must be safe to read throughout the lifetime of this + /// function. + /// + /// Returns true if the viewport changed and a re-search is needed. + /// Returns false if the viewport is unchanged. + pub fn update( + self: *ViewportSearch, + list: *PageList, + ) Allocator.Error!bool { + // See if our viewport changed + var fingerprint: Fingerprint = try .init(self.window.alloc, list); + if (self.fingerprint) |*old| { + if (old.eql(fingerprint)) match: { + // Determine if we need to check if we overlap the active + // area. If we have dirty tracking on we also set it to + // false here. + const check_active: bool = active: { + const dirty = self.active_dirty orelse break :active true; + if (!dirty) break :active false; + self.active_dirty = false; + break :active true; + }; + + if (check_active) { + // If our fingerprint contains the active area, then we always + // re-search since the active area is mutable. + const active_tl = list.getTopLeft(.active); + const active_br = list.getBottomRight(.active).?; + + // If our viewport contains the start or end of the active area, + // we are in the active area. We purposely do this first + // because our viewport is always larger than the active area. + for (old.nodes) |node| { + if (node == active_tl.node) break :match; + if (node == active_br.node) break :match; + } + } + + // No change + fingerprint.deinit(self.window.alloc); + return false; + } + + old.deinit(self.window.alloc); + self.fingerprint = null; + } + assert(self.fingerprint == null); + self.fingerprint = fingerprint; + errdefer { + fingerprint.deinit(self.window.alloc); + self.fingerprint = null; + } + + // If our active area was set as dirty, we always unset it here + // because we're re-searching now. + if (self.active_dirty) |*v| v.* = false; + + // Clear our previous sliding window + self.window.clearAndRetainCapacity(); + + // Add enough overlap to cover needle.len - 1 bytes (if it + // exists) so we can cover the overlap. We only do this for the + // soft-wrapped prior pages. + var node_ = fingerprint.nodes[0].prev; + var added: usize = 0; + while (node_) |node| : (node_ = node.prev) { + // If the last row of this node isn't wrapped we can't overlap. + const row = node.data.getRow(node.data.size.rows - 1); + if (!row.wrap) break; + + // We could be more accurate here and count bytes since the + // last wrap but its complicated and unlikely multiple pages + // wrap so this should be fine. + added += try self.window.append(node); + if (added >= self.window.needle.len - 1) break; + } + + // We can use our fingerprint nodes to initialize our sliding + // window, since we already traversed the viewport once. + for (fingerprint.nodes) |node| { + _ = try self.window.append(node); + } + + // Add any trailing overlap as well. + trailing: { + const end: *PageList.List.Node = fingerprint.nodes[fingerprint.nodes.len - 1]; + if (!end.data.getRow(end.data.size.rows - 1).wrap) break :trailing; + + node_ = end.next; + added = 0; + while (node_) |node| : (node_ = node.next) { + added += try self.window.append(node); + if (added >= self.window.needle.len - 1) break; + + // If this row doesn't wrap, then we can quit + const row = node.data.getRow(node.data.size.rows - 1); + if (!row.wrap) break; + } + } + + return true; + } + + /// Find the next match for the needle in the active area. This returns + /// null when there are no more matches. + pub fn next(self: *ViewportSearch) ?FlattenedHighlight { + return self.window.next(); + } + + /// Viewport fingerprint so we can detect when the viewport moves. + const Fingerprint = struct { + /// The nodes that make up the viewport. We need to flatten this + /// to a single list because we can't safely traverse the cached values + /// because the page nodes may be invalid. All that is safe is comparing + /// the actual pointer values. + nodes: []const *PageList.List.Node, + + pub fn init(alloc: Allocator, pages: *PageList) Allocator.Error!Fingerprint { + var list: std.ArrayList(*PageList.List.Node) = .empty; + defer list.deinit(alloc); + + // Get our viewport area. Bottom right of a viewport can never + // fail. + const tl = pages.getTopLeft(.viewport); + const br = pages.getBottomRight(.viewport).?; + + var it = tl.pageIterator(.right_down, br); + while (it.next()) |chunk| try list.append(alloc, chunk.node); + return .{ .nodes = try list.toOwnedSlice(alloc) }; + } + + pub fn deinit(self: *Fingerprint, alloc: Allocator) void { + alloc.free(self.nodes); + } + + pub fn eql(self: Fingerprint, other: Fingerprint) bool { + if (self.nodes.len != other.nodes.len) return false; + for (self.nodes, other.nodes) |a, b| { + if (a != b) return false; + } + return true; + } + }; +}; + +test "simple search" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ViewportSearch = try .init(alloc, "Fizz"); + defer search.deinit(); + try testing.expect(try search.update(&t.screens.active.pages)); + + // Viewport contains active so update should always re-search. + try testing.expect(try search.update(&t.screens.active.pages)); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 2, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(search.next() == null); +} + +test "clear screen and search" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ViewportSearch = try .init(alloc, "Fizz"); + defer search.deinit(); + try testing.expect(try search.update(&t.screens.active.pages)); + + s.nextSlice("\x1b[2J"); // Clear screen + s.nextSlice("\x1b[H"); // Move cursor home + s.nextSlice("Buzz\r\nFizz\r\nBuzz"); + try testing.expect(try search.update(&t.screens.active.pages)); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(search.next() == null); +} + +test "clear screen and search dirty tracking" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: ViewportSearch = try .init(alloc, "Fizz"); + defer search.deinit(); + + // Turn on dirty tracking + search.active_dirty = false; + + // Should update since we've never searched before + try testing.expect(try search.update(&t.screens.active.pages)); + + // Should not update since nothing changed + try testing.expect(!try search.update(&t.screens.active.pages)); + + s.nextSlice("\x1b[2J"); // Clear screen + s.nextSlice("\x1b[H"); // Move cursor home + s.nextSlice("Buzz\r\nFizz\r\nBuzz"); + + // Should still not update since active area isn't dirty + try testing.expect(!try search.update(&t.screens.active.pages)); + + // Mark + search.active_dirty = true; + try testing.expect(try search.update(&t.screens.active.pages)); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .active = .{ + .x = 0, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.start).?); + try testing.expectEqual(point.Point{ .active = .{ + .x = 3, + .y = 1, + } }, t.screens.active.pages.pointFromPin(.active, sel.end).?); + } + try testing.expect(search.next() == null); +} + +test "history search, no active area" { + const alloc = testing.allocator; + var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + + // Fill up first page + const first_page_rows = t.screens.active.pages.pages.first.?.data.capacity.rows; + s.nextSlice("Fizz\r\n"); + for (1..first_page_rows - 1) |_| s.nextSlice("\r\n"); + try testing.expect(t.screens.active.pages.pages.first == t.screens.active.pages.pages.last); + + // Create second page + s.nextSlice("\r\n"); + try testing.expect(t.screens.active.pages.pages.first != t.screens.active.pages.pages.last); + s.nextSlice("Buzz\r\nFizz"); + + t.scrollViewport(.top); + + var search: ViewportSearch = try .init(alloc, "Fizz"); + defer search.deinit(); + try testing.expect(try search.update(&t.screens.active.pages)); + + { + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 0, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.start).?); + try testing.expectEqual(point.Point{ .screen = .{ + .x = 3, + .y = 0, + } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); + } + try testing.expect(search.next() == null); + + // Viewport doesn't contain active + try testing.expect(!try search.update(&t.screens.active.pages)); + try testing.expect(search.next() == null); +} diff --git a/vendor/libghostty-vt/src/terminal/sgr.zig b/vendor/libghostty-vt/src/terminal/sgr.zig new file mode 100644 index 00000000..e9b9354c --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/sgr.zig @@ -0,0 +1,1103 @@ +//! SGR (Select Graphic Rendition) attrinvbute parsing and types. + +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const testing = std.testing; +const lib = @import("lib.zig"); +const color = @import("color.zig"); +const SepList = @import("Parser.zig").Action.CSI.SepList; + +/// Attribute type for SGR +pub const Attribute = union(Tag) { + /// Unset all attributes + unset, + + /// Unknown attribute, the raw CSI command parameters are here. + unknown: Unknown, + + /// Bold the text. + bold, + reset_bold, + + /// Italic text. + italic, + reset_italic, + + /// Faint/dim text. + /// Note: reset faint is the same SGR code as reset bold + faint, + + /// Underline the text + underline: Underline, + underline_color: color.RGB, + @"256_underline_color": u8, + reset_underline_color, + + // Overline the text + overline, + reset_overline, + + /// Blink the text + blink, + reset_blink, + + /// Invert fg/bg colors. + inverse, + reset_inverse, + + /// Invisible + invisible, + reset_invisible, + + /// Strikethrough the text. + strikethrough, + reset_strikethrough, + + /// Set foreground color as RGB values. + direct_color_fg: color.RGB, + + /// Set background color as RGB values. + direct_color_bg: color.RGB, + + /// Set the background/foreground as a named color attribute. + @"8_bg": color.Name, + @"8_fg": color.Name, + + /// Reset the fg/bg to their default values. + reset_fg, + reset_bg, + + /// Set the background/foreground as a named bright color attribute. + @"8_bright_bg": color.Name, + @"8_bright_fg": color.Name, + + /// Set background color as 256-color palette. + @"256_bg": u8, + + /// Set foreground color as 256-color palette. + @"256_fg": u8, + + pub const Tag = lib.Enum( + lib.target, + &.{ + "unset", + "unknown", + "bold", + "reset_bold", + "italic", + "reset_italic", + "faint", + "underline", + "underline_color", + "256_underline_color", + "reset_underline_color", + "overline", + "reset_overline", + "blink", + "reset_blink", + "inverse", + "reset_inverse", + "invisible", + "reset_invisible", + "strikethrough", + "reset_strikethrough", + "direct_color_fg", + "direct_color_bg", + "8_bg", + "8_fg", + "reset_fg", + "reset_bg", + "8_bright_bg", + "8_bright_fg", + "256_bg", + "256_fg", + }, + ); + + pub const Unknown = struct { + /// Full is the full SGR input. + full: []const u16, + + /// Partial is the remaining, where we got hung up. + partial: []const u16, + + pub const C = extern struct { + full_ptr: [*]const u16, + full_len: usize, + partial_ptr: [*]const u16, + partial_len: usize, + }; + + pub fn cval(self: Unknown) Unknown.C { + return .{ + .full_ptr = self.full.ptr, + .full_len = self.full.len, + .partial_ptr = self.partial.ptr, + .partial_len = self.partial.len, + }; + } + }; + + pub const Underline = enum(u3) { + none = 0, + single = 1, + double = 2, + curly = 3, + dotted = 4, + dashed = 5, + + pub const C = c_int; + + pub fn cval(self: Underline) Underline.C { + return @intFromEnum(self); + } + }; + + /// C ABI functions. + const c_union = lib.TaggedUnion( + lib.target, + @This(), + // Padding size for C ABI compatibility. + // Largest variant is Unknown.C: 2 pointers + 2 usize = 32 bytes on 64-bit. + // We use [8]u64 (64 bytes) to allow room for future expansion while + // maintaining ABI compatibility. + [8]u64, + ); + pub const Value = c_union.Value; + pub const C = c_union.C; + pub const CValue = c_union.CValue; + pub const cval = c_union.cval; +}; + +/// Parser parses the attributes from a list of SGR parameters. +pub const Parser = struct { + params: []const u16 = &.{}, + params_sep: SepList = .initEmpty(), + idx: usize = 0, + + /// Empty state parser. + pub const empty: Parser = .{}; + + /// Next returns the next attribute or null if there are no more attributes. + pub fn next(self: *Parser) ?Attribute { + if (self.idx >= self.params.len) { + // We're more likely to not be done than to be done. + @branchHint(.unlikely); + + // Add one to ensure we don't loop on unset + defer self.idx += 1; + + // If we're at index zero it means we must have an empty list + // and an empty list implicitly means unset, otherwise we're + // done and return null. + return if (self.idx == 0) .unset else null; + } + + const slice = self.params[self.idx..self.params.len]; + // Call inlined for performance reasons. + const colon = @call( + .always_inline, + SepList.isSet, + .{ self.params_sep, self.idx }, + ); + self.idx += 1; + + // Our last one will have an idx be the last value. + if (slice.len == 0) return null; + + // If we have a colon separator then we need to ensure we're + // parsing a value that allows it. + if (colon) { + // Colons are fairly rare in the wild. + @branchHint(.unlikely); + + switch (slice[0]) { + 4, 38, 48, 58 => {}, + + else => { + // In real world use it's very rare + // that we receive an invalid sequence. + @branchHint(.cold); + + // Consume all the colon separated + // values and return them as unknown. + const start = self.idx; + while (self.params_sep.isSet(self.idx)) self.idx += 1; + self.idx += 1; + return .{ .unknown = .{ + .full = self.params, + .partial = slice[0..@min(self.idx - start + 1, slice.len)], + } }; + }, + } + } + + switch (slice[0]) { + 0 => return .unset, + + 1 => return .bold, + + 2 => return .faint, + + 3 => return .italic, + + 4 => underline: { + if (colon) { + // Colons are fairly rare in the wild. + @branchHint(.unlikely); + + // A trailing colon with no following sub-param + // (e.g. "ESC[58:4:m") leaves the colon separator + // bit set on the last param without adding another + // entry, so we can see param 4 with a colon but + // nothing after it. + if (slice.len < 2) { + @branchHint(.cold); + break :underline; + } + + if (self.isColon()) { + // Invalid/unknown SGRs are just not very likely. + @branchHint(.cold); + + self.consumeUnknownColon(); + break :underline; + } + + self.idx += 1; + return .{ + .underline = switch (slice[1]) { + 0 => .none, + 1 => .single, + 2 => .double, + 3 => .curly, + 4 => .dotted, + 5 => .dashed, + + // For unknown underline styles, + // just render a single underline. + else => single: { + // This is quite a rare condition. + @branchHint(.cold); + break :single .single; + }, + }, + }; + } + + return .{ .underline = .single }; + }, + + 5 => return .blink, + + 6 => return .blink, + + 7 => return .inverse, + + 8 => return .invisible, + + 9 => return .strikethrough, + + 21 => return .{ .underline = .double }, + + 22 => return .reset_bold, + + 23 => return .reset_italic, + + 24 => return .{ .underline = .none }, + + 25 => return .reset_blink, + + 27 => return .reset_inverse, + + 28 => return .reset_invisible, + + 29 => return .reset_strikethrough, + + 30...37 => return .{ + .@"8_fg" = @enumFromInt(slice[0] - 30), + }, + + 38 => if (slice.len >= 2) { + // We are very likely to have enough parameters. + @branchHint(.likely); + + switch (slice[1]) { + // `2` indicates direct-color (r, g, b). + // We need at least 3 more params for this to make sense. + 2 => if (self.parseDirectColor( + .direct_color_fg, + slice, + colon, + )) |v| return v, + + // `5` indicates indexed color. + 5 => if (slice.len >= 3) { + // We are very likely to have enough parameters. + @branchHint(.likely); + + self.idx += 2; + return .{ + .@"256_fg" = @truncate(slice[2]), + }; + }, + + else => {}, + } + }, + + 39 => return .reset_fg, + + 40...47 => return .{ + .@"8_bg" = @enumFromInt(slice[0] - 40), + }, + + 48 => if (slice.len >= 2) { + // We are very likely to have enough parameters. + @branchHint(.likely); + + switch (slice[1]) { + // `2` indicates direct-color (r, g, b). + // We need at least 3 more params for this to make sense. + 2 => if (self.parseDirectColor( + .direct_color_bg, + slice, + colon, + )) |v| return v, + + // `5` indicates indexed color. + 5 => if (slice.len >= 3) { + // We are very likely to have enough parameters. + @branchHint(.likely); + + self.idx += 2; + return .{ + .@"256_bg" = @truncate(slice[2]), + }; + }, + + else => {}, + } + }, + + 49 => return .reset_bg, + + 53 => return .overline, + 55 => return .reset_overline, + + 58 => if (slice.len >= 2) { + // We are very likely to have enough parameters. + @branchHint(.likely); + + switch (slice[1]) { + // `2` indicates direct-color (r, g, b). + // We need at least 3 more params for this to make sense. + 2 => if (self.parseDirectColor( + .underline_color, + slice, + colon, + )) |v| return v, + + // `5` indicates indexed color. + 5 => if (slice.len >= 3) { + // We are very likely to have enough parameters. + @branchHint(.likely); + + self.idx += 2; + return .{ + .@"256_underline_color" = @truncate(slice[2]), + }; + }, + else => {}, + } + }, + + 59 => return .reset_underline_color, + + 90...97 => return .{ + // 82 instead of 90 to offset to "bright" colors + .@"8_bright_fg" = @enumFromInt(slice[0] - 82), + }, + + 100...107 => return .{ + .@"8_bright_bg" = @enumFromInt(slice[0] - 92), + }, + + else => {}, + } + + return .{ .unknown = .{ .full = self.params, .partial = slice } }; + } + + fn parseDirectColor( + self: *Parser, + comptime tag: Attribute.Tag, + slice: []const u16, + colon: bool, + ) ?Attribute { + // Any direct color style must have at least 5 values. + if (slice.len < 5) return null; + + // Only used for direct color sets (38, 48, 58) and subparam 2. + assert(slice[1] == 2); + + // Note: We use @truncate because the value should be 0 to 255. If + // it isn't, the behavior is undefined so we just... truncate it. + + // If we don't have a colon, then we expect exactly 3 semicolon + // separated values. + if (!colon) { + // Semicolons are much more common than colons. + @branchHint(.likely); + + self.idx += 4; + return @unionInit(Attribute, @tagName(tag), .{ + .r = @truncate(slice[2]), + .g = @truncate(slice[3]), + .b = @truncate(slice[4]), + }); + } + + // We have a colon, we might have either 5 or 6 values depending + // on if the colorspace is present. + const count = self.countColon(); + switch (count) { + 3 => { + // This is the much more common case in the wild. + @branchHint(.likely); + + self.idx += 4; + return @unionInit(Attribute, @tagName(tag), .{ + .r = @truncate(slice[2]), + .g = @truncate(slice[3]), + .b = @truncate(slice[4]), + }); + }, + + 4 => { + self.idx += 5; + return @unionInit(Attribute, @tagName(tag), .{ + .r = @truncate(slice[3]), + .g = @truncate(slice[4]), + .b = @truncate(slice[5]), + }); + }, + + else => { + // Invalid/unknown SGRs just don't happen very often at all. + @branchHint(.cold); + + self.consumeUnknownColon(); + return null; + }, + } + } + + /// Returns true if the present position has a colon separator. + /// This always returns false for the last value since it has no + /// separator. + inline fn isColon(self: *Parser) bool { + // Call inlined for performance reasons. + return @call( + .always_inline, + SepList.isSet, + .{ self.params_sep, self.idx }, + ); + } + + fn countColon(self: *Parser) usize { + var count: usize = 0; + var idx = self.idx; + while (idx < self.params.len - 1 and self.params_sep.isSet(idx)) : (idx += 1) { + count += 1; + } + return count; + } + + /// Consumes all the remaining parameters separated by a colon and + /// returns an unknown attribute. + fn consumeUnknownColon(self: *Parser) void { + const count = self.countColon(); + self.idx += count + 1; + } +}; + +fn testParse(params: []const u16) Attribute { + var p: Parser = .{ .params = params }; + return p.next().?; +} + +fn testParseColon(params: []const u16) Attribute { + var p: Parser = .{ .params = params }; + // Mark all parameters except the last as having a colon after. + for (0..params.len - 1) |i| p.params_sep.set(i); + return p.next().?; +} + +test "sgr: Attribute C compat" { + _ = Attribute.C; +} + +test "sgr: Parser" { + try testing.expect(testParse(&[_]u16{}) == .unset); + try testing.expect(testParse(&[_]u16{0}) == .unset); + + { + const v = testParse(&[_]u16{ 38, 2, 40, 44, 52 }); + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 40), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 44), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 52), v.direct_color_fg.b); + } + + try testing.expect(testParse(&[_]u16{ 38, 2, 44, 52 }) == .unknown); + + { + const v = testParse(&[_]u16{ 48, 2, 40, 44, 52 }); + try testing.expect(v == .direct_color_bg); + try testing.expectEqual(@as(u8, 40), v.direct_color_bg.r); + try testing.expectEqual(@as(u8, 44), v.direct_color_bg.g); + try testing.expectEqual(@as(u8, 52), v.direct_color_bg.b); + } + + try testing.expect(testParse(&[_]u16{ 48, 2, 44, 52 }) == .unknown); +} + +test "sgr: Parser multiple" { + var p: Parser = .{ .params = &[_]u16{ 0, 38, 2, 40, 44, 52 } }; + try testing.expect(p.next().? == .unset); + try testing.expect(p.next().? == .direct_color_fg); + try testing.expect(p.next() == null); + try testing.expect(p.next() == null); +} + +test "sgr: unsupported with colon" { + var p: Parser = .{ + .params = &[_]u16{ 0, 4, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(0); + break :sep list; + }, + }; + try testing.expect(p.next().? == .unknown); + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +test "sgr: unsupported with multiple colon" { + var p: Parser = .{ + .params = &[_]u16{ 0, 4, 2, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(0); + list.set(1); + break :sep list; + }, + }; + try testing.expect(p.next().? == .unknown); + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +test "sgr: bold" { + { + const v = testParse(&[_]u16{1}); + try testing.expect(v == .bold); + } + + { + const v = testParse(&[_]u16{22}); + try testing.expect(v == .reset_bold); + } +} + +test "sgr: italic" { + { + const v = testParse(&[_]u16{3}); + try testing.expect(v == .italic); + } + + { + const v = testParse(&[_]u16{23}); + try testing.expect(v == .reset_italic); + } +} + +test "sgr: underline" { + { + const v = testParse(&[_]u16{4}); + try testing.expect(v == .underline); + } + + { + const v = testParse(&[_]u16{24}); + try testing.expect(v == .underline); + try testing.expect(v.underline == .none); + } +} + +test "sgr: underline styles" { + { + const v = testParseColon(&[_]u16{ 4, 2 }); + try testing.expect(v == .underline); + try testing.expect(v.underline == .double); + } + + { + const v = testParseColon(&[_]u16{ 4, 0 }); + try testing.expect(v == .underline); + try testing.expect(v.underline == .none); + } + + { + const v = testParseColon(&[_]u16{ 4, 1 }); + try testing.expect(v == .underline); + try testing.expect(v.underline == .single); + } + + { + const v = testParseColon(&[_]u16{ 4, 3 }); + try testing.expect(v == .underline); + try testing.expect(v.underline == .curly); + } + + { + const v = testParseColon(&[_]u16{ 4, 4 }); + try testing.expect(v == .underline); + try testing.expect(v.underline == .dotted); + } + + { + const v = testParseColon(&[_]u16{ 4, 5 }); + try testing.expect(v == .underline); + try testing.expect(v.underline == .dashed); + } +} + +test "sgr: underline style with more" { + var p: Parser = .{ + .params = &[_]u16{ 4, 2, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(0); + break :sep list; + }, + }; + + try testing.expect(p.next().? == .underline); + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +test "sgr: underline style with too many colons" { + var p: Parser = .{ + .params = &[_]u16{ 4, 2, 3, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(0); + list.set(1); + break :sep list; + }, + }; + + try testing.expect(p.next().? == .unknown); + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +test "sgr: blink" { + { + const v = testParse(&[_]u16{5}); + try testing.expect(v == .blink); + } + + { + const v = testParse(&[_]u16{6}); + try testing.expect(v == .blink); + } + + { + const v = testParse(&[_]u16{25}); + try testing.expect(v == .reset_blink); + } +} + +test "sgr: inverse" { + { + const v = testParse(&[_]u16{7}); + try testing.expect(v == .inverse); + } + + { + const v = testParse(&[_]u16{27}); + try testing.expect(v == .reset_inverse); + } +} + +test "sgr: strikethrough" { + { + const v = testParse(&[_]u16{9}); + try testing.expect(v == .strikethrough); + } + + { + const v = testParse(&[_]u16{29}); + try testing.expect(v == .reset_strikethrough); + } +} + +test "sgr: 8 color" { + var p: Parser = .{ .params = &[_]u16{ 31, 43, 90, 103 } }; + + { + const v = p.next().?; + try testing.expect(v == .@"8_fg"); + try testing.expect(v.@"8_fg" == .red); + } + + { + const v = p.next().?; + try testing.expect(v == .@"8_bg"); + try testing.expect(v.@"8_bg" == .yellow); + } + + { + const v = p.next().?; + try testing.expect(v == .@"8_bright_fg"); + try testing.expect(v.@"8_bright_fg" == .bright_black); + } + + { + const v = p.next().?; + try testing.expect(v == .@"8_bright_bg"); + try testing.expect(v.@"8_bright_bg" == .bright_yellow); + } +} + +test "sgr: 256 color" { + var p: Parser = .{ .params = &[_]u16{ 38, 5, 161, 48, 5, 236 } }; + try testing.expect(p.next().? == .@"256_fg"); + try testing.expect(p.next().? == .@"256_bg"); + try testing.expect(p.next() == null); +} + +test "sgr: 256 color underline" { + var p: Parser = .{ .params = &[_]u16{ 58, 5, 9 } }; + try testing.expect(p.next().? == .@"256_underline_color"); + try testing.expect(p.next() == null); +} + +test "sgr: 24-bit bg color" { + { + const v = testParseColon(&[_]u16{ 48, 2, 1, 2, 3 }); + try testing.expect(v == .direct_color_bg); + try testing.expectEqual(@as(u8, 1), v.direct_color_bg.r); + try testing.expectEqual(@as(u8, 2), v.direct_color_bg.g); + try testing.expectEqual(@as(u8, 3), v.direct_color_bg.b); + } +} + +test "sgr: underline color" { + { + const v = testParseColon(&[_]u16{ 58, 2, 1, 2, 3 }); + try testing.expect(v == .underline_color); + try testing.expectEqual(@as(u8, 1), v.underline_color.r); + try testing.expectEqual(@as(u8, 2), v.underline_color.g); + try testing.expectEqual(@as(u8, 3), v.underline_color.b); + } + + { + const v = testParseColon(&[_]u16{ 58, 2, 0, 1, 2, 3 }); + try testing.expect(v == .underline_color); + try testing.expectEqual(@as(u8, 1), v.underline_color.r); + try testing.expectEqual(@as(u8, 2), v.underline_color.g); + try testing.expectEqual(@as(u8, 3), v.underline_color.b); + } +} + +test "sgr: reset underline color" { + var p: Parser = .{ .params = &[_]u16{59} }; + try testing.expect(p.next().? == .reset_underline_color); +} + +test "sgr: invisible" { + var p: Parser = .{ .params = &[_]u16{ 8, 28 } }; + try testing.expect(p.next().? == .invisible); + try testing.expect(p.next().? == .reset_invisible); +} + +test "sgr: underline, bg, and fg" { + var p: Parser = .{ + .params = &[_]u16{ 4, 38, 2, 255, 247, 219, 48, 2, 242, 93, 147, 4 }, + }; + { + const v = p.next().?; + try testing.expect(v == .underline); + try testing.expectEqual(Attribute.Underline.single, v.underline); + } + { + const v = p.next().?; + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 255), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 247), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 219), v.direct_color_fg.b); + } + { + const v = p.next().?; + try testing.expect(v == .direct_color_bg); + try testing.expectEqual(@as(u8, 242), v.direct_color_bg.r); + try testing.expectEqual(@as(u8, 93), v.direct_color_bg.g); + try testing.expectEqual(@as(u8, 147), v.direct_color_bg.b); + } + { + const v = p.next().?; + try testing.expect(v == .underline); + try testing.expectEqual(Attribute.Underline.single, v.underline); + } +} + +test "sgr: direct color fg missing color" { + // This used to crash + var p: Parser = .{ .params = &[_]u16{ 38, 5 } }; + while (p.next()) |_| {} +} + +test "sgr: direct color bg missing color" { + // This used to crash + var p: Parser = .{ .params = &[_]u16{ 48, 5 } }; + while (p.next()) |_| {} +} + +test "sgr: direct fg/bg/underline ignore optional color space" { + // These behaviors have been verified against xterm. + + // Colon version should skip the optional color space identifier + { + // 3 8 : 2 : Pi : Pr : Pg : Pb + const v = testParseColon(&[_]u16{ 38, 2, 0, 1, 2, 3 }); + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 1), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 2), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 3), v.direct_color_fg.b); + } + { + // 4 8 : 2 : Pi : Pr : Pg : Pb + const v = testParseColon(&[_]u16{ 48, 2, 0, 1, 2, 3 }); + try testing.expect(v == .direct_color_bg); + try testing.expectEqual(@as(u8, 1), v.direct_color_bg.r); + try testing.expectEqual(@as(u8, 2), v.direct_color_bg.g); + try testing.expectEqual(@as(u8, 3), v.direct_color_bg.b); + } + { + // 5 8 : 2 : Pi : Pr : Pg : Pb + const v = testParseColon(&[_]u16{ 58, 2, 0, 1, 2, 3 }); + try testing.expect(v == .underline_color); + try testing.expectEqual(@as(u8, 1), v.underline_color.r); + try testing.expectEqual(@as(u8, 2), v.underline_color.g); + try testing.expectEqual(@as(u8, 3), v.underline_color.b); + } + + // Semicolon version should not parse optional color space identifier + { + // 3 8 ; 2 ; Pr ; Pg ; Pb + const v = testParse(&[_]u16{ 38, 2, 0, 1, 2, 3 }); + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 0), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 1), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 2), v.direct_color_fg.b); + } + { + // 4 8 ; 2 ; Pr ; Pg ; Pb + const v = testParse(&[_]u16{ 48, 2, 0, 1, 2, 3 }); + try testing.expect(v == .direct_color_bg); + try testing.expectEqual(@as(u8, 0), v.direct_color_bg.r); + try testing.expectEqual(@as(u8, 1), v.direct_color_bg.g); + try testing.expectEqual(@as(u8, 2), v.direct_color_bg.b); + } + { + // 5 8 ; 2 ; Pr ; Pg ; Pb + const v = testParse(&[_]u16{ 58, 2, 0, 1, 2, 3 }); + try testing.expect(v == .underline_color); + try testing.expectEqual(@as(u8, 0), v.underline_color.r); + try testing.expectEqual(@as(u8, 1), v.underline_color.g); + try testing.expectEqual(@as(u8, 2), v.underline_color.b); + } +} + +test "sgr: direct fg colon with too many colons" { + var p: Parser = .{ + .params = &[_]u16{ 38, 2, 0, 1, 2, 3, 4, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + for (0..6) |idx| list.set(idx); + break :sep list; + }, + }; + + try testing.expect(p.next().? == .unknown); + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +test "sgr: direct fg colon with colorspace and extra param" { + var p: Parser = .{ + .params = &[_]u16{ 38, 2, 0, 1, 2, 3, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + for (0..5) |idx| list.set(idx); + break :sep list; + }, + }; + + { + const v = p.next().?; + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 1), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 2), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 3), v.direct_color_fg.b); + } + + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +test "sgr: direct fg colon no colorspace and extra param" { + var p: Parser = .{ + .params = &[_]u16{ 38, 2, 1, 2, 3, 1 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + for (0..4) |idx| list.set(idx); + break :sep list; + }, + }; + + { + const v = p.next().?; + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 1), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 2), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 3), v.direct_color_fg.b); + } + + try testing.expect(p.next().? == .bold); + try testing.expect(p.next() == null); +} + +// Kakoune sent this complex SGR sequence that caused invalid behavior. +test "sgr: kakoune input" { + // This used to crash + var p: Parser = .{ + .params = &[_]u16{ 0, 4, 3, 38, 2, 175, 175, 215, 58, 2, 0, 190, 80, 70 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(1); + list.set(8); + list.set(9); + list.set(10); + list.set(11); + list.set(12); + break :sep list; + }, + }; + + { + const v = p.next().?; + try testing.expect(v == .unset); + } + { + const v = p.next().?; + try testing.expect(v == .underline); + try testing.expectEqual(Attribute.Underline.curly, v.underline); + } + { + const v = p.next().?; + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 175), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 175), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 215), v.direct_color_fg.b); + } + { + const v = p.next().?; + try testing.expect(v == .underline_color); + try testing.expectEqual(@as(u8, 190), v.underline_color.r); + try testing.expectEqual(@as(u8, 80), v.underline_color.g); + try testing.expectEqual(@as(u8, 70), v.underline_color.b); + } + + //try testing.expect(p.next() == null); +} + +// Discussion #5930, another input sent by kakoune +test "sgr: kakoune input issue underline, fg, and bg" { + // echo -e "\033[4:3;38;2;51;51;51;48;2;170;170;170;58;2;255;97;136mset everything in one sequence, broken\033[m" + + // This used to crash + var p: Parser = .{ + .params = &[_]u16{ 4, 3, 38, 2, 51, 51, 51, 48, 2, 170, 170, 170, 58, 2, 255, 97, 136 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(0); + break :sep list; + }, + }; + + { + const v = p.next().?; + try testing.expect(v == .underline); + try testing.expectEqual(Attribute.Underline.curly, v.underline); + } + + { + const v = p.next().?; + try testing.expect(v == .direct_color_fg); + try testing.expectEqual(@as(u8, 51), v.direct_color_fg.r); + try testing.expectEqual(@as(u8, 51), v.direct_color_fg.g); + try testing.expectEqual(@as(u8, 51), v.direct_color_fg.b); + } + + { + const v = p.next().?; + try testing.expect(v == .direct_color_bg); + try testing.expectEqual(@as(u8, 170), v.direct_color_bg.r); + try testing.expectEqual(@as(u8, 170), v.direct_color_bg.g); + try testing.expectEqual(@as(u8, 170), v.direct_color_bg.b); + } + + { + const v = p.next().?; + try testing.expect(v == .underline_color); + try testing.expectEqual(@as(u8, 255), v.underline_color.r); + try testing.expectEqual(@as(u8, 97), v.underline_color.g); + try testing.expectEqual(@as(u8, 136), v.underline_color.b); + } + + try testing.expect(p.next() == null); +} + +// Fuzz crash: afl-out/stream/default/crashes/id:000021 +// Input "ESC [ 5 8 : 4 : m" produces params [58, 4] with colon +// separator bits set at indices 0 and 1. The trailing colon causes +// the second iteration to see param 4 (underline) with a colon, +// triggering assert(slice.len >= 2) with slice.len == 1. +test "sgr: underline colon with trailing separator and short slice" { + var p: Parser = .{ + .params = &[_]u16{ 58, 4 }, + .params_sep = sep: { + var list = SepList.initEmpty(); + list.set(0); + list.set(1); + break :sep list; + }, + }; + + // 58:4 is not a valid underline color (sub-param 4 is not 2 or 5), + // so it falls through as unknown. + try testing.expect(p.next().? == .unknown); + + // Param 4 with a trailing colon but no sub-param is malformed, + // so it also falls through as unknown rather than panicking. + try testing.expect(p.next().? == .unknown); + + try testing.expect(p.next() == null); +} diff --git a/vendor/libghostty-vt/src/terminal/size.zig b/vendor/libghostty-vt/src/terminal/size.zig new file mode 100644 index 00000000..7be09739 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/size.zig @@ -0,0 +1,227 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; + +/// The maximum size of a page in bytes. We use a u16 here because any +/// smaller bit size by Zig is upgraded anyways to a u16 on mainstream +/// CPU architectures, and because 65KB is a reasonable page size. To +/// support better configurability, we derive everything from this. +pub const max_page_size = std.math.maxInt(u32); + +/// The int type that can contain the maximum memory offset in bytes, +/// derived from the maximum terminal page size. +pub const OffsetInt = std.math.IntFittingRange(0, max_page_size - 1); + +/// Int types for maximum values of things. A lot of these sizes are +/// based on "X is enough for any reasonable use case" principles. +// The goal is that a user can have the maxInt amount of all of these +// present at one time and be able to address them in a single Page.zig. + +// Total number of cells that are possible in each dimension (row/col). +// Based on 2^16 being enough for any reasonable terminal size and allowing +// IDs to remain 16-bit. +pub const CellCountInt = u16; + +// Total number of styles and hyperlinks that are possible in a page. +// We match CellCountInt here because each cell in a single row can have at +// most one style, making it simple to split a page by splitting rows. +// +// Note due to the way RefCountedSet works, we are short one value, but +// this is a theoretical limit we accept. A page with a single row max +// columns wide would be one short of having every cell have a unique style. +pub const StyleCountInt = CellCountInt; +pub const HyperlinkCountInt = CellCountInt; + +// Total number of bytes that can be taken up by grapheme data and string +// data. Both of these technically unlimited with malicious input, but +// we choose a reasonable limit of 2^32 (4GB) per. +pub const GraphemeBytesInt = u32; +pub const StringBytesInt = u32; + +/// The offset from the base address of the page to the start of some data. +/// This is typed for ease of use. +/// +/// This is a packed struct so we can attach methods to an int. +pub fn Offset(comptime T: type) type { + return packed struct(OffsetInt) { + const Self = @This(); + + offset: OffsetInt = 0, + + /// A slice of type T that stores via a base offset and len. + pub const Slice = struct { + offset: Self = .{}, + len: usize = 0, + + /// Returns a slice for the data, properly typed. + pub inline fn slice(self: Slice, base: anytype) []T { + return self.offset.ptr(base)[0..self.len]; + } + }; + + /// Returns a pointer to the start of the data, properly typed. + pub inline fn ptr(self: Self, base: anytype) [*]T { + // The offset must be properly aligned for the type since + // our return type is naturally aligned. We COULD modify this + // to return arbitrary alignment, but its not something we need. + const addr = intFromBase(base) + self.offset; + assert(addr % @alignOf(T) == 0); + return @ptrFromInt(addr); + } + }; +} + +/// Represents a buffer that is offset from some base pointer. +/// Offset-based structures should use this as their initialization +/// parameter so that they can know what segment of memory they own +/// while at the same time initializing their offset fields to be +/// against the true base. +/// +/// The term "true base" is used to describe the base address of +/// the allocation, which i.e. can include memory that you do NOT +/// own and is used by some other structures. All offsets are against +/// this "true base" so that to determine addresses structures don't +/// need to add up all the intermediary offsets. +pub const OffsetBuf = struct { + /// The true base pointer to the backing memory. This is + /// "byte zero" of the allocation. This plus the offset make + /// it easy to pass in the base pointer in all usage to this + /// structure and the offsets are correct. + base: [*]u8, + + /// Offset from base where the beginning of /this/ data + /// structure is located. We use this so that we can slowly + /// build up a chain of offset-based structures but always + /// have the base pointer sent into functions be the true base. + offset: usize = 0, + + /// Initialize a zero-offset buffer from a base. + pub fn init(base: anytype) OffsetBuf { + return initOffset(base, 0); + } + + /// Initialize from some base pointer and offset. + pub fn initOffset(base: anytype, offset: usize) OffsetBuf { + return .{ + .base = @ptrFromInt(intFromBase(base)), + .offset = offset, + }; + } + + /// The base address for the start of the data for the user + /// of this OffsetBuf. This is where your data structure should + /// begin; anything before this is NOT your memory. + pub fn start(self: OffsetBuf) [*]u8 { + const ptr = self.base + self.offset; + return @ptrCast(ptr); + } + + /// Returns an Offset calculation for some child member of + /// your struct. The offset is against the true base pointer + /// so that future callers can pass that in as the base. + pub fn member( + self: OffsetBuf, + comptime T: type, + len: usize, + ) Offset(T) { + return .{ .offset = @intCast(self.offset + len) }; + } + + /// Add an offset to the current offset. + pub fn add(self: OffsetBuf, offset: usize) OffsetBuf { + return .{ + .base = self.base, + .offset = self.offset + offset, + }; + } + + /// Rebase the offset to have a zero offset by rebasing onto start. + /// This is similar to `add` but all of the offsets are merged into base. + pub fn rebase(self: OffsetBuf, offset: usize) OffsetBuf { + return .{ + .base = self.start() + offset, + .offset = 0, + }; + } +}; + +/// Get the offset for a given type from some base pointer to the +/// actual pointer to the type. +pub inline fn getOffset( + comptime T: type, + base: anytype, + ptr: *const T, +) Offset(T) { + const base_int = intFromBase(base); + const ptr_int = @intFromPtr(ptr); + const offset = ptr_int - base_int; + return .{ .offset = @intCast(offset) }; +} + +inline fn intFromBase(base: anytype) usize { + const T = @TypeOf(base); + return switch (@typeInfo(T)) { + .pointer => |v| switch (v.size) { + .one, + .many, + .c, + => @intFromPtr(base), + + .slice => @intFromPtr(base.ptr), + }, + + else => switch (T) { + OffsetBuf => @intFromPtr(base.base), + + else => @compileError("invalid base type"), + }, + }; +} + +test "Offset" { + // This test is here so that if Offset changes, we can be very aware + // of this effect and think about the implications of it. + const testing = std.testing; + try testing.expect(OffsetInt == u32); +} + +test "Offset ptr u8" { + const testing = std.testing; + const offset: Offset(u8) = .{ .offset = 42 }; + const base_int: usize = @intFromPtr(&offset); + const actual = offset.ptr(&offset); + try testing.expectEqual(@as(usize, base_int + 42), @intFromPtr(actual)); +} + +test "Offset ptr structural" { + const Struct = struct { x: u32, y: u32 }; + const testing = std.testing; + const offset: Offset(Struct) = .{ .offset = @alignOf(Struct) * 4 }; + const base_int: usize = std.mem.alignForward(usize, @intFromPtr(&offset), @alignOf(Struct)); + const base: [*]u8 = @ptrFromInt(base_int); + const actual = offset.ptr(base); + try testing.expectEqual(@as(usize, base_int + offset.offset), @intFromPtr(actual)); +} + +test "getOffset bytes" { + const testing = std.testing; + var widgets: []const u8 = "ABCD"; + const offset = getOffset(u8, widgets.ptr, &widgets[2]); + try testing.expectEqual(@as(OffsetInt, 2), offset.offset); +} + +test "getOffset structs" { + const testing = std.testing; + const Widget = struct { x: u32, y: u32 }; + const widgets: []const Widget = &.{ + .{ .x = 1, .y = 2 }, + .{ .x = 3, .y = 4 }, + .{ .x = 5, .y = 6 }, + .{ .x = 7, .y = 8 }, + .{ .x = 9, .y = 10 }, + }; + const offset = getOffset(Widget, widgets.ptr, &widgets[2]); + try testing.expectEqual( + @as(OffsetInt, @sizeOf(Widget) * 2), + offset.offset, + ); +} diff --git a/vendor/libghostty-vt/src/terminal/size_report.zig b/vendor/libghostty-vt/src/terminal/size_report.zig new file mode 100644 index 00000000..2ce89a93 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/size_report.zig @@ -0,0 +1,160 @@ +const std = @import("std"); +const lib = @import("lib.zig"); +const CellCountInt = @import("size.zig").CellCountInt; + +/// Output formats for terminal size reports written to the PTY. +pub const Style = lib.Enum(lib.target, &.{ + // In-band size reports (mode 2048) + "mode_2048", + // XTWINOPS: report text area size in pixels + "csi_14_t", + // XTWINOPS: report cell size in pixels + "csi_16_t", + // XTWINOPS: report text area size in characters + "csi_18_t", +}); + +/// Runtime size values used to encode terminal size reports. +pub const Size = lib.Struct(lib.target, struct { + /// Terminal row count in cells. + rows: CellCountInt, + + /// Terminal column count in cells. + columns: CellCountInt, + + /// Width of a single terminal cell in pixels. + cell_width: u32, + + /// Height of a single terminal cell in pixels. + cell_height: u32, +}); + +fn widthPixels(s: Size) u64 { + return @as(u64, s.columns) * @as(u64, s.cell_width); +} + +fn heightPixels(s: Size) u64 { + return @as(u64, s.rows) * @as(u64, s.cell_height); +} + +/// Encode a terminal size report sequence. +pub fn encode( + writer: *std.Io.Writer, + style: Style, + size: Size, +) std.Io.Writer.Error!void { + switch (style) { + .mode_2048 => try writer.print( + "\x1B[48;{};{};{};{}t", + .{ + size.rows, + size.columns, + heightPixels(size), + widthPixels(size), + }, + ), + + .csi_14_t => try writer.print( + "\x1b[4;{};{}t", + .{ + heightPixels(size), + widthPixels(size), + }, + ), + + .csi_16_t => try writer.print( + "\x1b[6;{};{}t", + .{ + size.cell_height, + size.cell_width, + }, + ), + + .csi_18_t => try writer.print( + "\x1b[8;{};{}t", + .{ + size.rows, + size.columns, + }, + ), + } +} + +fn testSize() Size { + return .{ + .rows = 24, + .columns = 80, + .cell_width = 9, + .cell_height = 18, + }; +} + +test "encode mode 2048" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, .mode_2048, testSize()); + + try std.testing.expectEqualStrings("\x1B[48;24;80;432;720t", writer.buffered()); +} + +test "encode csi 14 t" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, .csi_14_t, testSize()); + + try std.testing.expectEqualStrings("\x1b[4;432;720t", writer.buffered()); +} + +test "encode csi 16 t" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, .csi_16_t, testSize()); + + try std.testing.expectEqualStrings("\x1b[6;18;9t", writer.buffered()); +} + +test "encode csi 18 t" { + var buf: [64]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, .csi_18_t, testSize()); + + try std.testing.expectEqualStrings("\x1b[8;24;80t", writer.buffered()); +} + +test "encode max values for all fields" { + const max_size: Size = .{ + .rows = std.math.maxInt(@FieldType(Size, "rows")), + .columns = std.math.maxInt(@FieldType(Size, "columns")), + .cell_width = std.math.maxInt(@FieldType(Size, "cell_width")), + .cell_height = std.math.maxInt(@FieldType(Size, "cell_height")), + }; + + const Case = struct { + style: Style, + expected: []const u8, + }; + + inline for ([_]Case{ + .{ + .style = .mode_2048, + .expected = "\x1B[48;65535;65535;281470681677825;281470681677825t", + }, + .{ + .style = .csi_14_t, + .expected = "\x1b[4;281470681677825;281470681677825t", + }, + .{ + .style = .csi_16_t, + .expected = "\x1b[6;4294967295;4294967295t", + }, + .{ + .style = .csi_18_t, + .expected = "\x1b[8;65535;65535t", + }, + }) |case| { + var buf: [128]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try encode(&writer, case.style, max_size); + try std.testing.expectEqualStrings(case.expected, writer.buffered()); + } +} diff --git a/vendor/libghostty-vt/src/terminal/stream.zig b/vendor/libghostty-vt/src/terminal/stream.zig new file mode 100644 index 00000000..9771334f --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/stream.zig @@ -0,0 +1,3449 @@ +const streampkg = @This(); +const std = @import("std"); +const build_options = @import("terminal_options"); +const assert = @import("../quirks.zig").inlineAssert; +const testing = std.testing; +const Allocator = std.mem.Allocator; +const simd = @import("../simd/main.zig"); +const lib = @import("lib.zig"); +const Parser = @import("Parser.zig"); +const ansi = @import("ansi.zig"); +const charsets = @import("charsets.zig"); +const device_attributes = @import("device_attributes.zig"); +const device_status = @import("device_status.zig"); +const csi = @import("csi.zig"); +const kitty = @import("kitty.zig"); +const modes = @import("modes.zig"); +const osc = @import("osc.zig"); +const sgr = @import("sgr.zig"); +const UTF8Decoder = @import("UTF8Decoder.zig"); +const MouseShape = @import("mouse.zig").Shape; + +const log = std.log.scoped(.stream); + +/// Flip this to true when you want verbose debug output for +/// debugging terminal stream issues. In addition to louder +/// output this will also disable the SIMD optimizations in +/// order to make it easier to see every byte. So if you're +/// debugging an issue in the SIMD code then you'll need to +/// do something else. +const debug = false; + +/// The possible actions that can be emitted by the Stream +/// function for handling. +pub const Action = union(Key) { + print: Print, + print_repeat: usize, + bell, + backspace, + horizontal_tab: u16, + horizontal_tab_back: u16, + linefeed, + carriage_return, + enquiry, + invoke_charset: InvokeCharset, + cursor_up: CursorMovement, + cursor_down: CursorMovement, + cursor_left: CursorMovement, + cursor_right: CursorMovement, + cursor_col: CursorMovement, + cursor_row: CursorMovement, + cursor_col_relative: CursorMovement, + cursor_row_relative: CursorMovement, + cursor_pos: CursorPos, + cursor_style: ansi.CursorStyle, + erase_display_below: bool, + erase_display_above: bool, + erase_display_complete: bool, + erase_display_scrollback: bool, + erase_display_scroll_complete: bool, + erase_line_right: bool, + erase_line_left: bool, + erase_line_complete: bool, + erase_line_right_unless_pending_wrap: bool, + delete_chars: usize, + erase_chars: usize, + insert_lines: usize, + insert_blanks: usize, + delete_lines: usize, + scroll_up: usize, + scroll_down: usize, + tab_clear_current, + tab_clear_all, + tab_set, + tab_reset, + index, + next_line, + reverse_index, + full_reset, + set_mode: Mode, + reset_mode: Mode, + save_mode: Mode, + restore_mode: Mode, + request_mode: Mode, + request_mode_unknown: RawMode, + top_and_bottom_margin: Margin, + left_and_right_margin: Margin, + left_and_right_margin_ambiguous, + save_cursor, + restore_cursor, + modify_key_format: ansi.ModifyKeyFormat, + mouse_shift_capture: bool, + protected_mode_off, + protected_mode_iso, + protected_mode_dec, + size_report: csi.SizeReportStyle, + title_push: u16, + title_pop: u16, + xtversion, + device_attributes: device_attributes.Req, + device_status: DeviceStatus, + kitty_keyboard_query, + kitty_keyboard_push: KittyKeyboardFlags, + kitty_keyboard_pop: u16, + kitty_keyboard_set: KittyKeyboardFlags, + kitty_keyboard_set_or: KittyKeyboardFlags, + kitty_keyboard_set_not: KittyKeyboardFlags, + dcs_hook: Parser.Action.DCS, + dcs_put: u8, + dcs_unhook, + apc_start, + apc_end, + apc_put: u8, + end_hyperlink, + active_status_display: ansi.StatusDisplay, + decaln, + window_title: WindowTitle, + report_pwd: ReportPwd, + show_desktop_notification: ShowDesktopNotification, + progress_report: osc.Command.ProgressReport, + start_hyperlink: StartHyperlink, + clipboard_contents: ClipboardContents, + mouse_shape: MouseShape, + configure_charset: ConfigureCharset, + set_attribute: sgr.Attribute, + kitty_color_report: kitty.color.OSC, + color_operation: ColorOperation, + semantic_prompt: SemanticPrompt, + + pub const Key = lib.Enum( + lib.target, + &.{ + "print", + "print_repeat", + "bell", + "backspace", + "horizontal_tab", + "horizontal_tab_back", + "linefeed", + "carriage_return", + "enquiry", + "invoke_charset", + "cursor_up", + "cursor_down", + "cursor_left", + "cursor_right", + "cursor_col", + "cursor_row", + "cursor_col_relative", + "cursor_row_relative", + "cursor_pos", + "cursor_style", + "erase_display_below", + "erase_display_above", + "erase_display_complete", + "erase_display_scrollback", + "erase_display_scroll_complete", + "erase_line_right", + "erase_line_left", + "erase_line_complete", + "erase_line_right_unless_pending_wrap", + "delete_chars", + "erase_chars", + "insert_lines", + "insert_blanks", + "delete_lines", + "scroll_up", + "scroll_down", + "tab_clear_current", + "tab_clear_all", + "tab_set", + "tab_reset", + "index", + "next_line", + "reverse_index", + "full_reset", + "set_mode", + "reset_mode", + "save_mode", + "restore_mode", + "request_mode", + "request_mode_unknown", + "top_and_bottom_margin", + "left_and_right_margin", + "left_and_right_margin_ambiguous", + "save_cursor", + "restore_cursor", + "modify_key_format", + "mouse_shift_capture", + "protected_mode_off", + "protected_mode_iso", + "protected_mode_dec", + "size_report", + "title_push", + "title_pop", + "xtversion", + "device_attributes", + "device_status", + "kitty_keyboard_query", + "kitty_keyboard_push", + "kitty_keyboard_pop", + "kitty_keyboard_set", + "kitty_keyboard_set_or", + "kitty_keyboard_set_not", + "dcs_hook", + "dcs_put", + "dcs_unhook", + "apc_start", + "apc_end", + "apc_put", + "end_hyperlink", + "active_status_display", + "decaln", + "window_title", + "report_pwd", + "show_desktop_notification", + "progress_report", + "start_hyperlink", + "clipboard_contents", + "mouse_shape", + "configure_charset", + "set_attribute", + "kitty_color_report", + "color_operation", + "semantic_prompt", + }, + ); + + /// C ABI functions. + const c_union = lib.TaggedUnion( + lib.target, + @This(), + // TODO: Before shipping an ABI-compatible libghostty, verify this. + // This was just arbitrarily chosen for now. + [16]u64, + ); + pub const Tag = c_union.Tag; + pub const Value = c_union.Value; + pub const C = c_union.C; + pub const CValue = c_union.CValue; + pub const cval = c_union.cval; + + /// Field types + pub const Print = struct { + cp: u21, + + pub const C = extern struct { + cp: u32, + }; + + pub fn cval(self: Print) Print.C { + return .{ .cp = @intCast(self.cp) }; + } + }; + + pub const InvokeCharset = lib.Struct(lib.target, struct { + bank: charsets.ActiveSlot, + charset: charsets.Slots, + locking: bool, + }); + + pub const CursorMovement = extern struct { + /// The value of the cursor movement. Depending on the tag of this + /// union this may be an absolute value or it may be a relative + /// value. For example, `cursor_up` is relative, but `cursor_row` + /// is absolute. + value: u16, + }; + + pub const CursorPos = extern struct { + row: u16, + col: u16, + }; + + pub const DeviceStatus = struct { + request: device_status.Request, + + pub const C = u16; + + pub fn cval(self: DeviceStatus) DeviceStatus.C { + return @bitCast(self.request); + } + }; + + pub const Mode = struct { + mode: modes.Mode, + + pub const C = u16; + + pub fn cval(self: Mode) Mode.C { + return @bitCast(self.mode); + } + }; + + pub const RawMode = extern struct { + mode: u16, + ansi: bool, + }; + + pub const Margin = extern struct { + top_left: u16, + bottom_right: u16, + }; + + pub const KittyKeyboardFlags = struct { + flags: kitty.KeyFlags, + + pub const C = u8; + + pub fn cval(self: KittyKeyboardFlags) KittyKeyboardFlags.C { + return @intCast(self.flags.int()); + } + }; + + pub const WindowTitle = struct { + title: []const u8, + + pub const C = lib.String; + + pub fn cval(self: WindowTitle) WindowTitle.C { + return .init(self.title); + } + }; + + pub const ReportPwd = struct { + url: []const u8, + + pub const C = lib.String; + + pub fn cval(self: ReportPwd) ReportPwd.C { + return .init(self.url); + } + }; + + pub const ShowDesktopNotification = struct { + title: []const u8, + body: []const u8, + + pub const C = extern struct { + title: lib.String, + body: lib.String, + }; + + pub fn cval(self: ShowDesktopNotification) ShowDesktopNotification.C { + return .{ + .title = .init(self.title), + .body = .init(self.body), + }; + } + }; + + pub const StartHyperlink = struct { + uri: []const u8, + id: ?[]const u8, + + pub const C = extern struct { + uri: lib.String, + id: lib.String, + }; + + pub fn cval(self: StartHyperlink) StartHyperlink.C { + return .{ + .uri = .init(self.uri), + .id = .init(self.id orelse ""), + }; + } + }; + + pub const ClipboardContents = struct { + kind: u8, + data: []const u8, + + pub const C = extern struct { + kind: u8, + data: lib.String, + }; + + pub fn cval(self: ClipboardContents) ClipboardContents.C { + return .{ + .kind = self.kind, + .data = .init(self.data), + }; + } + }; + + pub const ConfigureCharset = lib.Struct(lib.target, struct { + slot: charsets.Slots, + charset: charsets.Charset, + }); + + pub const ColorOperation = struct { + op: osc.color.Operation, + requests: osc.color.List, + terminator: osc.Terminator, + + pub const C = void; + + pub fn cval(_: ColorOperation) ColorOperation.C { + return {}; + } + }; + + pub const SemanticPrompt = osc.Command.SemanticPrompt; +}; + +/// Returns a type that can process a stream of tty control characters. +/// This will call the `vt` function on type T with the following signature: +/// +/// fn(comptime action: Action.Key, value: Action.Value(action)) void +/// +/// The handler type T can choose to react to whatever actions it cares +/// about in its pursuit of implementing a terminal emulator or other +/// functionality. +/// +/// The Handler type must also have a `deinit` function. +/// +/// The "comptime" key is on purpose (vs. a standard Zig tagged union) +/// because it allows the compiler to optimize away unimplemented actions. +/// e.g. you don't need to pay a conditional branching cost on every single +/// action because the Zig compiler codegens separate code paths for every +/// single action at comptime. +pub fn Stream(comptime H: type) type { + return struct { + const Self = @This(); + + pub const Action = streampkg.Action; + pub const Handler = H; + + const T = switch (@typeInfo(Handler)) { + .pointer => |p| p.child, + else => Handler, + }; + + handler: Handler, + parser: Parser, + utf8decoder: UTF8Decoder, + + /// Initialize an allocation-free stream. This will preallocate various + /// sizes as necessary and anything over that will be dropped. If you + /// want to support more dynamic behavior use initAlloc instead. + /// + /// As a concrete example of something that requires heap allocation, + /// consider OSC 52 (clipboard operations) which can be arbitrarily + /// large. + /// + /// If you want to limit allocation size, use an allocator with + /// a size limit with initAlloc. + /// + /// This takes ownership of the handler and will call deinit + /// when the stream is deinitialized. + pub fn init(h: Handler) Self { + return .{ + .handler = h, + .parser = .init(), + .utf8decoder = .{}, + }; + } + + /// Initialize the stream that supports heap allocation as necessary. + pub fn initAlloc(alloc: Allocator, h: Handler) Self { + var self: Self = .init(h); + self.parser.osc_parser.alloc = alloc; + return self; + } + + pub fn deinit(self: *Self) void { + self.parser.deinit(); + self.handler.deinit(); + } + + /// Process a string of characters. + pub inline fn nextSlice(self: *Self, input: []const u8) void { + // Disable SIMD optimizations if build requests it or if our + // manual debug mode is on. + if (comptime debug or !build_options.simd) { + for (input) |c| self.next(c); + return; + } + + // This is the maximum number of codepoints we can decode + // at one time for this function call. This is somewhat arbitrary + // so if someone can demonstrate a better number then we can switch. + var cp_buf: [4096]u32 = undefined; + + // Split the input into chunks that fit into cp_buf. + var i: usize = 0; + while (true) { + const len = @min(cp_buf.len, input.len - i); + self.nextSliceCapped(input[i .. i + len], &cp_buf); + i += len; + if (i >= input.len) break; + } + } + + inline fn nextSliceCapped( + self: *Self, + input: []const u8, + cp_buf: []u32, + ) void { + assert(input.len <= cp_buf.len); + + var offset: usize = 0; + + // If the scalar UTF-8 decoder was in the middle of processing + // a code sequence, we continue until it's not. + while (self.utf8decoder.state != 0) { + if (offset >= input.len) return; + self.nextUtf8(input[offset]); + offset += 1; + } + if (offset >= input.len) return; + + // If we're not in the ground state then we process until + // we are. This can happen if the last chunk of input put us + // in the middle of a control sequence. + offset += self.consumeUntilGround(input[offset..]); + if (offset >= input.len) return; + offset += self.consumeAllEscapes(input[offset..]); + + // If we're in the ground state then we can use SIMD to process + // input until we see an ESC (0x1B), since all other characters + // up to that point are just UTF-8. + while (self.parser.state == .ground and offset < input.len) { + const res = simd.vt.utf8DecodeUntilControlSeq(input[offset..], cp_buf); + for (cp_buf[0..res.decoded]) |cp| { + if (cp <= 0xF) { + self.execute(@intCast(cp)); + } else { + self.print(@intCast(cp)); + } + } + // Consume the bytes we just processed. + offset += res.consumed; + + if (offset >= input.len) return; + + // If our offset is NOT an escape then we must have a + // partial UTF-8 sequence. In that case, we pass it off + // to the scalar parser. + if (input[offset] != 0x1B) { + const rem = input[offset..]; + for (rem) |c| self.nextUtf8(c); + return; + } + + // Process control sequences until we run out. + offset += self.consumeAllEscapes(input[offset..]); + } + } + + /// Parses back-to-back escape sequences until none are left. + /// Returns the number of bytes consumed from the provided input. + /// + /// Expects input to start with 0x1B, use consumeUntilGround first + /// if the stream may be in the middle of an escape sequence. + inline fn consumeAllEscapes(self: *Self, input: []const u8) usize { + var offset: usize = 0; + while (input[offset] == 0x1B) { + self.parser.state = .escape; + self.parser.clear(); + offset += 1; + offset += self.consumeUntilGround(input[offset..]); + if (offset >= input.len) return input.len; + } + return offset; + } + + /// Parses escape sequences until the parser reaches the ground state. + /// Returns the number of bytes consumed from the provided input. + inline fn consumeUntilGround(self: *Self, input: []const u8) usize { + var offset: usize = 0; + while (self.parser.state != .ground) { + if (offset >= input.len) return input.len; + self.nextNonUtf8(input[offset]); + offset += 1; + } + return offset; + } + + /// Like nextSlice but takes one byte and is necessarily a scalar + /// operation that can't use SIMD. Prefer nextSlice if you can and + /// try to get multiple bytes at once. + pub inline fn next(self: *Self, c: u8) void { + // The scalar path can be responsible for decoding UTF-8. + if (self.parser.state == .ground) { + self.nextUtf8(c); + return; + } + + self.nextNonUtf8(c); + } + + /// Process the next byte and print as necessary. + /// + /// This assumes we're in the UTF-8 decoding state. If we may not + /// be in the UTF-8 decoding state call nextSlice or next. + inline fn nextUtf8(self: *Self, c: u8) void { + assert(self.parser.state == .ground); + + const res = self.utf8decoder.next(c); + const consumed = res[1]; + if (res[0]) |codepoint| { + self.handleCodepoint(codepoint); + } + if (!consumed) { + // We optimize for the scenario where the text being + // printed in the terminal ISN'T full of ill-formed + // UTF-8 sequences. + @branchHint(.unlikely); + + const retry = self.utf8decoder.next(c); + // It should be impossible for the decoder + // to not consume the byte twice in a row. + assert(retry[1] == true); + if (retry[0]) |codepoint| { + self.handleCodepoint(codepoint); + } + } + } + + /// To be called whenever the utf-8 decoder produces a codepoint. + /// + /// This function is abstracted this way to handle the case where + /// the decoder emits a 0x1B after rejecting an ill-formed sequence. + inline fn handleCodepoint(self: *Self, c: u21) void { + // We need to increase the eval branch limit because a lot of + // tests end up running almost completely at comptime due to + // a chain of inline functions. + @setEvalBranchQuota(100_000); + + // C0 control + if (c <= 0xF) { + @branchHint(.unlikely); + self.execute(@intCast(c)); + return; + } + // ESC + if (c == 0x1B) { + self.parser.state = .escape; + self.parser.clear(); + return; + } + self.print(@intCast(c)); + } + + /// Process the next character and call any callbacks if necessary. + /// + /// This assumes that we're not in the UTF-8 decoding state. If + /// we may be in the UTF-8 decoding state call nextSlice or next. + fn nextNonUtf8(self: *Self, c: u8) void { + assert(self.parser.state != .ground); + + // Fast path for CSI entry. + if (self.parser.state == .escape and c == '[') { + self.parser.state = .csi_entry; + return; + } + // Fast path for CSI params. + if (self.parser.state == .csi_param) csi_param: { + // csi_param is the most common parser state + // other than ground by a fairly wide margin. + // + // ref: https://github.com/qwerasd205/asciinema-stats + @branchHint(.likely); + switch (c) { + // A C0 escape (yes, this is valid): + 0x00...0x0F => self.execute(c), + // We ignore C0 escapes > 0xF since execute + // doesn't have processing for them anyway: + 0x10...0x17, 0x19, 0x1C...0x1F => {}, + // We don't currently have any handling for + // 0x18 or 0x1A, but they should still move + // the parser state to ground. + 0x18, 0x1A => self.parser.state = .ground, + // A parameter digit: + '0'...'9' => if (self.parser.params_idx < Parser.MAX_PARAMS) { + self.parser.param_acc *|= 10; + self.parser.param_acc +|= c - '0'; + // The parser's CSI param action uses param_acc_idx + // to decide if there's a final param that needs to + // be consumed or not, but it doesn't matter really + // what it is as long as it's not 0. + self.parser.param_acc_idx |= 1; + }, + // A parameter separator: + ':', ';' => if (self.parser.params_idx < Parser.MAX_PARAMS) { + self.parser.params[self.parser.params_idx] = self.parser.param_acc; + if (c == ':') self.parser.params_sep.set(self.parser.params_idx); + self.parser.params_idx += 1; + + self.parser.param_acc = 0; + self.parser.param_acc_idx = 0; + }, + // Explicitly ignored: + 0x7F => {}, + // Defer to the state machine to + // handle any other characters: + else => break :csi_param, + } + return; + } + + // We explicitly inline this call here for performance reasons. + // + // We do this rather than mark Parser.next as inline because doing + // that causes weird behavior in some tests- I'm not sure if they + // miscompile or it's just very counter-intuitive comptime stuff, + // but regardless, this is the easy solution. + const actions = @call(.always_inline, Parser.next, .{ &self.parser, c }); + + for (actions) |action_opt| { + const action = action_opt orelse continue; + if (comptime debug) log.info("action: {f}", .{action}); + + // A handler can expose this to get the raw action before + // it is further parsed. If this returns `true` then we skip + // processing ourselves. + if (@hasDecl(T, "vtRaw")) { + const skip = self.handler.vtRaw(action) catch |err| err: { + log.warn("error handling action manually err={} action={f}", .{ + err, + action, + }); + // Always skip erroneous actions because we can't + // be sure... + break :err true; + }; + + if (skip) continue; + } + + switch (action) { + .print => |p| self.print(p), + .execute => |code| self.execute(code), + .csi_dispatch => |csi_action| self.csiDispatch(csi_action), + .esc_dispatch => |esc| self.escDispatch(esc), + .osc_dispatch => |cmd| self.oscDispatch(cmd), + .dcs_hook => |dcs| self.handler.vt(.dcs_hook, dcs), + .dcs_put => |code| self.handler.vt(.dcs_put, code), + .dcs_unhook => self.handler.vt(.dcs_unhook, {}), + .apc_start => self.handler.vt(.apc_start, {}), + .apc_put => |code| self.handler.vt(.apc_put, code), + .apc_end => self.handler.vt(.apc_end, {}), + } + } + } + + inline fn print(self: *Self, c: u21) void { + self.handler.vt(.print, .{ .cp = c }); + } + + inline fn execute(self: *Self, c: u8) void { + // If the character is > 0x7F, it's a C1 (8-bit) control, + // which is strictly equivalent to `ESC` plus `c - 0x40`. + if (c > 0x7F) { + @branchHint(.unlikely); + log.info("executing C1 0x{x} as ESC {c}", .{ c, c - 0x40 }); + self.escDispatch(.{ + .intermediates = &.{}, + .final = c - 0x40, + }); + return; + } + + const c0: ansi.C0 = @enumFromInt(c); + if (comptime debug) log.info("execute: {f}", .{c0}); + switch (c0) { + // We ignore SOH/STX: https://github.com/microsoft/terminal/issues/10786 + .NUL, .SOH, .STX => {}, + + .ENQ => self.handler.vt(.enquiry, {}), + .BEL => self.handler.vt(.bell, {}), + .BS => self.handler.vt(.backspace, {}), + .HT => self.handler.vt(.horizontal_tab, 1), + .LF, .VT, .FF => self.handler.vt(.linefeed, {}), + .CR => self.handler.vt(.carriage_return, {}), + .SO => self.handler.vt(.invoke_charset, .{ .bank = .GL, .charset = .G1, .locking = false }), + .SI => self.handler.vt(.invoke_charset, .{ .bank = .GL, .charset = .G0, .locking = false }), + + else => log.warn("invalid C0 character, ignoring: 0x{x}", .{c}), + } + } + + inline fn csiDispatch(self: *Self, input: Parser.Action.CSI) void { + // The branch hints here are based on real world data + // which indicates that the most common CSI finals are: + // + // 1. m + // 2. H + // 3. K + // 4. A + // 5. C + // 6. X + // 7. l + // 8. h + // 9. r + // + // Together, these 9 finals make up about 96% of all + // CSI sequences encountered in real world scenarios. + // + // Additionally, within the prongs, unlikely branch + // hints have been added to branches that deal with + // invalid sequences/commands, this is in order to + // optimize for the happy path where we're getting + // valid data from the program we're running. + // + // ref: https://github.com/qwerasd205/asciinema-stats + + switch (input.final) { + // CUU - Cursor Up + 'A', 'k' => { + @branchHint(.likely); + switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_up, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid cursor up command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI A with intermediates: {s}", + .{input.intermediates}, + ), + } + }, + + // CUD - Cursor Down + 'B' => switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_down, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid cursor down command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI B with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // CUF - Cursor Right + 'C' => { + @branchHint(.likely); + switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_right, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid cursor right command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI C with intermediates: {s}", + .{input.intermediates}, + ), + } + }, + + // CUB - Cursor Left + 'D', 'j' => switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_left, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid cursor left command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI D with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // CNL - Cursor Next Line + 'E' => switch (input.intermediates.len) { + 0 => { + self.handler.vt(.cursor_down, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid cursor up command: {f}", .{input}); + return; + }, + }, + }); + self.handler.vt(.carriage_return, {}); + }, + + else => log.warn( + "ignoring unimplemented CSI E with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // CPL - Cursor Previous Line + 'F' => switch (input.intermediates.len) { + 0 => { + self.handler.vt(.cursor_up, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid cursor down command: {f}", .{input}); + return; + }, + }, + }); + self.handler.vt(.carriage_return, {}); + }, + + else => log.warn( + "ignoring unimplemented CSI F with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // HPA - Cursor Horizontal Position Absolute + // TODO: test + 'G', '`' => switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_col, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid HPA command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI G with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // CUP - Set Cursor Position. + // TODO: test + 'H', 'f' => { + @branchHint(.likely); + switch (input.intermediates.len) { + 0 => { + const pos: streampkg.Action.CursorPos = switch (input.params.len) { + 0 => .{ .row = 1, .col = 1 }, + 1 => .{ .row = input.params[0], .col = 1 }, + 2 => .{ .row = input.params[0], .col = input.params[1] }, + else => { + @branchHint(.unlikely); + log.warn("invalid CUP command: {f}", .{input}); + return; + }, + }; + self.handler.vt(.cursor_pos, pos); + }, + + else => log.warn( + "ignoring unimplemented CSI H with intermediates: {s}", + .{input.intermediates}, + ), + } + }, + + // CHT - Cursor Horizontal Tabulation + 'I' => switch (input.intermediates.len) { + 0 => self.handler.vt(.horizontal_tab, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid horizontal tab command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI I with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Erase Display + 'J' => { + const protected_: ?bool = switch (input.intermediates.len) { + 0 => false, + 1 => if (input.intermediates[0] == '?') true else null, + else => null, + }; + + const protected = protected_ orelse { + log.warn("invalid erase display command: {f}", .{input}); + return; + }; + + const mode_: ?csi.EraseDisplay = switch (input.params.len) { + 0 => .below, + 1 => std.meta.intToEnum(csi.EraseDisplay, input.params[0]) catch null, + else => null, + }; + + const mode = mode_ orelse { + log.warn("invalid erase display command: {f}", .{input}); + return; + }; + + switch (mode) { + .below => self.handler.vt(.erase_display_below, protected), + .above => self.handler.vt(.erase_display_above, protected), + .complete => self.handler.vt(.erase_display_complete, protected), + .scrollback => self.handler.vt(.erase_display_scrollback, protected), + .scroll_complete => self.handler.vt(.erase_display_scroll_complete, protected), + } + }, + + // Erase Line + 'K' => { + @branchHint(.likely); + const protected_: ?bool = switch (input.intermediates.len) { + 0 => false, + 1 => if (input.intermediates[0] == '?') true else null, + else => null, + }; + + const protected = protected_ orelse { + @branchHint(.unlikely); + log.warn("invalid erase line command: {f}", .{input}); + return; + }; + + const mode_: ?csi.EraseLine = switch (input.params.len) { + 0 => .right, + 1 => if (input.params[0] < 3) @enumFromInt(input.params[0]) else null, + else => null, + }; + + const mode = mode_ orelse { + @branchHint(.unlikely); + log.warn("invalid erase line command: {f}", .{input}); + return; + }; + + switch (mode) { + .right => self.handler.vt(.erase_line_right, protected), + .left => self.handler.vt(.erase_line_left, protected), + .complete => self.handler.vt(.erase_line_complete, protected), + .right_unless_pending_wrap => self.handler.vt(.erase_line_right_unless_pending_wrap, protected), + _ => { + @branchHint(.unlikely); + log.warn("invalid erase line mode: {}", .{mode}); + }, + } + }, + + // IL - Insert Lines + // TODO: test + 'L' => switch (input.intermediates.len) { + 0 => self.handler.vt(.insert_lines, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid IL command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI L with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // DL - Delete Lines + // TODO: test + 'M' => switch (input.intermediates.len) { + 0 => self.handler.vt(.delete_lines, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid DL command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI M with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Delete Character (DCH) + 'P' => switch (input.intermediates.len) { + 0 => self.handler.vt(.delete_chars, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid delete characters command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI P with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Scroll Up (SD) + + 'S' => switch (input.intermediates.len) { + 0 => self.handler.vt(.scroll_up, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid scroll up command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI S with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Scroll Down (SD) + 'T' => switch (input.intermediates.len) { + 0 => self.handler.vt(.scroll_down, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid scroll down command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI T with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Cursor Tabulation Control + 'W' => switch (input.intermediates.len) { + 0 => { + if (input.params.len == 0 or + (input.params.len == 1 and input.params[0] == 0)) + { + self.handler.vt(.tab_set, {}); + return; + } + + switch (input.params.len) { + 0 => unreachable, + + 1 => switch (input.params[0]) { + 0 => unreachable, + + 2 => self.handler.vt(.tab_clear_current, {}), + + 5 => self.handler.vt(.tab_clear_all, {}), + + else => {}, + }, + + else => {}, + } + + log.warn("invalid cursor tabulation control: {f}", .{input}); + return; + }, + + 1 => if (input.intermediates[0] == '?' and + input.params.len == 1 and + input.params[0] == 5) + { + self.handler.vt(.tab_reset, {}); + } else log.warn("invalid cursor tabulation control: {f}", .{input}), + + else => log.warn( + "ignoring unimplemented CSI W with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Erase Characters (ECH) + 'X' => { + @branchHint(.likely); + switch (input.intermediates.len) { + 0 => self.handler.vt(.erase_chars, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + @branchHint(.unlikely); + log.warn("invalid erase characters command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI X with intermediates: {s}", + .{input.intermediates}, + ), + } + }, + + // CHT - Cursor Horizontal Tabulation Back + 'Z' => switch (input.intermediates.len) { + 0 => self.handler.vt(.horizontal_tab_back, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid horizontal tab back command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI Z with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // HPR - Cursor Horizontal Position Relative + 'a' => switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_col_relative, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid HPR command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI a with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // Repeat Previous Char (REP) + 'b' => switch (input.intermediates.len) { + 0 => self.handler.vt(.print_repeat, switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid print repeat command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI b with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // c - Device Attributes (DA1) + 'c' => { + const req: ?device_attributes.Req = switch (input.intermediates.len) { + 0 => .primary, + 1 => switch (input.intermediates[0]) { + '>' => .secondary, + '=' => .tertiary, + else => null, + }, + else => null, + }; + + if (req) |r| { + self.handler.vt(.device_attributes, r); + } else { + log.warn("invalid device attributes command: {f}", .{input}); + return; + } + }, + + // VPA - Cursor Vertical Position Absolute + 'd' => switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_row, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid VPA command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI d with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // VPR - Cursor Vertical Position Relative + 'e' => switch (input.intermediates.len) { + 0 => self.handler.vt(.cursor_row_relative, .{ + .value = switch (input.params.len) { + 0 => 1, + 1 => input.params[0], + else => { + log.warn("invalid VPR command: {f}", .{input}); + return; + }, + }, + }), + + else => log.warn( + "ignoring unimplemented CSI e with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // TBC - Tab Clear + // TODO: test + 'g' => switch (input.intermediates.len) { + 0 => { + const mode: csi.TabClear = switch (input.params.len) { + 1 => std.meta.intToEnum(csi.TabClear, input.params[0]) catch { + log.warn("invalid tab clear mode: {}", .{input.params[0]}); + return; + }, + else => { + log.warn("invalid tab clear command: {f}", .{input}); + return; + }, + }; + switch (mode) { + .current => self.handler.vt(.tab_clear_current, {}), + .all => self.handler.vt(.tab_clear_all, {}), + _ => log.warn("unknown tab clear mode: {}", .{mode}), + } + }, + + else => log.warn( + "ignoring unimplemented CSI g with intermediates: {s}", + .{input.intermediates}, + ), + }, + + // SM - Set Mode + 'h' => mode: { + @branchHint(.likely); + const ansi_mode = ansi: { + if (input.intermediates.len == 0) break :ansi true; + if (input.intermediates.len == 1 and + input.intermediates[0] == '?') break :ansi false; + + log.warn("invalid set mode command: {f}", .{input}); + break :mode; + }; + + for (input.params) |mode_int| { + if (modes.modeFromInt(mode_int, ansi_mode)) |mode| { + self.handler.vt(.set_mode, .{ .mode = mode }); + } else { + log.warn("unimplemented mode: {}", .{mode_int}); + } + } + }, + + // RM - Reset Mode + 'l' => mode: { + @branchHint(.likely); + const ansi_mode = ansi: { + if (input.intermediates.len == 0) break :ansi true; + if (input.intermediates.len == 1 and + input.intermediates[0] == '?') break :ansi false; + + log.warn("invalid set mode command: {f}", .{input}); + break :mode; + }; + + for (input.params) |mode_int| { + if (modes.modeFromInt(mode_int, ansi_mode)) |mode| { + self.handler.vt(.reset_mode, .{ .mode = mode }); + } else { + log.warn("unimplemented mode: {}", .{mode_int}); + } + } + }, + + // SGR - Select Graphic Rendition + 'm' => { + @branchHint(.likely); + switch (input.intermediates.len) { + 0 => { + // This is the most common case. + @branchHint(.likely); + // log.info("parse SGR params={any}", .{input.params}); + var p: sgr.Parser = .{ + .params = input.params, + .params_sep = input.params_sep, + }; + while (p.next()) |attr| { + // log.info("SGR attribute: {}", .{attr}); + self.handler.vt(.set_attribute, attr); + } + }, + + 1 => switch (input.intermediates[0]) { + '>' => blk: { + if (input.params.len == 0) { + // Reset + self.handler.vt(.modify_key_format, .legacy); + break :blk; + } + + var format: ansi.ModifyKeyFormat = switch (input.params[0]) { + 0 => .legacy, + 1 => .cursor_keys, + 2 => .function_keys, + 4 => .other_keys_none, + else => { + @branchHint(.unlikely); + log.warn("invalid setModifyKeyFormat: {f}", .{input}); + break :blk; + }, + }; + + if (input.params.len > 2) { + @branchHint(.unlikely); + log.warn("invalid setModifyKeyFormat: {f}", .{input}); + break :blk; + } + + if (input.params.len == 2) { + switch (format) { + // We don't support any of the subparams yet for these. + .legacy => {}, + .cursor_keys => {}, + .function_keys => {}, + + // We only support the numeric form. + .other_keys_none => switch (input.params[1]) { + 2 => format = .other_keys_numeric, + else => {}, + }, + .other_keys_numeric_except => {}, + .other_keys_numeric => {}, + } + } + + self.handler.vt(.modify_key_format, format); + }, + + else => log.warn( + "unknown CSI m with intermediate: {}", + .{input.intermediates[0]}, + ), + }, + + else => { + // Nothing, but I wanted a place to put this comment: + // there are others forms of CSI m that have intermediates. + // `vim --clean` uses `CSI ? 4 m` and I don't know what + // that means. + log.warn( + "ignoring unimplemented CSI m with intermediates: {s}", + .{input.intermediates}, + ); + }, + } + }, + + // TODO: test + 'n' => { + // Handle deviceStatusReport first + if (input.intermediates.len == 0 or + input.intermediates[0] == '?') + { + if (input.params.len != 1) { + log.warn("invalid device status report command: {f}", .{input}); + return; + } + + const question = question: { + if (input.intermediates.len == 0) break :question false; + if (input.intermediates.len == 1 and + input.intermediates[0] == '?') break :question true; + + log.warn("invalid set mode command: {f}", .{input}); + return; + }; + + const req = device_status.reqFromInt(input.params[0], question) orelse { + log.warn("invalid device status report command: {f}", .{input}); + return; + }; + + self.handler.vt(.device_status, .{ .request = req }); + return; + } + + // Handle other forms of CSI n + switch (input.intermediates.len) { + 0 => unreachable, // handled above + + 1 => switch (input.intermediates[0]) { + '>' => { + // This isn't strictly correct. CSI > n has parameters that + // control what exactly is being disabled. However, we + // only support reverting back to modify other keys in + // numeric except format. + self.handler.vt(.modify_key_format, .other_keys_numeric_except); + }, + + else => log.warn( + "unknown CSI n with intermediate: {}", + .{input.intermediates[0]}, + ), + }, + + else => log.warn( + "ignoring unimplemented CSI n with intermediates: {s}", + .{input.intermediates}, + ), + } + }, + + // DECRQM - Request Mode + 'p' => switch (input.intermediates.len) { + 2 => decrqm: { + const ansi_mode = ansi: { + switch (input.intermediates.len) { + 1 => if (input.intermediates[0] == '$') break :ansi true, + 2 => if (input.intermediates[0] == '?' and + input.intermediates[1] == '$') break :ansi false, + else => {}, + } + + log.warn( + "ignoring unimplemented CSI p with intermediates: {s}", + .{input.intermediates}, + ); + break :decrqm; + }; + + if (input.params.len != 1) { + log.warn("invalid DECRQM command: {f}", .{input}); + break :decrqm; + } + + const mode_raw = input.params[0]; + const mode = modes.modeFromInt(mode_raw, ansi_mode); + if (mode) |m| { + self.handler.vt(.request_mode, .{ .mode = m }); + } else { + self.handler.vt(.request_mode_unknown, .{ + .mode = mode_raw, + .ansi = ansi_mode, + }); + } + }, + + else => log.warn( + "ignoring unimplemented CSI p with intermediates: {s}", + .{input.intermediates}, + ), + }, + + 'q' => switch (input.intermediates.len) { + 1 => switch (input.intermediates[0]) { + // DECSCUSR - Select Cursor Style + // TODO: test + ' ' => { + const style: ansi.CursorStyle = switch (input.params.len) { + 0 => .default, + 1 => switch (input.params[0]) { + 0 => .default, + 1 => .blinking_block, + 2 => .steady_block, + 3 => .blinking_underline, + 4 => .steady_underline, + 5 => .blinking_bar, + 6 => .steady_bar, + else => { + log.warn("invalid cursor style value: {}", .{input.params[0]}); + return; + }, + }, + else => { + log.warn("invalid set cursor style command: {f}", .{input}); + return; + }, + }; + self.handler.vt(.cursor_style, style); + }, + + // DECSCA + '"' => { + const mode_: ?ansi.ProtectedMode = switch (input.params.len) { + else => null, + 0 => .off, + 1 => switch (input.params[0]) { + 0, 2 => .off, + 1 => .dec, + else => null, + }, + }; + + const mode = mode_ orelse { + log.warn("invalid set protected mode command: {f}", .{input}); + return; + }; + + switch (mode) { + .off => self.handler.vt(.protected_mode_off, {}), + .iso => self.handler.vt(.protected_mode_iso, {}), + .dec => self.handler.vt(.protected_mode_dec, {}), + } + }, + + // XTVERSION + '>' => self.handler.vt(.xtversion, {}), + else => { + log.warn( + "ignoring unimplemented CSI q with intermediates: {s}", + .{input.intermediates}, + ); + }, + }, + + else => log.warn( + "ignoring unimplemented CSI p with intermediates: {s}", + .{input.intermediates}, + ), + }, + + 'r' => { + @branchHint(.likely); + switch (input.intermediates.len) { + // DECSTBM - Set Top and Bottom Margins + 0 => switch (input.params.len) { + 0 => self.handler.vt(.top_and_bottom_margin, .{ .top_left = 0, .bottom_right = 0 }), + 1 => self.handler.vt(.top_and_bottom_margin, .{ .top_left = input.params[0], .bottom_right = 0 }), + 2 => self.handler.vt(.top_and_bottom_margin, .{ .top_left = input.params[0], .bottom_right = input.params[1] }), + else => { + @branchHint(.unlikely); + log.warn("invalid DECSTBM command: {f}", .{input}); + }, + }, + + 1 => switch (input.intermediates[0]) { + // Restore Mode + '?' => { + for (input.params) |mode_int| { + if (modes.modeFromInt(mode_int, false)) |mode| { + self.handler.vt(.restore_mode, .{ .mode = mode }); + } else { + log.warn( + "unimplemented restore mode: {}", + .{mode_int}, + ); + } + } + }, + + else => log.warn( + "unknown CSI s with intermediate: {f}", + .{input}, + ), + }, + + else => log.warn( + "ignoring unimplemented CSI s with intermediates: {f}", + .{input}, + ), + } + }, + + 's' => switch (input.intermediates.len) { + // DECSLRM + 0 => switch (input.params.len) { + // CSI S is ambiguous with zero params so we defer + // to our handler to do the proper logic. If mode 69 + // is set, then we should invoke DECSLRM, otherwise + // we should invoke SC. + 0 => self.handler.vt(.left_and_right_margin_ambiguous, {}), + 1 => self.handler.vt(.left_and_right_margin, .{ .top_left = input.params[0], .bottom_right = 0 }), + 2 => self.handler.vt(.left_and_right_margin, .{ .top_left = input.params[0], .bottom_right = input.params[1] }), + else => log.warn("invalid DECSLRM command: {f}", .{input}), + }, + + 1 => switch (input.intermediates[0]) { + '?' => { + for (input.params) |mode_int| { + if (modes.modeFromInt(mode_int, false)) |mode| { + self.handler.vt(.save_mode, .{ .mode = mode }); + } else { + log.warn( + "unimplemented save mode: {}", + .{mode_int}, + ); + } + } + }, + + // XTSHIFTESCAPE + '>' => capture: { + const capture = switch (input.params.len) { + 0 => false, + 1 => switch (input.params[0]) { + 0 => false, + 1 => true, + else => { + log.warn("invalid XTSHIFTESCAPE command: {f}", .{input}); + break :capture; + }, + }, + else => { + log.warn("invalid XTSHIFTESCAPE command: {f}", .{input}); + break :capture; + }, + }; + + self.handler.vt(.mouse_shift_capture, capture); + }, + + else => log.warn( + "unknown CSI s with intermediate: {f}", + .{input}, + ), + }, + + else => log.warn( + "ignoring unimplemented CSI s with intermediates: {f}", + .{input}, + ), + }, + + // XTWINOPS + 't' => switch (input.intermediates.len) { + 0 => { + if (input.params.len > 0) { + switch (input.params[0]) { + 14 => if (input.params.len == 1) { + // report the text area size in pixels + self.handler.vt(.size_report, .csi_14_t); + } else log.warn( + "ignoring CSI 14 t with extra parameters: {f}", + .{input}, + ), + 16 => if (input.params.len == 1) { + // report cell size in pixels + self.handler.vt(.size_report, .csi_16_t); + } else log.warn( + "ignoring CSI 16 t with extra parameters: {f}", + .{input}, + ), + 18 => if (input.params.len == 1) { + // report screen size in characters + self.handler.vt(.size_report, .csi_18_t); + } else log.warn( + "ignoring CSI 18 t with extra parameters: {f}", + .{input}, + ), + 21 => if (input.params.len == 1) { + // report window title + self.handler.vt(.size_report, .csi_21_t); + } else log.warn( + "ignoring CSI 21 t with extra parameters: {f}", + .{input}, + ), + inline 22, 23 => |number| if ((input.params.len == 2 or + input.params.len == 3) and + // we only support window title + (input.params[1] == 0 or + input.params[1] == 2)) + { + // push/pop title + const index: u16 = if (input.params.len == 3) + input.params[2] + else + 0; + switch (number) { + 22 => self.handler.vt(.title_push, index), + 23 => self.handler.vt(.title_pop, index), + else => @compileError("unreachable"), + } + } else log.warn( + "ignoring CSI 22/23 t with extra parameters: {f}", + .{input}, + ), + else => log.warn( + "ignoring CSI t with unimplemented parameter: {f}", + .{input}, + ), + } + } else log.err( + "ignoring CSI t with no parameters: {f}", + .{input}, + ); + }, + else => log.warn( + "ignoring unimplemented CSI t with intermediates: {f}", + .{input}, + ), + }, + + 'u' => switch (input.intermediates.len) { + 0 => self.handler.vt(.restore_cursor, {}), + + // Kitty keyboard protocol + 1 => switch (input.intermediates[0]) { + '?' => self.handler.vt(.kitty_keyboard_query, {}), + + '>' => push: { + const flags: u5 = if (input.params.len == 1) + std.math.cast(u5, input.params[0]) orelse { + log.warn("invalid pushKittyKeyboard command: {f}", .{input}); + break :push; + } + else + 0; + + self.handler.vt(.kitty_keyboard_push, .{ .flags = @as(kitty.KeyFlags, @bitCast(flags)) }); + }, + + '<' => { + const number: u16 = if (input.params.len == 1) + input.params[0] + else + 1; + + self.handler.vt(.kitty_keyboard_pop, number); + }, + + '=' => set: { + const flags: u5 = if (input.params.len >= 1) + std.math.cast(u5, input.params[0]) orelse { + log.warn("invalid setKittyKeyboard command: {f}", .{input}); + break :set; + } + else + 0; + + const number: u16 = if (input.params.len >= 2) + input.params[1] + else + 1; + + const action_tag: streampkg.Action.Tag = switch (number) { + 1 => .kitty_keyboard_set, + 2 => .kitty_keyboard_set_or, + 3 => .kitty_keyboard_set_not, + else => { + log.warn("invalid setKittyKeyboard command: {f}", .{input}); + break :set; + }, + }; + + const kitty_flags: streampkg.Action.KittyKeyboardFlags = .{ .flags = @as(kitty.KeyFlags, @bitCast(flags)) }; + switch (action_tag) { + .kitty_keyboard_set => self.handler.vt(.kitty_keyboard_set, kitty_flags), + .kitty_keyboard_set_or => self.handler.vt(.kitty_keyboard_set_or, kitty_flags), + .kitty_keyboard_set_not => self.handler.vt(.kitty_keyboard_set_not, kitty_flags), + else => unreachable, + } + }, + + else => log.warn( + "unknown CSI s with intermediate: {f}", + .{input}, + ), + }, + + else => log.warn( + "ignoring unimplemented CSI u: {f}", + .{input}, + ), + }, + + // ICH - Insert Blanks + '@' => switch (input.intermediates.len) { + 0 => self.handler.vt(.insert_blanks, switch (input.params.len) { + 0 => 1, + 1 => @max(1, input.params[0]), + else => { + @branchHint(.unlikely); + log.warn("invalid ICH command: {f}", .{input}); + return; + }, + }), + + else => log.warn( + "ignoring unimplemented CSI @: {f}", + .{input}, + ), + }, + + // DECSASD - Select Active Status Display + '}' => decsasd: { + // Verify we're getting a DECSASD command + if (input.intermediates.len != 1 or input.intermediates[0] != '$') { + log.warn("unimplemented CSI callback: {f}", .{input}); + break :decsasd; + } + if (input.params.len != 1) { + log.warn("unimplemented CSI callback: {f}", .{input}); + break :decsasd; + } + + const display: ansi.StatusDisplay = switch (input.params[0]) { + 0 => .main, + 1 => .status_line, + else => { + log.warn("unimplemented CSI callback: {f}", .{input}); + break :decsasd; + }, + }; + + self.handler.vt(.active_status_display, display); + }, + + else => log.warn("unimplemented CSI action: {f}", .{input}), + } + } + + inline fn oscDispatch(self: *Self, cmd: osc.Command) void { + // The branch hints here are based on real world data + // which indicates that the most common OSC commands are: + // + // 1. hyperlink_end + // 2. change_window_title + // 3. change_window_icon + // 4. hyperlink_start + // 5. report_pwd + // 6. color_operation + // 7. semantic_prompt + // + // Together, these 7 commands make up about 96% of all + // OSC commands encountered in real world scenarios. + // + // Additionally, within the prongs, unlikely branch + // hints have been added to branches that deal with + // invalid sequences/commands, this is in order to + // optimize for the happy path where we're getting + // valid data from the program we're running. + // + // ref: https://github.com/qwerasd205/asciinema-stats + + switch (cmd) { + .semantic_prompt => |sp| { + @branchHint(.likely); + self.handler.vt(.semantic_prompt, sp); + }, + + .change_window_title => |title| { + @branchHint(.likely); + if (!std.unicode.utf8ValidateSlice(title)) { + @branchHint(.unlikely); + log.warn("change title request: invalid utf-8, ignoring request", .{}); + return; + } + + self.handler.vt(.window_title, .{ .title = title }); + }, + + .change_window_icon => |icon| { + @branchHint(.likely); + log.info("OSC 1 (change icon) received and ignored icon={s}", .{icon}); + }, + + .clipboard_contents => |clip| { + self.handler.vt(.clipboard_contents, .{ + .kind = clip.kind, + .data = clip.data, + }); + }, + + .report_pwd => |v| { + @branchHint(.likely); + self.handler.vt(.report_pwd, .{ .url = v.value }); + }, + + .mouse_shape => |v| { + const shape = MouseShape.fromString(v.value) orelse { + @branchHint(.unlikely); + log.warn("unknown cursor shape: {s}", .{v.value}); + return; + }; + + self.handler.vt(.mouse_shape, shape); + }, + + .color_operation => |v| { + @branchHint(.likely); + self.handler.vt(.color_operation, .{ + .op = v.op, + .requests = v.requests, + .terminator = v.terminator, + }); + }, + + .kitty_color_protocol => |v| { + self.handler.vt(.kitty_color_report, v); + }, + + .show_desktop_notification => |v| { + self.handler.vt(.show_desktop_notification, .{ + .title = v.title, + .body = v.body, + }); + }, + + .hyperlink_start => |v| { + @branchHint(.likely); + self.handler.vt(.start_hyperlink, .{ + .uri = v.uri, + .id = v.id, + }); + }, + + .hyperlink_end => { + @branchHint(.likely); + self.handler.vt(.end_hyperlink, {}); + }, + + .conemu_progress_report => |v| { + self.handler.vt(.progress_report, v); + }, + + .conemu_sleep, + .conemu_show_message_box, + .conemu_change_tab_title, + .conemu_wait_input, + .conemu_guimacro, + .conemu_comment, + .conemu_xterm_emulation, + .conemu_output_environment_variable, + .conemu_run_process, + .kitty_text_sizing, + .kitty_clipboard_protocol, + .context_signal, + => { + log.debug("unimplemented OSC callback: {}", .{cmd}); + }, + + .invalid => { + @branchHint(.cold); + // This is an invalid internal state, not an invalid OSC + // string being parsed. We shouldn't see this. + log.warn("invalid OSC, should never happen", .{}); + }, + } + } + + inline fn configureCharset( + self: *Self, + intermediates: []const u8, + set: charsets.Charset, + ) void { + if (intermediates.len != 1) { + log.warn("invalid charset intermediate: {any}", .{intermediates}); + return; + } + + const slot: charsets.Slots = switch (intermediates[0]) { + // TODO: support slots '-', '.', '/' + + '(' => .G0, + ')' => .G1, + '*' => .G2, + '+' => .G3, + else => { + @branchHint(.unlikely); + log.warn("invalid charset intermediate: {any}", .{intermediates}); + return; + }, + }; + + self.handler.vt(.configure_charset, .{ + .slot = slot, + .charset = set, + }); + } + + inline fn escDispatch( + self: *Self, + action: Parser.Action.ESC, + ) void { + // The branch hints here are based on real world data + // which indicates that the most common ESC finals are: + // + // 1. B + // 2. \ + // 3. 0 + // 4. M + // 5. 8 + // 6. 7 + // 7. > + // 8. = + // + // Together, these 8 finals make up nearly 99% of all + // ESC sequences encountered in real world scenarios. + // + // Additionally, within the prongs, unlikely branch + // hints have been added to branches that deal with + // invalid sequences/commands, this is in order to + // optimize for the happy path where we're getting + // valid data from the program we're running. + // + // ref: https://github.com/qwerasd205/asciinema-stats + + switch (action.final) { + // Charsets + 'B' => { + @branchHint(.likely); + self.configureCharset(action.intermediates, .ascii); + }, + 'A' => self.configureCharset(action.intermediates, .british), + '0' => { + @branchHint(.likely); + self.configureCharset(action.intermediates, .dec_special); + }, + + // DECSC - Save Cursor + '7' => { + @branchHint(.likely); + switch (action.intermediates.len) { + 0 => self.handler.vt(.save_cursor, {}), + else => { + @branchHint(.unlikely); + log.warn("invalid command: {f}", .{action}); + return; + }, + } + }, + + '8' => blk: { + @branchHint(.likely); + switch (action.intermediates.len) { + // DECRC - Restore Cursor + 0 => { + self.handler.vt(.restore_cursor, {}); + break :blk {}; + }, + + 1 => switch (action.intermediates[0]) { + // DECALN - Fill Screen with E + '#' => { + self.handler.vt(.decaln, {}); + break :blk {}; + }, + + else => {}, + }, + + else => {}, // fall through + } + + log.warn("unimplemented ESC action: {f}", .{action}); + }, + + // IND - Index + 'D' => switch (action.intermediates.len) { + 0 => self.handler.vt(.index, {}), + else => { + @branchHint(.unlikely); + log.warn("invalid index command: {f}", .{action}); + return; + }, + }, + + // NEL - Next Line + 'E' => switch (action.intermediates.len) { + 0 => self.handler.vt(.next_line, {}), + else => { + @branchHint(.unlikely); + log.warn("invalid next line command: {f}", .{action}); + return; + }, + }, + + // HTS - Horizontal Tab Set + 'H' => switch (action.intermediates.len) { + 0 => self.handler.vt(.tab_set, {}), + else => { + @branchHint(.unlikely); + log.warn("invalid tab set command: {f}", .{action}); + return; + }, + }, + + // RI - Reverse Index + 'M' => { + @branchHint(.likely); + switch (action.intermediates.len) { + 0 => self.handler.vt(.reverse_index, {}), + else => { + @branchHint(.unlikely); + log.warn("invalid reverse index command: {f}", .{action}); + return; + }, + } + }, + + // SS2 - Single Shift 2 + 'N' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GL, + .charset = .G2, + .locking = true, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid single shift 2 command: {f}", .{action}); + return; + }, + }, + + // SS3 - Single Shift 3 + 'O' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GL, + .charset = .G3, + .locking = true, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid single shift 3 command: {f}", .{action}); + return; + }, + }, + + // SPA - Start of Guarded Area + 'V' => switch (action.intermediates.len) { + 0 => self.handler.vt(.protected_mode_iso, {}), + else => log.warn("unimplemented ESC callback: {f}", .{action}), + }, + + // EPA - End of Guarded Area + 'W' => switch (action.intermediates.len) { + 0 => self.handler.vt(.protected_mode_off, {}), + else => log.warn("unimplemented ESC callback: {f}", .{action}), + }, + + // DECID + 'Z' => if (action.intermediates.len == 0) { + self.handler.vt(.device_attributes, .primary); + } else log.warn("unimplemented ESC callback: {f}", .{action}), + + // RIS - Full Reset + 'c' => switch (action.intermediates.len) { + 0 => self.handler.vt(.full_reset, {}), + else => { + log.warn("invalid full reset command: {f}", .{action}); + return; + }, + }, + + // LS2 - Locking Shift 2 + 'n' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GL, + .charset = .G2, + .locking = false, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid single shift 2 command: {f}", .{action}); + return; + }, + }, + + // LS3 - Locking Shift 3 + 'o' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GL, + .charset = .G3, + .locking = false, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid single shift 3 command: {f}", .{action}); + return; + }, + }, + + // LS1R - Locking Shift 1 Right + '~' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GR, + .charset = .G1, + .locking = false, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid locking shift 1 right command: {f}", .{action}); + return; + }, + }, + + // LS2R - Locking Shift 2 Right + '}' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GR, + .charset = .G2, + .locking = false, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid locking shift 2 right command: {f}", .{action}); + return; + }, + }, + + // LS3R - Locking Shift 3 Right + '|' => switch (action.intermediates.len) { + 0 => self.handler.vt(.invoke_charset, .{ + .bank = .GR, + .charset = .G3, + .locking = false, + }), + else => { + @branchHint(.unlikely); + log.warn("invalid locking shift 3 right command: {f}", .{action}); + return; + }, + }, + + // Set application keypad mode + '=' => { + @branchHint(.likely); + switch (action.intermediates.len) { + 0 => self.handler.vt(.set_mode, .{ .mode = .keypad_keys }), + else => log.warn("unimplemented setMode: {f}", .{action}), + } + }, + + // Reset application keypad mode + '>' => { + @branchHint(.likely); + switch (action.intermediates.len) { + 0 => self.handler.vt(.reset_mode, .{ .mode = .keypad_keys }), + else => log.warn("unimplemented setMode: {f}", .{action}), + } + }, + + // Sets ST (string terminator). We don't have to do anything + // because our parser always accepts ST. + '\\' => { + @branchHint(.likely); + }, + + else => log.warn("unimplemented ESC action: {f}", .{action}), + } + } + }; +} + +test Action { + // Forces the C type to be reified when the target is C, ensuring + // all our types are C ABI compatible. + _ = Action.C; +} + +test "stream: print" { + const H = struct { + c: ?u21 = 0, + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + switch (action) { + .print => self.c = value.cp, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.next('x'); + try testing.expectEqual(@as(u21, 'x'), s.handler.c.?); +} + +test "simd: print invalid utf-8" { + const H = struct { + c: ?u21 = 0, + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + switch (action) { + .print => self.c = value.cp, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice(&.{0xFF}); + try testing.expectEqual(@as(u21, 0xFFFD), s.handler.c.?); +} + +test "simd: complete incomplete utf-8" { + const H = struct { + c: ?u21 = null, + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + switch (action) { + .print => self.c = value.cp, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice(&.{0xE0}); // 3 byte + try testing.expect(s.handler.c == null); + s.nextSlice(&.{0xA0}); // still incomplete + try testing.expect(s.handler.c == null); + s.nextSlice(&.{0x80}); + try testing.expectEqual(@as(u21, 0x800), s.handler.c.?); +} + +test "stream: cursor right (CUF)" { + const H = struct { + amount: u16 = 0, + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + switch (action) { + .cursor_right => self.amount = value.value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[C"); + try testing.expectEqual(@as(u16, 1), s.handler.amount); + + s.nextSlice("\x1B[5C"); + try testing.expectEqual(@as(u16, 5), s.handler.amount); + + s.handler.amount = 0; + s.nextSlice("\x1B[5;4C"); + try testing.expectEqual(@as(u16, 0), s.handler.amount); + + s.handler.amount = 0; + s.nextSlice("\x1b[?3C"); + try testing.expectEqual(@as(u16, 0), s.handler.amount); +} + +test "stream: dec set mode (SM) and reset mode (RM)" { + const H = struct { + mode: modes.Mode = @as(modes.Mode, @enumFromInt(1)), + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + switch (action) { + .set_mode => self.mode = value.mode, + .reset_mode => self.mode = @as(modes.Mode, @enumFromInt(1)), + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[?6h"); + try testing.expectEqual(@as(modes.Mode, .origin), s.handler.mode); + + s.nextSlice("\x1B[?6l"); + try testing.expectEqual(@as(modes.Mode, @enumFromInt(1)), s.handler.mode); + + s.handler.mode = @as(modes.Mode, @enumFromInt(1)); + s.nextSlice("\x1B[6 h"); + try testing.expectEqual(@as(modes.Mode, @enumFromInt(1)), s.handler.mode); +} + +test "stream: ansi set mode (SM) and reset mode (RM)" { + const H = struct { + mode: ?modes.Mode = null, + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + switch (action) { + .set_mode => self.mode = value.mode, + .reset_mode => self.mode = null, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[4h"); + try testing.expectEqual(@as(modes.Mode, .insert), s.handler.mode.?); + + s.nextSlice("\x1B[4l"); + try testing.expect(s.handler.mode == null); + + s.handler.mode = null; + s.nextSlice("\x1B[>5h"); + try testing.expect(s.handler.mode == null); +} + +test "stream: ansi set mode (SM) and reset mode (RM) with unknown value" { + const H = struct { + mode: ?modes.Mode = null, + + pub fn setMode(self: *@This(), mode: modes.Mode, v: bool) !void { + self.mode = null; + if (v) self.mode = mode; + } + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + _ = self; + _ = value; + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[6h"); + try testing.expect(s.handler.mode == null); + + s.nextSlice("\x1B[6l"); + try testing.expect(s.handler.mode == null); +} + +test "stream: restore mode" { + const H = struct { + const Self = @This(); + called: bool = false, + + pub fn vt( + self: *Self, + comptime action: Stream(Self).Action.Tag, + value: Stream(Self).Action.Value(action), + ) void { + _ = value; + switch (action) { + .top_and_bottom_margin => self.called = true, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + for ("\x1B[?42r") |c| s.next(c); + try testing.expect(!s.handler.called); +} + +test "stream: pop kitty keyboard with no params defaults to 1" { + const H = struct { + const Self = @This(); + n: u16 = 0, + + pub fn vt( + self: *Self, + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .kitty_keyboard_pop => self.n = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + for ("\x1B[ self.v = .off, + .protected_mode_iso => self.v = .iso, + .protected_mode_dec => self.v = .dec, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + { + for ("\x1B[\"q") |c| s.next(c); + try testing.expectEqual(ansi.ProtectedMode.off, s.handler.v.?); + } + { + for ("\x1B[0\"q") |c| s.next(c); + try testing.expectEqual(ansi.ProtectedMode.off, s.handler.v.?); + } + { + for ("\x1B[2\"q") |c| s.next(c); + try testing.expectEqual(ansi.ProtectedMode.off, s.handler.v.?); + } + { + for ("\x1B[1\"q") |c| s.next(c); + try testing.expectEqual(ansi.ProtectedMode.dec, s.handler.v.?); + } +} + +test "stream: DECED, DECSED" { + const H = struct { + const Self = @This(); + mode: ?csi.EraseDisplay = null, + protected: ?bool = null, + + pub fn vt( + self: *Self, + comptime action: anytype, + value: anytype, + ) void { + switch (action) { + .erase_display_below => { + self.mode = .below; + self.protected = value; + }, + .erase_display_above => { + self.mode = .above; + self.protected = value; + }, + .erase_display_complete => { + self.mode = .complete; + self.protected = value; + }, + .erase_display_scrollback => { + self.mode = .scrollback; + self.protected = value; + }, + .erase_display_scroll_complete => { + self.mode = .scroll_complete; + self.protected = value; + }, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + { + for ("\x1B[?J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?0J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?1J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.above, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?2J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.complete, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?3J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.scrollback, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + + { + for ("\x1B[J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[0J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.below, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[1J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.above, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[2J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.complete, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[3J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.scrollback, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + // Invalid and ignored by the handler + for ("\x1B[>0J") |c| s.next(c); + try testing.expectEqual(csi.EraseDisplay.scrollback, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } +} + +test "stream: DECEL, DECSEL" { + const H = struct { + const Self = @This(); + mode: ?csi.EraseLine = null, + protected: ?bool = null, + + pub fn vt( + self: *Self, + comptime action: anytype, + value: anytype, + ) void { + switch (action) { + .erase_line_right => { + self.mode = .right; + self.protected = value; + }, + .erase_line_left => { + self.mode = .left; + self.protected = value; + }, + .erase_line_complete => { + self.mode = .complete; + self.protected = value; + }, + .erase_line_right_unless_pending_wrap => { + self.mode = .right_unless_pending_wrap; + self.protected = value; + }, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + { + for ("\x1B[?K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?0K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?1K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.left, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + { + for ("\x1B[?2K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.complete, s.handler.mode.?); + try testing.expect(s.handler.protected.?); + } + + { + for ("\x1B[K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[0K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.right, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[1K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.left, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + for ("\x1B[2K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.complete, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } + { + // Invalid and ignored by the handler + for ("\x1B[<1K") |c| s.next(c); + try testing.expectEqual(csi.EraseLine.complete, s.handler.mode.?); + try testing.expect(!s.handler.protected.?); + } +} + +test "stream: DECSCUSR" { + const H = struct { + style: ?ansi.CursorStyle = null, + + pub fn vt( + self: *@This(), + comptime action: Stream(@This()).Action.Tag, + value: Stream(@This()).Action.Value(action), + ) void { + switch (action) { + .cursor_style => self.style = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[ q"); + try testing.expect(s.handler.style.? == .default); + + s.nextSlice("\x1B[1 q"); + try testing.expect(s.handler.style.? == .blinking_block); + + // Invalid and ignored by the handler + s.nextSlice("\x1B[?0 q"); + try testing.expect(s.handler.style.? == .blinking_block); +} + +test "stream: DECSCUSR without space" { + const H = struct { + style: ?ansi.CursorStyle = null, + + pub fn vt( + self: *@This(), + comptime action: Stream(@This()).Action.Tag, + value: Stream(@This()).Action.Value(action), + ) void { + switch (action) { + .cursor_style => self.style = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[q"); + try testing.expect(s.handler.style == null); + + s.nextSlice("\x1B[1q"); + try testing.expect(s.handler.style == null); +} + +test "stream: XTSHIFTESCAPE" { + const H = struct { + escape: ?bool = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .mouse_shift_capture => self.escape = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[>2s"); + try testing.expect(s.handler.escape == null); + + s.nextSlice("\x1B[>s"); + try testing.expect(s.handler.escape.? == false); + + s.nextSlice("\x1B[>0s"); + try testing.expect(s.handler.escape.? == false); + + s.nextSlice("\x1B[>1s"); + try testing.expect(s.handler.escape.? == true); + + // Invalid and ignored by the handler + s.nextSlice("\x1B[1 s"); + try testing.expect(s.handler.escape.? == true); +} + +test "stream: change window title with invalid utf-8" { + const H = struct { + seen: bool = false, + + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = value; + switch (action) { + .window_title => self.seen = true, + else => {}, + } + } + }; + + { + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1b]2;abc\x1b\\"); + try testing.expect(s.handler.seen); + } + + { + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1b]2;abc\xc0\x1b\\"); + try testing.expect(!s.handler.seen); + } +} + +test "stream: insert characters" { + const H = struct { + const Self = @This(); + called: bool = false, + + pub fn vt( + self: *Self, + comptime action: anytype, + value: anytype, + ) void { + _ = value; + switch (action) { + .insert_blanks => self.called = true, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + for ("\x1B[42@") |c| s.next(c); + try testing.expect(s.handler.called); + + s.handler.called = false; + for ("\x1B[?42@") |c| s.next(c); + try testing.expect(!s.handler.called); +} + +test "stream: insert characters explicit zero clamps to 1" { + const H = struct { + const Self = @This(); + value: ?usize = null, + + pub fn vt( + self: *Self, + comptime action: anytype, + value: anytype, + ) void { + switch (action) { + .insert_blanks => self.value = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + for ("\x1B[0@") |c| s.next(c); + try testing.expectEqual(@as(usize, 1), s.handler.value.?); +} + +test "stream: SCOSC" { + const H = struct { + const Self = @This(); + called: bool = false, + + pub fn vt( + self: *Self, + comptime action: Stream(Self).Action.Tag, + value: Stream(Self).Action.Value(action), + ) void { + _ = value; + switch (action) { + .left_and_right_margin => @panic("bad"), + .left_and_right_margin_ambiguous => self.called = true, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + for ("\x1B[s") |c| s.next(c); + try testing.expect(s.handler.called); +} + +test "stream: SCORC" { + const H = struct { + const Self = @This(); + called: bool = false, + + pub fn vt( + self: *Self, + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + _ = value; + switch (action) { + .restore_cursor => self.called = true, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + for ("\x1B[u") |c| s.next(c); + try testing.expect(s.handler.called); +} + +test "stream: too many csi params" { + const H = struct { + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = self; + _ = value; + switch (action) { + .cursor_right => unreachable, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1C"); +} + +test "stream: csi param too long" { + const H = struct { + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = self; + _ = action; + _ = value; + } + }; + + var s: Stream(H) = .init(.{}); + s.nextSlice("\x1B[1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111C"); +} + +test "stream: send report with CSI t" { + const H = struct { + style: ?csi.SizeReportStyle = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .size_report => self.style = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[14t"); + try testing.expectEqual(csi.SizeReportStyle.csi_14_t, s.handler.style); + + s.nextSlice("\x1b[16t"); + try testing.expectEqual(csi.SizeReportStyle.csi_16_t, s.handler.style); + + s.nextSlice("\x1b[18t"); + try testing.expectEqual(csi.SizeReportStyle.csi_18_t, s.handler.style); + + s.nextSlice("\x1b[21t"); + try testing.expectEqual(csi.SizeReportStyle.csi_21_t, s.handler.style); +} + +test "stream: invalid CSI t" { + const H = struct { + style: ?csi.SizeReportStyle = null, + + pub fn sendSizeReport(self: *@This(), style: csi.SizeReportStyle) void { + self.style = style; + } + + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = self; + _ = action; + _ = value; + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[19t"); + try testing.expectEqual(null, s.handler.style); +} + +test "stream: CSI t push title" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_push => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[22;0t"); + try testing.expectEqual(@as(u16, 0), s.handler.index.?); +} + +test "stream: CSI t push title with explicit window" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_push => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[22;2t"); + try testing.expectEqual(@as(u16, 0), s.handler.index.?); +} + +test "stream: CSI t push title with explicit icon" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_push => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[22;1t"); + try testing.expectEqual(null, s.handler.index); +} + +test "stream: CSI t push title with index" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_push => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[22;0;5t"); + try testing.expectEqual(@as(u16, 5), s.handler.index.?); +} + +test "stream: CSI t pop title" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_pop => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[23;0t"); + try testing.expectEqual(@as(u16, 0), s.handler.index.?); +} + +test "stream: CSI t pop title with explicit window" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_pop => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[23;2t"); + try testing.expectEqual(@as(u16, 0), s.handler.index.?); +} + +test "stream: CSI t pop title with explicit icon" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_pop => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[23;1t"); + try testing.expectEqual(null, s.handler.index); +} + +test "stream: CSI t pop title with index" { + const H = struct { + index: ?u16 = null, + + pub fn vt( + self: *@This(), + comptime action: streampkg.Action.Tag, + value: streampkg.Action.Value(action), + ) void { + switch (action) { + .title_pop => self.index = value, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[23;0;5t"); + try testing.expectEqual(@as(u16, 5), s.handler.index.?); +} + +test "stream CSI W clear tab stops" { + const H = struct { + action: ?Action.Key = null, + + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = value; + self.action = action; + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[2W"); + try testing.expectEqual(Action.Key.tab_clear_current, s.handler.action.?); + + s.nextSlice("\x1b[5W"); + try testing.expectEqual(Action.Key.tab_clear_all, s.handler.action.?); +} + +test "stream CSI W tab set" { + const H = struct { + action: ?Action.Key = null, + + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = value; + self.action = action; + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[W"); + try testing.expectEqual(Action.Key.tab_set, s.handler.action.?); + + s.handler.action = null; + s.nextSlice("\x1b[0W"); + try testing.expectEqual(Action.Key.tab_set, s.handler.action.?); + + s.handler.action = null; + s.nextSlice("\x1b[>W"); + try testing.expect(s.handler.action == null); + + s.handler.action = null; + s.nextSlice("\x1b[99W"); + try testing.expect(s.handler.action == null); +} + +test "stream CSI ? W reset tab stops" { + const H = struct { + action: ?Action.Key = null, + + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + _ = value; + self.action = action; + } + }; + + var s: Stream(H) = .init(.{}); + + s.nextSlice("\x1b[?2W"); + try testing.expect(s.handler.action == null); + + s.nextSlice("\x1b[?5W"); + try testing.expectEqual(Action.Key.tab_reset, s.handler.action.?); + + // Invalid and ignored by the handler + s.handler.action = null; + s.nextSlice("\x1b[?1;2;3W"); + try testing.expect(s.handler.action == null); +} + +test "stream: SGR with 17+ parameters for underline color" { + const H = struct { + attrs: ?sgr.Attribute = null, + called: bool = false, + + pub fn vt( + self: *@This(), + comptime action: anytype, + value: anytype, + ) void { + switch (action) { + .set_attribute => { + self.attrs = value; + self.called = true; + }, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + + // Kakoune-style SGR with underline color as 17th parameter + // This tests the fix where param 17 was being dropped + s.nextSlice("\x1b[4:3;38;2;51;51;51;48;2;170;170;170;58;2;255;97;136;0m"); + try testing.expect(s.handler.called); +} + +test "stream: tab clear with overflowing param" { + // Regression test for a fuzz crash: CSI with a parameter value that + // saturates to 65535 (u16 max) causes @enumFromInt to panic when + // converting to TabClear (enum(u8)). + const H = struct { + called: bool = false, + + pub fn vt( + self: *@This(), + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + _ = value; + switch (action) { + .tab_clear_current, .tab_clear_all => self.called = true, + else => {}, + } + } + }; + + var s: Stream(H) = .init(.{}); + // This is the exact input from the fuzz crash (minus the mode byte): + // CSI with a huge numeric param that saturates to 65535, followed by 'g'. + s.nextSlice("\x1b[388888888888888888888888888888888888g\x1b[0m"); +} diff --git a/vendor/libghostty-vt/src/terminal/stream_terminal.zig b/vendor/libghostty-vt/src/terminal/stream_terminal.zig new file mode 100644 index 00000000..8e0f9111 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/stream_terminal.zig @@ -0,0 +1,2071 @@ +const std = @import("std"); +const testing = std.testing; +const csi = @import("csi.zig"); +const device_attributes = @import("device_attributes.zig"); +const device_status = @import("device_status.zig"); +const stream = @import("stream.zig"); +const Action = stream.Action; +const Screen = @import("Screen.zig"); +const modes = @import("modes.zig"); +const osc_color = @import("osc/parsers/color.zig"); +const kitty_color = @import("kitty/color.zig"); +const size_report = @import("size_report.zig"); +const Terminal = @import("Terminal.zig"); + +const log = std.log.scoped(.stream_terminal); + +/// This is a Stream implementation that processes actions against +/// a Terminal and updates the Terminal state. +pub const Stream = stream.Stream(Handler); + +/// A stream handler that updates terminal state. By default, it is +/// readonly in the sense that it only updates terminal state and ignores +/// all other sequences that require a response or otherwise have side +/// effects (e.g. clipboards). +/// +/// You can manually set various effects callbacks in the `effects` field +/// to implement certain effects such as bells, titles, clipboard, etc. +pub const Handler = struct { + /// The terminal state to modify. + terminal: *Terminal, + + /// Callbacks for certain effects that handlers may have. These + /// may or may not fully replace internal handling of certain effects, + /// but they allow for the handler to trigger or query external + /// effects. + effects: Effects = .readonly, + + pub const Effects = struct { + /// Called when the terminal needs to write data back to the pty, + /// e.g. in response to a DECRQM query. The data is only valid + /// during the lifetime of the call so callers must copy it + /// if it needs to be stored or used after the call returns. + write_pty: ?*const fn (*Handler, [:0]const u8) void, + + /// Called when the bell is rung (BEL). + bell: ?*const fn (*Handler) void, + + /// Called in response to a color scheme DSR query (CSI ? 996 n). + /// Returns the current color scheme. Return null to silently + /// ignore the query. + color_scheme: ?*const fn (*Handler) ?device_status.ColorScheme, + + /// Called in response to a device attributes query (CSI c, + /// CSI > c, CSI = c). Returns the response to encode and + /// write back to the pty. + device_attributes: ?*const fn (*Handler) device_attributes.Attributes, + + /// Called in response to ENQ (0x05). Returns the raw response + /// bytes to write back to the pty. The returned memory must be + /// valid for the lifetime of the call. + enquiry: ?*const fn (*Handler) []const u8, + + /// Called in response to XTWINOPS size queries (CSI 14/16/18 t). + /// Returns the current terminal geometry used for encoding. + /// Return null to silently ignore the query. + size: ?*const fn (*Handler) ?size_report.Size, + + /// Called when the terminal title changes via escape sequences + /// (e.g. OSC 0/2). The new title can be queried via + /// handler.terminal.getTitle(). + title_changed: ?*const fn (*Handler) void, + + /// Called in response to an XTVERSION query. Returns the version + /// string to report (e.g. "ghostty 1.2.3"). The returned memory + /// must be valid for the lifetime of the call. The maximum length + /// is 256 bytes; longer strings will be silently ignored. + xtversion: ?*const fn (*Handler) []const u8, + + /// No effects means that the stream effectively becomes readonly + /// that only affects pure terminal state and ignores all side + /// effects beyond that. + pub const readonly: Effects = .{ + .bell = null, + .color_scheme = null, + .device_attributes = null, + .enquiry = null, + .size = null, + .title_changed = null, + .write_pty = null, + .xtversion = null, + }; + }; + + pub fn init(terminal: *Terminal) Handler { + return .{ + .terminal = terminal, + }; + } + + pub fn deinit(self: *Handler) void { + // Currently does nothing but may in the future so callers should + // call this. + _ = self; + } + + pub fn vt( + self: *Handler, + comptime action: Action.Tag, + value: Action.Value(action), + ) void { + self.vtFallible(action, value) catch |err| { + log.warn("error handling VT action action={} err={}", .{ action, err }); + }; + } + + inline fn vtFallible( + self: *Handler, + comptime action: Action.Tag, + value: Action.Value(action), + ) !void { + switch (action) { + .print => try self.terminal.print(value.cp), + .print_repeat => try self.terminal.printRepeat(value), + .backspace => self.terminal.backspace(), + .carriage_return => self.terminal.carriageReturn(), + .linefeed => try self.terminal.linefeed(), + .index => try self.terminal.index(), + .next_line => { + try self.terminal.index(); + self.terminal.carriageReturn(); + }, + .reverse_index => self.terminal.reverseIndex(), + .cursor_up => self.terminal.cursorUp(value.value), + .cursor_down => self.terminal.cursorDown(value.value), + .cursor_left => self.terminal.cursorLeft(value.value), + .cursor_right => self.terminal.cursorRight(value.value), + .cursor_pos => self.terminal.setCursorPos(value.row, value.col), + .cursor_col => self.terminal.setCursorPos(self.terminal.screens.active.cursor.y + 1, value.value), + .cursor_row => self.terminal.setCursorPos(value.value, self.terminal.screens.active.cursor.x + 1), + .cursor_col_relative => self.terminal.setCursorPos( + self.terminal.screens.active.cursor.y + 1, + self.terminal.screens.active.cursor.x + 1 +| value.value, + ), + .cursor_row_relative => self.terminal.setCursorPos( + self.terminal.screens.active.cursor.y + 1 +| value.value, + self.terminal.screens.active.cursor.x + 1, + ), + .cursor_style => { + const blink = switch (value) { + .default, .steady_block, .steady_bar, .steady_underline => false, + .blinking_block, .blinking_bar, .blinking_underline => true, + }; + const style: Screen.CursorStyle = switch (value) { + .default, .blinking_block, .steady_block => .block, + .blinking_bar, .steady_bar => .bar, + .blinking_underline, .steady_underline => .underline, + }; + self.terminal.modes.set(.cursor_blinking, blink); + self.terminal.screens.active.cursor.cursor_style = style; + }, + .erase_display_below => self.terminal.eraseDisplay(.below, value), + .erase_display_above => self.terminal.eraseDisplay(.above, value), + .erase_display_complete => self.terminal.eraseDisplay(.complete, value), + .erase_display_scrollback => self.terminal.eraseDisplay(.scrollback, value), + .erase_display_scroll_complete => self.terminal.eraseDisplay(.scroll_complete, value), + .erase_line_right => self.terminal.eraseLine(.right, value), + .erase_line_left => self.terminal.eraseLine(.left, value), + .erase_line_complete => self.terminal.eraseLine(.complete, value), + .erase_line_right_unless_pending_wrap => self.terminal.eraseLine(.right_unless_pending_wrap, value), + .delete_chars => self.terminal.deleteChars(value), + .erase_chars => self.terminal.eraseChars(value), + .insert_lines => self.terminal.insertLines(value), + .insert_blanks => self.terminal.insertBlanks(value), + .delete_lines => self.terminal.deleteLines(value), + .scroll_up => try self.terminal.scrollUp(value), + .scroll_down => self.terminal.scrollDown(value), + .horizontal_tab => self.horizontalTab(value), + .horizontal_tab_back => self.horizontalTabBack(value), + .tab_clear_current => self.terminal.tabClear(.current), + .tab_clear_all => self.terminal.tabClear(.all), + .tab_set => self.terminal.tabSet(), + .tab_reset => self.terminal.tabReset(), + .set_mode => try self.setMode(value.mode, true), + .reset_mode => try self.setMode(value.mode, false), + .save_mode => self.terminal.modes.save(value.mode), + .restore_mode => { + const v = self.terminal.modes.restore(value.mode); + try self.setMode(value.mode, v); + }, + .top_and_bottom_margin => self.terminal.setTopAndBottomMargin(value.top_left, value.bottom_right), + .left_and_right_margin => self.terminal.setLeftAndRightMargin(value.top_left, value.bottom_right), + .left_and_right_margin_ambiguous => { + if (self.terminal.modes.get(.enable_left_and_right_margin)) { + self.terminal.setLeftAndRightMargin(0, 0); + } else { + self.terminal.saveCursor(); + } + }, + .save_cursor => self.terminal.saveCursor(), + .restore_cursor => self.terminal.restoreCursor(), + .invoke_charset => self.terminal.invokeCharset(value.bank, value.charset, value.locking), + .configure_charset => self.terminal.configureCharset(value.slot, value.charset), + .set_attribute => switch (value) { + .unknown => {}, + else => self.terminal.setAttribute(value) catch {}, + }, + .protected_mode_off => self.terminal.setProtectedMode(.off), + .protected_mode_iso => self.terminal.setProtectedMode(.iso), + .protected_mode_dec => self.terminal.setProtectedMode(.dec), + .mouse_shift_capture => self.terminal.flags.mouse_shift_capture = if (value) .true else .false, + .kitty_keyboard_push => self.terminal.screens.active.kitty_keyboard.push(value.flags), + .kitty_keyboard_pop => self.terminal.screens.active.kitty_keyboard.pop(@intCast(value)), + .kitty_keyboard_set => self.terminal.screens.active.kitty_keyboard.set(.set, value.flags), + .kitty_keyboard_set_or => self.terminal.screens.active.kitty_keyboard.set(.@"or", value.flags), + .kitty_keyboard_set_not => self.terminal.screens.active.kitty_keyboard.set(.not, value.flags), + .modify_key_format => { + self.terminal.flags.modify_other_keys_2 = false; + switch (value) { + .other_keys_numeric => self.terminal.flags.modify_other_keys_2 = true, + else => {}, + } + }, + .active_status_display => self.terminal.status_display = value, + .decaln => try self.terminal.decaln(), + .full_reset => self.terminal.fullReset(), + .start_hyperlink => try self.terminal.screens.active.startHyperlink(value.uri, value.id), + .end_hyperlink => self.terminal.screens.active.endHyperlink(), + .semantic_prompt => try self.terminal.semanticPrompt(value), + .mouse_shape => self.terminal.mouse_shape = value, + .color_operation => try self.colorOperation(value.op, &value.requests), + .kitty_color_report => try self.kittyColorOperation(value), + + // Effect-based handlers + .bell => self.bell(), + .device_attributes => self.reportDeviceAttributes(value), + .device_status => self.deviceStatus(value.request), + .enquiry => self.reportEnquiry(), + .kitty_keyboard_query => self.queryKittyKeyboard(), + .request_mode => self.requestMode(value.mode), + .request_mode_unknown => self.requestModeUnknown(value.mode, value.ansi), + .size_report => self.reportSize(value), + .window_title => self.windowTitle(value.title), + .xtversion => self.reportXtversion(), + + // No supported DCS commands have any terminal-modifying effects, + // but they may in the future. For now we just ignore it. + .dcs_hook, + .dcs_put, + .dcs_unhook, + => {}, + + // APC can modify terminal state (Kitty graphics) but we don't + // currently support it in the readonly stream. + .apc_start, + .apc_end, + .apc_put, + => {}, + + // Have no terminal-modifying effect + .report_pwd, + .show_desktop_notification, + .progress_report, + .clipboard_contents, + .title_push, + .title_pop, + => {}, + } + } + + inline fn writePty(self: *Handler, data: [:0]const u8) void { + const func = self.effects.write_pty orelse return; + func(self, data); + } + + fn bell(self: *Handler) void { + const func = self.effects.bell orelse return; + func(self); + } + + fn reportDeviceAttributes(self: *Handler, req: device_attributes.Req) void { + const func = self.effects.device_attributes orelse return; + const attrs = func(self); + + var stack = std.heap.stackFallback(128, self.terminal.gpa()); + const alloc = stack.get(); + + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + + attrs.encode(req, &aw.writer) catch return; + + const written = aw.toOwnedSliceSentinel(0) catch return; + defer alloc.free(written); + self.writePty(written); + } + + fn deviceStatus(self: *Handler, req: device_status.Request) void { + switch (req) { + .operating_status => self.writePty("\x1B[0n"), + + .cursor_position => { + const pos: struct { + x: usize, + y: usize, + } = if (self.terminal.modes.get(.origin)) .{ + .x = self.terminal.screens.active.cursor.x -| self.terminal.scrolling_region.left, + .y = self.terminal.screens.active.cursor.y -| self.terminal.scrolling_region.top, + } else .{ + .x = self.terminal.screens.active.cursor.x, + .y = self.terminal.screens.active.cursor.y, + }; + + var buf: [64]u8 = undefined; + const resp = std.fmt.bufPrintZ(&buf, "\x1B[{};{}R", .{ + pos.y + 1, + pos.x + 1, + }) catch return; + self.writePty(resp); + }, + + .color_scheme => { + const func = self.effects.color_scheme orelse return; + const scheme = func(self) orelse return; + self.writePty(switch (scheme) { + .dark => "\x1B[?997;1n", + .light => "\x1B[?997;2n", + }); + }, + } + } + + fn reportEnquiry(self: *Handler) void { + const func = self.effects.enquiry orelse return; + const response = func(self); + if (response.len == 0) return; + var buf: [256]u8 = undefined; + if (response.len >= buf.len) return; + @memcpy(buf[0..response.len], response); + buf[response.len] = 0; + self.writePty(buf[0..response.len :0]); + } + + fn reportXtversion(self: *Handler) void { + const version = if (self.effects.xtversion) |func| func(self) else ""; + var buf: [288]u8 = undefined; + const resp = std.fmt.bufPrintZ( + &buf, + "\x1BP>|{s}\x1B\\", + .{if (version.len > 0) version else "libghostty"}, + ) catch return; + self.writePty(resp); + } + + fn reportSize(self: *Handler, style: csi.SizeReportStyle) void { + // Almost all size reports will fit in 256 bytes so try that + // on the stack before falling back to a heap allocation. + var stack = std.heap.stackFallback( + 256, + self.terminal.gpa(), + ); + const alloc = stack.get(); + + // Allocating writing to accumulate the response. + var aw: std.Io.Writer.Allocating = .init(alloc); + defer aw.deinit(); + + // Build the response. + switch (style) { + .csi_21_t => { + const title = self.terminal.getTitle() orelse ""; + aw.writer.print("\x1b]l{s}\x1b\\", .{title}) catch return; + }, + + .csi_14_t, .csi_16_t, .csi_18_t => { + const get_size = self.effects.size orelse return; + const s = get_size(self) orelse return; + const report_style: size_report.Style = switch (style) { + .csi_14_t => .csi_14_t, + .csi_16_t => .csi_16_t, + .csi_18_t => .csi_18_t, + .csi_21_t => unreachable, + }; + size_report.encode( + &aw.writer, + report_style, + s, + ) catch |err| { + log.warn("error encoding size report err={}", .{err}); + return; + }; + }, + } + + const resp = aw.toOwnedSliceSentinel(0) catch return; + defer alloc.free(resp); + self.writePty(resp); + } + + fn windowTitle(self: *Handler, title_raw: []const u8) void { + // Prevent DoS attacks by limiting title length. + const max_title_len = 1024; + const title = if (title_raw.len > max_title_len) title: { + log.warn("title length {d} exceeds max length {d}, truncating", .{ + title_raw.len, + max_title_len, + }); + break :title title_raw[0..max_title_len]; + } else title_raw; + + self.terminal.setTitle(title) catch |err| { + log.warn("error setting title err={}", .{err}); + return; + }; + + const func = self.effects.title_changed orelse return; + func(self); + } + + fn requestMode(self: *Handler, mode: modes.Mode) void { + const report = self.terminal.modes.getReport(.fromMode(mode)); + self.sendModeReport(report); + } + + fn requestModeUnknown(self: *Handler, mode_raw: u16, ansi: bool) void { + const report = self.terminal.modes.getReport(.{ + .value = @truncate(mode_raw), + .ansi = ansi, + }); + self.sendModeReport(report); + } + + fn sendModeReport(self: *Handler, report: modes.Report) void { + var buf: [modes.Report.max_size + 1]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + report.encode(&writer) catch |err| { + log.warn("error encoding mode report err={}", .{err}); + return; + }; + const len = writer.buffered().len; + buf[len] = 0; + self.writePty(buf[0..len :0]); + } + + fn queryKittyKeyboard(self: *Handler) void { + // Max response is "\x1b[?31u\x00" (7 bytes): the flags are a u5 (max 31). + var buf: [32]u8 = undefined; + const resp = std.fmt.bufPrintZ(&buf, "\x1b[?{}u", .{ + self.terminal.screens.active.kitty_keyboard.current().int(), + }) catch return; + self.writePty(resp); + } + + inline fn horizontalTab(self: *Handler, count: u16) void { + for (0..count) |_| { + const x = self.terminal.screens.active.cursor.x; + self.terminal.horizontalTab(); + if (x == self.terminal.screens.active.cursor.x) break; + } + } + + inline fn horizontalTabBack(self: *Handler, count: u16) void { + for (0..count) |_| { + const x = self.terminal.screens.active.cursor.x; + self.terminal.horizontalTabBack(); + if (x == self.terminal.screens.active.cursor.x) break; + } + } + + fn setMode(self: *Handler, mode: modes.Mode, enabled: bool) !void { + // Set the mode on the terminal + self.terminal.modes.set(mode, enabled); + + // Some modes require additional processing + switch (mode) { + .autorepeat, + .reverse_colors, + => {}, + + .origin => self.terminal.setCursorPos(1, 1), + + .enable_left_and_right_margin => if (!enabled) { + self.terminal.scrolling_region.left = 0; + self.terminal.scrolling_region.right = self.terminal.cols - 1; + }, + + .alt_screen_legacy => try self.terminal.switchScreenMode(.@"47", enabled), + .alt_screen => try self.terminal.switchScreenMode(.@"1047", enabled), + .alt_screen_save_cursor_clear_enter => try self.terminal.switchScreenMode(.@"1049", enabled), + + .save_cursor => if (enabled) { + self.terminal.saveCursor(); + } else { + self.terminal.restoreCursor(); + }, + + .enable_mode_3 => {}, + + .@"132_column" => try self.terminal.deccolm( + self.terminal.screens.active.alloc, + if (enabled) .@"132_cols" else .@"80_cols", + ), + + .synchronized_output, + .linefeed, + .in_band_size_reports, + .focus_event, + => {}, + + .mouse_event_x10 => { + if (enabled) { + self.terminal.flags.mouse_event = .x10; + } else { + self.terminal.flags.mouse_event = .none; + } + }, + .mouse_event_normal => { + if (enabled) { + self.terminal.flags.mouse_event = .normal; + } else { + self.terminal.flags.mouse_event = .none; + } + }, + .mouse_event_button => { + if (enabled) { + self.terminal.flags.mouse_event = .button; + } else { + self.terminal.flags.mouse_event = .none; + } + }, + .mouse_event_any => { + if (enabled) { + self.terminal.flags.mouse_event = .any; + } else { + self.terminal.flags.mouse_event = .none; + } + }, + + .mouse_format_utf8 => self.terminal.flags.mouse_format = if (enabled) .utf8 else .x10, + .mouse_format_sgr => self.terminal.flags.mouse_format = if (enabled) .sgr else .x10, + .mouse_format_urxvt => self.terminal.flags.mouse_format = if (enabled) .urxvt else .x10, + .mouse_format_sgr_pixels => self.terminal.flags.mouse_format = if (enabled) .sgr_pixels else .x10, + + else => {}, + } + } + + fn colorOperation( + self: *Handler, + op: osc_color.Operation, + requests: *const osc_color.List, + ) !void { + _ = op; + if (requests.count() == 0) return; + + var it = requests.constIterator(0); + while (it.next()) |req| { + switch (req.*) { + .set => |set| { + switch (set.target) { + .palette => |i| { + self.terminal.flags.dirty.palette = true; + self.terminal.colors.palette.set(i, set.color); + }, + .dynamic => |dynamic| switch (dynamic) { + .foreground => self.terminal.colors.foreground.set(set.color), + .background => self.terminal.colors.background.set(set.color), + .cursor => self.terminal.colors.cursor.set(set.color), + .pointer_foreground, + .pointer_background, + .tektronix_foreground, + .tektronix_background, + .highlight_background, + .tektronix_cursor, + .highlight_foreground, + => {}, + }, + .special => {}, + } + }, + + .reset => |target| switch (target) { + .palette => |i| { + self.terminal.flags.dirty.palette = true; + self.terminal.colors.palette.reset(i); + }, + .dynamic => |dynamic| switch (dynamic) { + .foreground => self.terminal.colors.foreground.reset(), + .background => self.terminal.colors.background.reset(), + .cursor => self.terminal.colors.cursor.reset(), + .pointer_foreground, + .pointer_background, + .tektronix_foreground, + .tektronix_background, + .highlight_background, + .tektronix_cursor, + .highlight_foreground, + => {}, + }, + .special => {}, + }, + + .reset_palette => { + const mask = &self.terminal.colors.palette.mask; + var mask_it = mask.iterator(.{}); + while (mask_it.next()) |i| { + self.terminal.flags.dirty.palette = true; + self.terminal.colors.palette.reset(@intCast(i)); + } + mask.* = .initEmpty(); + }, + + .query, + .reset_special, + => {}, + } + } + } + + fn kittyColorOperation( + self: *Handler, + request: kitty_color.OSC, + ) !void { + for (request.list.items) |item| { + switch (item) { + .set => |v| switch (v.key) { + .palette => |palette| { + self.terminal.flags.dirty.palette = true; + self.terminal.colors.palette.set(palette, v.color); + }, + .special => |special| switch (special) { + .foreground => self.terminal.colors.foreground.set(v.color), + .background => self.terminal.colors.background.set(v.color), + .cursor => self.terminal.colors.cursor.set(v.color), + else => {}, + }, + }, + .reset => |key| switch (key) { + .palette => |palette| { + self.terminal.flags.dirty.palette = true; + self.terminal.colors.palette.reset(palette); + }, + .special => |special| switch (special) { + .foreground => self.terminal.colors.foreground.reset(), + .background => self.terminal.colors.background.reset(), + .cursor => self.terminal.colors.cursor.reset(), + else => {}, + }, + }, + .query => {}, + } + } + } +}; + +test "basic print" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + s.nextSlice("Hello"); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Hello", str); +} + +test "cursor movement" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Move cursor using escape sequences + s.nextSlice("Hello\x1B[1;1H"); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + + // Move to position 2,3 + s.nextSlice("\x1B[2;3H"); + try testing.expectEqual(@as(usize, 2), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); +} + +test "erase operations" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 20, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Print some text + s.nextSlice("Hello World"); + try testing.expectEqual(@as(usize, 11), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + + // Move cursor to position 1,6 and erase from cursor to end of line + s.nextSlice("\x1B[1;6H"); + s.nextSlice("\x1B[K"); + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Hello", str); +} + +test "tabs" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + s.nextSlice("A\tB"); + try testing.expectEqual(@as(usize, 9), t.screens.active.cursor.x); + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("A B", str); +} + +test "modes" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Test wraparound mode + try testing.expect(t.modes.get(.wraparound)); + s.nextSlice("\x1B[?7l"); // Disable wraparound + try testing.expect(!t.modes.get(.wraparound)); + s.nextSlice("\x1B[?7h"); // Enable wraparound + try testing.expect(t.modes.get(.wraparound)); +} + +test "scrolling regions" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set scrolling region from line 5 to 20 + s.nextSlice("\x1B[5;20r"); + try testing.expectEqual(@as(usize, 4), t.scrolling_region.top); + try testing.expectEqual(@as(usize, 19), t.scrolling_region.bottom); + try testing.expectEqual(@as(usize, 0), t.scrolling_region.left); + try testing.expectEqual(@as(usize, 79), t.scrolling_region.right); +} + +test "charsets" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Configure G0 as DEC special graphics + s.nextSlice("\x1B(0"); + s.nextSlice("`"); // Should print diamond character + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("◆", str); +} + +test "alt screen" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 5 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Write to primary screen + s.nextSlice("Primary"); + try testing.expectEqual(.primary, t.screens.active_key); + + // Switch to alt screen + s.nextSlice("\x1B[?1049h"); + try testing.expectEqual(.alternate, t.screens.active_key); + + // Write to alt screen + s.nextSlice("Alt"); + + // Switch back to primary + s.nextSlice("\x1B[?1049l"); + try testing.expectEqual(.primary, t.screens.active_key); + + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Primary", str); +} + +test "cursor save and restore" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Move cursor to 10,15 + s.nextSlice("\x1B[10;15H"); + try testing.expectEqual(@as(usize, 14), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 9), t.screens.active.cursor.y); + + // Save cursor + s.nextSlice("\x1B7"); + + // Move cursor elsewhere + s.nextSlice("\x1B[1;1H"); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + + // Restore cursor + s.nextSlice("\x1B8"); + try testing.expectEqual(@as(usize, 14), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 9), t.screens.active.cursor.y); +} + +test "attributes" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set bold and write text + s.nextSlice("\x1B[1mBold\x1B[0m"); + + // Verify we can write attributes - just check the string was written + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Bold", str); +} + +test "DECALN screen alignment" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 3 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Run DECALN + s.nextSlice("\x1B#8"); + + // Verify entire screen is filled with 'E' + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("EEEEEEEEEE\nEEEEEEEEEE\nEEEEEEEEEE", str); + + // Cursor should be at 1,1 + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); +} + +test "full reset" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Make some changes + s.nextSlice("Hello"); + s.nextSlice("\x1B[10;20H"); + s.nextSlice("\x1B[5;20r"); // Set scroll region + s.nextSlice("\x1B[?7l"); // Disable wraparound + + // Full reset + s.nextSlice("\x1Bc"); + + // Verify reset state + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(@as(usize, 0), t.scrolling_region.top); + try testing.expectEqual(@as(usize, 23), t.scrolling_region.bottom); + try testing.expect(t.modes.get(.wraparound)); +} + +test "ignores query actions" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // These should be ignored without error + s.nextSlice("\x1B[c"); // Device attributes + s.nextSlice("\x1B[5n"); // Device status report + s.nextSlice("\x1B[6n"); // Cursor position report + + // Terminal should still be functional + s.nextSlice("Test"); + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Test", str); +} + +test "OSC 4 set and reset palette" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Save default color + const default_color_0 = t.colors.palette.original[0]; + + // Set color 0 to red + s.nextSlice("\x1b]4;0;rgb:ff/00/00\x1b\\"); + try testing.expectEqual(@as(u8, 0xff), t.colors.palette.current[0].r); + try testing.expectEqual(@as(u8, 0x00), t.colors.palette.current[0].g); + try testing.expectEqual(@as(u8, 0x00), t.colors.palette.current[0].b); + try testing.expect(t.colors.palette.mask.isSet(0)); + + // Reset color 0 + s.nextSlice("\x1b]104;0\x1b\\"); + try testing.expectEqual(default_color_0, t.colors.palette.current[0]); + try testing.expect(!t.colors.palette.mask.isSet(0)); +} + +test "OSC 104 reset all palette colors" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set multiple colors + s.nextSlice("\x1b]4;0;rgb:ff/00/00\x1b\\"); + s.nextSlice("\x1b]4;1;rgb:00/ff/00\x1b\\"); + s.nextSlice("\x1b]4;2;rgb:00/00/ff\x1b\\"); + try testing.expect(t.colors.palette.mask.isSet(0)); + try testing.expect(t.colors.palette.mask.isSet(1)); + try testing.expect(t.colors.palette.mask.isSet(2)); + + // Reset all palette colors + s.nextSlice("\x1b]104\x1b\\"); + try testing.expectEqual(t.colors.palette.original[0], t.colors.palette.current[0]); + try testing.expectEqual(t.colors.palette.original[1], t.colors.palette.current[1]); + try testing.expectEqual(t.colors.palette.original[2], t.colors.palette.current[2]); + try testing.expect(!t.colors.palette.mask.isSet(0)); + try testing.expect(!t.colors.palette.mask.isSet(1)); + try testing.expect(!t.colors.palette.mask.isSet(2)); +} + +test "OSC 10 set and reset foreground color" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Initially unset + try testing.expect(t.colors.foreground.get() == null); + + // Set foreground to red + s.nextSlice("\x1b]10;rgb:ff/00/00\x1b\\"); + const fg = t.colors.foreground.get().?; + try testing.expectEqual(@as(u8, 0xff), fg.r); + try testing.expectEqual(@as(u8, 0x00), fg.g); + try testing.expectEqual(@as(u8, 0x00), fg.b); + + // Reset foreground + s.nextSlice("\x1b]110\x1b\\"); + try testing.expect(t.colors.foreground.get() == null); +} + +test "OSC 11 set and reset background color" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set background to green + s.nextSlice("\x1b]11;rgb:00/ff/00\x1b\\"); + const bg = t.colors.background.get().?; + try testing.expectEqual(@as(u8, 0x00), bg.r); + try testing.expectEqual(@as(u8, 0xff), bg.g); + try testing.expectEqual(@as(u8, 0x00), bg.b); + + // Reset background + s.nextSlice("\x1b]111\x1b\\"); + try testing.expect(t.colors.background.get() == null); +} + +test "OSC 12 set and reset cursor color" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set cursor to blue + s.nextSlice("\x1b]12;rgb:00/00/ff\x1b\\"); + const cursor = t.colors.cursor.get().?; + try testing.expectEqual(@as(u8, 0x00), cursor.r); + try testing.expectEqual(@as(u8, 0x00), cursor.g); + try testing.expectEqual(@as(u8, 0xff), cursor.b); + + // Reset cursor + s.nextSlice("\x1b]112\x1b\\"); + // After reset, cursor might be null (using default) +} + +test "kitty color protocol set palette" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set palette color 5 to magenta using kitty protocol + s.nextSlice("\x1b]21;5=rgb:ff/00/ff\x1b\\"); + try testing.expectEqual(@as(u8, 0xff), t.colors.palette.current[5].r); + try testing.expectEqual(@as(u8, 0x00), t.colors.palette.current[5].g); + try testing.expectEqual(@as(u8, 0xff), t.colors.palette.current[5].b); + try testing.expect(t.colors.palette.mask.isSet(5)); + try testing.expect(t.flags.dirty.palette); +} + +test "kitty color protocol reset palette" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set and then reset palette color + const original = t.colors.palette.original[7]; + s.nextSlice("\x1b]21;7=rgb:aa/bb/cc\x1b\\"); + try testing.expect(t.colors.palette.mask.isSet(7)); + + s.nextSlice("\x1b]21;7=\x1b\\"); + try testing.expectEqual(original, t.colors.palette.current[7]); + try testing.expect(!t.colors.palette.mask.isSet(7)); +} + +test "kitty color protocol set foreground" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set foreground using kitty protocol + s.nextSlice("\x1b]21;foreground=rgb:12/34/56\x1b\\"); + const fg = t.colors.foreground.get().?; + try testing.expectEqual(@as(u8, 0x12), fg.r); + try testing.expectEqual(@as(u8, 0x34), fg.g); + try testing.expectEqual(@as(u8, 0x56), fg.b); +} + +test "kitty color protocol set background" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set background using kitty protocol + s.nextSlice("\x1b]21;background=rgb:78/9a/bc\x1b\\"); + const bg = t.colors.background.get().?; + try testing.expectEqual(@as(u8, 0x78), bg.r); + try testing.expectEqual(@as(u8, 0x9a), bg.g); + try testing.expectEqual(@as(u8, 0xbc), bg.b); +} + +test "kitty color protocol set cursor" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set cursor using kitty protocol + s.nextSlice("\x1b]21;cursor=rgb:de/f0/12\x1b\\"); + const cursor = t.colors.cursor.get().?; + try testing.expectEqual(@as(u8, 0xde), cursor.r); + try testing.expectEqual(@as(u8, 0xf0), cursor.g); + try testing.expectEqual(@as(u8, 0x12), cursor.b); +} + +test "kitty color protocol reset foreground" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set and reset foreground + s.nextSlice("\x1b]21;foreground=rgb:11/22/33\x1b\\"); + try testing.expect(t.colors.foreground.get() != null); + + s.nextSlice("\x1b]21;foreground=\x1b\\"); + // After reset, should be unset + try testing.expect(t.colors.foreground.get() == null); +} + +test "palette dirty flag set on color change" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Clear dirty flag + t.flags.dirty.palette = false; + + // Setting palette color should set dirty flag + s.nextSlice("\x1b]4;0;rgb:ff/00/00\x1b\\"); + try testing.expect(t.flags.dirty.palette); + + // Clear and test reset + t.flags.dirty.palette = false; + s.nextSlice("\x1b]104;0\x1b\\"); + try testing.expect(t.flags.dirty.palette); + + // Clear and test kitty protocol + t.flags.dirty.palette = false; + s.nextSlice("\x1b]21;1=rgb:00/ff/00\x1b\\"); + try testing.expect(t.flags.dirty.palette); +} + +test "semantic prompt fresh line" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + s.nextSlice("Hello"); + s.nextSlice("\x1b]133;L\x07"); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); +} + +test "semantic prompt fresh line new prompt" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Write some text and then send OSC 133;A (fresh_line_new_prompt) + s.nextSlice("Hello"); + s.nextSlice("\x1b]133;A\x07"); + + // Should do a fresh line (carriage return + index) + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + + // Should set cursor semantic_content to prompt + try testing.expectEqual(.prompt, t.screens.active.cursor.semantic_content); + + // Test with redraw option + s.nextSlice("prompt$ "); + s.nextSlice("\x1b]133;A;redraw=1\x07"); + try testing.expect(t.flags.shell_redraws_prompt == .true); +} + +test "semantic prompt end of input, then start output" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Write some text and then send OSC 133;A (fresh_line_new_prompt) + s.nextSlice("Hello"); + s.nextSlice("\x1b]133;A\x07"); + s.nextSlice("prompt$ "); + s.nextSlice("\x1b]133;B\x07"); + try testing.expectEqual(.input, t.screens.active.cursor.semantic_content); + s.nextSlice("\x1b]133;C\x07"); + try testing.expectEqual(.output, t.screens.active.cursor.semantic_content); +} + +test "semantic prompt prompt_start" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Write some text + s.nextSlice("Hello"); + + // OSC 133;P marks the start of a prompt (without fresh line behavior) + s.nextSlice("\x1b]133;P\x07"); + try testing.expectEqual(.prompt, t.screens.active.cursor.semantic_content); + try testing.expectEqual(@as(usize, 5), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); +} + +test "semantic prompt new_command" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Write some text + s.nextSlice("Hello"); + s.nextSlice("\x1b]133;N\x07"); + + // Should behave like fresh_line_new_prompt - cursor moves to column 0 + // on next line since we had content + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 1), t.screens.active.cursor.y); + try testing.expectEqual(.prompt, t.screens.active.cursor.semantic_content); +} + +test "semantic prompt new_command at column zero" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // OSC 133;N when already at column 0 should stay on same line + s.nextSlice("\x1b]133;N\x07"); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.x); + try testing.expectEqual(@as(usize, 0), t.screens.active.cursor.y); + try testing.expectEqual(.prompt, t.screens.active.cursor.semantic_content); +} + +test "semantic prompt end_prompt_start_input_terminate_eol clears on linefeed" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 10, .rows = 10 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Set input terminated by EOL + s.nextSlice("\x1b]133;I\x07"); + try testing.expectEqual(.input, t.screens.active.cursor.semantic_content); + + // Linefeed should reset semantic content to output + s.nextSlice("\n"); + try testing.expectEqual(.output, t.screens.active.cursor.semantic_content); +} + +test "bell effect callback" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + // Test bell with null callback (default readonly effects) doesn't crash + { + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + s.nextSlice("\x07"); + + // Terminal should still be functional after bell + s.nextSlice("AfterBell"); + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("AfterBell", str); + } + + t.fullReset(); + + // Test bell with a callback + { + const S = struct { + var bell_count: usize = 0; + fn bell(_: *Handler) void { + bell_count += 1; + } + }; + S.bell_count = 0; + + var handler: Handler = .init(&t); + handler.effects.bell = &S.bell; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x07"); + try testing.expectEqual(@as(usize, 1), S.bell_count); + + s.nextSlice("\x07\x07"); + try testing.expectEqual(@as(usize, 3), S.bell_count); + } +} + +test "request mode DECRQM with write_pty callback" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + // Without callback, DECRQM should not crash + { + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // DECRQM for mode 7 (wraparound) — should be silently ignored + s.nextSlice("\x1B[?7$p"); + } + + t.fullReset(); + + // With callback, DECRQM should produce a response + { + const S = struct { + var last_response: ?[:0]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (last_response) |old| testing.allocator.free(old); + last_response = testing.allocator.dupeZ(u8, data) catch @panic("OOM"); + } + }; + S.last_response = null; + defer if (S.last_response) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Wraparound mode (7) is set by default + s.nextSlice("\x1B[?7$p"); + try testing.expectEqualStrings("\x1B[?7;1$y", S.last_response.?); + + // Disable wraparound and query again + s.nextSlice("\x1B[?7l"); + s.nextSlice("\x1B[?7$p"); + try testing.expectEqualStrings("\x1B[?7;2$y", S.last_response.?); + + // Query an unknown mode + s.nextSlice("\x1B[?9999$p"); + try testing.expectEqualStrings("\x1B[?9999;0$y", S.last_response.?); + } +} + +test "stream: CSI W with intermediate but no params" { + // Regression test from AFL++ crash. CSI ? W without + // parameters caused an out-of-bounds access on input.params[0]. + var t: Terminal = try .init(testing.allocator, .{ + .cols = 80, + .rows = 24, + .max_scrollback = 100, + }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + s.nextSlice("\x1b[?W"); +} + +test "window_title effect is called" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var title_changed_count: usize = 0; + fn titleChanged(_: *Handler) void { + title_changed_count += 1; + } + }; + S.title_changed_count = 0; + + var handler: Handler = .init(&t); + handler.effects.title_changed = &S.titleChanged; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Set window title via OSC 2 + s.nextSlice("\x1b]2;Hello World\x1b\\"); + try testing.expectEqualStrings("Hello World", t.getTitle().?); + try testing.expectEqual(@as(usize, 1), S.title_changed_count); +} + +test "window_title effect not called without callback" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // Should not crash when no callback is set + s.nextSlice("\x1b]2;Hello World\x1b\\"); + + // Title should still be set on terminal state + try testing.expectEqualStrings("Hello World", t.getTitle().?); + + // Terminal should still be functional + s.nextSlice("Test"); + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Test", str); +} + +test "window_title effect with empty title" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var title_changed_count: usize = 0; + fn titleChanged(_: *Handler) void { + title_changed_count += 1; + } + }; + S.title_changed_count = 0; + + var handler: Handler = .init(&t); + handler.effects.title_changed = &S.titleChanged; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Set empty window title + s.nextSlice("\x1b]2;\x1b\\"); + try testing.expect(t.getTitle() == null); + try testing.expectEqual(@as(usize, 1), S.title_changed_count); +} + +test "kitty_keyboard_query" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[:0]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = data; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Default kitty keyboard flags should be 0 + s.nextSlice("\x1b[?u"); + try testing.expectEqualStrings("\x1b[?0u", S.written.?); + + // Push kitty keyboard mode with flags and query again + S.written = null; + s.nextSlice("\x1b[>1u"); // push with disambiguate flag + s.nextSlice("\x1b[?u"); + try testing.expectEqualStrings("\x1b[?1u", S.written.?); +} + +test "xtversion default" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[:0]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = data; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Without xtversion effect set, should report "libghostty" + s.nextSlice("\x1b[>0q"); + try testing.expectEqualStrings("\x1bP>|libghostty\x1b\\", S.written.?); +} + +test "xtversion with effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[:0]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = data; + } + fn xtversion(_: *Handler) []const u8 { + return "ghostty 1.2.3"; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.xtversion = &S.xtversion; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x1b[>0q"); + try testing.expectEqualStrings("\x1bP>|ghostty 1.2.3\x1b\\", S.written.?); +} + +test "xtversion with empty string effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[:0]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = data; + } + fn xtversion(_: *Handler) []const u8 { + return ""; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.xtversion = &S.xtversion; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Empty string from effect should fall back to "libghostty" + s.nextSlice("\x1b[>0q"); + try testing.expectEqualStrings("\x1bP>|libghostty\x1b\\", S.written.?); +} + +test "size report csi_14_t with effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn getSize(_: *Handler) ?size_report.Size { + return .{ .rows = 24, .columns = 80, .cell_width = 9, .cell_height = 18 }; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.size = &S.getSize; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // CSI 14 t - report text area size in pixels + s.nextSlice("\x1b[14t"); + defer testing.allocator.free(S.written.?); + try testing.expectEqualStrings("\x1b[4;432;720t", S.written.?); +} + +test "size report csi_16_t with effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn getSize(_: *Handler) ?size_report.Size { + return .{ .rows = 24, .columns = 80, .cell_width = 9, .cell_height = 18 }; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.size = &S.getSize; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // CSI 16 t - report cell size in pixels + s.nextSlice("\x1b[16t"); + defer testing.allocator.free(S.written.?); + try testing.expectEqualStrings("\x1b[6;18;9t", S.written.?); +} + +test "size report csi_18_t with effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn getSize(_: *Handler) ?size_report.Size { + return .{ .rows = 24, .columns = 80, .cell_width = 9, .cell_height = 18 }; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.size = &S.getSize; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // CSI 18 t - report text area size in characters + s.nextSlice("\x1b[18t"); + defer testing.allocator.free(S.written.?); + try testing.expectEqualStrings("\x1b[8;24;80t", S.written.?); +} + +test "size report no effect callback" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Without size effect, size reports should be silently ignored + s.nextSlice("\x1b[14t"); + try testing.expect(S.written == null); +} + +test "size report csi_21_t title" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Set a title first + s.nextSlice("\x1b]2;My Title\x1b\\"); + + // CSI 21 t - report title (no size effect needed) + s.nextSlice("\x1b[21t"); + defer testing.allocator.free(S.written.?); + try testing.expectEqualStrings("\x1b]lMy Title\x1b\\", S.written.?); +} + +test "enquiry no effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // ENQ without enquiry effect should not write anything + s.nextSlice("\x05"); + try testing.expect(S.written == null); +} + +test "enquiry with effect" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn enquiry(_: *Handler) []const u8 { + return "ghostty"; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.enquiry = &S.enquiry; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x05"); + defer testing.allocator.free(S.written.?); + try testing.expectEqualStrings("ghostty", S.written.?); +} + +test "enquiry with empty response" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn enquiry(_: *Handler) []const u8 { + return ""; + } + }; + S.written = null; + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.enquiry = &S.enquiry; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Empty enquiry response should not write anything + s.nextSlice("\x05"); + try testing.expect(S.written == null); +} + +test "device status: operating status" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // CSI 5 n — operating status report + s.nextSlice("\x1B[5n"); + try testing.expectEqualStrings("\x1B[0n", S.written.?); +} + +test "device status: cursor position" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Default position is 0,0 — reported as 1,1 + s.nextSlice("\x1B[6n"); + try testing.expectEqualStrings("\x1B[1;1R", S.written.?); + + // Move cursor to row 5, col 10 + s.nextSlice("\x1B[5;10H"); + s.nextSlice("\x1B[6n"); + try testing.expectEqualStrings("\x1B[5;10R", S.written.?); +} + +test "device status: cursor position with origin mode" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Set scroll region rows 5-20 + s.nextSlice("\x1B[5;20r"); + // Enable origin mode + s.nextSlice("\x1B[?6h"); + // Move to row 3, col 5 within the region + s.nextSlice("\x1B[3;5H"); + // Query cursor position + s.nextSlice("\x1B[6n"); + // Should report position relative to the scroll region + try testing.expectEqualStrings("\x1B[3;5R", S.written.?); +} + +test "device status: color scheme dark" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn colorScheme(_: *Handler) ?device_status.ColorScheme { + return .dark; + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.color_scheme = &S.colorScheme; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // CSI ? 996 n — color scheme query + s.nextSlice("\x1B[?996n"); + try testing.expectEqualStrings("\x1B[?997;1n", S.written.?); +} + +test "device status: color scheme light" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn colorScheme(_: *Handler) ?device_status.ColorScheme { + return .light; + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.color_scheme = &S.colorScheme; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // CSI ? 996 n — color scheme query + s.nextSlice("\x1B[?996n"); + try testing.expectEqualStrings("\x1B[?997;2n", S.written.?); +} + +test "device status: color scheme without callback" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + // Without color_scheme effect, query should be silently ignored + s.nextSlice("\x1B[?996n"); + try testing.expect(S.written == null); +} + +test "device status: readonly ignores all" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // All device status queries should be silently ignored without effects + s.nextSlice("\x1B[5n"); + s.nextSlice("\x1B[6n"); + s.nextSlice("\x1B[?996n"); + + // Terminal should still be functional + s.nextSlice("Test"); + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Test", str); +} + +test "device attributes: primary DA" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn da(_: *Handler) device_attributes.Attributes { + return .{}; + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.device_attributes = &S.da; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x1B[c"); + try testing.expectEqualStrings("\x1b[?62;22c", S.written.?); +} + +test "device attributes: secondary DA" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn da(_: *Handler) device_attributes.Attributes { + return .{}; + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.device_attributes = &S.da; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x1B[>c"); + try testing.expectEqualStrings("\x1b[>1;0;0c", S.written.?); +} + +test "device attributes: tertiary DA" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn da(_: *Handler) device_attributes.Attributes { + return .{}; + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.device_attributes = &S.da; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x1B[=c"); + try testing.expectEqualStrings("\x1bP!|00000000\x1b\\", S.written.?); +} + +test "device attributes: readonly ignores" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + var s: Stream = .initAlloc(testing.allocator, .init(&t)); + defer s.deinit(); + + // All DA queries should be silently ignored without effects + s.nextSlice("\x1B[c"); + s.nextSlice("\x1B[>c"); + s.nextSlice("\x1B[=c"); + + // Terminal should still be functional + s.nextSlice("Test"); + const str = try t.plainString(testing.allocator); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Test", str); +} + +test "device attributes: custom response" { + var t: Terminal = try .init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer t.deinit(testing.allocator); + + const S = struct { + var written: ?[]const u8 = null; + fn writePty(_: *Handler, data: [:0]const u8) void { + if (written) |old| testing.allocator.free(old); + written = testing.allocator.dupe(u8, data) catch @panic("OOM"); + } + fn da(_: *Handler) device_attributes.Attributes { + return .{ + .primary = .{ + .conformance_level = .vt420, + .features = &.{ .ansi_color, .clipboard }, + }, + .secondary = .{ + .device_type = .vt420, + .firmware_version = 100, + }, + }; + } + }; + S.written = null; + defer if (S.written) |old| testing.allocator.free(old); + + var handler: Handler = .init(&t); + handler.effects.write_pty = &S.writePty; + handler.effects.device_attributes = &S.da; + + var s: Stream = .initAlloc(testing.allocator, handler); + defer s.deinit(); + + s.nextSlice("\x1B[c"); + try testing.expectEqualStrings("\x1b[?64;22;52c", S.written.?); + + s.nextSlice("\x1B[>c"); + try testing.expectEqualStrings("\x1b[>41;100;0c", S.written.?); +} diff --git a/vendor/libghostty-vt/src/terminal/style.zig b/vendor/libghostty-vt/src/terminal/style.zig new file mode 100644 index 00000000..ae9488af --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/style.zig @@ -0,0 +1,1078 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const color = @import("color.zig"); +const sgr = @import("sgr.zig"); +const page = @import("page.zig"); +const size = @import("size.zig"); +const Offset = size.Offset; +const OffsetBuf = size.OffsetBuf; +const RefCountedSet = @import("ref_counted_set.zig").RefCountedSet; + +/// The unique identifier for a style. This is at most the number of cells +/// that can fit into a terminal page. +pub const Id = size.StyleCountInt; + +/// The Id to use for default styling. +pub const default_id: Id = 0; + +/// The style attributes for a cell. +pub const Style = struct { + /// Various colors, all self-explanatory. + fg_color: Color = .none, + bg_color: Color = .none, + underline_color: Color = .none, + + /// On/off attributes that don't require much bit width so we use + /// a packed struct to make this take up significantly less space. + flags: Flags = .{}, + + const Flags = packed struct(u16) { + bold: bool = false, + italic: bool = false, + faint: bool = false, + blink: bool = false, + inverse: bool = false, + invisible: bool = false, + strikethrough: bool = false, + overline: bool = false, + underline: sgr.Attribute.Underline = .none, + _padding: u5 = 0, + }; + + /// The color for an SGR attribute. A color can come from multiple + /// sources so we use this to track the source plus color value so that + /// we can properly react to things like palette changes. + pub const Color = union(Tag) { + none: void, + palette: u8, + rgb: color.RGB, + + const Tag = enum(u8) { + none, + palette, + rgb, + }; + + /// True if the color is equal to another color. + pub fn eql(self: Color, other: Color) bool { + return @as(Tag, self) == @as(Tag, other) and switch (self) { + .none => true, + .palette => self.palette == other.palette, + .rgb => self.rgb == other.rgb, + }; + } + + /// Formatting to make debug logs easier to read + /// by only including non-default attributes. + pub fn format( + self: Color, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: *std.Io.Writer, + ) !void { + _ = fmt; + _ = options; + switch (self) { + .none => { + _ = try writer.write("Color.none"); + }, + .palette => |p| { + _ = try writer.print("Color.palette{{ {} }}", .{p}); + }, + .rgb => |rgb| { + _ = try writer.print("Color.rgb{{ {}, {}, {} }}", .{ rgb.r, rgb.g, rgb.b }); + }, + } + } + }; + + /// True if the style is the default style. + pub inline fn default(self: Style) bool { + return self.eql(.{}); + } + + /// True if the style is equal to another style. + pub fn eql(self: Style, other: Style) bool { + return self.flags == other.flags and + self.fg_color.eql(other.fg_color) and + self.bg_color.eql(other.bg_color) and + self.underline_color.eql(other.underline_color); + } + + /// Returns the bg color for a cell with this style given the cell + /// that has this style and the palette to use. + /// + /// Note that generally if a cell is a color-only cell, it SHOULD + /// only have the default style, but this is meant to work with the + /// default style as well. + pub fn bg( + self: Style, + cell: *const page.Cell, + palette: *const color.Palette, + ) ?color.RGB { + return switch (cell.content_tag) { + .bg_color_palette => palette[cell.content.color_palette], + .bg_color_rgb => rgb: { + const rgb = cell.content.color_rgb; + break :rgb .{ .r = rgb.r, .g = rgb.g, .b = rgb.b }; + }, + + else => switch (self.bg_color) { + .none => null, + .palette => |idx| palette[idx], + .rgb => |rgb| rgb, + }, + }; + } + + /// The color to use for bold text. This avoids a dependency on the + /// config module by using terminal-native color types. + pub const BoldColor = union(enum) { + color: color.RGB, + bright, + }; + + pub const Fg = struct { + /// The default color to use if the style doesn't specify a + /// foreground color and no configuration options override + /// it. + default: color.RGB, + + /// The current color palette. Required to map palette indices to + /// real color values. + palette: *const color.Palette, + + /// If specified, the color to use for bold text. + bold: ?BoldColor = null, + }; + + /// Returns the fg color for a cell with this style given the palette + /// and various configuration options. + pub fn fg( + self: Style, + opts: Fg, + ) color.RGB { + // Note we don't pull the bold check to the top-level here because + // we don't want to duplicate the conditional multiple times since + // certain colors require more checks (e.g. `bold_is_bright`). + + return switch (self.fg_color) { + .none => default: { + if (self.flags.bold) { + if (opts.bold) |bold| switch (bold) { + .bright => {}, + .color => |v| break :default v, + }; + } + + break :default opts.default; + }, + + .palette => |idx| palette: { + if (self.flags.bold) { + if (opts.bold) |_| { + const bright_offset = @intFromEnum(color.Name.bright_black); + if (idx < bright_offset) { + break :palette opts.palette[idx + bright_offset]; + } + } + } + + break :palette opts.palette[idx]; + }, + + .rgb => |rgb| rgb: { + if (self.flags.bold and rgb.eql(opts.default)) { + if (opts.bold) |bold| switch (bold) { + .color => |v| break :rgb v, + .bright => {}, + }; + } + + break :rgb rgb; + }, + }; + } + + /// Returns the underline color for this style. + pub fn underlineColor( + self: Style, + palette: *const color.Palette, + ) ?color.RGB { + return switch (self.underline_color) { + .none => null, + .palette => |idx| palette[idx], + .rgb => |rgb| rgb, + }; + } + + /// Returns a bg-color only cell from this style, if it exists. + pub fn bgCell(self: Style) ?page.Cell { + return switch (self.bg_color) { + .none => null, + .palette => |idx| .{ + .content_tag = .bg_color_palette, + .content = .{ .color_palette = idx }, + }, + .rgb => |rgb| .{ + .content_tag = .bg_color_rgb, + .content = .{ .color_rgb = .{ + .r = rgb.r, + .g = rgb.g, + .b = rgb.b, + } }, + }, + }; + } + + /// Formatting to make debug logs easier to read + /// by only including non-default attributes. + pub fn format( + self: Style, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: *std.Io.Writer, + ) !void { + _ = fmt; + _ = options; + + const dflt: Style = .{}; + + _ = try writer.write("Style{ "); + + var started = false; + + inline for (std.meta.fields(Style)) |f| { + if (std.mem.eql(u8, f.name, "flags")) { + if (started) { + _ = try writer.write(", "); + } + + _ = try writer.write("flags={ "); + + started = false; + + inline for (std.meta.fields(@TypeOf(self.flags))) |ff| { + const v = @as(ff.type, @field(self.flags, ff.name)); + const d = @as(ff.type, @field(dflt.flags, ff.name)); + if (ff.type == bool) { + if (v) { + if (started) { + _ = try writer.write(", "); + } + _ = try writer.print("{s}", .{ff.name}); + started = true; + } + } else if (!std.meta.eql(v, d)) { + if (started) { + _ = try writer.write(", "); + } + _ = try writer.print( + "{s}={any}", + .{ ff.name, v }, + ); + started = true; + } + } + _ = try writer.write(" }"); + + started = true; + comptime continue; + } + const value = @as(f.type, @field(self, f.name)); + const d_val = @as(f.type, @field(dflt, f.name)); + if (!std.meta.eql(value, d_val)) { + if (started) { + _ = try writer.write(", "); + } + _ = try writer.print( + "{s}={any}", + .{ f.name, value }, + ); + started = true; + } + } + + _ = try writer.write(" }"); + } + + /// Returns a formatter that renders this style as VT sequences, + /// to be used with `{f}`. This always resets the style first `\x1b[0m` + /// since a style is meant to be fully self-contained. + /// + /// For individual styles, this always emits multiple SGR sequences + /// (i.e. an individual `\x1b[m` for each attribute) rather than + /// trying to combine them into a single sequence. We do this because + /// terminals have varying levels of support for combined sequences + /// especially with mixed separators (e.g. `:` vs `;`). + pub fn formatterVt(self: *const Style) VTFormatter { + return .{ .style = self }; + } + + /// Returns a formatter that renders this style as inline CSS properties, + /// to be used with `{f}`. The output is a valid CSS style string suitable + /// for use in a `style` attribute (e.g., "color: rgb(255, 0, 0); font-weight: bold;"). + /// + /// Palette colors are emitted as CSS variables like `var(--vt-palette-N)`. + pub fn formatterHtml(self: *const Style) HtmlFormatter { + return .{ .style = self }; + } + + const VTFormatter = struct { + style: *const Style, + + /// If set, palette colors will be emitted as RGB values instead of + /// palette indices. This is useful when you want to capture the + /// exact colors at formatting time rather than relying on the + /// terminal's palette. + palette: ?*const color.Palette = null, + + pub fn format( + self: VTFormatter, + writer: *std.Io.Writer, + ) !void { + // Always reset the style. Styles are fully self-contained. + // Even if this style is empty, then that means we want to go + // back to the default. + try writer.writeAll("\x1b[0m"); + + // Our flags + if (self.style.flags.bold) try writer.writeAll("\x1b[1m"); + if (self.style.flags.faint) try writer.writeAll("\x1b[2m"); + if (self.style.flags.italic) try writer.writeAll("\x1b[3m"); + if (self.style.flags.blink) try writer.writeAll("\x1b[5m"); + if (self.style.flags.inverse) try writer.writeAll("\x1b[7m"); + if (self.style.flags.invisible) try writer.writeAll("\x1b[8m"); + if (self.style.flags.strikethrough) try writer.writeAll("\x1b[9m"); + if (self.style.flags.overline) try writer.writeAll("\x1b[53m"); + switch (self.style.flags.underline) { + .none => {}, + .single => try writer.writeAll("\x1b[4m"), + .double => try writer.writeAll("\x1b[4:2m"), + .curly => try writer.writeAll("\x1b[4:3m"), + .dotted => try writer.writeAll("\x1b[4:4m"), + .dashed => try writer.writeAll("\x1b[4:5m"), + } + + // Various RGB colors. + try self.formatColor(writer, 38, self.style.fg_color); + try self.formatColor(writer, 48, self.style.bg_color); + try self.formatColor(writer, 58, self.style.underline_color); + } + + fn formatColor( + self: VTFormatter, + writer: *std.Io.Writer, + prefix: u8, + value: Color, + ) !void { + switch (value) { + .none => {}, + .palette => |idx| { + if (self.palette) |p| { + const rgb = p[idx]; + try writer.print( + "\x1b[{d};2;{d};{d};{d}m", + .{ prefix, rgb.r, rgb.g, rgb.b }, + ); + } else { + try writer.print( + "\x1b[{d};5;{d}m", + .{ prefix, idx }, + ); + } + }, + .rgb => |rgb| try writer.print( + "\x1b[{d};2;{d};{d};{d}m", + .{ prefix, rgb.r, rgb.g, rgb.b }, + ), + } + } + }; + + const HtmlFormatter = struct { + style: *const Style, + + /// If set, palette colors will be emitted as RGB values instead of + /// CSS variables. This is useful when you want to capture the exact + /// colors at formatting time rather than relying on CSS variables. + palette: ?*const color.Palette = null, + + pub fn format( + self: HtmlFormatter, + writer: *std.Io.Writer, + ) !void { + // Colors + try self.formatColor(writer, "color", self.style.fg_color); + try self.formatColor(writer, "background-color", self.style.bg_color); + try self.formatColor(writer, "text-decoration-color", self.style.underline_color); + + // Text decoration line + const has_line = self.style.flags.underline != .none or + self.style.flags.strikethrough or + self.style.flags.overline or + self.style.flags.blink; + if (has_line) { + try writer.writeAll("text-decoration-line:"); + if (self.style.flags.underline != .none) try writer.writeAll(" underline"); + if (self.style.flags.strikethrough) try writer.writeAll(" line-through"); + if (self.style.flags.overline) try writer.writeAll(" overline"); + if (self.style.flags.blink) try writer.writeAll(" blink"); + try writer.writeAll(";"); + } + + // Text decoration style + switch (self.style.flags.underline) { + .none => {}, + .single => try writer.writeAll("text-decoration-style: solid;"), + .double => try writer.writeAll("text-decoration-style: double;"), + .curly => try writer.writeAll("text-decoration-style: wavy;"), + .dotted => try writer.writeAll("text-decoration-style: dotted;"), + .dashed => try writer.writeAll("text-decoration-style: dashed;"), + } + + if (self.style.flags.bold) try writer.writeAll("font-weight: bold;"); + if (self.style.flags.italic) try writer.writeAll("font-style: italic;"); + if (self.style.flags.faint) try writer.writeAll("opacity: 0.5;"); + if (self.style.flags.invisible) try writer.writeAll("visibility: hidden;"); + if (self.style.flags.inverse) try writer.writeAll("filter: invert(100%);"); + } + + fn formatColor( + self: HtmlFormatter, + writer: *std.Io.Writer, + property: []const u8, + c: Color, + ) !void { + switch (c) { + .none => {}, + .palette => |idx| { + if (self.palette) |p| { + const rgb = p[idx]; + try writer.print("{s}: rgb({d}, {d}, {d});", .{ property, rgb.r, rgb.g, rgb.b }); + } else { + try writer.print("{s}: var(--vt-palette-{d});", .{ property, idx }); + } + }, + .rgb => |rgb| try writer.print("{s}: rgb({d}, {d}, {d});", .{ property, rgb.r, rgb.g, rgb.b }), + } + } + }; + + /// `PackedStyle` represents the same data as `Style` but without padding, + /// which is necessary for hashing via re-interpretation of the underlying + /// bytes. + /// + /// `Style` is still preferred for everything else as it has type-safety + /// when using the `Color` tagged union. + /// + /// Empirical testing shows that storing all of the tags first and then the + /// data provides a better layout for serializing into and is faster on + /// benchmarks. + const PackedStyle = packed struct(u128) { + tags: packed struct { + fg: Color.Tag, + bg: Color.Tag, + underline: Color.Tag, + }, + data: packed struct { + fg: Data, + bg: Data, + underline: Data, + }, + flags: Flags, + _padding: u16 = 0, + + /// After https://github.com/ziglang/zig/issues/19754 is implemented, + /// it will be an compiler-error to have packed union fields of + /// differing size. + /// + /// For now we just need to be careful not to accidentally introduce + /// padding. + const Data = packed union { + none: u24, + palette: packed struct(u24) { + idx: u8, + _padding: u16 = 0, + }, + rgb: color.RGB, + + fn fromColor(c: Color) Data { + return switch (c) { + inline else => |v, t| @unionInit( + Data, + @tagName(t), + switch (t) { + .none => 0, + .palette => .{ .idx = v }, + .rgb => v, + }, + ), + }; + } + }; + + inline fn fromStyle(style: Style) PackedStyle { + return .{ + .tags = .{ + .fg = @as(Color.Tag, style.fg_color), + .bg = @as(Color.Tag, style.bg_color), + .underline = @as(Color.Tag, style.underline_color), + }, + .data = .{ + .fg = .fromColor(style.fg_color), + .bg = .fromColor(style.bg_color), + .underline = .fromColor(style.underline_color), + }, + .flags = style.flags, + }; + } + }; + + pub fn hash(self: *const Style) u64 { + // We pack the style in to 128 bits, fold it to 64 bits, + // then use std.hash.int to make it sufficiently uniform. + const packed_style: PackedStyle = .fromStyle(self.*); + const wide: [2]u64 = @bitCast(packed_style); + return @call(.always_inline, std.hash.int, .{wide[0] ^ wide[1]}); + } + + comptime { + assert(@sizeOf(PackedStyle) == 16); + assert(std.meta.hasUniqueRepresentation(PackedStyle)); + for (@typeInfo(PackedStyle.Data).@"union".fields) |field| { + assert(@bitSizeOf(field.type) == @bitSizeOf(PackedStyle.Data)); + } + } +}; + +pub const Set = RefCountedSet( + Style, + Id, + size.CellCountInt, + struct { + pub fn hash(self: *const @This(), style: Style) u64 { + _ = self; + return style.hash(); + } + + pub fn eql(self: *const @This(), a: Style, b: Style) bool { + _ = self; + return a.eql(b); + } + }, +); + +test "Style VT formatting empty" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{}; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m", builder.writer.buffered()); +} + +test "Style VT formatting bold" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .bold = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[1m", builder.writer.buffered()); +} + +test "Style VT formatting faint" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .faint = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[2m", builder.writer.buffered()); +} + +test "Style VT formatting italic" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .italic = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[3m", builder.writer.buffered()); +} + +test "Style VT formatting blink" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .blink = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[5m", builder.writer.buffered()); +} + +test "Style VT formatting inverse" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .inverse = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[7m", builder.writer.buffered()); +} + +test "Style VT formatting invisible" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .invisible = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[8m", builder.writer.buffered()); +} + +test "Style VT formatting strikethrough" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .strikethrough = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[9m", builder.writer.buffered()); +} + +test "Style VT formatting overline" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .overline = true } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[53m", builder.writer.buffered()); +} + +test "Style VT formatting underline single" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .single } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[4m", builder.writer.buffered()); +} + +test "Style VT formatting underline double" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .double } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[4:2m", builder.writer.buffered()); +} + +test "Style VT formatting underline curly" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .curly } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[4:3m", builder.writer.buffered()); +} + +test "Style VT formatting underline dotted" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .dotted } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[4:4m", builder.writer.buffered()); +} + +test "Style VT formatting underline dashed" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .dashed } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[4:5m", builder.writer.buffered()); +} + +test "Style VT formatting fg palette" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .fg_color = .{ .palette = 42 } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[38;5;42m", builder.writer.buffered()); +} + +test "Style VT formatting fg rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .fg_color = .{ .rgb = .{ .r = 255, .g = 128, .b = 64 } } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[38;2;255;128;64m", builder.writer.buffered()); +} + +test "Style VT formatting bg palette" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .bg_color = .{ .palette = 7 } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[48;5;7m", builder.writer.buffered()); +} + +test "Style VT formatting bg rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .bg_color = .{ .rgb = .{ .r = 32, .g = 64, .b = 96 } } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[48;2;32;64;96m", builder.writer.buffered()); +} + +test "Style VT formatting underline_color palette" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .underline_color = .{ .palette = 15 } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[58;5;15m", builder.writer.buffered()); +} + +test "Style VT formatting underline_color rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .underline_color = .{ .rgb = .{ .r = 200, .g = 100, .b = 50 } } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[58;2;200;100;50m", builder.writer.buffered()); +} + +test "Style VT formatting multiple flags" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .bold = true, .italic = true, .underline = .single } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings("\x1b[0m\x1b[1m\x1b[3m\x1b[4m", builder.writer.buffered()); +} + +test "Style VT formatting all flags" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ + .bold = true, + .faint = true, + .italic = true, + .blink = true, + .inverse = true, + .invisible = true, + .strikethrough = true, + .overline = true, + .underline = .curly, + } }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings( + "\x1b[0m\x1b[1m\x1b[2m\x1b[3m\x1b[5m\x1b[7m\x1b[8m\x1b[9m\x1b[53m\x1b[4:3m", + builder.writer.buffered(), + ); +} + +test "Style VT formatting combined colors and flags" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ + .fg_color = .{ .rgb = .{ .r = 255, .g = 0, .b = 0 } }, + .bg_color = .{ .palette = 8 }, + .underline_color = .{ .rgb = .{ .r = 0, .g = 255, .b = 0 } }, + .flags = .{ .bold = true, .italic = true, .underline = .double }, + }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings( + "\x1b[0m\x1b[1m\x1b[3m\x1b[4:2m\x1b[38;2;255;0;0m\x1b[48;5;8m\x1b[58;2;0;255;0m", + builder.writer.buffered(), + ); +} + +test "Style VT formatting all colors rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ + .fg_color = .{ .rgb = .{ .r = 10, .g = 20, .b = 30 } }, + .bg_color = .{ .rgb = .{ .r = 40, .g = 50, .b = 60 } }, + .underline_color = .{ .rgb = .{ .r = 70, .g = 80, .b = 90 } }, + }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings( + "\x1b[0m\x1b[38;2;10;20;30m\x1b[48;2;40;50;60m\x1b[58;2;70;80;90m", + builder.writer.buffered(), + ); +} + +test "Style VT formatting all colors palette" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ + .fg_color = .{ .palette = 1 }, + .bg_color = .{ .palette = 2 }, + .underline_color = .{ .palette = 3 }, + }; + try builder.writer.print("{f}", .{style.formatterVt()}); + try testing.expectEqualStrings( + "\x1b[0m\x1b[38;5;1m\x1b[48;5;2m\x1b[58;5;3m", + builder.writer.buffered(), + ); +} + +test "Style VT formatting palette with palette set emits rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .fg_color = .{ .palette = 1 } }; + var formatter = style.formatterVt(); + formatter.palette = &color.default; + try builder.writer.print("{f}", .{formatter}); + try testing.expectEqualStrings("\x1b[0m\x1b[38;2;204;102;102m", builder.writer.buffered()); +} + +test "Style VT formatting all palette colors with palette set" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ + .fg_color = .{ .palette = 1 }, + .bg_color = .{ .palette = 2 }, + .underline_color = .{ .palette = 3 }, + }; + var formatter = style.formatterVt(); + formatter.palette = &color.default; + try builder.writer.print("{f}", .{formatter}); + try testing.expectEqualStrings( + "\x1b[0m\x1b[38;2;204;102;102m\x1b[48;2;181;189;104m\x1b[58;2;240;198;116m", + builder.writer.buffered(), + ); +} + +test "Set basic usage" { + const testing = std.testing; + const alloc = testing.allocator; + const layout: Set.Layout = .init(16); + const buf = try alloc.alignedAlloc(u8, Set.base_align, layout.total_size); + defer alloc.free(buf); + + const style: Style = .{ .flags = .{ .bold = true } }; + const style2: Style = .{ .flags = .{ .italic = true } }; + + var set = Set.init(.init(buf), layout, .{}); + + // Add style + const id = try set.add(buf, style); + try testing.expect(id > 0); + + // Second add should return the same metadata. + { + const id2 = try set.add(buf, style); + try testing.expectEqual(id, id2); + } + + // Look it up + { + const v = set.get(buf, id); + try testing.expect(v.flags.bold); + + const v2 = set.get(buf, id); + try testing.expectEqual(v, v2); + } + + // Add a second style + const id2 = try set.add(buf, style2); + + // Look it up + { + const v = set.get(buf, id2); + try testing.expect(v.flags.italic); + } + + // Ref count + try testing.expect(set.refCount(buf, id) == 2); + try testing.expect(set.refCount(buf, id2) == 1); + + // Release + set.release(buf, id); + try testing.expect(set.refCount(buf, id) == 1); + set.release(buf, id2); + try testing.expect(set.refCount(buf, id2) == 0); + + // We added the first one twice, so + set.release(buf, id); + try testing.expect(set.refCount(buf, id) == 0); +} + +test "Set capacities" { + // We want to support at least this many styles without overflowing. + _ = Set.Layout.init(16384); +} + +test "Style HTML formatting basic bold" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .bold = true } }; + try builder.writer.print("{f}", .{style.formatterHtml()}); + try testing.expectEqualStrings("font-weight: bold;", builder.writer.buffered()); +} + +test "Style HTML formatting fg color rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .fg_color = .{ .rgb = .{ .r = 255, .g = 128, .b = 64 } } }; + try builder.writer.print("{f}", .{style.formatterHtml()}); + try testing.expectEqualStrings("color: rgb(255, 128, 64);", builder.writer.buffered()); +} + +test "Style HTML formatting bg color palette" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .bg_color = .{ .palette = 7 } }; + try builder.writer.print("{f}", .{style.formatterHtml()}); + try testing.expectEqualStrings("background-color: var(--vt-palette-7);", builder.writer.buffered()); +} + +test "Style HTML formatting combined colors and flags" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ + .fg_color = .{ .rgb = .{ .r = 255, .g = 0, .b = 0 } }, + .bg_color = .{ .rgb = .{ .r = 0, .g = 0, .b = 255 } }, + .flags = .{ .bold = true, .italic = true }, + }; + try builder.writer.print("{f}", .{style.formatterHtml()}); + const result = builder.writer.buffered(); + try testing.expect(std.mem.indexOf(u8, result, "color: rgb(255, 0, 0);") != null); + try testing.expect(std.mem.indexOf(u8, result, "background-color: rgb(0, 0, 255);") != null); + try testing.expect(std.mem.indexOf(u8, result, "font-weight: bold;") != null); + try testing.expect(std.mem.indexOf(u8, result, "font-style: italic;") != null); +} + +test "Style HTML formatting single decoration line" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .single } }; + try builder.writer.print("{f}", .{style.formatterHtml()}); + const result = builder.writer.buffered(); + try testing.expect(std.mem.indexOf(u8, result, "text-decoration-line: underline;") != null); + try testing.expect(std.mem.indexOf(u8, result, "text-decoration-style: solid;") != null); +} + +test "Style HTML formatting multiple decoration lines" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .flags = .{ .underline = .curly, .strikethrough = true, .overline = true } }; + try builder.writer.print("{f}", .{style.formatterHtml()}); + const result = builder.writer.buffered(); + try testing.expect(std.mem.indexOf(u8, result, "text-decoration-line: underline line-through overline;") != null); + try testing.expect(std.mem.indexOf(u8, result, "text-decoration-style: wavy;") != null); +} + +test "Style HTML formatting palette with palette set emits rgb" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ .bg_color = .{ .palette = 7 } }; + var formatter = style.formatterHtml(); + formatter.palette = &color.default; + try builder.writer.print("{f}", .{formatter}); + try testing.expectEqualStrings("background-color: rgb(197, 200, 198);", builder.writer.buffered()); +} + +test "Style HTML formatting all palette colors with palette set" { + const testing = std.testing; + const alloc = testing.allocator; + var builder: std.Io.Writer.Allocating = .init(alloc); + defer builder.deinit(); + + var style: Style = .{ + .fg_color = .{ .palette = 1 }, + .bg_color = .{ .palette = 2 }, + .underline_color = .{ .palette = 3 }, + }; + var formatter = style.formatterHtml(); + formatter.palette = &color.default; + try builder.writer.print("{f}", .{formatter}); + try testing.expectEqualStrings( + "color: rgb(204, 102, 102);background-color: rgb(181, 189, 104);text-decoration-color: rgb(240, 198, 116);", + builder.writer.buffered(), + ); +} diff --git a/vendor/libghostty-vt/src/terminal/tmux.zig b/vendor/libghostty-vt/src/terminal/tmux.zig new file mode 100644 index 00000000..c7cda144 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/tmux.zig @@ -0,0 +1,13 @@ +//! Types and functions related to tmux protocols. + +const control = @import("tmux/control.zig"); +const layout = @import("tmux/layout.zig"); +pub const output = @import("tmux/output.zig"); +pub const ControlParser = control.Parser; +pub const ControlNotification = control.Notification; +pub const Layout = layout.Layout; +pub const Viewer = @import("tmux/viewer.zig").Viewer; + +test { + @import("std").testing.refAllDecls(@This()); +} diff --git a/vendor/libghostty-vt/src/terminal/tmux/control.zig b/vendor/libghostty-vt/src/terminal/tmux/control.zig new file mode 100644 index 00000000..3b94eb16 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/tmux/control.zig @@ -0,0 +1,839 @@ +//! This file contains the implementation for tmux control mode. See +//! tmux(1) for more information on control mode. Some basics are documented +//! here but this is not meant to be a comprehensive source of protocol +//! documentation. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const assert = @import("../../quirks.zig").inlineAssert; +const oni = @import("oniguruma"); + +const log = std.log.scoped(.terminal_tmux); + +/// A tmux control mode parser. This takes in output from tmux control +/// mode and parses it into a structured notifications. +/// +/// It is up to the caller to establish the connection to the tmux +/// control mode session in some way (e.g. via exec, a network socket, +/// whatever). This is fully agnostic to how the data is received and sent. +pub const Parser = struct { + /// Current state of the client. + state: State = .idle, + + /// The buffer used to store in-progress notifications, output, etc. + buffer: std.Io.Writer.Allocating, + + /// The maximum size in bytes of the buffer. This is used to limit + /// memory usage. If the buffer exceeds this size, the client will + /// enter a broken state (the control mode session will be forcibly + /// exited and future data dropped). + max_bytes: usize = 1024 * 1024, + + const State = enum { + /// Outside of any active notifications. This should drop any output + /// unless it is '%' on the first byte of a line. The buffer will be + /// cleared when it sees '%', this is so that the previous notification + /// data is valid until we receive/process new data. + idle, + + /// We experienced unexpected input and are in a broken state + /// so we cannot continue processing. When this state is set, + /// the buffer has been deinited and must not be accessed. + broken, + + /// Inside an active notification (started with '%'). + notification, + + /// Inside a begin/end block. + block, + }; + + pub fn deinit(self: *Parser) void { + // If we're in a broken state, we already deinited + // the buffer, so we don't need to do anything. + if (self.state == .broken) return; + + self.buffer.deinit(); + } + + // Handle a byte of input. + // + // If we reach our byte limit this will return OutOfMemory. It only + // does this on the first time we exceed the limit; subsequent calls + // will return null as we drop all input in a broken state. + pub fn put(self: *Parser, byte: u8) Allocator.Error!?Notification { + // If we're in a broken state, just do nothing. + // + // We have to do this check here before we check the buffer, because if + // we're in a broken state then we'd have already deinited the buffer. + if (self.state == .broken) return null; + + if (self.buffer.written().len >= self.max_bytes) { + self.broken(); + return error.OutOfMemory; + } + + switch (self.state) { + // Drop because we're in a broken state. + .broken => return null, + + // Waiting for a notification so if the byte is not '%' then + // we're in a broken state. Control mode output should always + // be wrapped in '%begin/%end' orelse we expect a notification. + // Return an exit notification. + .idle => if (byte != '%') { + self.broken(); + return .{ .exit = {} }; + } else { + self.buffer.clearRetainingCapacity(); + self.state = .notification; + }, + + // If we're in a notification and its not a newline then + // we accumulate. If it is a newline then we have a + // complete notification we need to parse. + .notification => if (byte == '\n') { + // We have a complete notification, parse it. + return self.parseNotification() catch { + // If parsing failed, then we do not mark the state + // as broken because we may be able to continue parsing + // other types of notifications. + // + // In the future we may want to emit a notification + // here about unknown or unsupported notifications. + return null; + }; + }, + + // If we're in a block then we accumulate until we see a newline + // and then we check to see if that line ended the block. + .block => if (byte == '\n') { + const written = self.buffer.written(); + const idx = if (std.mem.lastIndexOfScalar( + u8, + written, + '\n', + )) |v| v + 1 else 0; + const line = written[idx..]; + + if (parseBlockTerminator(line)) |terminator| { + const output = std.mem.trimRight( + u8, + written[0..idx], + "\r\n", + ); + + // Important: do not clear buffer since the notification + // contains it. + self.state = .idle; + switch (terminator) { + .end => return .{ .block_end = output }, + .err => { + log.warn("tmux control mode error={s}", .{output}); + return .{ .block_err = output }; + }, + } + } + + // Didn't end the block, continue accumulating. + }, + } + + self.buffer.writer.writeByte(byte) catch |err| switch (err) { + error.WriteFailed => return error.OutOfMemory, + }; + + return null; + } + + const ParseError = error{RegexError}; + + const BlockTerminator = enum { end, err }; + + /// Block payload is raw data, so a line only terminates a block if it + /// exactly matches tmux's `%end`/`%error` guard-line shape. + fn parseBlockTerminator(line_raw: []const u8) ?BlockTerminator { + var line = line_raw; + if (line.len > 0 and line[line.len - 1] == '\r') { + line = line[0 .. line.len - 1]; + } + + var fields = std.mem.tokenizeScalar(u8, line, ' '); + const cmd = fields.next() orelse return null; + const terminator: BlockTerminator = if (std.mem.eql(u8, cmd, "%end")) + .end + else if (std.mem.eql(u8, cmd, "%error")) + .err + else + return null; + + const time = fields.next() orelse return null; + const command_id = fields.next() orelse return null; + const flags = fields.next() orelse return null; + const extra = fields.next(); + + // In the future, we should compare these to the %begin block + // because the tmux source guarantees that these always match and + // that is a more robust way to match. + _ = std.fmt.parseInt(usize, time, 10) catch return null; + _ = std.fmt.parseInt(usize, command_id, 10) catch return null; + _ = std.fmt.parseInt(usize, flags, 10) catch return null; + if (extra != null) return null; + + return terminator; + } + + fn parseNotification(self: *Parser) ParseError!?Notification { + assert(self.state == .notification); + + const line = line: { + var line = self.buffer.written(); + if (line[line.len - 1] == '\r') line = line[0 .. line.len - 1]; + break :line line; + }; + const cmd = cmd: { + const idx = std.mem.indexOfScalar(u8, line, ' ') orelse line.len; + break :cmd line[0..idx]; + }; + + // The notification MUST exist because we guard entering the notification + // state on seeing at least a '%'. + if (std.mem.eql(u8, cmd, "%begin")) { + // We don't use the rest of the tokens for now because tmux + // claims to guarantee that begin/end are always in order and + // never intermixed. In the future, we should probably validate + // this. + // TODO(tmuxcc): do this before merge? + + // Move to block state because we expect a corresponding end/error + // and want to accumulate the data. + self.state = .block; + self.buffer.clearRetainingCapacity(); + return null; + } else if (std.mem.eql(u8, cmd, "%output")) cmd: { + var re = oni.Regex.init( + "^%output %([0-9]+) (.+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const id = std.fmt.parseInt( + usize, + line[@intCast(starts[1])..@intCast(ends[1])], + 10, + ) catch unreachable; + const data = line[@intCast(starts[2])..@intCast(ends[2])]; + + // Important: do not clear buffer here since name points to it + self.state = .idle; + return .{ .output = .{ .pane_id = id, .data = data } }; + } else if (std.mem.eql(u8, cmd, "%session-changed")) cmd: { + var re = oni.Regex.init( + "^%session-changed \\$([0-9]+) (.+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const id = std.fmt.parseInt( + usize, + line[@intCast(starts[1])..@intCast(ends[1])], + 10, + ) catch unreachable; + const name = line[@intCast(starts[2])..@intCast(ends[2])]; + + // Important: do not clear buffer here since name points to it + self.state = .idle; + return .{ .session_changed = .{ .id = id, .name = name } }; + } else if (std.mem.eql(u8, cmd, "%sessions-changed")) cmd: { + if (!std.mem.eql(u8, line, "%sessions-changed")) { + log.warn("failed to match notification cmd={s} line=\"{s}\"", .{ cmd, line }); + break :cmd; + } + + self.buffer.clearRetainingCapacity(); + self.state = .idle; + return .{ .sessions_changed = {} }; + } else if (std.mem.eql(u8, cmd, "%layout-change")) cmd: { + var re = oni.Regex.init( + "^%layout-change @([0-9]+) (.+) (.+) (.*)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const id = std.fmt.parseInt( + usize, + line[@intCast(starts[1])..@intCast(ends[1])], + 10, + ) catch unreachable; + const layout = line[@intCast(starts[2])..@intCast(ends[2])]; + const visible_layout = line[@intCast(starts[3])..@intCast(ends[3])]; + const raw_flags = line[@intCast(starts[4])..@intCast(ends[4])]; + + // Important: do not clear buffer here since layout strings point to it + self.state = .idle; + return .{ .layout_change = .{ + .window_id = id, + .layout = layout, + .visible_layout = visible_layout, + .raw_flags = raw_flags, + } }; + } else if (std.mem.eql(u8, cmd, "%window-add")) cmd: { + var re = oni.Regex.init( + "^%window-add @([0-9]+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const id = std.fmt.parseInt( + usize, + line[@intCast(starts[1])..@intCast(ends[1])], + 10, + ) catch unreachable; + + self.buffer.clearRetainingCapacity(); + self.state = .idle; + return .{ .window_add = .{ .id = id } }; + } else if (std.mem.eql(u8, cmd, "%window-renamed")) cmd: { + var re = oni.Regex.init( + "^%window-renamed @([0-9]+) (.+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const id = std.fmt.parseInt( + usize, + line[@intCast(starts[1])..@intCast(ends[1])], + 10, + ) catch unreachable; + const name = line[@intCast(starts[2])..@intCast(ends[2])]; + + // Important: do not clear buffer here since name points to it + self.state = .idle; + return .{ .window_renamed = .{ .id = id, .name = name } }; + } else if (std.mem.eql(u8, cmd, "%window-pane-changed")) cmd: { + var re = oni.Regex.init( + "^%window-pane-changed @([0-9]+) %([0-9]+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const window_id = std.fmt.parseInt( + usize, + line[@intCast(starts[1])..@intCast(ends[1])], + 10, + ) catch unreachable; + const pane_id = std.fmt.parseInt( + usize, + line[@intCast(starts[2])..@intCast(ends[2])], + 10, + ) catch unreachable; + + self.buffer.clearRetainingCapacity(); + self.state = .idle; + return .{ .window_pane_changed = .{ .window_id = window_id, .pane_id = pane_id } }; + } else if (std.mem.eql(u8, cmd, "%client-detached")) cmd: { + var re = oni.Regex.init( + "^%client-detached (.+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const client = line[@intCast(starts[1])..@intCast(ends[1])]; + + // Important: do not clear buffer here since client points to it + self.state = .idle; + return .{ .client_detached = .{ .client = client } }; + } else if (std.mem.eql(u8, cmd, "%client-session-changed")) cmd: { + var re = oni.Regex.init( + "^%client-session-changed (.+) \\$([0-9]+) (.+)$", + .{ .capture_group = true }, + oni.Encoding.utf8, + oni.Syntax.default, + null, + ) catch |err| { + log.warn("regex init failed error={}", .{err}); + return error.RegexError; + }; + defer re.deinit(); + + var region = re.search(line, .{}) catch |err| { + log.warn("failed to match notification cmd={s} line=\"{s}\" err={}", .{ cmd, line, err }); + break :cmd; + }; + defer region.deinit(); + const starts = region.starts(); + const ends = region.ends(); + + const client = line[@intCast(starts[1])..@intCast(ends[1])]; + const session_id = std.fmt.parseInt( + usize, + line[@intCast(starts[2])..@intCast(ends[2])], + 10, + ) catch unreachable; + const name = line[@intCast(starts[3])..@intCast(ends[3])]; + + // Important: do not clear buffer here since client/name point to it + self.state = .idle; + return .{ .client_session_changed = .{ .client = client, .session_id = session_id, .name = name } }; + } else { + // Unknown notification, log it and return to idle state. + log.warn("unknown tmux control mode notification={s}", .{cmd}); + } + + // Unknown command. Clear the buffer and return to idle state. + self.buffer.clearRetainingCapacity(); + self.state = .idle; + + return null; + } + + // Mark the tmux state as broken. + fn broken(self: *Parser) void { + self.state = .broken; + self.buffer.deinit(); + } +}; + +/// Possible notification types from tmux control mode. These are documented +/// in tmux(1). A lot of the simple documentation was copied from that man +/// page here. +pub const Notification = union(enum) { + /// Entering tmux control mode. This isn't an actual event sent by + /// tmux but is one sent by us to indicate that we have detected that + /// tmux control mode is starting. + enter, + + /// Exit. + /// + /// NOTE: The tmux protocol contains a "reason" string (human friendly) + /// associated with this. We currently drop it because we don't need it + /// but this may be something we want to add later. If we do add it, + /// we have to consider buffer limits and how we handle those (dropping + /// vs truncating, etc.). + exit, + + /// Dispatched at the end of a begin/end block with the raw data. + /// The control mode parser can't parse the data because it is unaware + /// of the command that was sent to trigger this output. + block_end: []const u8, + block_err: []const u8, + + /// Raw output from a pane. + output: struct { + pane_id: usize, + data: []const u8, // unescaped + }, + + /// The client is now attached to the session with ID session-id, which is + /// named name. + session_changed: struct { + id: usize, + name: []const u8, + }, + + /// A session was created or destroyed. + sessions_changed, + + /// The layout of the window with ID window-id changed. + layout_change: struct { + window_id: usize, + layout: []const u8, + visible_layout: []const u8, + raw_flags: []const u8, + }, + + /// The window with ID window-id was linked to the current session. + window_add: struct { + id: usize, + }, + + /// The window with ID window-id was renamed to name. + window_renamed: struct { + id: usize, + name: []const u8, + }, + + /// The active pane in the window with ID window-id changed to the pane + /// with ID pane-id. + window_pane_changed: struct { + window_id: usize, + pane_id: usize, + }, + + /// The client has detached. + client_detached: struct { + client: []const u8, + }, + + /// The client is now attached to the session with ID session-id, which is + /// named name. + client_session_changed: struct { + client: []const u8, + session_id: usize, + name: []const u8, + }, + + pub fn format(self: Notification, writer: *std.Io.Writer) !void { + const T = Notification; + const info = @typeInfo(T).@"union"; + + try writer.writeAll(@typeName(T)); + if (info.tag_type) |TagType| { + try writer.writeAll("{ ."); + try writer.writeAll(@tagName(@as(TagType, self))); + try writer.writeAll(" = "); + + inline for (info.fields) |u_field| { + if (self == @field(TagType, u_field.name)) { + const value = @field(self, u_field.name); + switch (u_field.type) { + []const u8 => try writer.print("\"{s}\"", .{std.mem.trim(u8, value, " \t\r\n")}), + else => try writer.print("{any}", .{value}), + } + } + } + + try writer.writeAll(" }"); + } + } +}; + +test "tmux begin/end empty" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1578922740 269 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1578922740 269 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_end); + try testing.expectEqualStrings("", n.block_end); +} + +test "tmux begin/error empty" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1578922740 269 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%error 1578922740 269 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_err); + try testing.expectEqualStrings("", n.block_err); +} + +test "tmux begin/end data" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1578922740 269 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("hello\nworld\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1578922740 269 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_end); + try testing.expectEqualStrings("hello\nworld", n.block_end); +} + +test "tmux block payload may start with %end" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1 1 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end not really\n") |byte| try testing.expect(try c.put(byte) == null); + for ("hello\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1 1 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_end); + try testing.expectEqualStrings("%end not really\nhello", n.block_end); +} + +test "tmux block payload may start with %error" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1 1 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%error not really\n") |byte| try testing.expect(try c.put(byte) == null); + for ("hello\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1 1 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_end); + try testing.expectEqualStrings("%error not really\nhello", n.block_end); +} + +test "tmux block may terminate with real %error after misleading payload" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1 1 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%error not really\n") |byte| try testing.expect(try c.put(byte) == null); + for ("hello\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%error 1 1 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_err); + try testing.expectEqualStrings("%error not really\nhello", n.block_err); +} + +test "tmux block terminator requires exact token count" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1 1 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1 1 1 trailing\n") |byte| try testing.expect(try c.put(byte) == null); + for ("hello\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1 1 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_end); + try testing.expectEqualStrings("%end 1 1 1 trailing\nhello", n.block_end); +} + +test "tmux block terminator requires numeric metadata" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%begin 1 1 1\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end foo bar baz\n") |byte| try testing.expect(try c.put(byte) == null); + for ("hello\n") |byte| try testing.expect(try c.put(byte) == null); + for ("%end 1 1 1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .block_end); + try testing.expectEqualStrings("%end foo bar baz\nhello", n.block_end); +} + +test "tmux output" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%output %42 foo bar baz") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .output); + try testing.expectEqual(42, n.output.pane_id); + try testing.expectEqualStrings("foo bar baz", n.output.data); +} + +test "tmux session-changed" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%session-changed $42 foo") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .session_changed); + try testing.expectEqual(42, n.session_changed.id); + try testing.expectEqualStrings("foo", n.session_changed.name); +} + +test "tmux sessions-changed" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%sessions-changed") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .sessions_changed); +} + +test "tmux sessions-changed carriage return" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%sessions-changed\r") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .sessions_changed); +} + +test "tmux layout-change" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%layout-change @2 1234x791,0,0{617x791,0,0,0,617x791,618,0,1} 1234x791,0,0{617x791,0,0,0,617x791,618,0,1} *-") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .layout_change); + try testing.expectEqual(2, n.layout_change.window_id); + try testing.expectEqualStrings("1234x791,0,0{617x791,0,0,0,617x791,618,0,1}", n.layout_change.layout); + try testing.expectEqualStrings("1234x791,0,0{617x791,0,0,0,617x791,618,0,1}", n.layout_change.visible_layout); + try testing.expectEqualStrings("*-", n.layout_change.raw_flags); +} + +test "tmux window-add" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%window-add @14") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .window_add); + try testing.expectEqual(14, n.window_add.id); +} + +test "tmux window-renamed" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%window-renamed @42 bar") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .window_renamed); + try testing.expectEqual(42, n.window_renamed.id); + try testing.expectEqualStrings("bar", n.window_renamed.name); +} + +test "tmux window-pane-changed" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%window-pane-changed @42 %2") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .window_pane_changed); + try testing.expectEqual(42, n.window_pane_changed.window_id); + try testing.expectEqual(2, n.window_pane_changed.pane_id); +} + +test "tmux client-detached" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%client-detached /dev/pts/1") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .client_detached); + try testing.expectEqualStrings("/dev/pts/1", n.client_detached.client); +} + +test "tmux client-session-changed" { + const testing = std.testing; + const alloc = testing.allocator; + + var c: Parser = .{ .buffer = .init(alloc) }; + defer c.deinit(); + for ("%client-session-changed /dev/pts/1 $2 mysession") |byte| try testing.expect(try c.put(byte) == null); + const n = (try c.put('\n')).?; + try testing.expect(n == .client_session_changed); + try testing.expectEqualStrings("/dev/pts/1", n.client_session_changed.client); + try testing.expectEqual(2, n.client_session_changed.session_id); + try testing.expectEqualStrings("mysession", n.client_session_changed.name); +} diff --git a/vendor/libghostty-vt/src/terminal/tmux/layout.zig b/vendor/libghostty-vt/src/terminal/tmux/layout.zig new file mode 100644 index 00000000..df1a5391 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/tmux/layout.zig @@ -0,0 +1,638 @@ +const std = @import("std"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; + +/// A tmux layout. +/// +/// This is a tree structure so by definition it pretty much needs to be +/// allocated. We leave allocation up to the user of this struct, but +/// a general recommendation is to use an arena allocator for simplicity +/// in freeing the entire layout at once. +pub const Layout = struct { + /// Width, height of the node + width: usize, + height: usize, + + /// X and Y offset from the top-left corner of the window. + x: usize, + y: usize, + + /// The content of this node, either a pane (leaf) or more nodes + /// (split) horizontally or vertically. + content: Content, + + pub const Content = union(enum) { + pane: usize, + horizontal: []const Layout, + vertical: []const Layout, + }; + + pub const ParseError = Allocator.Error || error{SyntaxError}; + + /// Parse a layout string that includes a 4-character checksum prefix. + /// + /// The expected format is: `XXXX,layout_string` where XXXX is the + /// 4-character hexadecimal checksum and the layout string follows + /// after the comma. For example: `f8f9,80x24,0,0{40x24,0,0,1,40x24,40,0,2}`. + /// + /// Returns `ChecksumMismatch` if the checksum doesn't match the layout. + /// Returns `SyntaxError` if the format is invalid. + pub fn parseWithChecksum( + alloc: Allocator, + str: []const u8, + ) (ParseError || error{ChecksumMismatch})!Layout { + // If the string is less than 5 characters, it can't possibly + // be correct. 4-char checksum + comma. In practice it should + // be even longer, but that'll fail parse later. + if (str.len < 5) return error.SyntaxError; + if (str[4] != ',') return error.SyntaxError; + + // The layout string should start with a 4-character checksum. + const checksum: Checksum = .calculate(str[5..]); + if (!std.mem.startsWith( + u8, + str, + &checksum.asString(), + )) return error.ChecksumMismatch; + + // Checksum matches, parse the rest. + return try parse(alloc, str[5..]); + } + + /// Parse a layout string into a Layout structure. The given allocator + /// will be used for all allocations within the layout. Note that + /// individual nodes can't be freed so this allocator must be some + /// kind of arena allocator. + /// + /// The layout string must be fully provided as a single string. + /// Layouts are generally small so this should not be a problem. + /// + /// Tmux layout strings have the following format: + /// + /// - WxH,X,Y,ID Leaf pane: width×height, x-offset, y-offset, pane ID + /// - WxH,X,Y{...} Horizontal split (left-right), children comma-separated + /// - WxH,X,Y[...] Vertical split (top-bottom), children comma-separated + pub fn parse(alloc: Allocator, str: []const u8) ParseError!Layout { + var offset: usize = 0; + const root = try parseNext( + alloc, + str, + &offset, + ); + if (offset != str.len) return error.SyntaxError; + return root; + } + + fn parseNext( + alloc: Allocator, + str: []const u8, + offset: *usize, + ) ParseError!Layout { + // Find the first `x` to grab the width. + const width: usize = if (std.mem.indexOfScalar( + u8, + str[offset.*..], + 'x', + )) |idx| width: { + defer offset.* += idx + 1; // Consume `x` + break :width std.fmt.parseInt( + usize, + str[offset.* .. offset.* + idx], + 10, + ) catch return error.SyntaxError; + } else return error.SyntaxError; + + // Find the height, up to a comma. + const height: usize = if (std.mem.indexOfScalar( + u8, + str[offset.*..], + ',', + )) |idx| height: { + defer offset.* += idx + 1; // Consume `,` + break :height std.fmt.parseInt( + usize, + str[offset.* .. offset.* + idx], + 10, + ) catch return error.SyntaxError; + } else return error.SyntaxError; + + // Find X + const x: usize = if (std.mem.indexOfScalar( + u8, + str[offset.*..], + ',', + )) |idx| x: { + defer offset.* += idx + 1; // Consume `,` + break :x std.fmt.parseInt( + usize, + str[offset.* .. offset.* + idx], + 10, + ) catch return error.SyntaxError; + } else return error.SyntaxError; + + // Find Y, which can end in any of `,{,[` + const y: usize = if (std.mem.indexOfAny( + u8, + str[offset.*..], + ",{[", + )) |idx| y: { + defer offset.* += idx; // Don't consume the delimiter! + break :y std.fmt.parseInt( + usize, + str[offset.* .. offset.* + idx], + 10, + ) catch return error.SyntaxError; + } else return error.SyntaxError; + + // Determine our child node. + const content: Layout.Content = switch (str[offset.*]) { + ',' => content: { + // Consume the delimiter + offset.* += 1; + + // Leaf pane. Read up to `,}]` because we may be in + // a set of nodes. If none exist, end of string is fine. + const idx = std.mem.indexOfAny( + u8, + str[offset.*..], + ",}]", + ) orelse str.len - offset.*; + + defer offset.* += idx; // Consume the pane ID, not the delimiter + const pane_id = std.fmt.parseInt( + usize, + str[offset.* .. offset.* + idx], + 10, + ) catch return error.SyntaxError; + + break :content .{ .pane = pane_id }; + }, + + '{', '[' => |opening| content: { + var nodes: std.ArrayList(Layout) = .empty; + defer nodes.deinit(alloc); + + // Move beyond our opening + offset.* += 1; + + while (true) { + try nodes.append(alloc, try parseNext( + alloc, + str, + offset, + )); + + // We should not reach the end of string here because + // we expect a closing bracket. + if (offset.* >= str.len) return error.SyntaxError; + + // If it is a comma, we expect another node. + if (str[offset.*] == ',') { + offset.* += 1; // Consume + continue; + } + + // We expect a closing bracket now. + switch (opening) { + '{' => if (str[offset.*] != '}') return error.SyntaxError, + '[' => if (str[offset.*] != ']') return error.SyntaxError, + else => return error.SyntaxError, + } + + // Successfully parsed all children. + offset.* += 1; // Consume closing bracket + break :content switch (opening) { + '{' => .{ .horizontal = try nodes.toOwnedSlice(alloc) }, + '[' => .{ .vertical = try nodes.toOwnedSlice(alloc) }, + else => unreachable, + }; + } + }, + + // indexOfAny above guarantees we have only the above + else => unreachable, + }; + + return .{ + .width = width, + .height = height, + .x = x, + .y = y, + .content = content, + }; + } +}; + +pub const Checksum = enum(u16) { + _, + + /// Calculate the checksum of a tmux layout string. + /// The algorithm rotates the checksum right by 1 bit (with wraparound) + /// and adds the ASCII value of each character. + pub fn calculate(str: []const u8) Checksum { + var result: u16 = 0; + for (str) |c| { + // Rotate right by 1: (result >> 1) + ((result & 1) << 15) + result = (result >> 1) | ((result & 1) << 15); + result +%= c; + } + + return @enumFromInt(result); + } + + /// Convert the checksum to a 4-character hexadecimal string. This + /// is always zero-padded to match the tmux implementation + /// (in layout-custom.c). + pub fn asString(self: Checksum) [4]u8 { + const value = @intFromEnum(self); + const charset = "0123456789abcdef"; + return .{ + charset[(value >> 12) & 0xf], + charset[(value >> 8) & 0xf], + charset[(value >> 4) & 0xf], + charset[value & 0xf], + }; + } +}; + +test "simple single pane" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parse(arena.allocator(), "80x24,0,0,42"); + try testing.expectEqual(80, layout.width); + try testing.expectEqual(24, layout.height); + try testing.expectEqual(0, layout.x); + try testing.expectEqual(0, layout.y); + try testing.expectEqual(42, layout.content.pane); +} + +test "single pane with offset" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parse(arena.allocator(), "40x12,10,5,7"); + try testing.expectEqual(40, layout.width); + try testing.expectEqual(12, layout.height); + try testing.expectEqual(10, layout.x); + try testing.expectEqual(5, layout.y); + try testing.expectEqual(7, layout.content.pane); +} + +test "single pane large values" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parse(arena.allocator(), "1920x1080,100,200,999"); + try testing.expectEqual(1920, layout.width); + try testing.expectEqual(1080, layout.height); + try testing.expectEqual(100, layout.x); + try testing.expectEqual(200, layout.y); + try testing.expectEqual(999, layout.content.pane); +} + +test "horizontal split two panes" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parse(arena.allocator(), "80x24,0,0{40x24,0,0,1,40x24,40,0,2}"); + try testing.expectEqual(80, layout.width); + try testing.expectEqual(24, layout.height); + try testing.expectEqual(0, layout.x); + try testing.expectEqual(0, layout.y); + + const children = layout.content.horizontal; + try testing.expectEqual(2, children.len); + + try testing.expectEqual(40, children[0].width); + try testing.expectEqual(24, children[0].height); + try testing.expectEqual(0, children[0].x); + try testing.expectEqual(0, children[0].y); + try testing.expectEqual(1, children[0].content.pane); + + try testing.expectEqual(40, children[1].width); + try testing.expectEqual(24, children[1].height); + try testing.expectEqual(40, children[1].x); + try testing.expectEqual(0, children[1].y); + try testing.expectEqual(2, children[1].content.pane); +} + +test "vertical split two panes" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parse(arena.allocator(), "80x24,0,0[80x12,0,0,1,80x12,0,12,2]"); + try testing.expectEqual(80, layout.width); + try testing.expectEqual(24, layout.height); + try testing.expectEqual(0, layout.x); + try testing.expectEqual(0, layout.y); + + const children = layout.content.vertical; + try testing.expectEqual(2, children.len); + + try testing.expectEqual(80, children[0].width); + try testing.expectEqual(12, children[0].height); + try testing.expectEqual(0, children[0].x); + try testing.expectEqual(0, children[0].y); + try testing.expectEqual(1, children[0].content.pane); + + try testing.expectEqual(80, children[1].width); + try testing.expectEqual(12, children[1].height); + try testing.expectEqual(0, children[1].x); + try testing.expectEqual(12, children[1].y); + try testing.expectEqual(2, children[1].content.pane); +} + +test "horizontal split three panes" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parse(arena.allocator(), "120x24,0,0{40x24,0,0,1,40x24,40,0,2,40x24,80,0,3}"); + try testing.expectEqual(120, layout.width); + try testing.expectEqual(24, layout.height); + + const children = layout.content.horizontal; + try testing.expectEqual(3, children.len); + try testing.expectEqual(1, children[0].content.pane); + try testing.expectEqual(2, children[1].content.pane); + try testing.expectEqual(3, children[2].content.pane); +} + +test "nested horizontal in vertical" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + // Vertical split with top pane and bottom horizontal split + const layout: Layout = try .parse(arena.allocator(), "80x24,0,0[80x12,0,0,1,80x12,0,12{40x12,0,12,2,40x12,40,12,3}]"); + try testing.expectEqual(80, layout.width); + try testing.expectEqual(24, layout.height); + + const vert_children = layout.content.vertical; + try testing.expectEqual(2, vert_children.len); + + // First child is a simple pane + try testing.expectEqual(1, vert_children[0].content.pane); + + // Second child is a horizontal split + const horiz_children = vert_children[1].content.horizontal; + try testing.expectEqual(2, horiz_children.len); + try testing.expectEqual(2, horiz_children[0].content.pane); + try testing.expectEqual(3, horiz_children[1].content.pane); +} + +test "nested vertical in horizontal" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + // Horizontal split with left pane and right vertical split + const layout: Layout = try .parse(arena.allocator(), "80x24,0,0{40x24,0,0,1,40x24,40,0[40x12,40,0,2,40x12,40,12,3]}"); + try testing.expectEqual(80, layout.width); + try testing.expectEqual(24, layout.height); + + const horiz_children = layout.content.horizontal; + try testing.expectEqual(2, horiz_children.len); + + // First child is a simple pane + try testing.expectEqual(1, horiz_children[0].content.pane); + + // Second child is a vertical split + const vert_children = horiz_children[1].content.vertical; + try testing.expectEqual(2, vert_children.len); + try testing.expectEqual(2, vert_children[0].content.pane); + try testing.expectEqual(3, vert_children[1].content.pane); +} + +test "deeply nested layout" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + // Three levels deep + const layout: Layout = try .parse(arena.allocator(), "80x24,0,0{40x24,0,0[40x12,0,0,1,40x12,0,12,2],40x24,40,0,3}"); + + const horiz = layout.content.horizontal; + try testing.expectEqual(2, horiz.len); + + const vert = horiz[0].content.vertical; + try testing.expectEqual(2, vert.len); + try testing.expectEqual(1, vert[0].content.pane); + try testing.expectEqual(2, vert[1].content.pane); + + try testing.expectEqual(3, horiz[1].content.pane); +} + +test "syntax error empty string" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "")); +} + +test "syntax error missing width" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "x24,0,0,1")); +} + +test "syntax error missing height" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x,0,0,1")); +} + +test "syntax error missing x" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,,0,1")); +} + +test "syntax error missing y" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,,1")); +} + +test "syntax error missing pane id" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0,")); +} + +test "syntax error non-numeric width" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "abcx24,0,0,1")); +} + +test "syntax error non-numeric pane id" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0,abc")); +} + +test "syntax error unclosed horizontal bracket" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0{40x24,0,0,1")); +} + +test "syntax error unclosed vertical bracket" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0[40x24,0,0,1")); +} + +test "syntax error mismatched brackets" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0{40x24,0,0,1]")); + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0[40x24,0,0,1}")); +} + +test "syntax error trailing data" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0,1extra")); +} + +test "syntax error no x separator" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "8024,0,0,1")); +} + +test "syntax error no content delimiter" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parse(arena.allocator(), "80x24,0,0")); +} + +// parseWithChecksum tests + +test "parseWithChecksum valid" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + const layout: Layout = try .parseWithChecksum(arena.allocator(), "f8f9,80x24,0,0{40x24,0,0,1,40x24,40,0,2}"); + try testing.expectEqual(80, layout.width); + try testing.expectEqual(24, layout.height); +} + +test "parseWithChecksum mismatch" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.ChecksumMismatch, Layout.parseWithChecksum(arena.allocator(), "0000,80x24,0,0{40x24,0,0,1,40x24,40,0,2}")); +} + +test "parseWithChecksum too short" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parseWithChecksum(arena.allocator(), "bb62")); + try testing.expectError(error.SyntaxError, Layout.parseWithChecksum(arena.allocator(), "")); +} + +test "parseWithChecksum missing comma" { + var arena: ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + + try testing.expectError(error.SyntaxError, Layout.parseWithChecksum(arena.allocator(), "bb62x159x48,0,0")); +} + +// Checksum tests + +test "checksum empty string" { + const checksum = Checksum.calculate(""); + try testing.expectEqual(@as(u16, 0), @intFromEnum(checksum)); + try testing.expectEqualStrings("0000", &checksum.asString()); +} + +test "checksum single character" { + // 'A' = 65, first iteration: csum = 0 >> 1 | 0 = 0, then 0 + 65 = 65 + const checksum = Checksum.calculate("A"); + try testing.expectEqual(@as(u16, 65), @intFromEnum(checksum)); + try testing.expectEqualStrings("0041", &checksum.asString()); +} + +test "checksum two characters" { + // 'A' (65): csum = 0, rotate = 0, add 65 => 65 + // 'B' (66): csum = 65, rotate => (65 >> 1) | ((65 & 1) << 15) = 32 | 32768 = 32800 + // add 66 => 32800 + 66 = 32866 + const checksum = Checksum.calculate("AB"); + try testing.expectEqual(@as(u16, 32866), @intFromEnum(checksum)); + try testing.expectEqualStrings("8062", &checksum.asString()); +} + +test "checksum simple layout" { + const checksum = Checksum.calculate("80x24,0,0,42"); + try testing.expectEqualStrings("d962", &checksum.asString()); +} + +test "checksum horizontal split layout" { + const checksum = Checksum.calculate("80x24,0,0{40x24,0,0,1,40x24,40,0,2}"); + try testing.expectEqualStrings("f8f9", &checksum.asString()); +} + +test "checksum asString zero padding" { + // Value 0x000f should produce "000f" + const checksum: Checksum = @enumFromInt(0x000f); + try testing.expectEqualStrings("000f", &checksum.asString()); +} + +test "checksum asString all digits" { + // Value 0x1234 should produce "1234" + const checksum: Checksum = @enumFromInt(0x1234); + try testing.expectEqualStrings("1234", &checksum.asString()); +} + +test "checksum asString with letters" { + // Value 0xabcd should produce "abcd" + const checksum: Checksum = @enumFromInt(0xabcd); + try testing.expectEqualStrings("abcd", &checksum.asString()); +} + +test "checksum asString max value" { + // Value 0xffff should produce "ffff" + const checksum: Checksum = @enumFromInt(0xffff); + try testing.expectEqualStrings("ffff", &checksum.asString()); +} + +test "checksum wraparound" { + const checksum = Checksum.calculate("\xff\xff\xff\xff\xff\xff\xff\xff"); + try testing.expectEqualStrings("03fc", &checksum.asString()); +} + +test "checksum deterministic" { + // Same input should always produce same output + const str = "159x48,0,0{79x48,0,0,79x48,80,0}"; + const checksum1 = Checksum.calculate(str); + const checksum2 = Checksum.calculate(str); + try testing.expectEqual(checksum1, checksum2); +} + +test "checksum different inputs different outputs" { + const checksum1 = Checksum.calculate("80x24,0,0,1"); + const checksum2 = Checksum.calculate("80x24,0,0,2"); + try testing.expect(@intFromEnum(checksum1) != @intFromEnum(checksum2)); +} + +test "checksum known tmux layout bb62" { + // From tmux documentation: "bb62,159x48,0,0{79x48,0,0,79x48,80,0}" + // The checksum "bb62" corresponds to the layout "159x48,0,0{79x48,0,0,79x48,80,0}" + const checksum = Checksum.calculate("159x48,0,0{79x48,0,0,79x48,80,0}"); + try testing.expectEqualStrings("bb62", &checksum.asString()); +} diff --git a/vendor/libghostty-vt/src/terminal/tmux/output.zig b/vendor/libghostty-vt/src/terminal/tmux/output.zig new file mode 100644 index 00000000..6b8073e4 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/tmux/output.zig @@ -0,0 +1,590 @@ +const std = @import("std"); +const testing = std.testing; + +pub const ParseError = error{ + MissingEntry, + ExtraEntry, + FormatError, +}; + +/// Parse the output from a command with the given format struct +/// (returned usually by FormatStruct). The format struct is expected +/// to be in the order of the variables used in the format string and +/// the variables are expected to be plain variables (no conditionals, +/// extra formatting, etc.). Each variable is expected to be separated +/// by a single `delimiter` character. +pub fn parseFormatStruct( + comptime T: type, + str: []const u8, + delimiter: u8, +) ParseError!T { + // Parse all our fields + const fields = @typeInfo(T).@"struct".fields; + var it = std.mem.splitScalar(u8, str, delimiter); + var result: T = undefined; + inline for (fields) |field| { + const part = it.next() orelse return error.MissingEntry; + @field(result, field.name) = Variable.parse( + @field(Variable, field.name), + part, + ) catch return error.FormatError; + } + + // We should have consumed all parts now. + if (it.next() != null) return error.ExtraEntry; + + return result; +} + +pub fn comptimeFormat( + comptime vars: []const Variable, + comptime delimiter: u8, +) []const u8 { + comptime { + @setEvalBranchQuota(50000); + var counter: std.Io.Writer.Discarding = .init(&.{}); + try format(&counter.writer, vars, delimiter); + + var buf: [counter.count]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try format(&writer, vars, delimiter); + const final = buf; + return final[0..writer.end]; + } +} + +/// Format a set of variables into the proper format string for tmux +/// that we can handle with `parseFormatStruct`. +pub fn format( + writer: *std.Io.Writer, + vars: []const Variable, + delimiter: u8, +) std.Io.Writer.Error!void { + for (vars, 0..) |variable, i| { + if (i != 0) try writer.writeByte(delimiter); + try writer.print("#{{{t}}}", .{variable}); + } +} + +/// Returns a struct type that contains fields for each of the given +/// format variables. This can be used with `parseFormatStruct` to +/// parse an output string into a format struct. +pub fn FormatStruct(comptime vars: []const Variable) type { + var fields: [vars.len]std.builtin.Type.StructField = undefined; + for (vars, &fields) |variable, *field| { + field.* = .{ + .name = @tagName(variable), + .type = variable.Type(), + .default_value_ptr = null, + .is_comptime = false, + .alignment = @alignOf(variable.Type()), + }; + } + + return @Type(.{ .@"struct" = .{ + .layout = .auto, + .fields = &fields, + .decls = &.{}, + .is_tuple = false, + } }); +} + +/// Possible variables in a tmux format string that we support. +/// +/// Tmux supports a large number of variables, but we only implement +/// a subset of them here that are relevant to the use case of implementing +/// control mode for terminal emulators. +pub const Variable = enum { + /// 1 if pane is in alternate screen. + alternate_on, + /// Saved cursor X in alternate screen. + alternate_saved_x, + /// Saved cursor Y in alternate screen. + alternate_saved_y, + /// 1 if bracketed paste mode is enabled. + bracketed_paste, + /// 1 if the cursor is blinking. + cursor_blinking, + /// Cursor colour in pane. Possible formats: + /// - Named colors: `black`, `red`, `green`, `yellow`, `blue`, `magenta`, + /// `cyan`, `white`, `default`, `terminal`, or bright variants. + /// - 256 colors: `colour` where N is 0-255 (e.g., `colour100`). + /// - RGB hex: `#RRGGBB` (e.g., `#ff0000`). + /// - Empty string if unset. + cursor_colour, + /// Pane cursor flag. + cursor_flag, + /// Cursor shape in pane. Possible values: `block`, `underline`, `bar`, + /// or `default`. + cursor_shape, + /// Cursor X position in pane. + cursor_x, + /// Cursor Y position in pane. + cursor_y, + /// 1 if focus reporting is enabled. + focus_flag, + /// Pane insert flag. + insert_flag, + /// Pane keypad cursor flag. + keypad_cursor_flag, + /// Pane keypad flag. + keypad_flag, + /// Pane mouse all flag. + mouse_all_flag, + /// Pane mouse any flag. + mouse_any_flag, + /// Pane mouse button flag. + mouse_button_flag, + /// Pane mouse SGR flag. + mouse_sgr_flag, + /// Pane mouse standard flag. + mouse_standard_flag, + /// Pane mouse UTF-8 flag. + mouse_utf8_flag, + /// Pane origin flag. + origin_flag, + /// Unique pane ID prefixed with `%` (e.g., `%0`, `%42`). + pane_id, + /// Pane tab positions as a comma-separated list of 0-indexed column + /// numbers (e.g., `8,16,24,32`). Empty string if no tabs are set. + pane_tabs, + /// Bottom of scroll region in pane. + scroll_region_lower, + /// Top of scroll region in pane. + scroll_region_upper, + /// Unique session ID prefixed with `$` (e.g., `$0`, `$42`). + session_id, + /// Server version (e.g., `3.5a`). + version, + /// Unique window ID prefixed with `@` (e.g., `@0`, `@42`). + window_id, + /// Width of window. + window_width, + /// Height of window. + window_height, + /// Window layout description, ignoring zoomed window panes. Format is + /// `,` where checksum is a 4-digit hex CRC16 and layout + /// encodes pane dimensions as `WxH,X,Y[,ID]` with `{...}` for horizontal + /// splits and `[...]` for vertical splits. + window_layout, + /// Pane wrap flag. + wrap_flag, + + /// Parse the given string value into the appropriate resulting + /// type for this variable. + pub fn parse(comptime self: Variable, value: []const u8) !Type(self) { + return switch (self) { + .alternate_on, + .bracketed_paste, + .cursor_blinking, + .cursor_flag, + .focus_flag, + .insert_flag, + .keypad_cursor_flag, + .keypad_flag, + .mouse_all_flag, + .mouse_any_flag, + .mouse_button_flag, + .mouse_sgr_flag, + .mouse_standard_flag, + .mouse_utf8_flag, + .origin_flag, + .wrap_flag, + => std.mem.eql(u8, value, "1"), + .alternate_saved_x, + .alternate_saved_y, + .cursor_x, + .cursor_y, + .scroll_region_lower, + .scroll_region_upper, + => try std.fmt.parseInt(usize, value, 10), + .session_id => if (value.len >= 2 and value[0] == '$') + try std.fmt.parseInt(usize, value[1..], 10) + else + return error.FormatError, + .window_id => if (value.len >= 2 and value[0] == '@') + try std.fmt.parseInt(usize, value[1..], 10) + else + return error.FormatError, + .pane_id => if (value.len >= 2 and value[0] == '%') + try std.fmt.parseInt(usize, value[1..], 10) + else + return error.FormatError, + .window_width => try std.fmt.parseInt(usize, value, 10), + .window_height => try std.fmt.parseInt(usize, value, 10), + .cursor_colour, + .cursor_shape, + .pane_tabs, + .version, + .window_layout, + => value, + }; + } + + /// The type of the parsed value for this variable type. + pub fn Type(comptime self: Variable) type { + return switch (self) { + .alternate_on, + .bracketed_paste, + .cursor_blinking, + .cursor_flag, + .focus_flag, + .insert_flag, + .keypad_cursor_flag, + .keypad_flag, + .mouse_all_flag, + .mouse_any_flag, + .mouse_button_flag, + .mouse_sgr_flag, + .mouse_standard_flag, + .mouse_utf8_flag, + .origin_flag, + .wrap_flag, + => bool, + .alternate_saved_x, + .alternate_saved_y, + .cursor_x, + .cursor_y, + .scroll_region_lower, + .scroll_region_upper, + .session_id, + .window_id, + .pane_id, + .window_width, + .window_height, + => usize, + .cursor_colour, + .cursor_shape, + .pane_tabs, + .version, + .window_layout, + => []const u8, + }; + } +}; + +test "parse alternate_on" { + try testing.expectEqual(true, try Variable.parse(.alternate_on, "1")); + try testing.expectEqual(false, try Variable.parse(.alternate_on, "0")); + try testing.expectEqual(false, try Variable.parse(.alternate_on, "")); + try testing.expectEqual(false, try Variable.parse(.alternate_on, "true")); + try testing.expectEqual(false, try Variable.parse(.alternate_on, "yes")); +} + +test "parse alternate_saved_x" { + try testing.expectEqual(0, try Variable.parse(.alternate_saved_x, "0")); + try testing.expectEqual(42, try Variable.parse(.alternate_saved_x, "42")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.alternate_saved_x, "abc")); +} + +test "parse alternate_saved_y" { + try testing.expectEqual(0, try Variable.parse(.alternate_saved_y, "0")); + try testing.expectEqual(42, try Variable.parse(.alternate_saved_y, "42")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.alternate_saved_y, "abc")); +} + +test "parse cursor_x" { + try testing.expectEqual(0, try Variable.parse(.cursor_x, "0")); + try testing.expectEqual(79, try Variable.parse(.cursor_x, "79")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.cursor_x, "abc")); +} + +test "parse cursor_y" { + try testing.expectEqual(0, try Variable.parse(.cursor_y, "0")); + try testing.expectEqual(23, try Variable.parse(.cursor_y, "23")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.cursor_y, "abc")); +} + +test "parse scroll_region_upper" { + try testing.expectEqual(0, try Variable.parse(.scroll_region_upper, "0")); + try testing.expectEqual(5, try Variable.parse(.scroll_region_upper, "5")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.scroll_region_upper, "abc")); +} + +test "parse scroll_region_lower" { + try testing.expectEqual(0, try Variable.parse(.scroll_region_lower, "0")); + try testing.expectEqual(23, try Variable.parse(.scroll_region_lower, "23")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.scroll_region_lower, "abc")); +} + +test "parse session id" { + try testing.expectEqual(42, try Variable.parse(.session_id, "$42")); + try testing.expectEqual(0, try Variable.parse(.session_id, "$0")); + try testing.expectError(error.FormatError, Variable.parse(.session_id, "0")); + try testing.expectError(error.FormatError, Variable.parse(.session_id, "@0")); + try testing.expectError(error.FormatError, Variable.parse(.session_id, "$")); + try testing.expectError(error.FormatError, Variable.parse(.session_id, "")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.session_id, "$abc")); +} + +test "parse window id" { + try testing.expectEqual(42, try Variable.parse(.window_id, "@42")); + try testing.expectEqual(0, try Variable.parse(.window_id, "@0")); + try testing.expectEqual(12345, try Variable.parse(.window_id, "@12345")); + try testing.expectError(error.FormatError, Variable.parse(.window_id, "0")); + try testing.expectError(error.FormatError, Variable.parse(.window_id, "$0")); + try testing.expectError(error.FormatError, Variable.parse(.window_id, "@")); + try testing.expectError(error.FormatError, Variable.parse(.window_id, "")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.window_id, "@abc")); +} + +test "parse window width" { + try testing.expectEqual(80, try Variable.parse(.window_width, "80")); + try testing.expectEqual(0, try Variable.parse(.window_width, "0")); + try testing.expectEqual(12345, try Variable.parse(.window_width, "12345")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.window_width, "abc")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.window_width, "80px")); + try testing.expectError(error.Overflow, Variable.parse(.window_width, "-1")); +} + +test "parse window height" { + try testing.expectEqual(24, try Variable.parse(.window_height, "24")); + try testing.expectEqual(0, try Variable.parse(.window_height, "0")); + try testing.expectEqual(12345, try Variable.parse(.window_height, "12345")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.window_height, "abc")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.window_height, "24px")); + try testing.expectError(error.Overflow, Variable.parse(.window_height, "-1")); +} + +test "parse window layout" { + try testing.expectEqualStrings("abc123", try Variable.parse(.window_layout, "abc123")); + try testing.expectEqualStrings("", try Variable.parse(.window_layout, "")); + try testing.expectEqualStrings("a]b,c{d}e(f)", try Variable.parse(.window_layout, "a]b,c{d}e(f)")); +} + +test "parse cursor_flag" { + try testing.expectEqual(true, try Variable.parse(.cursor_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.cursor_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.cursor_flag, "")); + try testing.expectEqual(false, try Variable.parse(.cursor_flag, "true")); +} + +test "parse insert_flag" { + try testing.expectEqual(true, try Variable.parse(.insert_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.insert_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.insert_flag, "")); + try testing.expectEqual(false, try Variable.parse(.insert_flag, "true")); +} + +test "parse keypad_cursor_flag" { + try testing.expectEqual(true, try Variable.parse(.keypad_cursor_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.keypad_cursor_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.keypad_cursor_flag, "")); + try testing.expectEqual(false, try Variable.parse(.keypad_cursor_flag, "true")); +} + +test "parse keypad_flag" { + try testing.expectEqual(true, try Variable.parse(.keypad_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.keypad_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.keypad_flag, "")); + try testing.expectEqual(false, try Variable.parse(.keypad_flag, "true")); +} + +test "parse mouse_any_flag" { + try testing.expectEqual(true, try Variable.parse(.mouse_any_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.mouse_any_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.mouse_any_flag, "")); + try testing.expectEqual(false, try Variable.parse(.mouse_any_flag, "true")); +} + +test "parse mouse_button_flag" { + try testing.expectEqual(true, try Variable.parse(.mouse_button_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.mouse_button_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.mouse_button_flag, "")); + try testing.expectEqual(false, try Variable.parse(.mouse_button_flag, "true")); +} + +test "parse mouse_sgr_flag" { + try testing.expectEqual(true, try Variable.parse(.mouse_sgr_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.mouse_sgr_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.mouse_sgr_flag, "")); + try testing.expectEqual(false, try Variable.parse(.mouse_sgr_flag, "true")); +} + +test "parse mouse_standard_flag" { + try testing.expectEqual(true, try Variable.parse(.mouse_standard_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.mouse_standard_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.mouse_standard_flag, "")); + try testing.expectEqual(false, try Variable.parse(.mouse_standard_flag, "true")); +} + +test "parse mouse_utf8_flag" { + try testing.expectEqual(true, try Variable.parse(.mouse_utf8_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.mouse_utf8_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.mouse_utf8_flag, "")); + try testing.expectEqual(false, try Variable.parse(.mouse_utf8_flag, "true")); +} + +test "parse wrap_flag" { + try testing.expectEqual(true, try Variable.parse(.wrap_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.wrap_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.wrap_flag, "")); + try testing.expectEqual(false, try Variable.parse(.wrap_flag, "true")); +} + +test "parse bracketed_paste" { + try testing.expectEqual(true, try Variable.parse(.bracketed_paste, "1")); + try testing.expectEqual(false, try Variable.parse(.bracketed_paste, "0")); + try testing.expectEqual(false, try Variable.parse(.bracketed_paste, "")); + try testing.expectEqual(false, try Variable.parse(.bracketed_paste, "true")); +} + +test "parse cursor_blinking" { + try testing.expectEqual(true, try Variable.parse(.cursor_blinking, "1")); + try testing.expectEqual(false, try Variable.parse(.cursor_blinking, "0")); + try testing.expectEqual(false, try Variable.parse(.cursor_blinking, "")); + try testing.expectEqual(false, try Variable.parse(.cursor_blinking, "true")); +} + +test "parse focus_flag" { + try testing.expectEqual(true, try Variable.parse(.focus_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.focus_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.focus_flag, "")); + try testing.expectEqual(false, try Variable.parse(.focus_flag, "true")); +} + +test "parse mouse_all_flag" { + try testing.expectEqual(true, try Variable.parse(.mouse_all_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.mouse_all_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.mouse_all_flag, "")); + try testing.expectEqual(false, try Variable.parse(.mouse_all_flag, "true")); +} + +test "parse origin_flag" { + try testing.expectEqual(true, try Variable.parse(.origin_flag, "1")); + try testing.expectEqual(false, try Variable.parse(.origin_flag, "0")); + try testing.expectEqual(false, try Variable.parse(.origin_flag, "")); + try testing.expectEqual(false, try Variable.parse(.origin_flag, "true")); +} + +test "parse pane_id" { + try testing.expectEqual(42, try Variable.parse(.pane_id, "%42")); + try testing.expectEqual(0, try Variable.parse(.pane_id, "%0")); + try testing.expectError(error.FormatError, Variable.parse(.pane_id, "0")); + try testing.expectError(error.FormatError, Variable.parse(.pane_id, "@0")); + try testing.expectError(error.FormatError, Variable.parse(.pane_id, "%")); + try testing.expectError(error.FormatError, Variable.parse(.pane_id, "")); + try testing.expectError(error.InvalidCharacter, Variable.parse(.pane_id, "%abc")); +} + +test "parse cursor_colour" { + try testing.expectEqualStrings("red", try Variable.parse(.cursor_colour, "red")); + try testing.expectEqualStrings("#ff0000", try Variable.parse(.cursor_colour, "#ff0000")); + try testing.expectEqualStrings("", try Variable.parse(.cursor_colour, "")); +} + +test "parse cursor_shape" { + try testing.expectEqualStrings("block", try Variable.parse(.cursor_shape, "block")); + try testing.expectEqualStrings("underline", try Variable.parse(.cursor_shape, "underline")); + try testing.expectEqualStrings("bar", try Variable.parse(.cursor_shape, "bar")); + try testing.expectEqualStrings("", try Variable.parse(.cursor_shape, "")); +} + +test "parse pane_tabs" { + try testing.expectEqualStrings("0,8,16,24", try Variable.parse(.pane_tabs, "0,8,16,24")); + try testing.expectEqualStrings("", try Variable.parse(.pane_tabs, "")); + try testing.expectEqualStrings("0", try Variable.parse(.pane_tabs, "0")); +} + +test "parse version" { + try testing.expectEqualStrings("3.5a", try Variable.parse(.version, "3.5a")); + try testing.expectEqualStrings("3.5", try Variable.parse(.version, "3.5")); + try testing.expectEqualStrings("next-3.5", try Variable.parse(.version, "next-3.5")); + try testing.expectEqualStrings("", try Variable.parse(.version, "")); +} + +test "parseFormatStruct single field" { + const T = FormatStruct(&.{.session_id}); + const result = try parseFormatStruct(T, "$42", ' '); + try testing.expectEqual(42, result.session_id); +} + +test "parseFormatStruct multiple fields" { + const T = FormatStruct(&.{ .session_id, .window_id, .window_width, .window_height }); + const result = try parseFormatStruct(T, "$1 @2 80 24", ' '); + try testing.expectEqual(1, result.session_id); + try testing.expectEqual(2, result.window_id); + try testing.expectEqual(80, result.window_width); + try testing.expectEqual(24, result.window_height); +} + +test "parseFormatStruct with string field" { + const T = FormatStruct(&.{ .window_id, .window_layout }); + const result = try parseFormatStruct(T, "@5,abc123", ','); + try testing.expectEqual(5, result.window_id); + try testing.expectEqualStrings("abc123", result.window_layout); +} + +test "parseFormatStruct different delimiter" { + const T = FormatStruct(&.{ .window_width, .window_height }); + const result = try parseFormatStruct(T, "120\t40", '\t'); + try testing.expectEqual(120, result.window_width); + try testing.expectEqual(40, result.window_height); +} + +test "parseFormatStruct missing entry" { + const T = FormatStruct(&.{ .session_id, .window_id }); + try testing.expectError(error.MissingEntry, parseFormatStruct(T, "$1", ' ')); +} + +test "parseFormatStruct extra entry" { + const T = FormatStruct(&.{.session_id}); + try testing.expectError(error.ExtraEntry, parseFormatStruct(T, "$1 @2", ' ')); +} + +test "parseFormatStruct format error" { + const T = FormatStruct(&.{.session_id}); + try testing.expectError(error.FormatError, parseFormatStruct(T, "42", ' ')); + try testing.expectError(error.FormatError, parseFormatStruct(T, "@42", ' ')); + try testing.expectError(error.FormatError, parseFormatStruct(T, "$abc", ' ')); +} + +test "parseFormatStruct empty string" { + const T = FormatStruct(&.{.session_id}); + try testing.expectError(error.FormatError, parseFormatStruct(T, "", ' ')); +} + +test "parseFormatStruct with empty layout field" { + const T = FormatStruct(&.{ .session_id, .window_layout }); + const result = try parseFormatStruct(T, "$1,", ','); + try testing.expectEqual(1, result.session_id); + try testing.expectEqualStrings("", result.window_layout); +} + +fn testFormat( + comptime vars: []const Variable, + comptime delimiter: u8, + comptime expected: []const u8, +) !void { + const comptime_result = comptime comptimeFormat(vars, delimiter); + try testing.expectEqualStrings(expected, comptime_result); + + var buf: [256]u8 = undefined; + var writer: std.Io.Writer = .fixed(&buf); + try format(&writer, vars, delimiter); + try testing.expectEqualStrings(expected, buf[0..writer.end]); +} + +test "format single variable" { + try testFormat(&.{.session_id}, ' ', "#{session_id}"); +} + +test "format multiple variables" { + try testFormat(&.{ .session_id, .window_id, .window_width, .window_height }, ' ', "#{session_id} #{window_id} #{window_width} #{window_height}"); +} + +test "format with comma delimiter" { + try testFormat(&.{ .window_id, .window_layout }, ',', "#{window_id},#{window_layout}"); +} + +test "format with tab delimiter" { + try testFormat(&.{ .window_width, .window_height }, '\t', "#{window_width}\t#{window_height}"); +} + +test "format empty variables" { + try testFormat(&.{}, ' ', ""); +} + +test "format all variables" { + try testFormat(&.{ .session_id, .window_id, .window_width, .window_height, .window_layout }, ' ', "#{session_id} #{window_id} #{window_width} #{window_height} #{window_layout}"); +} diff --git a/vendor/libghostty-vt/src/terminal/tmux/viewer.zig b/vendor/libghostty-vt/src/terminal/tmux/viewer.zig new file mode 100644 index 00000000..585c9540 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/tmux/viewer.zig @@ -0,0 +1,2283 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArenaAllocator = std.heap.ArenaAllocator; +const testing = std.testing; +const assert = @import("../../quirks.zig").inlineAssert; +const size = @import("../size.zig"); +const CircBuf = @import("../../datastruct/main.zig").CircBuf; +const CursorStyle = @import("../cursor.zig").Style; +const Screen = @import("../Screen.zig"); +const ScreenSet = @import("../ScreenSet.zig"); +const Terminal = @import("../Terminal.zig"); +const Layout = @import("layout.zig").Layout; +const control = @import("control.zig"); +const output = @import("output.zig"); + +const log = std.log.scoped(.terminal_tmux_viewer); + +// TODO: A list of TODOs as I think about them. +// - We need to make startup more robust so session and block can happen +// out of order. +// - We need to ignore `output` for panes that aren't yet initialized +// (until capture-panes are complete). +// - We should note what the active window pane is on the tmux side; +// we can use this at least for initial focus. + +// NOTE: There is some fragility here that can possibly break if tmux +// changes their implementation. In particular, the order of notifications +// and assurances about what is sent when are based on reading the tmux +// source code as of Dec, 2025. These aren't documented as fixed. +// +// I've tried not to depend on anything that seems like it'd change +// in the future. For example, it seems reasonable that command output +// always comes before session attachment. But, I am noting this here +// in case something breaks in the future we can consider it. We should +// be able to easily unit test all variations seen in the real world. + +/// The initial capacity of the command queue. We dynamically resize +/// as necessary so the initial value isn't that important, but if we +/// want to feel good about it we should make it large enough to support +/// our most realistic use cases without resizing. +const COMMAND_QUEUE_INITIAL = 8; + +/// A viewer is a tmux control mode client that attempts to create +/// a remote view of a tmux session, including providing the ability to send +/// new input to the session. +/// +/// This is the primary use case for tmux control mode, but technically +/// tmux control mode clients can do anything a normal tmux client can do, +/// so the `control.zig` and other files in this folder are more general +/// purpose. +/// +/// This struct helps move through a state machine of connecting to a tmux +/// session, negotiating capabilities, listing window state, etc. +/// +/// ## Viewer Lifecycle +/// +/// The viewer progresses through several states from initial connection +/// to steady-state operation. Here is the full flow: +/// +/// ``` +/// ┌─────────────────────────────────────────────┐ +/// │ TMUX CONTROL MODE START │ +/// │ (DCS 1000p received by host) │ +/// └─────────────────┬───────────────────────────┘ +/// │ +/// ▼ +/// ┌─────────────────────────────────────────────┐ +/// │ startup_block │ +/// │ │ +/// │ Wait for initial %begin/%end block from │ +/// │ tmux. This is the response to the initial │ +/// │ command (e.g., "attach -t 0"). │ +/// └─────────────────┬───────────────────────────┘ +/// │ %end / %error +/// ▼ +/// ┌─────────────────────────────────────────────┐ +/// │ startup_session │ +/// │ │ +/// │ Wait for %session-changed notification │ +/// │ to get the initial session ID. │ +/// └─────────────────┬───────────────────────────┘ +/// │ %session-changed +/// ▼ +/// ┌─────────────────────────────────────────────┐ +/// │ command_queue │ +/// │ │ +/// │ Main operating state. Process commands │ +/// │ sequentially and handle notifications. │ +/// └─────────────────────────────────────────────┘ +/// │ +/// ┌───────────────────────────┼───────────────────────────┐ +/// │ │ │ +/// ▼ ▼ ▼ +/// ┌──────────────────────────┐ ┌──────────────────────────┐ ┌────────────────────────┐ +/// │ tmux_version │ │ list_windows │ │ %output / %layout- │ +/// │ │ │ │ │ change / etc. │ +/// │ Query tmux version for │ │ Get all windows in the │ │ │ +/// │ compatibility checks. │ │ current session. │ │ Handle live updates │ +/// └──────────────────────────┘ └────────────┬─────────────┘ │ from tmux server. │ +/// │ └────────────────────────┘ +/// ▼ +/// ┌─────────────────────────────────────────────┐ +/// │ syncLayouts │ +/// │ │ +/// │ For each window, parse layout and sync │ +/// │ panes. New panes trigger capture commands. │ +/// └─────────────────┬───────────────────────────┘ +/// │ +/// ┌───────────────────────────┴───────────────────────────┐ +/// │ For each new pane: │ +/// ▼ ▼ +/// ┌──────────────────────────┐ ┌──────────────────────────┐ +/// │ pane_history │ │ pane_visible │ +/// │ (primary screen) │ │ (primary screen) │ +/// │ │ │ │ +/// │ Capture scrollback │ │ Capture visible area │ +/// │ history into terminal. │ │ into terminal. │ +/// └──────────────────────────┘ └──────────────────────────┘ +/// │ │ +/// ▼ ▼ +/// ┌──────────────────────────┐ ┌──────────────────────────┐ +/// │ pane_history │ │ pane_visible │ +/// │ (alternate screen) │ │ (alternate screen) │ +/// └──────────────────────────┘ └──────────────────────────┘ +/// │ │ +/// └───────────────────────────┬───────────────────────────┘ +/// ▼ +/// ┌─────────────────────────────────────────────┐ +/// │ pane_state │ +/// │ │ +/// │ Query cursor position, cursor style, │ +/// │ and alternate screen mode for all panes. │ +/// └─────────────────────────────────────────────┘ +/// │ +/// ▼ +/// ┌─────────────────────────────────────────────┐ +/// │ READY FOR OPERATION │ +/// │ │ +/// │ Panes are populated with content. The │ +/// │ viewer handles %output for live updates, │ +/// │ %layout-change for pane changes, and │ +/// │ %session-changed for session switches. │ +/// └─────────────────────────────────────────────┘ +/// ``` +/// +/// ## Error Handling +/// +/// At any point, if an unrecoverable error occurs or tmux sends `%exit`, +/// the viewer transitions to the `defunct` state and emits an `.exit` action. +/// +/// ## Session Changes +/// +/// When `%session-changed` is received during `command_queue` state, the +/// viewer resets itself completely: clears all windows/panes, emits an +/// empty windows action, and restarts the `list_windows` flow for the new +/// session. +/// +pub const Viewer = struct { + /// Allocator used for all internal state. + alloc: Allocator, + + /// Current state of the state machine. + state: State, + + /// The current session ID we're attached to. + session_id: usize, + + /// The tmux server version string (e.g., "3.5a"). We capture this + /// on startup because it will allow us to change behavior between + /// versions as necessary. + tmux_version: []const u8, + + /// The list of commands we've sent that we want to send and wait + /// for a response for. We only send one command at a time just + /// to avoid any possible confusion around ordering. + command_queue: CommandQueue, + + /// The windows in the current session. + windows: std.ArrayList(Window), + + /// The panes in the current session, mapped by pane ID. + panes: PanesMap, + + /// The arena used for the prior action allocated state. This contains + /// the contents for the actions as well as the actions slice itself. + action_arena: ArenaAllocator.State, + + /// A single action pre-allocated that we use for single-action + /// returns (common). This ensures that we can never get allocation + /// errors on single-action returns, especially those such as `.exit`. + action_single: [1]Action, + + pub const CommandQueue = CircBuf(Command, undefined); + pub const PanesMap = std.AutoArrayHashMapUnmanaged(usize, Pane); + + pub const Action = union(enum) { + /// Tmux has closed the control mode connection, we should end + /// our viewer session in some way. + exit, + + /// Send a command to tmux, e.g. `list-windows`. The caller + /// should not worry about parsing this or reading what command + /// it is; just send it to tmux as-is. This will include the + /// trailing newline so you can send it directly. + command: []const u8, + + /// Windows changed. This may add, remove or change windows. The + /// caller is responsible for diffing the new window list against + /// the prior one. Remember that for a given Viewer, window IDs + /// are guaranteed to be stable. Additionally, tmux (as of Dec 2025) + /// never reuses window IDs within a server process lifetime. + windows: []const Window, + + pub fn format(self: Action, writer: *std.Io.Writer) !void { + const T = Action; + const info = @typeInfo(T).@"union"; + + try writer.writeAll(@typeName(T)); + if (info.tag_type) |TagType| { + try writer.writeAll("{ ."); + try writer.writeAll(@tagName(@as(TagType, self))); + try writer.writeAll(" = "); + + inline for (info.fields) |u_field| { + if (self == @field(TagType, u_field.name)) { + const value = @field(self, u_field.name); + switch (u_field.type) { + []const u8 => try writer.print("\"{s}\"", .{std.mem.trim(u8, value, " \t\r\n")}), + else => try writer.print("{any}", .{value}), + } + } + } + + try writer.writeAll(" }"); + } + } + }; + + pub const Input = union(enum) { + /// Data from tmux was received that needs to be processed. + tmux: control.Notification, + }; + + pub const Window = struct { + id: usize, + width: usize, + height: usize, + layout_arena: ArenaAllocator.State, + layout: Layout, + + pub fn deinit(self: *Window, alloc: Allocator) void { + self.layout_arena.promote(alloc).deinit(); + } + }; + + pub const Pane = struct { + terminal: Terminal, + + pub fn deinit(self: *Pane, alloc: Allocator) void { + self.terminal.deinit(alloc); + } + }; + + /// Initialize a new viewer. + /// + /// The given allocator is used for all internal state. You must + /// call deinit when you're done with the viewer to free it. + pub fn init(alloc: Allocator) Allocator.Error!Viewer { + // Create our initial command queue + var command_queue: CommandQueue = try .init(alloc, COMMAND_QUEUE_INITIAL); + errdefer command_queue.deinit(alloc); + + return .{ + .alloc = alloc, + .state = .startup_block, + // The default value here is meaningless. We don't get started + // until we receive a session-changed notification which will + // set this to a real value. + .session_id = 0, + .tmux_version = "", + .command_queue = command_queue, + .windows = .empty, + .panes = .empty, + .action_arena = .{}, + .action_single = undefined, + }; + } + + pub fn deinit(self: *Viewer) void { + { + for (self.windows.items) |*window| window.deinit(self.alloc); + self.windows.deinit(self.alloc); + } + { + var it = self.command_queue.iterator(.forward); + while (it.next()) |command| command.deinit(self.alloc); + self.command_queue.deinit(self.alloc); + } + { + var it = self.panes.iterator(); + while (it.next()) |kv| kv.value_ptr.deinit(self.alloc); + self.panes.deinit(self.alloc); + } + if (self.tmux_version.len > 0) { + self.alloc.free(self.tmux_version); + } + self.action_arena.promote(self.alloc).deinit(); + } + + /// Send in an input event (such as a tmux protocol notification, + /// keyboard input for a pane, etc.) and process it. The returned + /// list is a set of actions to take as a result of the input prior + /// to the next input. This list may be empty. + pub fn next(self: *Viewer, input: Input) []const Action { + // Developer note: this function must never return an error. If + // an error occurs we must go into a defunct state or some other + // state to gracefully handle it. + return switch (input) { + .tmux => self.nextTmux(input.tmux), + }; + } + + fn nextTmux( + self: *Viewer, + n: control.Notification, + ) []const Action { + return switch (self.state) { + .defunct => defunct: { + log.info("received notification in defunct state, ignoring", .{}); + break :defunct &.{}; + }, + + .startup_block => self.nextStartupBlock(n), + .startup_session => self.nextStartupSession(n), + .command_queue => self.nextCommand(n), + }; + } + + fn nextStartupBlock( + self: *Viewer, + n: control.Notification, + ) []const Action { + assert(self.state == .startup_block); + + switch (n) { + // This is only sent by the DCS parser when we first get + // DCS 1000p, it should never reach us here. + .enter => unreachable, + + // I don't think this is technically possible (reading the + // tmux source code), but if we see an exit we can semantically + // handle this without issue. + .exit => return self.defunct(), + + // Any begin and end (even error) is fine! Now we wait for + // session-changed to get the initial session ID. session-changed + // is guaranteed to come after the initial command output + // since if the initial command is `attach` tmux will run that, + // queue the notification, then do notificatins. + .block_end, .block_err => { + self.state = .startup_session; + return &.{}; + }, + + // I don't like catch-all else branches but startup is such + // a special case of looking for very specific things that + // are unlikely to expand. + else => return &.{}, + } + } + + fn nextStartupSession( + self: *Viewer, + n: control.Notification, + ) []const Action { + assert(self.state == .startup_session); + + switch (n) { + .enter => unreachable, + + .exit => return self.defunct(), + + .session_changed => |info| { + self.session_id = info.id; + + var arena = self.action_arena.promote(self.alloc); + defer self.action_arena = arena.state; + _ = arena.reset(.free_all); + + return self.enterCommandQueue( + arena.allocator(), + &.{ .tmux_version, .list_windows }, + ) catch { + log.warn("failed to queue command, becoming defunct", .{}); + return self.defunct(); + }; + }, + + else => return &.{}, + } + } + + fn nextIdle( + self: *Viewer, + n: control.Notification, + ) []const Action { + assert(self.state == .idle); + + switch (n) { + .enter => unreachable, + .exit => return self.defunct(), + else => return &.{}, + } + } + + fn nextCommand( + self: *Viewer, + n: control.Notification, + ) []const Action { + // We have to be in a command queue, but the command queue MAY + // be empty. If it is empty, then receivedCommandOutput will + // handle it by ignoring any command output. That's okay! + assert(self.state == .command_queue); + + // Clear our prior arena so it is ready to be used for any + // actions immediately. + { + var arena = self.action_arena.promote(self.alloc); + _ = arena.reset(.free_all); + self.action_arena = arena.state; + } + + // Setup our empty actions list that commands can populate. + var actions: std.ArrayList(Action) = .empty; + + // Track whether the in-flight command slot is available. Starts true + // if queue is empty (no command in flight). Set to true when a command + // completes (block_end/block_err) or the queue is reset (session_changed). + var command_consumed = self.command_queue.empty(); + + switch (n) { + .enter => unreachable, + .exit => return self.defunct(), + + inline .block_end, + .block_err, + => |content, tag| { + self.receivedCommandOutput( + &actions, + content, + tag == .block_err, + ) catch { + log.warn("failed to process command output, becoming defunct", .{}); + return self.defunct(); + }; + + // Command is consumed since a block end/err is the output + // from a command. + command_consumed = true; + }, + + .output => |out| self.receivedOutput( + out.pane_id, + out.data, + ) catch |err| { + log.warn( + "failed to process output for pane id={}: {}", + .{ out.pane_id, err }, + ); + }, + + // Session changed means we switched to a different tmux session. + // We need to reset our state and start fresh with list-windows. + // This completely replaces the viewer, so treat it like a fresh start. + .session_changed => |info| { + self.sessionChanged( + &actions, + info.id, + ) catch { + log.warn("failed to handle session change, becoming defunct", .{}); + return self.defunct(); + }; + + // Command is consumed because sessionChanged resets + // our entire viewer. + command_consumed = true; + }, + + // Layout changed of a single window. + .layout_change => |info| self.layoutChanged( + &actions, + info.window_id, + info.layout, + ) catch { + // Note: in the future, we can probably handle a failure + // here with a fallback to remove this one window, list + // windows again, and try again. + log.warn("failed to handle layout change, becoming defunct", .{}); + return self.defunct(); + }, + + // A window was added to this session. + .window_add => |info| self.windowAdd(info.id) catch { + log.warn("failed to handle window add, becoming defunct", .{}); + return self.defunct(); + }, + + // The active pane changed. We don't care about this because + // we handle our own focus. + .window_pane_changed => {}, + + // We ignore this one. It means a session was created or + // destroyed. If it was our own session we will get an exit + // notification very soon. If it is another session we don't + // care. + .sessions_changed => {}, + + // We don't use window names for anything, currently. + .window_renamed => {}, + + // This is for other clients, which we don't do anything about. + // For us, we'll get `exit` or `session_changed`, respectively. + .client_detached, + .client_session_changed, + => {}, + } + + // After processing commands, we add our next command to + // execute if we have one. We do this last because command + // processing may itself queue more commands. We only emit a + // command if a prior command was consumed (or never existed). + if (self.state == .command_queue and command_consumed) { + if (self.command_queue.first()) |next_command| { + // We should not have any commands, because our nextCommand + // always queues them. + if (comptime std.debug.runtime_safety) { + for (actions.items) |action| { + if (action == .command) assert(false); + } + } + + var arena = self.action_arena.promote(self.alloc); + defer self.action_arena = arena.state; + const arena_alloc = arena.allocator(); + + var builder: std.Io.Writer.Allocating = .init(arena_alloc); + next_command.formatCommand(&builder.writer) catch + return self.defunct(); + actions.append( + arena_alloc, + .{ .command = builder.writer.buffered() }, + ) catch return self.defunct(); + } + } + + return actions.items; + } + + /// When the layout changes for a single window, a pane may be added + /// or removed that we've never seen, in addition to the layout itself + /// physically changing. + /// + /// To handle this, its similar to list-windows except we expect the + /// window to already exist. We update the layout, do the initLayout + /// call for any diffs, setup commands to capture any new panes, + /// prune any removed panes. + fn layoutChanged( + self: *Viewer, + actions: *std.ArrayList(Action), + window_id: usize, + layout_str: []const u8, + ) !void { + // Find the window this layout change is for. + const window: *Window = window: for (self.windows.items) |*w| { + if (w.id == window_id) break :window w; + } else { + log.info("layout change for unknown window id={}", .{window_id}); + return; + }; + + // Clear our prior window arena and setup our layout + window.layout = layout: { + var arena = window.layout_arena.promote(self.alloc); + defer window.layout_arena = arena.state; + _ = arena.reset(.retain_capacity); + break :layout Layout.parseWithChecksum( + arena.allocator(), + layout_str, + ) catch |err| { + log.info( + "failed to parse window layout id={} layout={s}", + .{ window_id, layout_str }, + ); + return err; + }; + }; + + // Reset our arena so we can build up actions. + var arena = self.action_arena.promote(self.alloc); + defer self.action_arena = arena.state; + const arena_alloc = arena.allocator(); + + // Our initial action is to definitely let the caller know that + // some windows changed. + try actions.append(arena_alloc, .{ .windows = self.windows.items }); + + // Sync up our panes + try self.syncLayouts(self.windows.items); + } + + /// When a window is added to the session, we need to refresh our window + /// list to get the new window's information. + fn windowAdd( + self: *Viewer, + window_id: usize, + ) !void { + _ = window_id; // We refresh all windows via list-windows + + // Queue list-windows to get the updated window list + try self.queueCommands(&.{.list_windows}); + } + + fn syncLayouts( + self: *Viewer, + windows: []const Window, + ) !void { + // Go through the window layout and setup all our panes. We move + // this into a new panes map so that we can easily prune our old + // list. + var panes: PanesMap = .empty; + errdefer { + // Clear out all the new panes. + var panes_it = panes.iterator(); + while (panes_it.next()) |kv| { + if (!self.panes.contains(kv.key_ptr.*)) { + kv.value_ptr.deinit(self.alloc); + } + } + panes.deinit(self.alloc); + } + for (windows) |window| try initLayout( + self.alloc, + &self.panes, + &panes, + window.layout, + ); + + // Build up the list of removed panes. + var removed: std.ArrayList(usize) = removed: { + var removed: std.ArrayList(usize) = .empty; + errdefer removed.deinit(self.alloc); + var panes_it = self.panes.iterator(); + while (panes_it.next()) |kv| { + if (panes.contains(kv.key_ptr.*)) continue; + try removed.append(self.alloc, kv.key_ptr.*); + } + + break :removed removed; + }; + defer removed.deinit(self.alloc); + + // Ensure we can add the windows + try self.windows.ensureTotalCapacity(self.alloc, windows.len); + + // Get our list of added panes and setup our command queue + // to populate them. + // TODO: errdefer cleanup + { + var panes_it = panes.iterator(); + var added: bool = false; + while (panes_it.next()) |kv| { + const pane_id: usize = kv.key_ptr.*; + if (self.panes.contains(pane_id)) continue; + added = true; + try self.queueCommands(&.{ + .{ .pane_history = .{ .id = pane_id, .screen_key = .primary } }, + .{ .pane_visible = .{ .id = pane_id, .screen_key = .primary } }, + .{ .pane_history = .{ .id = pane_id, .screen_key = .alternate } }, + .{ .pane_visible = .{ .id = pane_id, .screen_key = .alternate } }, + }); + } + + // If we added any panes, then we also want to resync the pane + // state (terminal modes and cursor positions and so on). + if (added) try self.queueCommands(&.{.pane_state}); + } + + // No more errors after this point. We're about to replace all + // our owned state with our temporary state, and our errdefers + // above will double-free if there is an error. + errdefer comptime unreachable; + + // Replace our window list if it changed. We assume it didn't + // change if our pointer is pointing to the same data. + if (windows.ptr != self.windows.items.ptr) { + for (self.windows.items) |*window| window.deinit(self.alloc); + self.windows.clearRetainingCapacity(); + self.windows.appendSliceAssumeCapacity(windows); + } + + // Replace our panes + { + // First remove our old panes + for (removed.items) |id| if (self.panes.fetchSwapRemove( + id, + )) |entry_const| { + var entry = entry_const; + entry.value.deinit(self.alloc); + }; + // We can now deinit self.panes because the existing + // entries are preserved. + self.panes.deinit(self.alloc); + self.panes = panes; + } + } + + /// When a session changes, we have to basically reset our whole state. + /// To do this, we emit an empty windows event (so callers can clear all + /// windows), reset ourself, and start all over. + fn sessionChanged( + self: *Viewer, + actions: *std.ArrayList(Action), + session_id: usize, + ) (Allocator.Error || std.Io.Writer.Error)!void { + // Build up a new viewer. Its the easiest way to reset ourselves. + var replacement: Viewer = try .init(self.alloc); + errdefer replacement.deinit(); + + // Our actions must start out empty so we don't mix arenas + assert(actions.items.len == 0); + errdefer actions.* = .empty; + + // Build actions: empty windows notification + list-windows command + var arena = replacement.action_arena.promote(replacement.alloc); + const arena_alloc = arena.allocator(); + try actions.append(arena_alloc, .{ .windows = &.{} }); + + // Setup our command queue and put ourselves in the command queue + // state. + try replacement.queueCommands(&.{.list_windows}); + replacement.state = .command_queue; + + // Transfer preserved version to replacement + replacement.tmux_version = try replacement.alloc.dupe(u8, self.tmux_version); + + // Save arena state back before swap + replacement.action_arena = arena.state; + + // Swap our self, no more error handling after this. + errdefer comptime unreachable; + self.deinit(); + self.* = replacement; + + // Set our session ID and jump directly to the list + self.session_id = session_id; + + assert(self.state == .command_queue); + } + + fn receivedCommandOutput( + self: *Viewer, + actions: *std.ArrayList(Action), + content: []const u8, + is_err: bool, + ) !void { + // Get the command we're expecting output for. We need to get the + // non-pointer value because we are deleting it from the circular + // buffer immediately. This shallow copy is all we need since + // all the memory in Command is owned by GPA. + const command: Command = if (self.command_queue.first()) |ptr| switch (ptr.*) { + // I truly can't explain this. A simple `ptr.*` copy will cause + // our memory to become undefined when deleteOldest is called + // below. I logged all the pointers and they don't match so I + // don't know how its being set to undefined. But a copy like + // this does work. + inline else => |v, tag| @unionInit( + Command, + @tagName(tag), + v, + ), + } else { + // If we have no pending commands, this is unexpected. + log.info("unexpected block output err={}", .{is_err}); + return; + }; + self.command_queue.deleteOldest(1); + defer command.deinit(self.alloc); + + // We'll use our arena for the return value here so we can + // easily accumulate actions. + var arena = self.action_arena.promote(self.alloc); + defer self.action_arena = arena.state; + const arena_alloc = arena.allocator(); + + // Process our command + switch (command) { + .user => {}, + + .pane_state => try self.receivedPaneState(content), + + .list_windows => try self.receivedListWindows( + arena_alloc, + actions, + content, + ), + + .pane_history => |cap| try self.receivedPaneHistory( + cap.screen_key, + cap.id, + content, + ), + + .pane_visible => |cap| try self.receivedPaneVisible( + cap.screen_key, + cap.id, + content, + ), + + .tmux_version => try self.receivedTmuxVersion(content), + } + } + + fn receivedTmuxVersion( + self: *Viewer, + content: []const u8, + ) !void { + const line = std.mem.trim(u8, content, " \t\r\n"); + if (line.len == 0) return; + + const data = output.parseFormatStruct( + Format.tmux_version.Struct(), + line, + Format.tmux_version.delim, + ) catch |err| { + log.info("failed to parse tmux version: {s}", .{line}); + return err; + }; + + if (self.tmux_version.len > 0) { + self.alloc.free(self.tmux_version); + } + self.tmux_version = try self.alloc.dupe(u8, data.version); + } + + fn receivedListWindows( + self: *Viewer, + arena_alloc: Allocator, + actions: *std.ArrayList(Action), + content: []const u8, + ) !void { + // If there is an error, reset our actions to what it was before. + errdefer actions.shrinkRetainingCapacity(actions.items.len); + + // This stores our new window state from this list-windows output. + var windows: std.ArrayList(Window) = .empty; + defer windows.deinit(self.alloc); + + // Parse all our windows + var it = std.mem.splitScalar(u8, content, '\n'); + while (it.next()) |line_raw| { + const line = std.mem.trim(u8, line_raw, " \t\r"); + if (line.len == 0) continue; + const data = output.parseFormatStruct( + Format.list_windows.Struct(), + line, + Format.list_windows.delim, + ) catch |err| { + log.info("failed to parse list-windows line: {s}", .{line}); + return err; + }; + + // Parse the layout + var arena: ArenaAllocator = .init(self.alloc); + errdefer arena.deinit(); + const window_alloc = arena.allocator(); + const layout: Layout = Layout.parseWithChecksum( + window_alloc, + data.window_layout, + ) catch |err| { + log.info( + "failed to parse window layout id={} layout={s}", + .{ data.window_id, data.window_layout }, + ); + return err; + }; + + try windows.append(self.alloc, .{ + .id = data.window_id, + .width = data.window_width, + .height = data.window_height, + .layout_arena = arena.state, + .layout = layout, + }); + } + + // Setup our windows action so the caller can process GUI + // window changes. + try actions.append(arena_alloc, .{ .windows = windows.items }); + + // Sync up our layouts. This will populate unknown panes, prune, etc. + try self.syncLayouts(windows.items); + } + + fn receivedPaneState( + self: *Viewer, + content: []const u8, + ) !void { + var it = std.mem.splitScalar(u8, content, '\n'); + while (it.next()) |line_raw| { + const line = std.mem.trim(u8, line_raw, " \t\r"); + if (line.len == 0) continue; + + const data = output.parseFormatStruct( + Format.list_panes.Struct(), + line, + Format.list_panes.delim, + ) catch |err| { + log.info("failed to parse list-panes line: {s}", .{line}); + return err; + }; + + // Get the pane for this ID + const entry = self.panes.getEntry(data.pane_id) orelse { + log.info("received pane state for untracked pane id={}", .{data.pane_id}); + continue; + }; + const pane: *Pane = entry.value_ptr; + const t: *Terminal = &pane.terminal; + + // Determine which screen to use based on alternate_on + const screen_key: ScreenSet.Key = if (data.alternate_on) .alternate else .primary; + + // Set cursor position on the appropriate screen (tmux uses 0-based) + if (t.screens.get(screen_key)) |screen| { + cursor: { + const cursor_x = std.math.cast( + size.CellCountInt, + data.cursor_x, + ) orelse break :cursor; + const cursor_y = std.math.cast( + size.CellCountInt, + data.cursor_y, + ) orelse break :cursor; + if (cursor_x >= screen.pages.cols or + cursor_y >= screen.pages.rows) break :cursor; + screen.cursorAbsolute(cursor_x, cursor_y); + } + + // Set cursor shape on this screen + if (data.cursor_shape.len > 0) { + if (std.mem.eql(u8, data.cursor_shape, "block")) { + screen.cursor.cursor_style = .block; + } else if (std.mem.eql(u8, data.cursor_shape, "underline")) { + screen.cursor.cursor_style = .underline; + } else if (std.mem.eql(u8, data.cursor_shape, "bar")) { + screen.cursor.cursor_style = .bar; + } + } + // "default" or unknown: leave as-is + } + + // Set alternate screen saved cursor position + if (t.screens.get(.alternate)) |alt_screen| cursor: { + const alt_x = std.math.cast( + size.CellCountInt, + data.alternate_saved_x, + ) orelse break :cursor; + const alt_y = std.math.cast( + size.CellCountInt, + data.alternate_saved_y, + ) orelse break :cursor; + + // If our coordinates are outside our screen we ignore it. + // tmux actually sends MAX_INT for when there isn't a set + // cursor position, so this isn't theoretical. + if (alt_x >= alt_screen.pages.cols or + alt_y >= alt_screen.pages.rows) break :cursor; + + alt_screen.cursorAbsolute(alt_x, alt_y); + } + + // Set cursor visibility + t.modes.set(.cursor_visible, data.cursor_flag); + + // Set cursor blinking + t.modes.set(.cursor_blinking, data.cursor_blinking); + + // Terminal modes + t.modes.set(.insert, data.insert_flag); + t.modes.set(.wraparound, data.wrap_flag); + t.modes.set(.keypad_keys, data.keypad_flag); + t.modes.set(.cursor_keys, data.keypad_cursor_flag); + t.modes.set(.origin, data.origin_flag); + + // Mouse modes + t.modes.set(.mouse_event_any, data.mouse_all_flag); + t.modes.set(.mouse_event_button, data.mouse_any_flag); + t.modes.set(.mouse_event_normal, data.mouse_button_flag); + t.modes.set(.mouse_event_x10, data.mouse_standard_flag); + t.modes.set(.mouse_format_utf8, data.mouse_utf8_flag); + t.modes.set(.mouse_format_sgr, data.mouse_sgr_flag); + + // Focus and bracketed paste + t.modes.set(.focus_event, data.focus_flag); + t.modes.set(.bracketed_paste, data.bracketed_paste); + + // Scroll region (tmux uses 0-based values) + scroll: { + const scroll_top = std.math.cast( + size.CellCountInt, + data.scroll_region_upper, + ) orelse break :scroll; + const scroll_bottom = std.math.cast( + size.CellCountInt, + data.scroll_region_lower, + ) orelse break :scroll; + t.scrolling_region.top = scroll_top; + t.scrolling_region.bottom = scroll_bottom; + } + + // Tab stops - parse comma-separated list and set + t.tabstops.reset(0); // Clear all tabstops first + if (data.pane_tabs.len > 0) { + var tabs_it = std.mem.splitScalar(u8, data.pane_tabs, ','); + while (tabs_it.next()) |tab_str| { + const col = std.fmt.parseInt(usize, tab_str, 10) catch continue; + const col_cell = std.math.cast(size.CellCountInt, col) orelse continue; + if (col_cell >= t.cols) continue; + t.tabstops.set(col_cell); + } + } + } + } + + fn receivedPaneHistory( + self: *Viewer, + screen_key: ScreenSet.Key, + id: usize, + content: []const u8, + ) !void { + // Get our pane + const entry = self.panes.getEntry(id) orelse { + log.info("received pane history for untracked pane id={}", .{id}); + return; + }; + const pane: *Pane = entry.value_ptr; + const t: *Terminal = &pane.terminal; + _ = try t.switchScreen(screen_key); + const screen: *Screen = t.screens.active; + + // Get a VT stream from the terminal so we can send data as-is into + // it. This will populate the active area too so it won't be exactly + // correct but we'll get the active contents soon. + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice(content); + + // Populate the active area to be empty since this is only history. + // We'll fill it with blanks and move the cursor to the top-left. + t.carriageReturn(); + for (0..t.rows) |_| try t.index(); + t.setCursorPos(1, 1); + + // Our active area should be empty + if (comptime std.debug.runtime_safety) { + var discarding: std.Io.Writer.Discarding = .init(&.{}); + screen.dumpString(&discarding.writer, .{ + .tl = screen.pages.getTopLeft(.active), + .unwrap = false, + }) catch unreachable; + assert(discarding.count == 0); + } + } + + fn receivedPaneVisible( + self: *Viewer, + screen_key: ScreenSet.Key, + id: usize, + content: []const u8, + ) !void { + // Get our pane + const entry = self.panes.getEntry(id) orelse { + log.info("received pane visible for untracked pane id={}", .{id}); + return; + }; + const pane: *Pane = entry.value_ptr; + const t: *Terminal = &pane.terminal; + _ = try t.switchScreen(screen_key); + + // Erase the active area and reset the cursor to the top-left + // before writing the visible content. + t.eraseDisplay(.complete, false); + t.setCursorPos(1, 1); + + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice(content); + } + + fn receivedOutput( + self: *Viewer, + id: usize, + data: []const u8, + ) !void { + const entry = self.panes.getEntry(id) orelse { + log.info("received output for untracked pane id={}", .{id}); + return; + }; + const pane: *Pane = entry.value_ptr; + const t: *Terminal = &pane.terminal; + + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice(data); + } + + fn initLayout( + gpa_alloc: Allocator, + panes_old: *const PanesMap, + panes_new: *PanesMap, + layout: Layout, + ) !void { + switch (layout.content) { + // Nested layouts, continue going. + .horizontal, .vertical => |layouts| { + for (layouts) |l| { + try initLayout( + gpa_alloc, + panes_old, + panes_new, + l, + ); + } + }, + + // A leaf! Initialize. + .pane => |id| pane: { + const gop = try panes_new.getOrPut(gpa_alloc, id); + if (gop.found_existing) break :pane; + errdefer _ = panes_new.swapRemove(gop.key_ptr.*); + + // If we already have this pane, it is already initialized + // so just copy it over. + if (panes_old.getEntry(id)) |entry| { + gop.value_ptr.* = entry.value_ptr.*; + break :pane; + } + + // TODO: We need to gracefully handle overflow of our + // max cols/width here. In practice we shouldn't hit this + // so we cast but its not safe. + var t: Terminal = try .init(gpa_alloc, .{ + .cols = @intCast(layout.width), + .rows = @intCast(layout.height), + }); + errdefer t.deinit(gpa_alloc); + + gop.value_ptr.* = .{ + .terminal = t, + }; + }, + } + } + + /// Enters the command queue state from any other state, queueing + /// the commands and returning an action to execute the first command. + fn enterCommandQueue( + self: *Viewer, + arena_alloc: Allocator, + commands: []const Command, + ) Allocator.Error![]const Action { + assert(self.state != .command_queue); + assert(commands.len > 0); + + // Build our command string to send for the action. + var builder: std.Io.Writer.Allocating = .init(arena_alloc); + commands[0].formatCommand(&builder.writer) catch return error.OutOfMemory; + const action: Action = .{ .command = builder.writer.buffered() }; + + // Add our commands + try self.command_queue.ensureUnusedCapacity(self.alloc, commands.len); + for (commands) |cmd| self.command_queue.appendAssumeCapacity(cmd); + + // Move into the command queue state + self.state = .command_queue; + + return self.singleAction(action); + } + + /// Queue multiple commands to execute. This doesn't add anything + /// to the actions queue or return actions or anything because the + /// command_queue state will automatically send the next command when + /// it receives output. + fn queueCommands( + self: *Viewer, + commands: []const Command, + ) Allocator.Error!void { + try self.command_queue.ensureUnusedCapacity( + self.alloc, + commands.len, + ); + for (commands) |command| { + self.command_queue.appendAssumeCapacity(command); + } + } + + /// Helper to return a single action. The input action may use the arena + /// for allocated memory; this will not touch the arena. + fn singleAction(self: *Viewer, action: Action) []const Action { + // Make our single action slice. + self.action_single[0] = action; + return &self.action_single; + } + + fn defunct(self: *Viewer) []const Action { + self.state = .defunct; + return self.singleAction(.exit); + } +}; + +const State = enum { + /// We start in this state just after receiving the initial + /// DCS 1000p opening sequence. We wait for an initial + /// begin/end block that is guaranteed to be sent by tmux for + /// the initial control mode command. (See tmux server-client.c + /// where control mode starts). + startup_block, + + /// After receiving the initial block, we wait for a session-changed + /// notification to record the initial session ID. + startup_session, + + /// Tmux has closed the control mode connection + defunct, + + /// We're sitting on the command queue waiting for command output + /// in the order provided in the `command_queue` field. This field + /// isn't part of the state because it can be queued at any state. + /// + /// Precondition: if self.command_queue.len > 0, then the first + /// command in the queue has already been sent to tmux (via a + /// `command` Action). The next output is assumed to be the result + /// of this command. + /// + /// To satisfy the above, any transitions INTO this state should + /// send a command Action for the first command in the queue. + command_queue, +}; + +const Command = union(enum) { + /// List all windows so we can sync our window state. + list_windows, + + /// Capture history for the given pane ID. + pane_history: CapturePane, + + /// Capture visible area for the given pane ID. + pane_visible: CapturePane, + + /// Capture the pane terminal state as best we can. The pane ID(s) + /// are part of the output so we can map it back to our panes. + pane_state, + + /// Get the tmux server version. + tmux_version, + + /// User command. This is a command provided by the user. Since + /// this is user provided, we can't be sure what it is. + user: []const u8, + + const CapturePane = struct { + id: usize, + screen_key: ScreenSet.Key, + }; + + pub fn deinit(self: Command, alloc: Allocator) void { + return switch (self) { + .list_windows, + .pane_history, + .pane_visible, + .pane_state, + .tmux_version, + => {}, + .user => |v| alloc.free(v), + }; + } + + /// Format the command into the command that should be executed + /// by tmux. Trailing newlines are appended so this can be sent as-is + /// to tmux. + pub fn formatCommand( + self: Command, + writer: *std.Io.Writer, + ) std.Io.Writer.Error!void { + switch (self) { + .list_windows => try writer.writeAll(std.fmt.comptimePrint( + "list-windows -F '{s}'\n", + .{comptime Format.list_windows.comptimeFormat()}, + )), + + .pane_history => |cap| try writer.print( + // -p = output to stdout instead of buffer + // -e = output escape sequences for SGR + // -a = capture alternate screen (only valid for alternate) + // -q = quiet, don't error if alternate screen doesn't exist + // -S - = start at the top of history ("-") + // -E -1 = end at the last line of history (1 before the + // visible area is -1). + // -t %{d} = target a specific pane ID + "capture-pane -p -e -q {s}-S - -E -1 -t %{d}\n", + .{ + if (cap.screen_key == .alternate) "-a " else "", + cap.id, + }, + ), + + .pane_visible => |cap| try writer.print( + // -p = output to stdout instead of buffer + // -e = output escape sequences for SGR + // -a = capture alternate screen (only valid for alternate) + // -q = quiet, don't error if alternate screen doesn't exist + // -t %{d} = target a specific pane ID + // (no -S/-E = capture visible area only) + "capture-pane -p -e -q {s}-t %{d}\n", + .{ + if (cap.screen_key == .alternate) "-a " else "", + cap.id, + }, + ), + + .pane_state => try writer.writeAll(std.fmt.comptimePrint( + "list-panes -F '{s}'\n", + .{comptime Format.list_panes.comptimeFormat()}, + )), + + .tmux_version => try writer.writeAll(std.fmt.comptimePrint( + "display-message -p '{s}'\n", + .{comptime Format.tmux_version.comptimeFormat()}, + )), + + .user => |v| try writer.writeAll(v), + } + } +}; + +/// Format strings used for commands in our viewer. +const Format = struct { + /// The variables included in this format, in order. + vars: []const output.Variable, + + /// The delimiter to use between variables. This must be a character + /// guaranteed to not appear in any of the variable outputs. + delim: u8, + + const list_panes: Format = .{ + .delim = ';', + .vars = &.{ + .pane_id, + // Cursor position & appearance + .cursor_x, + .cursor_y, + .cursor_flag, + .cursor_shape, + .cursor_colour, + .cursor_blinking, + // Alternate screen + .alternate_on, + .alternate_saved_x, + .alternate_saved_y, + // Terminal modes + .insert_flag, + .wrap_flag, + .keypad_flag, + .keypad_cursor_flag, + .origin_flag, + // Mouse modes + .mouse_all_flag, + .mouse_any_flag, + .mouse_button_flag, + .mouse_standard_flag, + .mouse_utf8_flag, + .mouse_sgr_flag, + // Focus & special features + .focus_flag, + .bracketed_paste, + // Scroll region + .scroll_region_upper, + .scroll_region_lower, + // Tab stops + .pane_tabs, + }, + }; + + const list_windows: Format = .{ + .delim = ' ', + .vars = &.{ + .session_id, + .window_id, + .window_width, + .window_height, + .window_layout, + }, + }; + + const tmux_version: Format = .{ + .delim = ' ', + .vars = &.{.version}, + }; + + /// The format string, available at comptime. + pub fn comptimeFormat(comptime self: Format) []const u8 { + return output.comptimeFormat(self.vars, self.delim); + } + + /// The struct that can contain the parsed output. + pub fn Struct(comptime self: Format) type { + return output.FormatStruct(self.vars); + } +}; + +const TestStep = struct { + input: Viewer.Input, + contains_tags: []const std.meta.Tag(Viewer.Action) = &.{}, + contains_command: []const u8 = "", + check: ?*const fn (viewer: *Viewer, []const Viewer.Action) anyerror!void = null, + check_command: ?*const fn (viewer: *Viewer, []const u8) anyerror!void = null, + + fn run(self: TestStep, viewer: *Viewer) !void { + const actions = viewer.next(self.input); + + // Common mistake, forgetting the newline on a command. + for (actions) |action| { + if (action == .command) { + try testing.expect(std.mem.endsWith(u8, action.command, "\n")); + } + } + + for (self.contains_tags) |tag| { + var found = false; + for (actions) |action| { + if (action == tag) { + found = true; + break; + } + } + try testing.expect(found); + } + + if (self.contains_command.len > 0) { + var found = false; + for (actions) |action| { + if (action == .command and + std.mem.startsWith(u8, action.command, self.contains_command)) + { + found = true; + break; + } + } + try testing.expect(found); + } + + if (self.check) |check_fn| { + try check_fn(viewer, actions); + } + + if (self.check_command) |check_fn| { + var found = false; + for (actions) |action| { + if (action == .command) { + found = true; + try check_fn(viewer, action.command); + } + } + try testing.expect(found); + } + } +}; + +/// A helper to run a series of test steps against a viewer and assert +/// that the expected actions are produced. +/// +/// I'm generally not a fan of these types of abstracted tests because +/// it makes diagnosing failures harder, but being able to construct +/// simulated tmux inputs and verify outputs is going to be extremely +/// important since the tmux control mode protocol is very complex and +/// fragile. +fn testViewer(viewer: *Viewer, steps: []const TestStep) !void { + for (steps, 0..) |step, i| { + step.run(viewer) catch |err| { + log.warn("testViewer step failed i={} step={}", .{ i, step }); + return err; + }; + } +} + +test "immediate exit" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + .{ + .input = .{ .tmux = .exit }, + .check = (struct { + fn check(_: *Viewer, actions: []const Viewer.Action) anyerror!void { + try testing.expectEqual(0, actions.len); + } + }).check, + }, + }); +} + +test "session changed resets state" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial startup + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 1, + .name = "first", + } } }, + .contains_command = "display-message", + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // Receive window layout with two panes (same format as "initial flow" test) + .{ + .input = .{ .tmux = .{ + .block_end = + \\$1 @0 83 44 027b,83x44,0,0[83x20,0,0,0,83x23,0,21,1] + , + } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(1, v.session_id); + try testing.expectEqual(1, v.windows.items.len); + try testing.expectEqual(2, v.panes.count()); + try testing.expectEqualStrings("3.5a", v.tmux_version); + } + }).check, + }, + // Now session changes - should reset everything but keep version + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 2, + .name = "second", + } } }, + .contains_tags = &.{ .windows, .command }, + .contains_command = "list-windows", + .check = (struct { + fn check(v: *Viewer, actions: []const Viewer.Action) anyerror!void { + // Session ID should be updated + try testing.expectEqual(2, v.session_id); + // Windows should be cleared (empty windows action sent) + var found_empty_windows = false; + for (actions) |action| { + if (action == .windows and action.windows.len == 0) { + found_empty_windows = true; + } + } + try testing.expect(found_empty_windows); + // Old windows should be cleared + try testing.expectEqual(0, v.windows.items.len); + // Old panes should be cleared + try testing.expectEqual(0, v.panes.count()); + // Version should still be preserved + try testing.expectEqualStrings("3.5a", v.tmux_version); + } + }).check, + }, + // Receive new window layout for new session (same layout, different session/window) + // Uses same pane IDs 0,1 - they should be re-created since old panes were cleared + .{ + .input = .{ .tmux = .{ + .block_end = + \\$2 @1 83 44 027b,83x44,0,0[83x20,0,0,0,83x23,0,21,1] + , + } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(2, v.session_id); + try testing.expectEqual(1, v.windows.items.len); + try testing.expectEqual(1, v.windows.items[0].id); + // Panes 0 and 1 should be created (fresh, since old ones were cleared) + try testing.expectEqual(2, v.panes.count()); + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "initial flow" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 42, + .name = "main", + } } }, + .contains_command = "display-message", + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(42, v.session_id); + } + }).check, + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqualStrings("3.5a", v.tmux_version); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 83 44 027b,83x44,0,0[83x20,0,0,0,83x23,0,21,1] + , + } }, + .contains_tags = &.{ .windows, .command }, + .contains_command = "capture-pane", + // pane_history for pane 0 (primary) + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %0")); + try testing.expect(!std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ + .block_end = + \\Hello, world! + , + } }, + // Moves on to pane_visible for pane 0 (primary) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %0")); + try testing.expect(!std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + const pane: *Viewer.Pane = v.panes.getEntry(0).?.value_ptr; + const screen: *Screen = pane.terminal.screens.active; + { + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .history = .{} }, + ); + defer testing.allocator.free(str); + try testing.expectEqualStrings("Hello, world!", str); + } + { + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .active = .{} }, + ); + defer testing.allocator.free(str); + try testing.expectEqualStrings("", str); + } + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + // Moves on to pane_history for pane 0 (alternate) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %0")); + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + // Moves on to pane_visible for pane 0 (alternate) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %0")); + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + // Moves on to pane_history for pane 1 (primary) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %1")); + try testing.expect(!std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + // Moves on to pane_visible for pane 1 (primary) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %1")); + try testing.expect(!std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + // Moves on to pane_history for pane 1 (alternate) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %1")); + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + // Moves on to pane_visible for pane 1 (alternate) + .contains_command = "capture-pane", + .check_command = (struct { + fn check(_: *Viewer, command: []const u8) anyerror!void { + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-t %1")); + try testing.expect(std.mem.containsAtLeast(u8, command, 1, "-a")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + }, + .{ + .input = .{ .tmux = .{ .output = .{ .pane_id = 0, .data = "new output" } } }, + .check = (struct { + fn check(v: *Viewer, actions: []const Viewer.Action) anyerror!void { + try testing.expectEqual(0, actions.len); + const pane: *Viewer.Pane = v.panes.getEntry(0).?.value_ptr; + const screen: *Screen = pane.terminal.screens.active; + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .active = .{} }, + ); + defer testing.allocator.free(str); + try testing.expect(std.mem.containsAtLeast(u8, str, 1, "new output")); + } + }).check, + }, + .{ + .input = .{ .tmux = .{ .output = .{ .pane_id = 999, .data = "ignored" } } }, + .check = (struct { + fn check(_: *Viewer, actions: []const Viewer.Action) anyerror!void { + try testing.expectEqual(0, actions.len); + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "layout change" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial startup + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 1, + .name = "test", + } } }, + .contains_command = "display-message", + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // Receive initial window layout with one pane + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 83 44 b7dd,83x44,0,0,0 + , + } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(1, v.windows.items.len); + try testing.expectEqual(1, v.panes.count()); + try testing.expect(v.panes.contains(0)); + } + }).check, + }, + // Complete all capture-pane commands for pane 0 (primary and alternate) + // plus pane_state + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // Now send a layout_change that splits into two panes + .{ + .input = .{ .tmux = .{ .layout_change = .{ + .window_id = 0, + .layout = "e07b,83x44,0,0[83x22,0,0,0,83x21,0,23,2]", + .visible_layout = "e07b,83x44,0,0[83x22,0,0,0,83x21,0,23,2]", + .raw_flags = "*", + } } }, + .contains_tags = &.{.windows}, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + // Should still have 1 window + try testing.expectEqual(1, v.windows.items.len); + // Should now have 2 panes (0 and 2) + try testing.expectEqual(2, v.panes.count()); + try testing.expect(v.panes.contains(0)); + try testing.expect(v.panes.contains(2)); + // Commands should be queued for the new pane (4 capture-pane + 1 pane_state) + try testing.expectEqual(5, v.command_queue.len()); + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "layout_change does not return command when queue not empty" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial startup + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 1, + .name = "test", + } } }, + .contains_command = "display-message", + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // Receive initial window layout with one pane + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 83 44 b7dd,83x44,0,0,0 + , + } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expect(!v.command_queue.empty()); + } + }).check, + }, + // Do NOT complete capture-pane commands - queue still has commands. + // Send a layout_change that splits into two panes. + // This should NOT return a command action since queue was not empty. + .{ + .input = .{ .tmux = .{ .layout_change = .{ + .window_id = 0, + .layout = "e07b,83x44,0,0[83x22,0,0,0,83x21,0,23,2]", + .visible_layout = "e07b,83x44,0,0[83x22,0,0,0,83x21,0,23,2]", + .raw_flags = "*", + } } }, + .contains_tags = &.{.windows}, + .check = (struct { + fn check(v: *Viewer, actions: []const Viewer.Action) anyerror!void { + try testing.expectEqual(2, v.panes.count()); + // Should not contain a command action + for (actions) |action| { + try testing.expect(action != .command); + } + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "layout_change returns command when queue was empty" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial startup + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 1, + .name = "test", + } } }, + .contains_command = "display-message", + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // Receive initial window layout with one pane + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 83 44 b7dd,83x44,0,0,0 + , + } }, + .contains_tags = &.{ .windows, .command }, + }, + // Complete all capture-pane commands for pane 0 + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // Queue should now be empty + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expect(v.command_queue.empty()); + } + }).check, + }, + // Now send a layout_change that splits into two panes. + // This should return a command action since we're queuing commands + // for the new pane and the queue was empty. + .{ + .input = .{ .tmux = .{ .layout_change = .{ + .window_id = 0, + .layout = "e07b,83x44,0,0[83x22,0,0,0,83x21,0,23,2]", + .visible_layout = "e07b,83x44,0,0[83x22,0,0,0,83x21,0,23,2]", + .raw_flags = "*", + } } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(2, v.panes.count()); + try testing.expect(!v.command_queue.empty()); + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "window_add queues list_windows when queue empty" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial startup + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 1, + .name = "test", + } } }, + .contains_command = "display-message", + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // Receive initial window layout with one pane + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 83 44 b7dd,83x44,0,0,0 + , + } }, + .contains_tags = &.{ .windows, .command }, + }, + // Complete all capture-pane commands for pane 0 + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // Queue should now be empty + .{ + .input = .{ .tmux = .{ .block_end = "" } }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expect(v.command_queue.empty()); + } + }).check, + }, + // Now send window_add - should trigger list-windows command + .{ + .input = .{ .tmux = .{ .window_add = .{ .id = 1 } } }, + .contains_command = "list-windows", + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + // Command queue should have list_windows + try testing.expect(!v.command_queue.empty()); + try testing.expectEqual(1, v.command_queue.len()); + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "window_add queues list_windows when queue not empty" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial startup + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 1, + .name = "test", + } } }, + .contains_command = "display-message", + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // Receive initial window layout with one pane + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 83 44 b7dd,83x44,0,0,0 + , + } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + // Queue should have capture-pane commands + try testing.expect(!v.command_queue.empty()); + } + }).check, + }, + // Do NOT complete capture-pane commands - queue still has commands. + // Send window_add - should queue list-windows but NOT return command action + .{ + .input = .{ .tmux = .{ .window_add = .{ .id = 1 } } }, + .check = (struct { + fn check(v: *Viewer, actions: []const Viewer.Action) anyerror!void { + // Should not contain a command action since queue was not empty + for (actions) |action| { + try testing.expect(action != .command); + } + // But list_windows should be in the queue + try testing.expect(!v.command_queue.empty()); + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} + +test "two pane flow with pane state" { + var viewer = try Viewer.init(testing.allocator); + defer viewer.deinit(); + + try testViewer(&viewer, &.{ + // Initial block_end from attach + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // Session changed notification + .{ + .input = .{ .tmux = .{ .session_changed = .{ + .id = 0, + .name = "0", + } } }, + .contains_command = "display-message", + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(0, v.session_id); + } + }).check, + }, + // Receive version response, which triggers list-windows + .{ + .input = .{ .tmux = .{ .block_end = "3.5a" } }, + .contains_command = "list-windows", + }, + // list-windows output with 2 panes in a vertical split + .{ + .input = .{ .tmux = .{ + .block_end = + \\$0 @0 165 79 ca97,165x79,0,0[165x40,0,0,0,165x38,0,41,4] + , + } }, + .contains_tags = &.{ .windows, .command }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + try testing.expectEqual(1, v.windows.items.len); + const window = v.windows.items[0]; + try testing.expectEqual(0, window.id); + try testing.expectEqual(165, window.width); + try testing.expectEqual(79, window.height); + try testing.expectEqual(2, v.panes.count()); + try testing.expect(v.panes.contains(0)); + try testing.expect(v.panes.contains(4)); + } + }).check, + }, + // capture-pane pane 0 primary history + .{ + .input = .{ .tmux = .{ + .block_end = + \\prompt % + \\prompt % + , + } }, + }, + // capture-pane pane 0 primary visible + .{ + .input = .{ .tmux = .{ + .block_end = + \\prompt % + , + } }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + const pane: *Viewer.Pane = v.panes.getEntry(0).?.value_ptr; + const screen: *Screen = pane.terminal.screens.active; + { + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .history = .{} }, + ); + defer testing.allocator.free(str); + // History has 2 lines with "prompt %" (padded to screen width) + try testing.expect(std.mem.containsAtLeast(u8, str, 2, "prompt %")); + } + { + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .active = .{} }, + ); + defer testing.allocator.free(str); + try testing.expectEqualStrings("prompt %", str); + } + } + }).check, + }, + // capture-pane pane 0 alternate history (empty) + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // capture-pane pane 0 alternate visible (empty) + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // capture-pane pane 4 primary history + .{ + .input = .{ .tmux = .{ + .block_end = + \\prompt % + , + } }, + }, + // capture-pane pane 4 primary visible + .{ + .input = .{ .tmux = .{ + .block_end = + \\prompt % + , + } }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + const pane: *Viewer.Pane = v.panes.getEntry(4).?.value_ptr; + const screen: *Screen = pane.terminal.screens.active; + { + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .history = .{} }, + ); + defer testing.allocator.free(str); + try testing.expectEqualStrings("prompt %", str); + } + { + const str = try screen.dumpStringAlloc( + testing.allocator, + .{ .active = .{} }, + ); + defer testing.allocator.free(str); + // Active screen starts with "prompt %" at beginning + try testing.expect(std.mem.startsWith(u8, str, "prompt %")); + } + } + }).check, + }, + // capture-pane pane 4 alternate history (empty) + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // capture-pane pane 4 alternate visible (empty) + .{ .input = .{ .tmux = .{ .block_end = "" } } }, + // list-panes output with terminal state + .{ + .input = .{ .tmux = .{ + .block_end = + \\%0;42;0;1;;;;0;4294967295;4294967295;0;1;0;0;0;0;0;0;0;0;0;;;0;39;8,16,24,32,40,48,56,64,72,80,88,96,104,112,120,128,136,144,152,160 + \\%4;10;5;1;;;;0;4294967295;4294967295;0;1;0;0;0;0;0;0;0;0;0;;;0;37;8,16,24,32,40,48,56,64,72,80,88,96,104,112,120,128,136,144,152,160 + , + } }, + .check = (struct { + fn check(v: *Viewer, _: []const Viewer.Action) anyerror!void { + // Pane 0: cursor at (42, 0), cursor visible, wraparound on + { + const pane: *Viewer.Pane = v.panes.getEntry(0).?.value_ptr; + const t: *Terminal = &pane.terminal; + const screen: *Screen = t.screens.get(.primary).?; + try testing.expectEqual(42, screen.cursor.x); + try testing.expectEqual(0, screen.cursor.y); + try testing.expect(t.modes.get(.cursor_visible)); + try testing.expect(t.modes.get(.wraparound)); + try testing.expect(!t.modes.get(.insert)); + try testing.expect(!t.modes.get(.origin)); + try testing.expect(!t.modes.get(.keypad_keys)); + try testing.expect(!t.modes.get(.cursor_keys)); + } + // Pane 4: cursor at (10, 5), cursor visible, wraparound on + { + const pane: *Viewer.Pane = v.panes.getEntry(4).?.value_ptr; + const t: *Terminal = &pane.terminal; + const screen: *Screen = t.screens.get(.primary).?; + try testing.expectEqual(10, screen.cursor.x); + try testing.expectEqual(5, screen.cursor.y); + try testing.expect(t.modes.get(.cursor_visible)); + try testing.expect(t.modes.get(.wraparound)); + try testing.expect(!t.modes.get(.insert)); + try testing.expect(!t.modes.get(.origin)); + try testing.expect(!t.modes.get(.keypad_keys)); + try testing.expect(!t.modes.get(.cursor_keys)); + } + } + }).check, + }, + .{ + .input = .{ .tmux = .exit }, + .contains_tags = &.{.exit}, + }, + }); +} diff --git a/vendor/libghostty-vt/src/terminal/x11_color.zig b/vendor/libghostty-vt/src/terminal/x11_color.zig new file mode 100644 index 00000000..97f3a7ce --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/x11_color.zig @@ -0,0 +1,69 @@ +const std = @import("std"); +const assert = @import("../quirks.zig").inlineAssert; +const RGB = @import("color.zig").RGB; + +/// The map of all available X11 colors. +pub const map = colorMap(); + +pub const ColorMap = std.StaticStringMapWithEql( + RGB, + std.static_string_map.eqlAsciiIgnoreCase, +); + +fn colorMap() ColorMap { + @setEvalBranchQuota(500_000); + + const KV = struct { []const u8, RGB }; + + // The length of our data is the number of lines in the rgb file. + const len = std.mem.count(u8, data, "\n"); + var kvs: [len]KV = undefined; + + // Parse the line. This is not very robust parsing, because we expect + // a very exact format for rgb.txt. However, this is all done at comptime + // so if our data is bad, we should hopefully get an error here or one + // of our unit tests will catch it. + var iter = std.mem.splitScalar(u8, data, '\n'); + var i: usize = 0; + while (iter.next()) |raw_line| { + // Trim \r so this works with both LF and CRLF line endings, + // since git may convert rgb.txt to CRLF on Windows checkouts. + const line = if (raw_line.len > 0 and raw_line[raw_line.len - 1] == '\r') + raw_line[0 .. raw_line.len - 1] + else + raw_line; + if (line.len == 0) continue; + const r = try std.fmt.parseInt(u8, std.mem.trim(u8, line[0..3], " "), 10); + const g = try std.fmt.parseInt(u8, std.mem.trim(u8, line[4..7], " "), 10); + const b = try std.fmt.parseInt(u8, std.mem.trim(u8, line[8..11], " "), 10); + const name = std.mem.trim(u8, line[12..], " \t"); + kvs[i] = .{ name, .{ .r = r, .g = g, .b = b } }; + i += 1; + } + assert(i == len); + + return .initComptime(kvs); +} + +/// This is the rgb.txt file from the X11 project. This was last sourced +/// from this location: https://gitlab.freedesktop.org/xorg/app/rgb +/// This data is licensed under the MIT/X11 license while this Zig file is +/// licensed under the same license as Ghostty. +const data = @embedFile("res/rgb.txt"); + +test { + const testing = std.testing; + try testing.expectEqual(null, map.get("nosuchcolor")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, map.get("white").?); + try testing.expectEqual(RGB{ .r = 0, .g = 250, .b = 154 }, map.get("medium spring green")); + try testing.expectEqual(RGB{ .r = 34, .g = 139, .b = 34 }, map.get("ForestGreen")); + try testing.expectEqual(RGB{ .r = 34, .g = 139, .b = 34 }, map.get("FoReStGReen")); + try testing.expectEqual(RGB{ .r = 0, .g = 0, .b = 0 }, map.get("black")); + try testing.expectEqual(RGB{ .r = 255, .g = 0, .b = 0 }, map.get("red")); + try testing.expectEqual(RGB{ .r = 0, .g = 255, .b = 0 }, map.get("green")); + try testing.expectEqual(RGB{ .r = 0, .g = 0, .b = 255 }, map.get("blue")); + try testing.expectEqual(RGB{ .r = 255, .g = 255, .b = 255 }, map.get("white")); + try testing.expectEqual(RGB{ .r = 124, .g = 252, .b = 0 }, map.get("lawngreen")); + try testing.expectEqual(RGB{ .r = 0, .g = 250, .b = 154 }, map.get("mediumspringgreen")); + try testing.expectEqual(RGB{ .r = 34, .g = 139, .b = 34 }, map.get("forestgreen")); +} -- cgit v1.2.3