diff options
| author | Can Celik <ogulcancelik@gmail.com> | 2026-09-10 21:51:57 +0300 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-09-10 21:51:57 +0300 |
| commit | 425c86179791cd32e2d4ce0ae7f269940b4b0663 (patch) | |
| tree | e52c4383a6d69216cbe2a32638bf90841d7e2189 /vendor/libghostty-vt/src/terminal/search | |
| parent | 90e947a6e26e02f10ec7f1694c4eb5b78a86406b (diff) | |
chore: upgrade libghostty and preserve terminal behavior (#3906)
Diffstat (limited to 'vendor/libghostty-vt/src/terminal/search')
7 files changed, 1287 insertions, 544 deletions
diff --git a/vendor/libghostty-vt/src/terminal/search/Thread.zig b/vendor/libghostty-vt/src/terminal/search/Thread.zig index d7f0d562..0b781321 100644 --- a/vendor/libghostty-vt/src/terminal/search/Thread.zig +++ b/vendor/libghostty-vt/src/terminal/search/Thread.zig @@ -12,9 +12,9 @@ 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 Mutex = std.Io.Mutex; +const global = @import("../../global.zig"); +const xev = global.xev; const internal_os = @import("../../os/main.zig"); const BlockingQueue = @import("../../datastruct/main.zig").BlockingQueue; const MessageData = @import("../../datastruct/main.zig").MessageData; @@ -22,11 +22,10 @@ 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 TerminalSearch = @import("terminal.zig").TerminalSearch; const log = std.log.scoped(.search_thread); @@ -71,7 +70,10 @@ refresh_active: bool = false, /// Search state. Starts as null and is populated when a search is /// started (a needle is given). -search: ?Search = null, +search: ?TerminalSearch = null, + +/// The last-notified values used to diff search state into events. +notify_state: NotifyState = .{}, /// The options used to initialize this thread. opts: Options, @@ -122,8 +124,8 @@ pub fn deinit(self: *Thread) void { self.mailbox.destroy(self.alloc); if (self.search) |*s| { - self.opts.mutex.lock(); - defer self.opts.mutex.unlock(); + self.opts.mutex.lockUncancelable(global.io()); + defer self.opts.mutex.unlock(global.io()); s.deinit(self.opts.terminal); } } @@ -182,14 +184,14 @@ fn threadMain_(self: *Thread) !void { while (true) { // If our loop is canceled then we drain our messages and quit. if (self.loop.stopped()) { - while (self.mailbox.pop()) |message| { + while (self.mailbox.pop(global.io())) |message| { log.debug("mailbox message ignored during shutdown={}", .{message}); } return; } - const s: *Search = if (self.search) |*s| s else { + const s: *TerminalSearch = 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); @@ -200,11 +202,7 @@ fn threadMain_(self: *Thread) !void { // 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, - ); + self.notify(s, cb, self.opts.event_userdata); } if (s.isComplete()) { @@ -225,9 +223,9 @@ fn threadMain_(self: *Thread) !void { // 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); + self.opts.mutex.lockUncancelable(global.io()); + defer self.opts.mutex.unlock(global.io()); + self.feedLocked(s); }, } @@ -240,9 +238,24 @@ fn threadMain_(self: *Thread) !void { } } +/// Feed the search from the terminal state. The terminal mutex must +/// be held by the caller. +fn feedLocked(self: *Thread, s: *TerminalSearch) void { + const t = self.opts.terminal; + + // 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 the active area must be + // re-scanned. + const active_dirty = t.flags.search_viewport_dirty; + t.flags.search_viewport_dirty = false; + + s.feed(t, active_dirty); +} + /// Drain the mailbox. fn drainMailbox(self: *Thread) !void { - while (self.mailbox.pop()) |message| { + while (self.mailbox.pop(global.io())) |message| { log.debug("mailbox message={}", .{message}); switch (message) { .change_needle => |v| { @@ -257,54 +270,15 @@ fn drainMailbox(self: *Thread) !void { fn select(self: *Thread, sel: ScreenSearch.Select) !void { const s = if (self.search) |*s| s else return; - self.opts.mutex.lock(); - defer self.opts.mutex.unlock(); - - // A screen can be removed or replaced between refresh ticks. Reconcile - // while holding the terminal lock before touching any ScreenSearch pins. - s.feed(self.alloc, self.opts.terminal); - const screen_search = s.screens.getPtr(s.last_screen.key) orelse return; - - // 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; - } - } + self.opts.mutex.lockUncancelable(global.io()); + defer self.opts.mutex.unlock(global.io()); - screen.scroll(.{ .pin = flattened.startPin() }); + if (try s.select(self.opts.terminal, sel, .if_needed)) { + // 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. + self.notify_state.selected = null; + } } /// Change the search term to the given value. @@ -314,14 +288,15 @@ fn changeNeedle(self: *Thread, needle: []const u8) !void { // Stop the previous search if (self.search) |*s| { // If our search is unchanged, do nothing. - if (std.ascii.eqlIgnoreCase(s.viewport.needle(), needle)) return; + if (std.ascii.eqlIgnoreCase(s.needle(), needle)) return; { - self.opts.mutex.lock(); - defer self.opts.mutex.unlock(); + self.opts.mutex.lockUncancelable(global.io()); + defer self.opts.mutex.unlock(global.io()); s.deinit(self.opts.terminal); } self.search = null; + self.notify_state = .{}; // When the search changes then we need to emit that it stopped. if (self.opts.event_cb) |cb| { @@ -345,11 +320,98 @@ fn changeNeedle(self: *Thread, needle: []const u8) !void { // Setup our search state. self.search = try .init(self.alloc, needle); + self.notify_state = .{}; // 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); + self.opts.mutex.lockUncancelable(global.io()); + defer self.opts.mutex.unlock(global.io()); + self.feedLocked(&self.search.?); +} + +/// Notify about any changes to the search state by diffing against +/// the last-notified values. +/// +/// This doesn't require any locking as it only reads search-owned state. +fn notify( + self: *Thread, + s: *TerminalSearch, + cb: EventCallback, + ud: ?*anyopaque, +) void { + const state = &self.notify_state; + + // A screen switch makes all previously notified per-screen state + // stale, so reset it to force recalculations and notifications. + if (state.key != s.active_key) { + state.key = s.active_key; + state.total = null; + state.selected = null; + } + + const screen_search = s.activeScreenSearch() orelse return; + + // Check our total match data + const total = screen_search.matchesLen(); + if (total != state.total) { + log.debug("notifying total matches={}", .{total}); + state.total = total; + cb(.{ .total_matches = total }, ud); + } + + // Check our viewport matches. If they're stale, we collect them + // 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 (s.stale_viewport_matches) viewport: { + const matches = s.viewportMatches() catch |err| { + log.warn("error collecting viewport matches err={}", .{err}); + break :viewport; + }; + + log.debug("notifying viewport matches len={}", .{matches.len}); + cb(.{ .viewport_matches = matches }, 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 (state.selected) |prev| { + if (prev.idx == m.idx and prev.highlight.eql(untracked)) { + // Same selection, don't update it. + break :match; + } + } + + // New selection, notify! + state.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 (state.selected != null) { + log.debug("notifying selection cleared", .{}); + state.selected = null; + cb( + .{ .selected_match = null }, + ud, + ); + } + + // Send our complete notification if we just completed. + if (!state.complete and s.isComplete()) { + log.debug("notifying search complete", .{}); + state.complete = true; + cb(.complete, ud); + } } fn startRefreshTimer(self: *Thread) void { @@ -423,9 +485,9 @@ fn refreshCallback( // 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); + self.opts.mutex.lockUncancelable(global.io()); + defer self.opts.mutex.unlock(global.io()); + self.feedLocked(s); } // Only continue if we're still active @@ -501,357 +563,30 @@ pub const Event = union(enum) { }; }; -/// 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), +/// The last-notified values used by `notify` to diff search state +/// into events. +const NotifyState = struct { + /// The active screen key the state below was captured against. + key: ScreenSet.Key = .primary, - /// ScreenSet generations captured when each searcher was initialized. - /// Allocators may reuse a destroyed Screen address, so pointer equality - /// alone cannot distinguish replacement screens from stale handles. - screen_generations: std.EnumMap(ScreenSet.Key, usize), + /// Last notified total matches count + total: ?usize = null, - /// All state related to screen switches, collected so that when - /// we switch screens it makes everything related stale, too. - last_screen: ScreenState, + /// Last notified selected match + selected: ?Selected = null, /// 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(.{}), - .screen_generations = .init(.{}), - .last_screen = .{ .key = .primary }, - .last_complete = false, - .stale_viewport_matches = true, - }; - } + complete: bool = false, - pub fn deinit(self: *Search, t: *Terminal) void { - self.viewport.deinit(); - var it = self.screens.iterator(); - while (it.next()) |entry| { - if (self.screenIsValid(&t.screens, entry.key, entry.value)) { - entry.value.deinit(); - } else { - entry.value.deinitScreenInvalid(); - } - } - } - - fn screenIsValid( - self: *const Search, - screens: *const ScreenSet, - key: ScreenSet.Key, - search: *const ScreenSearch, - ) bool { - const generation = self.screen_generations.get(key) orelse return false; - if (generation != screens.generation(key)) return false; - const actual = screens.get(key) orelse return false; - return actual == search.screen; - } - - /// 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, + const Selected = struct { + idx: usize, + highlight: UntrackedHighlight, }; - - /// 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 = !self.screenIsValid( - &t.screens, - entry.key, - entry.value, - ); - - if (remove) { - entry.value.deinitScreenInvalid(); - _ = self.screens.remove(entry.key); - _ = self.screen_generations.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; - const screen_search = 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; - }, - }; - self.screens.put(entry.key, screen_search); - self.screen_generations.put( - entry.key, - t.screens.generation(entry.key), - ); - } - } - - // 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 = .{}, + reset: std.Io.Event = .unset, total: usize = 0, selected: ?Event.SelectedMatch = null, viewport: []FlattenedHighlight = &.{}, @@ -865,7 +600,7 @@ const TestUserData = struct { const ud: *Self = @ptrCast(@alignCast(userdata.?)); switch (event) { .quit => {}, - .complete => ud.reset.set(), + .complete => ud.reset.set(global.io()), .total_matches => |v| ud.total = v, .selected_match => |v| ud.selected = v, .viewport_matches => |v| { @@ -886,8 +621,9 @@ const TestUserData = struct { test { const alloc = testing.allocator; - var mutex: std.Thread.Mutex = .{}; - var t: Terminal = try .init(alloc, .{ .cols = 20, .rows = 2 }); + const io = testing.io; + var mutex: std.Io.Mutex = .init; + var t: Terminal = try .init(io, alloc, .{ .cols = 20, .rows = 2 }); defer t.deinit(alloc); var stream = t.vtStream(); @@ -912,6 +648,7 @@ test { // Start our search _ = thread.mailbox.push( + io, .{ .change_needle = try .init( alloc, @as([]const u8, "world"), @@ -921,7 +658,7 @@ test { try thread.wakeup.notify(); // Wait for completion - try ud.reset.timedWait(100 * std.time.ns_per_ms); + try ud.reset.waitTimeout(testing.io, .{ .duration = .{ .clock = .awake, .raw = .fromMilliseconds(100) } }); // Stop the thread try thread.stop.notify(); @@ -942,32 +679,3 @@ test { } }, t.screens.active.pages.pointFromPin(.screen, sel.end).?); } } - -test "select after active screen removal" { - const alloc = testing.allocator; - var mutex: std.Thread.Mutex = .{}; - var t: Terminal = try .init(alloc, .{ .cols = 20, .rows = 2 }); - defer t.deinit(alloc); - - _ = try t.switchScreen(.alternate); - - var search: Search = try .init(alloc, "needle"); - search.feed(alloc, &t); - try testing.expectEqual(ScreenSet.Key.alternate, search.last_screen.key); - try testing.expect(search.screens.contains(.alternate)); - - var thread: Thread = undefined; - thread.search = search; - thread.opts = .{ - .mutex = &mutex, - .terminal = &t, - }; - defer if (thread.search) |*active| active.deinit(&t); - - _ = try t.switchScreen(.primary); - t.screens.remove(alloc, .alternate); - - try thread.select(.next); - try testing.expectEqual(ScreenSet.Key.primary, thread.search.?.last_screen.key); - try testing.expect(!thread.search.?.screens.contains(.alternate)); -} diff --git a/vendor/libghostty-vt/src/terminal/search/active.zig b/vendor/libghostty-vt/src/terminal/search/active.zig index b99b2357..b37f46d2 100644 --- a/vendor/libghostty-vt/src/terminal/search/active.zig +++ b/vendor/libghostty-vt/src/terminal/search/active.zig @@ -103,7 +103,8 @@ pub const ActiveSearch = struct { test "simple search" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -143,7 +144,8 @@ test "simple search" { test "clear screen and search" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); diff --git a/vendor/libghostty-vt/src/terminal/search/pagelist.zig b/vendor/libghostty-vt/src/terminal/search/pagelist.zig index 98a24c18..a5ee402e 100644 --- a/vendor/libghostty-vt/src/terminal/search/pagelist.zig +++ b/vendor/libghostty-vt/src/terminal/search/pagelist.zig @@ -147,7 +147,8 @@ pub const PageListSearch = struct { test "simple search" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -194,7 +195,8 @@ test "simple search" { test "feed multiple pages with matches" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -238,7 +240,8 @@ test "feed multiple pages with matches" { test "feed multiple pages no matches" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -277,7 +280,8 @@ test "feed multiple pages no matches" { test "feed iteratively through multiple matches" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 80, .rows = 24 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 80, .rows = 24 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -318,7 +322,8 @@ test "feed iteratively through multiple matches" { test "feed with match spanning page boundary" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 80, .rows = 24 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 80, .rows = 24 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -372,10 +377,11 @@ test "feed with match spanning page boundary" { test "compressed history match spanning page boundary remains compressed" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 80, .rows = 24, - .max_scrollback = 10 * 1024 * 1024, + .max_scrollback_bytes = 10 * 1024 * 1024, }); defer t.deinit(alloc); @@ -442,7 +448,8 @@ test "compressed history match spanning page boundary remains compressed" { test "feed with match spanning page boundary with newline" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 80, .rows = 24 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 80, .rows = 24 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -480,7 +487,11 @@ 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); + var p: PageList = try .init(alloc, .{ + .cols = 80, + .rows = 24, + .max_size = 0, + }); defer p.deinit(); // Grow to capacity @@ -523,7 +534,10 @@ test "feed with pruned page" { test "feed keeps its tracked pin within a shorter page" { const alloc = testing.allocator; - var pages: PageList = try .init(alloc, 10, 2, null); + var pages: PageList = try .init(alloc, .{ + .cols = 10, + .rows = 2, + }); defer pages.deinit(); const first = pages.pages.first.?; @@ -548,3 +562,60 @@ test "feed keeps its tracked pin within a shorter page" { try testing.expectEqual(shorter, search.pin.node); try testing.expect(pages.pinIsValid(search.pin.*)); } + +test "feed discovers pages prepended after exhaustion" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ + .cols = 10, + .rows = 10, + .max_scrollback_bytes = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + + var s = t.vtStream(); + defer s.deinit(); + s.nextSlice("Fizz"); + + // Exhaust the list: one match on the only page and nothing left to feed. + const pages = &t.screens.active.pages; + var search: PageListSearch = try .init( + alloc, + "Fizz", + pages, + pages.pages.last.?, + ); + defer search.deinit(); + try testing.expect(search.next() != null); + try testing.expect(search.next() == null); + try testing.expect(!try search.feed()); + + // Prepend an older page the way incremental snapshot history restore + // does. The frontier pin names the page that used to be first, and + // finalize keeps that node's identity, so the pin now has a `prev`. + const old_first = pages.pages.first.?; + { + var allocation = try pages.allocatePage(.{ .cols = 10, .rows = 2 }); + defer allocation.deinit(); + const page = allocation.page(); + page.size.rows = 2; + for ("Fizz", 0..) |c, x| page.getRowAndCell(x, 1).cell.* = .init(c); + try allocation.finalize(.prepend); + } + const prepended = pages.pages.first.?; + try testing.expect(prepended != old_first); + try testing.expectEqual(old_first, search.pin.node); + + // Feeding resumes into the restored history and finds its match. + try testing.expect(try search.feed()); + try testing.expectEqual(prepended, search.pin.node); + const h = search.next().?; + const sel = h.untracked(); + try testing.expectEqual(prepended, sel.start.node); + try testing.expectEqual(prepended, sel.end.node); + try testing.expectEqual(@as(size.CellCountInt, 1), sel.start.y); + try testing.expectEqual(@as(size.CellCountInt, 0), sel.start.x); + try testing.expectEqual(@as(size.CellCountInt, 3), sel.end.x); + try testing.expect(search.next() == null); + 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 index e0cd9911..ac6d2361 100644 --- a/vendor/libghostty-vt/src/terminal/search/screen.zig +++ b/vendor/libghostty-vt/src/terminal/search/screen.zig @@ -124,7 +124,9 @@ pub const ScreenSearch = struct { .history_feed => true, // Not obvious but complete search states will prune - // stale history results on feed. + // stale history results on feed, and pick up pages + // prepended below the searched frontier since the last + // feed (incremental snapshot history restore). .complete => true, else => false, @@ -305,6 +307,11 @@ pub const ScreenSearch = struct { /// /// Feed on a complete screen search will perform some cleanup of /// potentially stale history results (pruned) and reclaim some memory. + /// + /// If pages were prepended to the PageList since the search completed + /// (incremental snapshot history restore), the feed picks them up and + /// the search resumes, since "complete" only ever means caught up with + /// the PageList as of the last feed. pub fn feed(self: *ScreenSearch) Allocator.Error!void { // Resize/reflow invalidates every flattened result, not just search // state that needs another history feed. @@ -338,9 +345,13 @@ pub const ScreenSearch = struct { // 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, + // A complete search had exhausted the PageList as of its last + // feed, but pages can still be prepended below that afterward + // (incremental snapshot history restore). The history searcher's + // tracked pin keeps its node identity through a prepend, so it + // just discovered those older pages and loaded them. Resume + // searching history. + .complete => self.state = .history, } } @@ -765,24 +776,33 @@ pub const ScreenSearch = struct { } } - /// Return the selected match. + /// Return the match at the given index in newest-to-oldest order + /// (0 = most recent match). Returns null if the index is out of + /// range. /// /// 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; + pub fn matchAt(self: *const ScreenSearch, idx: usize) ?FlattenedHighlight { const active_len = self.active_results.items.len; - if (sel.idx < active_len) { - return self.active_results.items[active_len - 1 - sel.idx]; + if (idx < active_len) { + return self.active_results.items[active_len - 1 - 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]; + if (idx < active_len + history_len) { + return self.history_results.items[idx - active_len]; } return null; } + /// 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; + return self.matchAt(sel.idx); + } + pub const Select = enum { /// Next selection, in reverse order (newest to oldest), /// non-wrapping. @@ -928,7 +948,8 @@ pub const ScreenSearch = struct { test "simple search" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -972,10 +993,11 @@ test "simple search" { test "simple search with history" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1013,10 +1035,11 @@ test "simple search with history" { test "reload active with history change" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1099,7 +1122,8 @@ test "reload active with history change" { test "active change contents" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 5 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 5 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1139,7 +1163,8 @@ test "active change contents" { test "select next" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1198,10 +1223,11 @@ test "select next" { test "select after resize resets stale flattened results" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 3, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); @@ -1232,7 +1258,8 @@ test "select after resize resets stale flattened results" { test "select in active changes contents completely" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 5 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 5 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1296,10 +1323,11 @@ test "select in active changes contents completely" { test "select into history" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1368,7 +1396,8 @@ test "select into history" { test "select prev" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1427,7 +1456,8 @@ test "select prev" { test "select prev then next" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1471,10 +1501,11 @@ test "select prev then next" { test "select prev with history" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1525,10 +1556,11 @@ test "select prev wraps when all matches are in history" { // has none, so active_len == 0), selecting prev from index 0 must wrap // to the last result without underflowing `active_len - 1`. const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1561,7 +1593,8 @@ test "select after all matches disappear drops the selection" { // reload/prune empties the results, the selection is dropped, so the next // select() hits the "no matches" guard instead of the wrap arithmetic. const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1588,10 +1621,11 @@ test "select after all matches disappear drops the selection" { test "select after partial history erase drops a pruned selection" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1620,10 +1654,11 @@ test "select after partial history erase drops a pruned selection" { test "select after history compaction ignores replaced results" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1654,10 +1689,11 @@ test "select after history compaction ignores replaced results" { test "select after partial history page erase ignores shifted results" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1687,10 +1723,11 @@ test "select after partial history page erase ignores shifted results" { test "reload defers pruning unselected history results" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1721,10 +1758,11 @@ test "reload defers pruning unselected history results" { test "reload after partial history page erase drops shifted selection first" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1759,10 +1797,11 @@ test "reload after partial history page erase drops shifted selection first" { test "select after history page split ignores moved results" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1792,10 +1831,11 @@ test "select after history page split ignores moved results" { test "screen search no scrollback has no history" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = 0, + .max_scrollback_bytes = 0, }); defer t.deinit(alloc); @@ -1828,10 +1868,11 @@ 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, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1875,10 +1916,11 @@ test "reloadActive partial history cleanup on loop append error" { // (after some items have been appended), all FlattenedHighlight items // are properly cleaned up. const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1921,10 +1963,11 @@ 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, .{ + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2, - .max_scrollback = std.math.maxInt(usize), + .max_scrollback_bytes = std.math.maxInt(usize), }); defer t.deinit(alloc); const list: *PageList = &t.screens.active.pages; @@ -1960,3 +2003,124 @@ test "select after clearing scrollback" { _ = try search.select(.next); _ = try search.select(.prev); } + +test "feed after complete discovers prepended history pages" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback_bytes = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + const list: *PageList = &t.screens.active.pages; + + var s = t.vtStream(); + defer s.deinit(); + + // The screen begins with the tail of the needle so a restored page which + // soft-wraps into it can complete a match across the restore boundary. + s.nextSlice("st\r\nTest\r\n"); + while (list.totalPages() < 2) s.nextSlice("\r\n"); + for (0..list.rows) |_| s.nextSlice("\r\n"); + s.nextSlice("Test"); + const old_first = list.pages.first.?; + + // Search to completion, then select the oldest match so we can verify + // that restored (older) results never move an existing selection. + var search: ScreenSearch = try .init(alloc, t.screens.active, "Test"); + defer search.deinit(); + try search.searchAll(); + try testing.expect(search.state.isComplete()); + try testing.expectEqual(1, search.active_results.items.len); + try testing.expectEqual(1, search.history_results.items.len); + try testing.expect(try search.select(.prev)); + const selected_idx = search.selected.?.idx; + try testing.expectEqual(1, selected_idx); + const selected_before = search.selectedMatch().?.untracked(); + try testing.expectEqual(old_first, selected_before.start.node); + + // Restore the newest history page: a full match on its first row and a + // soft-wrapped last row ending in "Te" which joins the screen's "st". + { + var allocation = try list.allocatePage(.{ .cols = 10, .rows = 2 }); + defer allocation.deinit(); + const page = allocation.page(); + page.size.rows = 2; + for ("Test", 0..) |c, x| page.getRowAndCell(x, 0).cell.* = .init(c); + for ("xxxxxxxxTe", 0..) |c, x| page.getRowAndCell(x, 1).cell.* = .init(c); + page.getRow(1).wrap = true; + old_first.page().getRow(0).wrap_continuation = true; + try allocation.finalize(.prepend); + } + const newest = list.pages.first.?; + + // The completed search is fed like any periodic refresh. It must pick + // the page up and go back to searching rather than staying complete. + try search.feed(); + try testing.expect(!search.state.isComplete()); + try search.searchAll(); + try testing.expectEqual(1, search.active_results.items.len); + try testing.expectEqual(3, search.history_results.items.len); + + // New results are older than everything cached, so they append in + // newest-to-oldest order: the boundary match first, then the row above. + { + const boundary = search.history_results.items[1].untracked(); + try testing.expectEqual(newest, boundary.start.node); + try testing.expectEqual(old_first, boundary.end.node); + try testing.expectEqual(@as(size.CellCountInt, 1), boundary.start.y); + try testing.expectEqual(@as(size.CellCountInt, 8), boundary.start.x); + try testing.expectEqual(@as(size.CellCountInt, 0), boundary.end.y); + try testing.expectEqual(@as(size.CellCountInt, 1), boundary.end.x); + const str = try t.screens.active.selectionString(alloc, .{ + .sel = .init(boundary.start, boundary.end, false), + }); + defer alloc.free(str); + try testing.expectEqualStrings("Test", str); + } + { + const oldest = search.history_results.items[2].untracked(); + try testing.expectEqual(newest, oldest.start.node); + try testing.expectEqual(@as(size.CellCountInt, 0), oldest.start.y); + try testing.expectEqual(@as(size.CellCountInt, 0), oldest.start.x); + } + + // The selection kept both its index and its target. + try testing.expectEqual(selected_idx, search.selected.?.idx); + { + const selected_after = search.selectedMatch().?.untracked(); + try testing.expect(selected_before.start.eql(selected_after.start)); + try testing.expect(selected_before.end.eql(selected_after.end)); + } + + // Restore an even older page. Each incremental step is discovered from + // the frontier left behind by the previous one. + { + var allocation = try list.allocatePage(.{ .cols = 10, .rows = 2 }); + defer allocation.deinit(); + const page = allocation.page(); + page.size.rows = 2; + for ("Test", 0..) |c, x| page.getRowAndCell(x, 0).cell.* = .init(c); + try allocation.finalize(.prepend); + } + const oldest_node = list.pages.first.?; + try search.feed(); + try search.searchAll(); + try testing.expectEqual(4, search.history_results.items.len); + try testing.expectEqual( + oldest_node, + search.history_results.items[3].untracked().start.node, + ); + try testing.expectEqual(selected_idx, search.selected.?.idx); + { + const selected_after = search.selectedMatch().?.untracked(); + try testing.expect(selected_before.start.eql(selected_after.start)); + try testing.expect(selected_before.end.eql(selected_after.end)); + } + + // With nothing new, a feed on the complete search stays complete. + try search.feed(); + try testing.expect(search.state.isComplete()); + try testing.expectEqual(5, search.matchesLen()); +} diff --git a/vendor/libghostty-vt/src/terminal/search/sliding_window.zig b/vendor/libghostty-vt/src/terminal/search/sliding_window.zig index 2f858ec8..95b37d73 100644 --- a/vendor/libghostty-vt/src/terminal/search/sliding_window.zig +++ b/vendor/libghostty-vt/src/terminal/search/sliding_window.zig @@ -714,14 +714,15 @@ test "SlidingWindow empty on init" { test "SlidingWindow empty needle has no matches" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, ""); defer w.deinit(); - var s = try Screen.init(alloc, .{ + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, - .max_scrollback = 0, + .max_scrollback_bytes = 0, }); defer s.deinit(); try s.testWriteString("hello"); @@ -733,11 +734,12 @@ test "SlidingWindow empty needle has no matches" { test "SlidingWindow single append" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "boo!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("hello. boo! hello. boo!"); @@ -778,11 +780,12 @@ test "SlidingWindow single append" { test "SlidingWindow single append case insensitive ASCII" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "Boo!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("hello. boo! hello. boo!"); @@ -823,11 +826,12 @@ test "SlidingWindow single append case insensitive ASCII" { test "SlidingWindow single append single char" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "b"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("hello. boo! hello. boo!"); @@ -868,11 +872,12 @@ test "SlidingWindow single append single char" { test "SlidingWindow single append no match" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "nope!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("hello. boo! hello. boo!"); @@ -892,11 +897,12 @@ test "SlidingWindow single append no match" { test "SlidingWindow two pages" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "boo!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -947,11 +953,12 @@ test "SlidingWindow two pages" { test "SlidingWindow two pages single char" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "b"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1002,11 +1009,12 @@ test "SlidingWindow two pages single char" { test "SlidingWindow two pages match across boundary" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; 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 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1047,11 +1055,12 @@ test "SlidingWindow two pages match across boundary" { test "SlidingWindow two pages no match across boundary with newline" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; 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 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1080,11 +1089,12 @@ test "SlidingWindow two pages no match across boundary with newline" { test "SlidingWindow two pages no match across boundary with newline reverse" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; 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 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1110,11 +1120,12 @@ test "SlidingWindow two pages no match across boundary with newline reverse" { test "SlidingWindow two pages no match prunes first page" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "nope!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1145,8 +1156,9 @@ test "SlidingWindow two pages no match prunes first page" { test "SlidingWindow two pages no match keeps both pages" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1185,11 +1197,12 @@ test "SlidingWindow two pages no match keeps both pages" { test "SlidingWindow single append across circular buffer boundary" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "abc"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("XXXXXXXXXXXXXXXXXXXboo!XXXXX"); @@ -1241,11 +1254,12 @@ test "SlidingWindow single append across circular buffer boundary" { test "SlidingWindow single append match on boundary" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "abcd"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("o!XXXXXXXXXXXXXXXXXXXbo"); @@ -1300,11 +1314,12 @@ test "SlidingWindow single append match on boundary" { test "SlidingWindow single append reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "boo!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("hello. boo! hello. boo!"); @@ -1345,11 +1360,12 @@ test "SlidingWindow single append reversed" { test "SlidingWindow single append no match reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "nope!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("hello. boo! hello. boo!"); @@ -1369,11 +1385,12 @@ test "SlidingWindow single append no match reversed" { test "SlidingWindow two pages reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "boo!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1424,11 +1441,12 @@ test "SlidingWindow two pages reversed" { test "SlidingWindow two pages match across boundary reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; 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 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1479,11 +1497,12 @@ test "SlidingWindow two pages match across boundary reversed" { test "SlidingWindow two pages no match prunes first page reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "nope!"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1514,8 +1533,9 @@ test "SlidingWindow two pages no match prunes first page reversed" { test "SlidingWindow two pages no match keeps both pages reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 1000 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 1000 }); defer s.deinit(); // Fill up the first page. The final bytes in the first page @@ -1554,11 +1574,12 @@ test "SlidingWindow two pages no match keeps both pages reversed" { test "SlidingWindow single append across circular buffer boundary reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "abc"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("XXXXXXXXXXXXXXXXXXXboo!XXXXX"); @@ -1611,11 +1632,12 @@ test "SlidingWindow single append across circular buffer boundary reversed" { test "SlidingWindow single append match on boundary reversed" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "abcd"); defer w.deinit(); - var s = try Screen.init(alloc, .{ .cols = 80, .rows = 24, .max_scrollback = 0 }); + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, .max_scrollback_bytes = 0 }); defer s.deinit(); try s.testWriteString("o!XXXXXXXXXXXXXXXXXXXbo"); @@ -1671,11 +1693,12 @@ test "SlidingWindow single append match on boundary reversed" { test "SlidingWindow single append soft wrapped" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "boo!"); defer w.deinit(); - var t: Terminal = try .init(alloc, .{ .cols = 4, .rows = 5 }); + var t: Terminal = try .init(io, alloc, .{ .cols = 4, .rows = 5 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1708,11 +1731,12 @@ test "SlidingWindow single append soft wrapped" { test "SlidingWindow single append reversed soft wrapped" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .reverse, "boo!"); defer w.deinit(); - var t: Terminal = try .init(alloc, .{ .cols = 4, .rows = 5 }); + var t: Terminal = try .init(io, alloc, .{ .cols = 4, .rows = 5 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -1747,14 +1771,15 @@ test "SlidingWindow single append reversed soft wrapped" { test "SlidingWindow append whitespace only node" { const testing = std.testing; const alloc = testing.allocator; + const io = testing.io; var w: SlidingWindow = try .init(alloc, .forward, "x"); defer w.deinit(); - var s = try Screen.init(alloc, .{ + var s = try Screen.init(io, alloc, .{ .cols = 80, .rows = 24, - .max_scrollback = 0, + .max_scrollback_bytes = 0, }); defer s.deinit(); diff --git a/vendor/libghostty-vt/src/terminal/search/terminal.zig b/vendor/libghostty-vt/src/terminal/search/terminal.zig new file mode 100644 index 00000000..19f059c6 --- /dev/null +++ b/vendor/libghostty-vt/src/terminal/search/terminal.zig @@ -0,0 +1,767 @@ +const std = @import("std"); +const testing = std.testing; +const Allocator = std.mem.Allocator; +const point = @import("../point.zig"); +const FlattenedHighlight = @import("../highlight.zig").Flattened; +const ScreenSet = @import("../ScreenSet.zig"); +const Terminal = @import("../Terminal.zig"); + +const ScreenSearch = @import("screen.zig").ScreenSearch; +const ViewportSearch = @import("viewport.zig").ViewportSearch; + +const log = std.log.scoped(.search_terminal); + +/// Searches for a needle within an entire Terminal, orchestrating a +/// ScreenSearch per live screen plus a viewport search for the active +/// screen. +/// +/// This reconciles per-screen searchers against the terminal's active +/// ScreenSet, retains results across primary/alt screen switches, and +/// recovers from resize/reflow, resets, scrollback pruning, etc. +/// +/// The main ownership contract is that this is safe to call concurrently +/// with Terminal IO as long as you're not calling a function that takes +/// a terminal as an argument. Each function has more specific details about +/// its behavior. +pub const TerminalSearch = struct { + /// Allocator used for all search state. + alloc: Allocator, + + /// Active viewport search for the active screen. + viewport: ViewportSearch, + + /// The searchers for all the screens. + screens: std.EnumMap(ScreenSet.Key, ScreenSearch), + + /// ScreenSet generations captured when each searcher was initialized. + /// Allocators may reuse a destroyed Screen address, so pointer equality + /// alone cannot distinguish replacement screens from stale handles. + screen_generations: std.EnumMap(ScreenSet.Key, usize), + + /// The active screen key as of the last feed. All single-screen + /// reads (total matches, selection, etc.) resolve against this. + active_key: ScreenSet.Key, + + /// True when the cached viewport matches are stale and must be + /// recollected from the viewport searcher on the next + /// `viewportMatches` call. + stale_viewport_matches: bool, + + /// Cached viewport matches. The viewport search's sliding window + /// drains on read, so results are collected once per viewport + /// change and cached here. + viewport_matches: std.ArrayList(FlattenedHighlight), + + /// Overall status of the search. See `status`. + pub const Status = enum { + /// `tick` can make progress without terminal access. + running, + + /// Blocked until the next `feed`. This is also the initial + /// state, since a search that has never been fed has never + /// seen the terminal. + feed_required, + + /// Caught up with the terminal state as of the last feed. + complete, + }; + + /// Viewport scroll behavior applied by `select` when a match + /// becomes selected. + pub const SelectScroll = enum { + /// Scroll so the match is visible, only if it is not already. + if_needed, + + /// Never scroll. + none, + }; + + /// Initialize a search for the given needle. The needle is copied. + /// + /// This doesn't read any terminal state. The first `feed` does. + pub fn init( + alloc: Allocator, + needle_unowned: []const u8, + ) Allocator.Error!TerminalSearch { + var vp: ViewportSearch = try .init(alloc, needle_unowned); + 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 .{ + .alloc = alloc, + .viewport = vp, + .screens = .init(.{}), + .screen_generations = .init(.{}), + .active_key = .primary, + .stale_viewport_matches = true, + .viewport_matches = .empty, + }; + } + + /// Release all state. The terminal must be the same one given to + /// every other call, or null if the terminal has already been + /// deinitialized. When the terminal is alive this releases tracked + /// pins held within it. When it is null, those pins died with the + /// terminal's page storage, so only search-owned memory is freed. + pub fn deinit(self: *TerminalSearch, t_: ?*Terminal) void { + self.clearViewportMatches(); + self.viewport_matches.deinit(self.alloc); + self.viewport.deinit(); + var it = self.screens.iterator(); + while (it.next()) |entry| { + const valid = if (t_) |t| self.screenIsValid( + &t.screens, + entry.key, + entry.value, + ) else false; + if (valid) { + entry.value.deinit(); + } else { + entry.value.deinitScreenInvalid(); + } + } + } + + fn screenIsValid( + self: *const TerminalSearch, + screens: *const ScreenSet, + key: ScreenSet.Key, + search: *const ScreenSearch, + ) bool { + const generation = self.screen_generations.get(key) orelse return false; + if (generation != screens.generation(key)) return false; + const actual = screens.get(key) orelse return false; + return actual == search.screen; + } + + /// The needle that this search is using, borrowed. + pub fn needle(self: *const TerminalSearch) []const u8 { + return self.viewport.needle(); + } + + /// The searcher for the active screen as of the last feed. Null if + /// the search has never been fed (or the screen failed to + /// initialize). + pub fn activeScreenSearch(self: *TerminalSearch) ?*ScreenSearch { + return self.screens.getPtr(self.active_key); + } + + /// Returns true if all searches on all screens are complete. + pub fn isComplete(self: *TerminalSearch) bool { + var it = self.screens.iterator(); + while (it.next()) |entry| { + if (!entry.value.state.isComplete()) return false; + } + + return true; + } + + /// The overall search status derived from the per-screen search + /// states. + /// + /// Unlike `isComplete`, a search that has never been fed reports + /// `feed_required` rather than `complete`. An empty screen map + /// means the search has never seen the terminal, so reporting it + /// as complete would be technically true but useless to a caller + /// deciding what to do next. + pub fn status(self: *TerminalSearch) Status { + var saw_any = false; + var result: Status = .complete; + var it = self.screens.iterator(); + while (it.next()) |entry| { + saw_any = true; + switch (entry.value.state) { + // Progress is possible without a feed. + .active, .history => return .running, + + // Blocked until fed. + .history_feed => result = .feed_required, + + .complete => {}, + } + } + + if (!saw_any) return .feed_required; + return result; + } + + 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 reading + /// any terminal state, so this is safe to call concurrently with + /// terminal IO. Returns the overall tick progress. + pub fn tick(self: *TerminalSearch) 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 => {}, + }, + } + } + + return result; + } + + /// Read the terminal to update any search state that requires it, + /// such as reconciling screens, feeding more data to the + /// searchers, and detecting viewport changes. + /// + /// This reads the terminal, so the caller must ensure the terminal + /// isn't modified for the duration of this call (e.g. by holding a + /// lock). Feeding is also the only way the search learns about + /// terminal changes, so callers should feed periodically while a + /// search is in use, even after it reports complete. + /// + /// `active_dirty` should be true when the active area may have + /// changed since the last feed, which triggers a re-scan of the + /// active area. Callers that know when the active area changes + /// (e.g. Ghostty's renderer-maintained dirty flag) can pass false + /// to skip the re-scan. Callers without that knowledge should + /// always pass true. That is always correct, just slightly more + /// work, and the active area search is cheap by design. + pub fn feed( + self: *TerminalSearch, + t: *Terminal, + active_dirty: bool, + ) void { + const alloc = self.alloc; + + // Update our active screen + if (t.screens.active_key != self.active_key) { + self.active_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 = !self.screenIsValid( + &t.screens, + entry.key, + entry.value, + ); + + if (remove) { + entry.value.deinitScreenInvalid(); + _ = self.screens.remove(entry.key); + _ = self.screen_generations.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; + const screen_search = 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; + }, + }; + self.screens.put(entry.key, screen_search); + self.screen_generations.put( + entry.key, + t.screens.generation(entry.key), + ); + } + } + + // The caller told us the active area may have changed, so mark + // our viewport searcher dirty (forcing a re-search) and reload + // the active area for the active screen. + if (active_dirty) { + // 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 }, + ), + }; + } + } + } + + /// Return the matches on the pages covering the viewport, as of + /// the last feed. Note this can include matches slightly outside + /// the visible viewport when they share a page with it. + /// + /// The results are cached, since the underlying viewport search + /// drains as it is read. Matches are collected once after a feed + /// notices a viewport change and the cached results are returned + /// otherwise. The returned slice is owned by the search and valid + /// until the next call to this function, the next feed, or deinit. + /// + /// This doesn't read any terminal state, so it is safe to call + /// concurrently with terminal IO. + pub fn viewportMatches( + self: *TerminalSearch, + ) Allocator.Error![]const FlattenedHighlight { + if (!self.stale_viewport_matches) return self.viewport_matches.items; + + // We always mark the cache fresh, even if collection fails + // below: a failed collection isn't retried until the next feed + // marks the cache stale again. + self.stale_viewport_matches = false; + + self.clearViewportMatches(); + errdefer { + self.clearViewportMatches(); + + // Reset the viewport so we force an update (and therefore a + // re-collection) on the next feed. + self.viewport.reset(); + } + while (self.viewport.next()) |hl| { + var hl_cloned = try hl.clone(self.alloc); + errdefer hl_cloned.deinit(self.alloc); + try self.viewport_matches.append(self.alloc, hl_cloned); + } + + return self.viewport_matches.items; + } + + fn clearViewportMatches(self: *TerminalSearch) void { + for (self.viewport_matches.items) |*hl| hl.deinit(self.alloc); + self.viewport_matches.clearRetainingCapacity(); + } + + /// Select the next or previous search result on the active screen, + /// wrapping around at the ends, and optionally scrolling the + /// viewport so the newly selected match is visible. + /// + /// This feeds first so the selection always works against current + /// terminal state, making it safe to call at any time relative to + /// feeds. Like `feed`, this reads (and possibly scrolls) the + /// terminal, so the caller must ensure the terminal isn't + /// otherwise being used for the duration of this call. + /// + /// Returns true if a match is selected after the operation, or + /// false if there are no matches to select. + pub fn select( + self: *TerminalSearch, + t: *Terminal, + to: ScreenSearch.Select, + scroll: SelectScroll, + ) Allocator.Error!bool { + // A screen can be removed or replaced between feeds. Reconcile + // while holding the terminal lock before touching any + // ScreenSearch pins. + self.feed(t, false); + const screen_search = self.screens.getPtr(self.active_key) orelse + return false; + + // Make the selection. Ignore the result because we don't + // care if the selection didn't change. + _ = try screen_search.select(to); + + // Grab our match if we have one. If we don't have a selection + // then there was nothing to select. + const flattened = screen_search.selectedMatch() orelse return false; + + switch (scroll) { + .none => return true, + .if_needed => {}, + } + + // Grab the current screen and see if this match is visible within + // the viewport already. If it is, we do nothing. + const screen = t.screens.get(self.active_key) orelse return true; + + // 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 true; + } + } + + screen.scroll(.{ .pin = flattened.startPin() }); + return true; + } +}; + +test "starts feed required and runs to complete" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: TerminalSearch = try .init(alloc, "Fizz"); + defer search.deinit(&t); + + // A fresh search has never seen the terminal, so it must report + // feed_required even though isComplete() is trivially true. + try testing.expect(search.isComplete()); + try testing.expectEqual(TerminalSearch.Status.feed_required, search.status()); + + // Pump until complete. + while (search.status() != .complete) { + switch (search.status()) { + .feed_required => search.feed(&t, true), + .running => _ = search.tick(), + .complete => unreachable, + } + } + + const screen_search = search.activeScreenSearch().?; + try testing.expectEqual(2, screen_search.matchesLen()); +} + +test "viewport matches are cached until the next feed" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); + defer t.deinit(alloc); + + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice("Fizz\r\nBuzz\r\nFizz\r\nBang"); + + var search: TerminalSearch = try .init(alloc, "Fizz"); + defer search.deinit(&t); + search.feed(&t, true); + + // The sliding window drains on read, so a second read must return + // the cached results rather than an empty list. + try testing.expectEqual(2, (try search.viewportMatches()).len); + try testing.expectEqual(2, (try search.viewportMatches()).len); + + // A feed that observes a change refreshes the cache. + stream.nextSlice("\r\nFizz"); + search.feed(&t, true); + try testing.expectEqual(3, (try search.viewportMatches()).len); +} + +test "select after active screen removal" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 20, .rows = 2 }); + defer t.deinit(alloc); + + _ = try t.switchScreen(.alternate); + + var search: TerminalSearch = try .init(alloc, "needle"); + defer search.deinit(&t); + search.feed(&t, false); + try testing.expectEqual(ScreenSet.Key.alternate, search.active_key); + try testing.expect(search.screens.contains(.alternate)); + + _ = try t.switchScreen(.primary); + t.screens.remove(alloc, .alternate); + + // The select must reconcile against the live ScreenSet before + // touching any pins from the removed screen. + _ = try search.select(&t, .next, .if_needed); + try testing.expectEqual(ScreenSet.Key.primary, search.active_key); + try testing.expect(!search.screens.contains(.alternate)); +} + +test "select scrolls the viewport only when needed" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback_bytes = std.math.maxInt(usize), + }); + defer t.deinit(alloc); + + var stream = t.vtStream(); + defer stream.deinit(); + stream.nextSlice("Fizz\r\n"); + for (0..30) |_| stream.nextSlice("\r\n"); + stream.nextSlice("Fizz"); + + var search: TerminalSearch = try .init(alloc, "Fizz"); + defer search.deinit(&t); + while (search.status() != .complete) { + switch (search.status()) { + .feed_required => search.feed(&t, true), + .running => _ = search.tick(), + .complete => unreachable, + } + } + + // Whether the selected match is within the visible viewport rows. + // pointFromPin only bounds-checks the top of the region, so rows + // below the viewport must be rejected by the row count. + const Visible = struct { + fn check(term: *Terminal, s: *TerminalSearch) bool { + const pin = s.activeScreenSearch().?.selectedMatch().?.startPin(); + const pages = &term.screens.active.pages; + const pt = pages.pointFromPin(.viewport, pin) orelse return false; + return pt.viewport.y < pages.rows; + } + }; + + // First match is at the bottom which is already visible: no scroll. + try testing.expect(try search.select(&t, .next, .if_needed)); + try testing.expectEqual( + point.Point{ .active = .{ .x = 0, .y = 1 } }, + t.screens.active.pages.pointFromPin( + .active, + search.activeScreenSearch().?.selectedMatch().?.startPin(), + ).?, + ); + try testing.expect(Visible.check(&t, &search)); + + // Second match is in scrollback: selecting it must scroll the + // viewport so it becomes visible. + try testing.expect(try search.select(&t, .next, .if_needed)); + try testing.expect(Visible.check(&t, &search)); + + // With scrolling disabled the viewport must stay where it is even + // though the next selection (wrap back to the bottom) is not + // visible. + try testing.expect(try search.select(&t, .next, .none)); + try testing.expect(!Visible.check(&t, &search)); +} + +test "deinit after the terminal is gone" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback_bytes = std.math.maxInt(usize), + }); + + var stream = t.vtStream(); + stream.nextSlice("Fizz\r\nBuzz\r\nFizz"); + + // Run to complete and select a match so the search holds tracked + // pins within the terminal's page storage. + var search: TerminalSearch = try .init(alloc, "Fizz"); + while (search.status() != .complete) { + switch (search.status()) { + .feed_required => search.feed(&t, true), + .running => _ = search.tick(), + .complete => unreachable, + } + } + try testing.expect(try search.select(&t, .next, .none)); + + // Deinitialize the terminal first. The pins died with the page + // storage, so deinit with a null terminal must free only + // search-owned memory without touching the terminal. + stream.deinit(); + t.deinit(alloc); + search.deinit(null); +} + +test "no matches selects nothing" { + const alloc = testing.allocator; + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); + defer t.deinit(alloc); + + var search: TerminalSearch = try .init(alloc, "Fizz"); + defer search.deinit(&t); + search.feed(&t, true); + try testing.expect(!try search.select(&t, .next, .if_needed)); + try testing.expect(!try search.select(&t, .prev, .if_needed)); +} + +test "feed after complete discovers prepended snapshot history" { + const alloc = testing.allocator; + const io = testing.io; + const snapshot = @import("../snapshot/main.zig"); + + // A source terminal with several pages of scrollback where every line + // is a match, so the expected total is simply the number of lines. + var source: Terminal = try .init(io, alloc, .{ + .cols = 10, + .rows = 2, + .max_scrollback_bytes = std.math.maxInt(usize), + }); + defer source.deinit(alloc); + var needle_count: usize = 0; + { + var stream = source.vtStream(); + defer stream.deinit(); + const list = &source.screens.active.pages; + while (list.totalPages() < 4) : (needle_count += 1) { + stream.nextSlice("needle\r\n"); + } + } + + var encoded: std.Io.Writer.Allocating = .init(alloc); + defer encoded.deinit(); + try snapshot.encode(alloc, &encoded.writer, &source, .{ + .continuation = .ground, + }); + + // Restore only through READY. The terminal is usable while its history + // pages are still in flight. + var reader: std.Io.Reader = .fixed(encoded.written()); + var decoder: snapshot.Decoder = .init(&reader); + var decoded = try decoder.ready(alloc, io, .{ + .max_continuation_bytes = 0, + }); + defer decoded.deinit(alloc); + var t = decoded.toOwned(); + defer t.deinit(alloc); + const pages_at_ready = t.screens.active.pages.totalPages(); + + const Pump = struct { + fn run(search: *TerminalSearch, term: *Terminal) void { + while (search.status() != .complete) { + switch (search.status()) { + .feed_required => search.feed(term, true), + .running => _ = search.tick(), + .complete => unreachable, + } + } + } + }; + + // Search the READY state to completion and select the oldest match. + var search: TerminalSearch = try .init(alloc, "needle"); + defer search.deinit(&t); + Pump.run(&search, &t); + const partial = search.activeScreenSearch().?.matchesLen(); + try testing.expect(partial > 0); + try testing.expect(partial < needle_count); + try testing.expect(try search.select(&t, .prev, .none)); + const selected_idx = search.activeScreenSearch().?.selected.?.idx; + try testing.expectEqual(partial - 1, selected_idx); + const selected_before = search.activeScreenSearch().?.selectedMatch().?.untracked(); + + // Restore every history page below the live terminal. + var restored_pages: usize = 0; + while (try decoder.next(alloc, &t)) |progress| : (restored_pages += 1) { + try testing.expect(progress.rows > 0); + } + try testing.expect(restored_pages > 0); + try testing.expectEqual( + pages_at_ready + restored_pages, + t.screens.active.pages.totalPages(), + ); + + // Refresh the existing search the way ghostty_search_run does: feed, + // then tick to completion. It must now cover the restored history. + search.feed(&t, true); + Pump.run(&search, &t); + const screen_search = search.activeScreenSearch().?; + try testing.expectEqual(needle_count, screen_search.matchesLen()); + + // Restored results are older than everything already cached, so the + // selection keeps both its index and its target. + try testing.expectEqual(selected_idx, screen_search.selected.?.idx); + const selected_after = screen_search.selectedMatch().?.untracked(); + try testing.expect(selected_before.start.eql(selected_after.start)); + try testing.expect(selected_before.end.eql(selected_after.end)); + + // Results stay ordered newest to oldest, ending at the very first line. + const matches = try screen_search.matches(alloc); + defer alloc.free(matches); + const pages = &t.screens.active.pages; + var prev_y: ?usize = null; + for (matches) |hl| { + const pt = pages.pointFromPin(.screen, hl.startPin()).?; + if (prev_y) |y| try testing.expect(pt.screen.y < y); + prev_y = pt.screen.y; + } + try testing.expectEqual(0, prev_y.?); + + // A search created after the restore agrees with the refreshed one. + var fresh: TerminalSearch = try .init(alloc, "needle"); + defer fresh.deinit(&t); + Pump.run(&fresh, &t); + try testing.expectEqual( + needle_count, + fresh.activeScreenSearch().?.matchesLen(), + ); +} diff --git a/vendor/libghostty-vt/src/terminal/search/viewport.zig b/vendor/libghostty-vt/src/terminal/search/viewport.zig index 09d202be..93e63b88 100644 --- a/vendor/libghostty-vt/src/terminal/search/viewport.zig +++ b/vendor/libghostty-vt/src/terminal/search/viewport.zig @@ -228,7 +228,8 @@ pub const ViewportSearch = struct { test "simple search" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -271,7 +272,8 @@ test "simple search" { test "fingerprint detects node generation changes" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var search: ViewportSearch = try .init(alloc, "needle"); @@ -298,7 +300,8 @@ test "fingerprint detects node generation changes" { test "fingerprint only allocates on changes" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var failing = testing.FailingAllocator.init(alloc, .{}); @@ -320,7 +323,8 @@ test "fingerprint only allocates on changes" { test "clear screen and search" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -353,7 +357,8 @@ test "clear screen and search" { test "clear screen and search dirty tracking" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 10 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 10 }); defer t.deinit(alloc); var s = t.vtStream(); @@ -400,7 +405,8 @@ test "clear screen and search dirty tracking" { test "history search, no active area" { const alloc = testing.allocator; - var t: Terminal = try .init(alloc, .{ .cols = 10, .rows = 2 }); + const io = testing.io; + var t: Terminal = try .init(io, alloc, .{ .cols = 10, .rows = 2 }); defer t.deinit(alloc); var s = t.vtStream(); |
